Compare commits

..
Author SHA1 Message Date
sorokin.oleg.edu 4b9932236a Sync agent instructions from main 2026-09-13 11:40:17 +03:00
sorokin.oleg.edu afd81af1f1 Sync agent instructions from main 2026-09-12 13:43:57 +03:00
sorokin.oleg.edu 35d9eab302 Sync agent instructions from main 2026-09-12 13:40:39 +03:00
sorokin.oleg.edu 22e974da35 Sync agent instructions from main 2026-09-12 13:16:22 +03:00
sorokin.oleg.edu bf3f2f69a2 Sync agent instructions from main 2026-09-11 19:52:31 +03:00
sorokin.oleg.edu 75b8815a83 Sync agent instructions from main 2026-09-11 15:55:57 +03:00
sorokin.oleg.edu b2127cbe90 Sync agent instructions from main 2026-09-11 14:34:52 +03:00
sorokin.oleg.edu 1bf8ebca96 Record combined DATA scenario verification and frozen Windows artifact
Rust checks / check (windows-latest) (push) Canceled after 0s
Rust checks / check (ubuntu-latest) (push) Canceled after 0s
2026-09-06 05:04:32 +03:00
sorokin.oleg.edu dfd2e41259 Merge tested R6 data workflows into direct scenario workspace 2026-09-06 05:04:04 +03:00
sorokin.oleg.edu 05a84b217d Record final scenario save-scroll review and build evidence 2026-09-06 04:59:01 +03:00
sorokin.oleg.edu e7e37d485d Keep observed scenario scrolling current during async saves 2026-09-06 04:58:45 +03:00
sorokin.oleg.edu b35dede75f Browse message value properties by record with bounded pages 2026-09-06 04:56:41 +03:00
sorokin.oleg.edu 5fa9c905c8 Record verified scenario review fixes and fresh binary evidence 2026-09-06 04:54:22 +03:00
sorokin.oleg.edu 7a666076bf Fix scenario scroll cancellation, operand activations and picker cost 2026-09-06 04:53:23 +03:00
sorokin.oleg.edu f5467e50c5 Preserve authored source and reports through desktop migration 2026-09-06 04:43:41 +03:00
sorokin.oleg.edu 74989b6f25 Keep nested data field names visible in compact pickers 2026-09-06 04:40:08 +03:00
sorokin.oleg.edu 524dabb9c3 Record direct scenario checks and pending native acceptance 2026-09-06 04:33:36 +03:00
sorokin.oleg.edu d1d8f0bbed Add direct scenario gestures and atomic ordered message insertion 2026-09-06 04:33:13 +03:00
sorokin.oleg.edu 0edadeebdb Record R6 cross-platform tests and native data workflows 2026-09-06 04:29:29 +03:00
sorokin.oleg.edu 93e3137342 Plan direct scenario drawing and ordered insertion milestone 2026-09-06 04:14:22 +03:00
sorokin.oleg.edu ab661f2d33 Bound scenario value authoring to focused paged fields 2026-09-06 04:08:46 +03:00
sorokin.oleg.edu 15ed1ff3af Verify qualified scenario values through HTTP and record R6 evidence 2026-09-06 04:07:49 +03:00
sorokin.oleg.edu b403039d00 Add typed data contract editing and bounded dictionary views 2026-09-06 03:58:43 +03:00
sorokin.oleg.edu 7426c03f4e Explain R6 data authoring and record verification gaps 2026-09-06 03:58:12 +03:00
sorokin.oleg.edu 959b83c78f Specify R6 data contracts and verify coupled REST migration 2026-09-06 03:46:13 +03:00
sorokin.oleg.edu 0b58107097 Implement bounded typed data and identified interface contracts 2026-09-06 03:44:09 +03:00
sorokin.oleg.edu 1230ab8a3e Migrate frozen data contracts and authored source to schema 4 2026-09-06 03:39:02 +03:00
sorokin.oleg.edu c5276b1943 Record Windows and Linux direct state editing acceptance 2026-09-06 03:31:47 +03:00
sorokin.oleg.edu 9118218ac3 Reset state camera and tools only when navigation changes view 2026-09-06 03:24:01 +03:00
sorokin.oleg.edu 2bf4c5451a Freeze data contract integration scope and compatibility strategy 2026-09-06 03:17:33 +03:00
73 changed files with 14458 additions and 792 deletions
+3 -1
View File
@@ -53,6 +53,8 @@ The example opens in an architecture view with work nested inside its performers
**Model explorer** groups roots by engineering purpose and opens one container's direct children. Breadcrumbs navigate ownership; **Allocated work** is listed separately. Search names, kinds or `@aliases` to find elements with ancestor context. Results are paged in groups of 100. **Collapse all** folds the outline; **Locate** clears the filter and reveals the selected element's ancestry.
**Data & interfaces** separates exchange nature from mechanism, supports bounded reusable types and typed defaults, and gives each interface item allocation its own protocol and artifact identity. Operation parameters have provider-side directions; qualified message paths distinguish repeated Record uses. Record/item/interface specialization preserves inherited identities. See the [data contract](docs/language.rst) for exact semantics and compatibility.
The inspector exposes typed properties, references, ordered lists, aliases and UUID identity. Applying or navigating away attempts to commit the draft; invalid values remain editable. **Escaped strings (advanced)** uses quoted JSON escapes for exact tabs, line breaks and carriage returns, for example `"First\nSecond"`. UUID changes atomically update dependent references. Accepted model/source history retains up to 100 edits within an estimated 32 MiB history budget.
Choose **Interaction**, **Functional exchange** or **Boundary exchange** in the diagram palette, then click the source and a highlighted compatible target, or drag between them. Functional exchanges use output/input ports; function cards create or reuse real ports atomically. Boundary exchanges use compatible component ports. Middle-button drag pans without losing the chosen source; arrow keys also pan while drawing with the canvas focused. Click empty space to restart, or Escape to cancel. Each completed connection is one model/source history operation; edit its name and carried items in Properties.
@@ -70,7 +72,7 @@ In the state view, **Select / move** drags vertices and containers without repar
**Textual model** has a source-file folder tree, per-file drafts, syntax highlighting, live linting and explicit **Apply all**. Collapse/Locate navigate the hierarchy; collapsed folders retain draft and diagnostic indicators. Right-click a file for contextual actions. Projects can use relative includes to organize source into files. For example:
```text
arcadia 3;
arcadia 4;
project harbor "Harbor assistance" {
oa_entity control "Harbor control" {}
oa_activity respond "Respond to requests" {
File diff suppressed because it is too large Load Diff
+24 -11
View File
@@ -34,10 +34,7 @@ fn occurrence(
id
}
fn port(p: &mut Project, owner: Id, name: &str, direction: PortDirection, interface: Id) -> Id {
let items = match p.elements[&interface].shared() {
Some(SharedBody::Interface { items }) => items.clone(),
_ => vec![],
};
let items = crate::data::interface_items(p, interface);
let contract = if p.elements[&owner].kind() == Kind::Function {
if direction == PortDirection::Out {
PortContract::FunctionOutput {
@@ -168,6 +165,11 @@ pub fn coastal_rescue() -> Project {
"Distress report",
None,
);
if let Some(SharedBody::ExchangeItem { mechanism, .. }) =
p.elements.get_mut(&oa_item).unwrap().shared_mut()
{
*mechanism = ExchangeMechanism::Event;
}
p.relate(RelationKind::Allocation, "Reports distress", vessel, report);
p.relate(
RelationKind::Allocation,
@@ -308,6 +310,11 @@ pub fn coastal_rescue() -> Project {
"Digital distress report",
None,
);
if let Some(SharedBody::ExchangeItem { mechanism, .. }) =
p.elements.get_mut(&information).unwrap().shared_mut()
{
*mechanism = ExchangeMechanism::Event;
}
let material = add(
&mut p,
Kind::ExchangeItem,
@@ -317,6 +324,8 @@ pub fn coastal_rescue() -> Project {
);
*p.elements.get_mut(&material).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem {
kind: ExchangeItemKind::Material,
mechanism: ExchangeMechanism::Flow,
supertype: None,
};
let energy = add(
&mut p,
@@ -327,6 +336,8 @@ pub fn coastal_rescue() -> Project {
);
*p.elements.get_mut(&energy).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem {
kind: ExchangeItemKind::Energy,
mechanism: ExchangeMechanism::Flow,
supertype: None,
};
let field = add(
&mut p,
@@ -340,6 +351,9 @@ pub fn coastal_rescue() -> Project {
minimum: 1,
maximum: Some(1),
unit: "degrees north".into(),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
default: None,
};
let interface = add(
&mut p,
@@ -348,13 +362,12 @@ pub fn coastal_rescue() -> Project {
"Distress reporting interface",
None,
);
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface {
items: vec![information],
};
p.relate(
RelationKind::InterfaceItemAllocation,
"Distress payload",
interface,
information,
);
let vessel_port = port(
&mut p,
actor,
+92 -13
View File
@@ -1,4 +1,4 @@
//! Typed OA/SA language, tolerant source analysis, and explicit V1/V2 migration.
//! Typed OA/SA language, tolerant source analysis, and explicit V1/V2/V3 migration.
#[path = "migration_v2/source.rs"]
mod v2_source;
use crate::*;
@@ -340,6 +340,8 @@ fn reference_field(key: &str) -> bool {
| "referenced"
| "local"
| "field"
| "path"
| "supertype"
| "sender"
| "receiver"
| "action"
@@ -378,10 +380,14 @@ fn enum_field(key: &str) -> bool {
| "message_kind"
| "transition_kind"
| "side"
| "mechanism"
| "storage"
| "transmission"
| "acquisition"
)
}
/// Parse V3, or explicitly migrate a valid V1/V2 source candidate. Parsing never
/// Parse V4, or explicitly migrate a valid V1/V2/V3 source candidate. Parsing never
/// adopts a model and never overwrites an editor draft.
pub fn parse(source: &str) -> Result<Project, Vec<Diagnostic>> {
parse_limited(source, ParseLimits::UNLIMITED)
@@ -546,7 +552,7 @@ fn offset_for(source: &str, line: usize, column: usize) -> usize {
/// nested records are ordinary language fields; JSON documents are not embedded.
pub fn format(project: &Project) -> String {
let mut out = std::format!(
"arcadia 3;\nproject {} {} id \"{}\" {{\n description {};\n\n",
"arcadia 4;\nproject {} {} id \"{}\" {{\n description {};\n\n",
project.alias,
quote(&project.name),
project.id,
@@ -1337,12 +1343,12 @@ impl Parser<'_> {
.map(|(key, span)| ((d.id, key.clone()), span.start)),
);
}
let project =
let decoded =
resolve_declarations(header.project, &unit.declarations, &aliases, self.limits)
.map_err(|(_, error)| error)?;
Ok(ParsedDocument {
project,
migration: None,
project: decoded.project,
migration: decoded.migration,
locations,
fields,
})
@@ -1350,9 +1356,11 @@ impl Parser<'_> {
fn unit(&mut self, entry: bool, includes_allowed: bool) -> Result<SourceUnit, Error> {
let mut header = if entry {
self.take("arcadia")?;
if self.text() != "3" {
return Err(self.error("Unsupported schema version: expected 'arcadia 3;'."));
if !matches!(self.text(), "3" | "4") {
return Err(self
.error("Unsupported schema version: expected 'arcadia 3;' or 'arcadia 4;'."));
}
let schema_version = if self.text() == "3" { 3 } else { 4 };
self.cursor += 1;
self.take(";")?;
let start = self.current().span.start;
@@ -1365,7 +1373,7 @@ impl Parser<'_> {
self.take("{")?;
Some(SourceHeader {
project: Project {
schema_version: SCHEMA_VERSION,
schema_version,
id,
alias,
name,
@@ -1540,7 +1548,9 @@ pub(crate) fn resolve_declarations(
declarations: &[Declaration],
aliases: &BTreeMap<String, Id>,
limits: ParseLimits,
) -> Result<Project, (usize, Error)> {
) -> Result<crate::persistence::DecodeResult, (usize, Error)> {
let legacy = project.schema_version == 3;
let mut legacy_elements = serde_json::Map::new();
let mut nodes = Vec::new();
for (index, declaration) in declarations.iter().enumerate() {
(|| -> Result<(), Error> {
@@ -1561,6 +1571,9 @@ pub(crate) fn resolve_declarations(
};
match d.kind {
DeclKind::Element(kind, layer) => {
if legacy && !crate::persistence::v3::element_allowed(serde_json::to_value(kind).unwrap().as_str().unwrap()) {
return Err(conversion_error("Element constructor was not part of schema3.".into()));
}
let description =
take_string(&mut fields, "description", "").map_err(&conversion_error)?;
let explicit_parent = d.fields.contains_key("parent");
@@ -1601,9 +1614,17 @@ pub(crate) fn resolve_declarations(
*viewpoint = ScenarioViewpoint::MixedLegacy;
}
let mut body = serde_json::to_value(initial).unwrap();
let body_fields =
merge_fields(payload(&body), fields).map_err(&conversion_error)?;
let defaults = if legacy {
crate::persistence::v3::legacy_defaults(kind)
.and_then(|value| value.as_object().cloned())
.unwrap_or_else(|| payload(&body))
} else { payload(&body) };
let body_fields = merge_fields(defaults, fields).map_err(&conversion_error)?;
replace_payload(&mut body, body_fields);
if legacy {
legacy_elements.insert(d.id.to_string(), serde_json::json!({"id":d.id,"alias":d.alias,"name":d.name,"description":description,"parent":parent,"body":body}));
return Ok(());
}
let body: ElementBody = serde_json::from_value(body)
.map_err(|e| conversion_error(e.to_string()))?;
if body.kind() != kind || body.layer() != layer {
@@ -1624,6 +1645,9 @@ pub(crate) fn resolve_declarations(
);
}
DeclKind::Relation(kind) => {
if legacy && !crate::persistence::v3::relation_allowed(serde_json::to_value(kind).unwrap().as_str().unwrap()) {
return Err(conversion_error("Relation constructor was not part of schema3.".into()));
}
let description =
take_string(&mut fields, "description", "").map_err(&conversion_error)?;
let required: &[&str] = if kind == RelationKind::FunctionalExchange {
@@ -1725,6 +1749,58 @@ pub(crate) fn resolve_declarations(
.map_err(|error| (index, error))?;
target.nodes.insert(node.id, node);
}
if legacy {
let mut value = serde_json::to_value(&project).expect("project serialization");
value["elements"] = Value::Object(legacy_elements);
let migrated = serde_json::from_value(value)
.map_err(crate::persistence::FileError::Json)
.and_then(|old| crate::persistence::v3::migrate(old, limits))
.map_err(|error| {
let issue = if let crate::persistence::FileError::Model { issues, .. } = &error {
issues.first()
} else {
None
};
let index = issue
.and_then(|issue| issue.element)
.and_then(|id| declarations.iter().position(|d| d.id == id))
.unwrap_or(usize::MAX);
let offset = declarations.get(index).map_or(0, |d| {
issue
.and_then(|issue| issue.field.as_ref())
.and_then(|field| d.field_spans.get(field))
.map_or(d.offset, |span| span.start)
});
(
index,
Error {
code: if matches!(error, crate::persistence::FileError::Limit(_)) {
"model_limit"
} else {
"migration_error"
},
offset,
message: error.to_string(),
},
)
})?;
for (index, d) in declarations.iter().enumerate() {
if let DeclKind::Element(kind, layer) = d.kind {
let body = &migrated.project.elements[&d.id].body;
if body.kind() != kind || body.layer() != layer {
return Err((
index,
Error {
code: "invalid_source",
offset: d.offset,
message: "Declaration kind disagrees with its typed body.".into(),
},
));
}
}
}
return Ok(migrated);
}
limits.check_model(&project).map_err(|message| {
(
usize::MAX,
@@ -1735,7 +1811,10 @@ pub(crate) fn resolve_declarations(
},
)
})?;
Ok(project)
Ok(crate::persistence::DecodeResult {
project,
migration: None,
})
}
fn header(fields: &mut Map<String, Value>, d: &Declaration, named: bool) {
+40 -10
View File
@@ -3,7 +3,7 @@ use crate::source_project::{ProjectLimits, SourceBundle, compile_bundle, lint_bu
fn project_source(body: &str) -> String {
format!(
"arcadia 3; project model \"Model\" id \"00000000-0000-0000-0000-000000000001\" {{\n{body}\n}}"
"arcadia 4; project model \"Model\" id \"00000000-0000-0000-0000-000000000001\" {{\n{body}\n}}"
)
}
@@ -177,7 +177,7 @@ fn nested_fragment_id_stabilization_preserves_comments_and_indexes_real_bytes()
files: BTreeMap::from([
(
"project.arcadia".into(),
"arcadia 3; project model \"Model\" { include \"children.arcadia\"; }".into(),
"arcadia 4; project model \"Model\" { include \"children.arcadia\"; }".into(),
),
(
"children.arcadia".into(),
@@ -300,7 +300,7 @@ fn deep_declaration_parsing_and_positions_use_a_bounded_rust_stack() {
#[test]
fn tolerant_nested_analysis_retains_closed_children_before_an_unfinished_sibling() {
let source = "arcadia 3; project model \"航海\" {\noa_activity outer_one \"Outer\" {\n oa_activity ready \"Ready\" { description \"} is text\"; }\n oa_activity unfinished \"Unfinished\" { description \"unterminated";
let source = "arcadia 4; project model \"航海\" {\noa_activity outer_one \"Outer\" {\n oa_activity ready \"Ready\" { description \"} is text\"; }\n oa_activity unfinished \"Unfinished\" { description \"unterminated";
let analysis = analyze(source);
let ready = analysis
.declarations
@@ -406,12 +406,34 @@ fn checked_in_source_project() -> SourceBundle {
fn checked_in_nested_example_has_stable_ids_typed_exchanges_and_three_clear_views() {
let input = checked_in_source_project();
let compiled = compile_bundle(&input, ProjectLimits::default()).unwrap();
assert_eq!(
compiled.bundle, input,
"every example identity is already explicit"
);
assert_eq!(compiled.decoded.migration.as_ref().unwrap().from_schema, 3);
for (path, source) in &input.files {
let unit = parse_unit(source, path == &input.entry, ParseLimits::UNLIMITED).unwrap();
assert!(
unit.header
.as_ref()
.is_none_or(|header| header.id_insertion.is_none())
);
for declaration in unit.declarations {
assert!(
declaration.id_insertion.is_none(),
"every example identity is already explicit"
);
assert_eq!(
identity(&compiled.decoded.project, &declaration.alias),
declaration.id
);
}
}
let reopened = compile_bundle(&compiled.bundle, ProjectLimits::default()).unwrap();
assert_eq!(reopened.bundle, compiled.bundle);
assert!(reopened.decoded.migration.is_none());
assert_eq!(compiled.diagnostics.len(), 2);
assert!(
compiled.diagnostics.is_empty(),
compiled
.diagnostics
.iter()
.all(|issue| issue.diagnostic.code == "unspecified_exchange_mechanism"),
"{:?}",
compiled.diagnostics
);
@@ -473,7 +495,15 @@ fn checked_in_example_supports_cross_file_reparent_without_changing_allocations(
ProjectLimits::default(),
)
.unwrap();
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
assert_eq!(result.diagnostics.len(), 2);
assert!(
result
.diagnostics
.iter()
.all(|issue| issue.diagnostic.code == "unspecified_exchange_mechanism"),
"{:?}",
result.diagnostics
);
assert_eq!(
result.index.declarations[&assess].path,
"sa/assurance.arcadia"
@@ -500,6 +530,6 @@ fn checked_in_example_supports_cross_file_reparent_without_changing_allocations(
"sa/participants.arcadia",
"views.arcadia",
] {
assert_eq!(result.bundle.files[path], input.files[path]);
assert_eq!(result.bundle.files[path], compiled.bundle.files[path]);
}
}
+1
View File
@@ -1,4 +1,5 @@
//! Framework-independent OA/SA model, transactional commands and editing services.
pub mod data;
pub mod language;
pub mod model;
pub mod persistence;
+6 -4
View File
@@ -11,10 +11,12 @@ but constructs and validates the frozen DTO, preserves located old-contract
errors, then calls `adapter.rs`. Original staged scenario/state defaults and
generic port/optional FE endpoint contracts therefore remain explicit.
`adapter.rs` budgets generated data, validates V2, transforms only the changed
payloads, and validates schema 3. Serialization between the two typed DTOs copies
unchanged fields; original input bytes are never deserialized into the new
`Project`. V1 normalization also constructs this V2 DTO before the shared stage.
`adapter.rs` budgets generated data, validates V2 and transforms only the changed
port/endpoint payloads into an explicit schema 3 candidate. The schema 3 reader
then performs the data-contract upgrade and validates schema 4. Serialization
between compatibility DTOs copies unchanged fields; original input bytes are
never deserialized into the new `Project`. V1 normalization also constructs this
V2 DTO before the shared stages. Combined generation stays within one budget.
Do not update these frozen shapes when extending the current model. Add another
versioned migration when the persistent contract changes again. Golden V2
+18 -13
View File
@@ -62,16 +62,9 @@ pub(crate) fn migrate(
}],
});
}
let mut report = MigrationReport {
from_schema: 2,
to_schema: 3,
preserved_ports: vec![],
generated_endpoints: vec![],
orientation_defaults: vec![],
required_resolutions: vec![],
};
let mut report = MigrationReport::data_upgrade(2);
let mut value = serde_json::to_value(&old)?;
value["schema_version"] = Value::from(SCHEMA_VERSION);
value["schema_version"] = Value::from(3);
for element in old.elements.values() {
if let Some(super::model::SharedBody::Port {
direction,
@@ -204,11 +197,23 @@ pub(crate) fn migrate(
_ => {}
}
}
let project: Project = serde_json::from_value(value)?;
limits.check_model(&project).map_err(FileError::Limit)?;
super::super::validate_project(&project)?;
// Carry the endpoint-generation reference charge into the next migration;
// independent per-stage checks would undercount the combined generated graph.
let data_limits = ParseLimits {
max_step_references: limits
.max_step_references
.saturating_sub(additional_references),
..limits
};
let migrated = super::super::v3::migrate(serde_json::from_value(value)?, data_limits)?;
let data = migrated
.migration
.expect("the schema3 adapter reports its defaults");
report.semantic_defaults = data.semantic_defaults;
report.generated_interface_allocations = data.generated_interface_allocations;
report.unresolved_message_values = data.unresolved_message_values;
Ok(DecodeResult {
project,
project: migrated.project,
migration: Some(report),
})
}
+33
View File
@@ -0,0 +1,33 @@
# Schema 3 to 4 reader
Schema 3 is a real compatibility input. Its shapes were frozen at `5ce3eef`.
The small DTOs in `mod.rs` own the changed data payloads and old message values;
closed element/relation constructor lists prevent new vocabulary from entering
the old reader. Unchanged ports, diagram placements/routes, artifacts and traces
reuse their typed records. The intermediate JSON bridge rejects duplicate keys.
Nature, bounded types, field defaults/direction/storage, and single supertypes
receive explicit documented defaults. Interface lists become identified ordered
allocations with UUID v5 namespace equal to the project UUID and name
`v2-interface-item:<interface-uuid>:<item-uuid>`. The name remains the same for
V2 and V3 inputs so the migration route cannot change the generated identity.
Existing IDs never move; deterministic collisions fail with a located diagnostic.
Aliases use the normal deterministic collision suffix. Unique legacy message
paths are qualified; ambiguous annotations retain their expression and warning.
V1 first normalizes to the frozen V2 DTO. V2 port/endpoint normalization emits
an explicit schema3 candidate and then runs this reader before current decoding.
Generated object, record and reference budgets cover the combined stages.
`language::resolve_declarations` shares lexical/AST parsing, including nesting,
but chooses frozen source3 payload defaults and rejects new constructors. Both
single-file parsing and `source_project::compile_bundle` take this explicit path.
The bundle compiler first stabilizes omitted IDs, then performs targeted token
edits in `source_project/source_migration.rs`. Original files, includes, lexical
ownership and comments survive. New allocation declarations stay in the source
interface's module. The returned source and index describe schema4 bytes; loading
does not rewrite original disk files. Canonical output and second-save stability
are schema4. No whole-project formatting fallback handles authored source3.
Frozen source/JSON fixtures live under `tests/fixtures/v3-data-contract.*`; the
original V2 golden files remain unchanged.
+630
View File
@@ -0,0 +1,630 @@
//! Explicit schema-3 compatibility. Only changed payloads are frozen here;
//! unchanged typed records are shared after a closed old-constructor check.
use crate::language::ParseLimits;
use crate::persistence::{DecodeResult, FileError, MigrationReport};
use crate::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Project3 {
pub schema_version: u32,
pub id: Id,
pub alias: String,
pub name: String,
pub description: String,
#[serde(deserialize_with = "crate::unique_id_map")]
pub elements: BTreeMap<Id, Element3>,
#[serde(deserialize_with = "crate::unique_id_map")]
pub relations: BTreeMap<Id, Relation3>,
#[serde(deserialize_with = "crate::unique_id_map")]
pub diagrams: BTreeMap<Id, Diagram>,
#[serde(deserialize_with = "crate::unique_id_map")]
pub artifact_links: BTreeMap<Id, ArtifactLink>,
#[serde(deserialize_with = "crate::unique_id_map")]
pub traces: BTreeMap<Id, Trace>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Element3 {
pub id: Id,
pub alias: String,
pub name: String,
pub description: String,
pub parent: Option<Id>,
#[serde(deserialize_with = "strict_value")]
pub body: Value,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Relation3 {
pub id: Id,
pub alias: String,
pub name: String,
pub description: String,
#[serde(deserialize_with = "strict_value")]
pub body: Value,
}
// A Value bridge must retain the strict duplicate-field behavior of typed DTOs.
fn strict_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Value, D::Error> {
struct Strict;
impl<'de> serde::de::Visitor<'de> for Strict {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a value with unique object fields")
}
fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Value, E> {
Ok(v.into())
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Value, E> {
Ok(v.into())
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Value, E> {
Ok(v.into())
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Value, E> {
serde_json::Number::from_f64(v)
.map(Value::Number)
.ok_or_else(|| E::custom("Non-finite number"))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Value, E> {
Ok(v.into())
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Value, E> {
Ok(v.into())
}
fn visit_unit<E: serde::de::Error>(self) -> Result<Value, E> {
Ok(Value::Null)
}
fn visit_none<E: serde::de::Error>(self) -> Result<Value, E> {
Ok(Value::Null)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Value, A::Error> {
let mut out = Vec::new();
while let Some(v) = a.next_element::<StrictValue>()? {
out.push(v.0);
}
Ok(Value::Array(out))
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut a: A) -> Result<Value, A::Error> {
let mut out = serde_json::Map::new();
while let Some((k, v)) = a.next_entry::<String, StrictValue>()? {
if out.insert(k.clone(), v.0).is_some() {
return Err(serde::de::Error::custom(format!("Duplicate field '{k}'")));
}
}
Ok(Value::Object(out))
}
}
d.deserialize_any(Strict)
}
struct StrictValue(Value);
impl<'de> Deserialize<'de> for StrictValue {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
strict_value(d).map(Self)
}
}
#[derive(Deserialize)]
enum ItemKind3 {
Information,
Material,
Energy,
Event,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
enum Definition3 {
Boolean,
Integer,
Real,
String,
Enumeration { literals: Vec<String> },
Record,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Item3 {
kind: ItemKind3,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Type3 {
definition: Definition3,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Field3 {
type_ref: TypeRef,
minimum: u32,
maximum: Option<u32>,
unit: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Interface3 {
items: Vec<Id>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MessageValue3 {
field: Id,
expression: String,
}
pub(crate) fn relation_allowed(name: &str) -> bool {
matches!(
name,
"Allocation"
| "PortAllocation"
| "Interaction"
| "CapabilityInvolvement"
| "ChainInvolvement"
| "RoleRealization"
| "RoleAssignment"
| "FunctionalExchange"
| "BoundaryExchange"
| "MissionCapability"
| "CapabilityInclude"
| "CapabilityExtend"
| "CapabilityGeneralization"
| "MissionInvolvement"
| "SequenceLink"
| "StateTransition"
| "Availability"
| "ExchangeAllocation"
| "InterfaceProvision"
| "InterfaceRequirement"
| "StateAction"
)
}
pub(crate) fn element_allowed(name: &str) -> bool {
matches!(
name,
"Entity"
| "Actor"
| "Role"
| "Activity"
| "Capability"
| "OperationalMission"
| "Process"
| "System"
| "SystemActor"
| "Function"
| "SystemCapability"
| "Mission"
| "FunctionalChain"
| "ExchangeItem"
| "DataType"
| "DataField"
| "Interface"
| "Port"
| "Scenario"
| "Lifeline"
| "Occurrence"
| "StateMachine"
| "Region"
| "State"
| "Mode"
| "Initial"
| "Final"
| "Choice"
| "Junction"
| "Fork"
| "Join"
| "ShallowHistory"
| "DeepHistory"
| "EntryPoint"
| "ExitPoint"
| "Terminate"
| "Event"
| "Constraint"
)
}
pub(crate) fn legacy_defaults(kind: Kind) -> Option<Value> {
Some(match kind {
Kind::ExchangeItem => json!({"kind":"Information"}),
Kind::DataType => json!({"definition":"String"}),
Kind::DataField => json!({"type_ref":"String","minimum":1,"maximum":1,"unit":""}),
Kind::Interface => json!({"items":[]}),
_ => return None,
})
}
fn at(id: Id, field: &str, code: &str, message: impl Into<String>) -> FileError {
let message = message.into();
FileError::Model {
message: format!("V3 {code} at {id}.{field}: {message}"),
issues: vec![validation::Issue {
severity: validation::Severity::Error,
element: Some(id),
code: code.into(),
field: Some(field.into()),
message,
}],
}
}
fn singleton(value: &Value) -> Option<(&str, &Value)> {
let object = value.as_object()?;
(object.len() == 1)
.then(|| object.iter().next().unwrap())
.map(|(k, v)| (k.as_str(), v))
}
fn old_payload<T: serde::de::DeserializeOwned>(
id: Id,
field: &str,
value: Value,
) -> Result<T, FileError> {
serde_json::from_value(value).map_err(|error| at(id, field, "legacy_shape", error.to_string()))
}
pub(crate) fn migrate(old: Project3, limits: ParseLimits) -> Result<DecodeResult, FileError> {
if old.schema_version != 3 {
return Err(FileError::Invalid("Expected schema_version 3.".into()));
}
let graph = old.elements.len().saturating_add(old.relations.len());
let records = graph
.saturating_add(old.diagrams.len())
.saturating_add(old.diagrams.values().map(|d| d.nodes.len()).sum::<usize>())
.saturating_add(old.traces.len())
.saturating_add(old.artifact_links.len())
.saturating_add(1);
limits
.check_counts(graph, records, 0)
.map_err(FileError::Limit)?;
let mut report = MigrationReport::data_upgrade(3);
let mut value = serde_json::to_value(&old)?;
let mut allocations = Vec::new();
for (key, e) in &old.elements {
if *key != e.id {
return Err(at(
e.id,
"id",
"identity",
"Element map key differs from its identity.",
));
}
let mut body = e.body.clone();
let (layer, inner) = singleton(&body)
.filter(|(name, _)| matches!(*name, "Oa" | "Sa"))
.ok_or_else(|| {
at(
e.id,
"body",
"legacy_shape",
"Expected one OA or SA constructor.",
)
})?;
let layer = layer.to_owned();
let outer = inner
.as_str()
.or_else(|| singleton(inner).map(|(name, _)| name));
if !outer.is_some_and(|name| {
if layer == "Oa" {
matches!(
name,
"Entity"
| "Actor"
| "Role"
| "Activity"
| "Capability"
| "Mission"
| "Process"
| "Shared"
)
} else {
matches!(
name,
"System"
| "Actor"
| "Function"
| "Capability"
| "Mission"
| "FunctionalChain"
| "Shared"
)
}
}) {
return Err(at(
e.id,
"body",
"legacy_shape",
"Unknown schema3 layer constructor.",
));
}
if let Some(("Shared", shared)) = singleton(inner) {
let name = shared
.as_str()
.or_else(|| singleton(shared).map(|(name, _)| name))
.ok_or_else(|| {
at(
e.id,
"body",
"legacy_shape",
"Expected one schema3 shared constructor.",
)
})?
.to_owned();
if !matches!(
name.as_str(),
"ExchangeItem"
| "DataType"
| "DataField"
| "Interface"
| "Port"
| "Scenario"
| "Lifeline"
| "Occurrence"
| "StateMachine"
| "Event"
| "Region"
| "State"
| "Constraint"
) {
return Err(at(
e.id,
"body",
"legacy_shape",
format!("Unknown schema3 shared constructor '{name}'."),
));
}
let payload = shared.get(&name).cloned().unwrap_or(Value::Null);
let changed = match name.as_str() {
"ExchangeItem" => {
let old: Item3 = old_payload(e.id, "body.kind", payload)?;
let (kind, mechanism) = match old.kind {
ItemKind3::Information => ("Information", "Unspecified"),
ItemKind3::Material => ("Material", "Unspecified"),
ItemKind3::Energy => ("Energy", "Unspecified"),
ItemKind3::Event => ("Information", "Event"),
};
Some(json!({"kind":kind,"mechanism":mechanism,"supertype":null}))
}
"DataType" => {
let old: Type3 = old_payload(e.id, "body.definition", payload)?;
let definition = match old.definition {
Definition3::Boolean => json!("Boolean"),
Definition3::Integer => json!({"Integer":{"minimum":null,"maximum":null}}),
Definition3::Real => json!({"Real":{"minimum":null,"maximum":null}}),
Definition3::String => {
json!({"String":{"minimum_length":0,"maximum_length":null}})
}
Definition3::Enumeration { literals } => {
json!({"Enumeration":{"literals":literals}})
}
Definition3::Record => json!({"Record":{"supertype":null}}),
};
Some(json!({"definition":definition,"default":null,"unit":""}))
}
"DataField" => {
let old: Field3 = old_payload(e.id, "body", payload)?;
Some(
json!({"type_ref":old.type_ref,"minimum":old.minimum,"maximum":old.maximum,"unit":old.unit,"direction":"Unspecified","storage":"Value","default":null}),
)
}
"Interface" => {
let old: Interface3 = old_payload(e.id, "items", payload)?;
let mut seen = BTreeSet::new();
for (order, item) in old.items.into_iter().enumerate() {
if !seen.insert(item) {
return Err(at(
e.id,
"items",
"duplicate_reference",
"Interface items must be unique.",
));
}
allocations.push((e.id, item, order));
}
Some(json!({"supertype":null}))
}
"Occurrence" => {
let mut payload = payload;
if let Some(values) = payload.pointer_mut("/body/Exchange/values") {
let old: Vec<MessageValue3> =
old_payload(e.id, "body.values", values.clone())?;
*values=Value::Array(old.into_iter().map(|v|json!({"field":v.field,"expression":v.expression,"path":[]})).collect());
}
Some(payload)
}
_ => None,
};
if let Some(changed) = changed {
let description = match name.as_str() {
"ExchangeItem" if changed["mechanism"] == "Event" => {
"Legacy Event nature becomes Information with Event mechanism; supertype is absent."
}
"ExchangeItem" => {
"Nature is retained; mechanism is Unspecified and supertype is absent."
}
"DataType" => {
"Existing type is retained with unbounded numeric/string limits, no scalar default or unit, and no Record supertype."
}
"DataField" => {
"Type, ownership, multiplicity and unit are retained; direction is Unspecified, storage is Value and default is absent."
}
"Interface" => {
"Items become identified ordered allocations with Unspecified protocols; supertype is absent."
}
_ => {
"Value expressions are retained; unique enclosing field paths are resolved and ambiguous legacy paths remain unresolved."
}
};
body[&layer]["Shared"][&name] = changed;
report
.semantic_defaults
.push(crate::persistence::SemanticDefault {
object: e.id,
field: "body".into(),
description: description.into(),
});
}
}
// Current deserialization checks the reused, unchanged outer/typed parts.
let _: ElementBody = serde_json::from_value(body.clone())
.map_err(|error| at(e.id, "body", "legacy_shape", error.to_string()))?;
value["elements"][key.to_string()]["body"] = body;
}
for (key, r) in &old.relations {
if *key != r.id {
return Err(at(
r.id,
"id",
"identity",
"Relation map key differs from its identity.",
));
}
if !singleton(&r.body).is_some_and(|(name, _)| relation_allowed(name)) {
return Err(at(
r.id,
"body",
"legacy_shape",
"Relation constructor was not part of schema3.",
));
}
}
value["schema_version"] = SCHEMA_VERSION.into();
let mut project: Project = serde_json::from_value(value)?;
let mut references = project
.elements
.values()
.map(|e| e.steps().map_or(0, Vec::len))
.sum::<usize>()
.saturating_add(allocations.len().saturating_mul(2));
limits
.check_counts(
project
.elements
.len()
.saturating_add(project.relations.len())
.saturating_add(allocations.len()),
project.identities().len().saturating_add(allocations.len()),
references,
)
.map_err(FileError::Limit)?;
let mut ids: BTreeSet<_> = project.identities().into_iter().map(|(id, _)| id).collect();
for (source, target, order) in allocations {
let id = Id::new_v5(
&project.id,
format!("v2-interface-item:{source}:{target}").as_bytes(),
);
if !ids.insert(id) {
return Err(at(
source,
"items",
"identity_collision",
format!(
"Deterministic interface allocation {id} already belongs to another object."
),
));
}
let name = format!("{} · {}", project.named(source), project.named(target));
let alias = project.fresh_alias(
&format!(
"{}_{}_allocation",
project
.elements
.get(&source)
.map_or("interface", |e| e.alias.as_str()),
project
.elements
.get(&target)
.map_or("item", |e| e.alias.as_str())
),
"interface_item_allocation",
id,
);
project.relations.insert(
id,
Relation {
id,
alias: alias.clone(),
name,
description: String::new(),
body: RelationBody::InterfaceItemAllocation {
source,
target,
order: order.try_into().map_err(|_| {
at(source, "items", "model_limit", "Too many interface items.")
})?,
transmission: TransmissionProtocol::Unspecified,
acquisition: AcquisitionProtocol::Unspecified,
},
},
);
report.generated_interface_allocations.push(
crate::persistence::GeneratedInterfaceAllocation {
id,
source,
target,
alias,
order: order as u32,
},
);
}
let annotations: Vec<_> = project
.elements
.values()
.filter_map(|e| match e.shared() {
Some(SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
exchange: Some(exchange),
values,
..
},
..
}) => Some((e.id, *exchange, values.clone())),
_ => None,
})
.collect();
for (owner, exchange, values) in annotations {
let Some(relation) = project.relations.get(&exchange) else {
continue;
};
for (index, value) in values.into_iter().enumerate() {
let resolution =
crate::data::resolve_legacy_field_path(&project, relation, value.field)
.map_err(|message| at(owner, "body.values", "model_limit", message))?;
if let crate::data::LegacyFieldPathResolution::Unique(path) = resolution {
if !path.is_empty() {
references = references.saturating_add(path.len());
limits
.check_counts(
project
.elements
.len()
.saturating_add(project.relations.len()),
project.identities().len(),
references,
)
.map_err(FileError::Limit)?;
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = project
.elements
.get_mut(&owner)
.and_then(Element::shared_mut)
{
values[index].path = path;
}
}
} else if matches!(
resolution,
crate::data::LegacyFieldPathResolution::Ambiguous
) {
report.unresolved_message_values.push(crate::persistence::UnresolvedMessageValue { occurrence:owner,field:value.field,reason:"Several carried paths reach this legacy field; choose an explicit argument path.".into() });
}
}
}
limits.check_model(&project).map_err(FileError::Limit)?;
super::validate_project(&project)?;
Ok(DecodeResult {
project,
migration: Some(report),
})
}
+149 -14
View File
@@ -6,7 +6,7 @@ use std::{
use uuid::Uuid;
pub type Id = Uuid;
pub const SCHEMA_VERSION: u32 = 3;
pub const SCHEMA_VERSION: u32 = 4;
pub const MAX_COORDINATE: f32 = 1_000_000.;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
@@ -265,17 +265,79 @@ pub enum ExchangeItemKind {
Information,
Material,
Energy,
Event,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ExchangeMechanism {
#[default]
Unspecified,
Flow,
Event,
Operation,
SharedData,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ParameterDirection {
#[default]
Unspecified,
In,
Out,
InOut,
Return,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FieldStorage {
#[default]
Value,
Reference,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum DataValue {
Boolean(bool),
Integer(i64),
Real(f64),
String(String),
Enumeration(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum TransmissionProtocol {
#[default]
Unspecified,
Synchronous,
Asynchronous,
Unicast,
Multicast,
Broadcast,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AcquisitionProtocol {
#[default]
Unspecified,
Read,
Accept,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum DataTypeDefinition {
Boolean,
Integer,
Real,
String,
Enumeration { literals: Vec<String> },
Record,
Integer {
minimum: Option<i64>,
maximum: Option<i64>,
},
Real {
minimum: Option<f64>,
maximum: Option<f64>,
},
String {
minimum_length: u32,
maximum_length: Option<u32>,
},
Enumeration {
literals: Vec<String>,
},
Record {
supertype: Option<Id>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -453,6 +515,8 @@ pub struct LifelineBinding {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MessageValue {
#[serde(default)]
pub path: Vec<Id>,
pub field: Id,
pub expression: String,
}
@@ -502,18 +566,25 @@ pub enum OccurrenceBody {
pub enum SharedBody {
ExchangeItem {
kind: ExchangeItemKind,
mechanism: ExchangeMechanism,
supertype: Option<Id>,
},
DataType {
definition: DataTypeDefinition,
default: Option<DataValue>,
unit: String,
},
DataField {
type_ref: TypeRef,
minimum: u32,
maximum: Option<u32>,
unit: String,
direction: ParameterDirection,
storage: FieldStorage,
default: Option<Vec<DataValue>>,
},
Interface {
items: Vec<Id>,
supertype: Option<Id>,
},
Port {
contract: PortContract,
@@ -672,17 +743,27 @@ impl ElementBody {
match k {
Kind::ExchangeItem => SharedBody::ExchangeItem {
kind: ExchangeItemKind::Information,
mechanism: ExchangeMechanism::Unspecified,
supertype: None,
},
Kind::DataType => SharedBody::DataType {
definition: DataTypeDefinition::String,
definition: DataTypeDefinition::String {
minimum_length: 0,
maximum_length: None,
},
default: None,
unit: String::new(),
},
Kind::DataField => SharedBody::DataField {
type_ref: TypeRef::String,
minimum: 1,
maximum: Some(1),
unit: String::new(),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
default: None,
},
Kind::Interface => SharedBody::Interface { items: vec![] },
Kind::Interface => SharedBody::Interface { supertype: None },
// Port creation requires an explicit contract and owner.
Kind::Port => return None,
Kind::Scenario => SharedBody::Scenario {
@@ -752,6 +833,8 @@ impl SharedBody {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationKind {
InterfaceItemAllocation,
DataAssociation,
Allocation,
PortAllocation,
Interaction,
@@ -775,7 +858,9 @@ pub enum RelationKind {
StateAction,
}
impl RelationKind {
pub const ALL: [Self; 21] = [
pub const ALL: [Self; 23] = [
Self::InterfaceItemAllocation,
Self::DataAssociation,
Self::Allocation,
Self::PortAllocation,
Self::Interaction,
@@ -800,6 +885,8 @@ impl RelationKind {
];
pub fn permits(self, from: Kind, to: Kind) -> bool {
match self {
Self::InterfaceItemAllocation => from == Kind::Interface && to == Kind::ExchangeItem,
Self::DataAssociation => from == Kind::DataType && to == Kind::DataType,
Self::Allocation => from.is_performer() && to.is_work(),
Self::PortAllocation => from == Kind::Port && to == Kind::Port,
Self::Interaction => from == Kind::Activity && to == Kind::Activity,
@@ -855,6 +942,8 @@ impl RelationKind {
}
pub fn hint(self) -> &'static str {
match self {
Self::InterfaceItemAllocation => "Interface → allocated exchange item",
Self::DataAssociation => "Record type → record type",
Self::Allocation => "Performer → leaf activity/function",
Self::PortAllocation => "Component port → allocated function port",
Self::Interaction => "OA activity → OA activity",
@@ -886,6 +975,8 @@ impl RelationKind {
impl fmt::Display for RelationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InterfaceItemAllocation => "Interface item allocation",
Self::DataAssociation => "Data association",
Self::Allocation => "Allocation",
Self::PortAllocation => "Port allocation",
Self::Interaction => "Interaction",
@@ -922,6 +1013,25 @@ pub struct Relation {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum RelationBody {
InterfaceItemAllocation {
source: Id,
target: Id,
order: u32,
transmission: TransmissionProtocol,
acquisition: AcquisitionProtocol,
},
DataAssociation {
source: Id,
target: Id,
source_role: String,
target_role: String,
source_minimum: u32,
source_maximum: Option<u32>,
target_minimum: u32,
target_maximum: Option<u32>,
source_navigable: bool,
target_navigable: bool,
},
Allocation {
source: Id,
target: Id,
@@ -1039,6 +1149,8 @@ impl Relation {
impl RelationBody {
pub fn kind(&self) -> RelationKind {
match self {
Self::InterfaceItemAllocation { .. } => RelationKind::InterfaceItemAllocation,
Self::DataAssociation { .. } => RelationKind::DataAssociation,
Self::Allocation { .. } => RelationKind::Allocation,
Self::PortAllocation { .. } => RelationKind::PortAllocation,
Self::Interaction { .. } => RelationKind::Interaction,
@@ -1064,7 +1176,9 @@ impl RelationBody {
}
pub fn endpoints(&self) -> (Id, Id) {
match self {
Self::Allocation { source, target }
Self::InterfaceItemAllocation { source, target, .. }
| Self::DataAssociation { source, target, .. }
| Self::Allocation { source, target }
| Self::PortAllocation { source, target }
| Self::Interaction { source, target, .. }
| Self::CapabilityInvolvement { source, target }
@@ -1089,7 +1203,9 @@ impl RelationBody {
}
pub fn set_endpoints(&mut self, a: Id, b: Id) {
match self {
Self::Allocation { source, target }
Self::InterfaceItemAllocation { source, target, .. }
| Self::DataAssociation { source, target, .. }
| Self::Allocation { source, target }
| Self::PortAllocation { source, target }
| Self::Interaction { source, target, .. }
| Self::CapabilityInvolvement { source, target }
@@ -1125,6 +1241,25 @@ impl RelationBody {
}
pub fn new(kind: RelationKind, source: Id, target: Id) -> Self {
match kind {
RelationKind::InterfaceItemAllocation => Self::InterfaceItemAllocation {
source,
target,
order: 0,
transmission: TransmissionProtocol::Unspecified,
acquisition: AcquisitionProtocol::Unspecified,
},
RelationKind::DataAssociation => Self::DataAssociation {
source,
target,
source_role: String::new(),
target_role: String::new(),
source_minimum: 0,
source_maximum: None,
target_minimum: 0,
target_maximum: None,
source_navigable: false,
target_navigable: false,
},
RelationKind::Allocation => Self::Allocation { source, target },
RelationKind::PortAllocation => Self::PortAllocation { source, target },
RelationKind::Interaction => Self::Interaction {
+49 -2
View File
@@ -5,6 +5,8 @@ use thiserror::Error;
#[path = "migration_v2/mod.rs"]
pub(crate) mod v2;
pub(crate) use v2::adapter::migrate as migrate_v2_limited;
#[path = "migration_v3/mod.rs"]
pub(crate) mod v3;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -15,6 +17,50 @@ pub struct MigrationReport {
pub generated_endpoints: Vec<GeneratedEndpoint>,
pub orientation_defaults: Vec<OrientationDefault>,
pub required_resolutions: Vec<Id>,
#[serde(default)]
pub semantic_defaults: Vec<SemanticDefault>,
#[serde(default)]
pub generated_interface_allocations: Vec<GeneratedInterfaceAllocation>,
#[serde(default)]
pub unresolved_message_values: Vec<UnresolvedMessageValue>,
}
impl MigrationReport {
pub(crate) fn data_upgrade(from_schema: u32) -> Self {
Self {
from_schema,
to_schema: SCHEMA_VERSION,
preserved_ports: vec![],
generated_endpoints: vec![],
orientation_defaults: vec![],
required_resolutions: vec![],
semantic_defaults: vec![],
generated_interface_allocations: vec![],
unresolved_message_values: vec![],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SemanticDefault {
pub object: Id,
pub field: String,
pub description: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GeneratedInterfaceAllocation {
pub id: Id,
pub source: Id,
pub target: Id,
pub alias: String,
pub order: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnresolvedMessageValue {
pub occurrence: Id,
pub field: Id,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -101,13 +147,14 @@ pub fn decode_with_report_limited(
migrate_v1_with_report_limited(old, limits)?
}
Some(2) => migrate_v2_limited(serde_json::from_slice(bytes)?, limits)?,
Some(3) => DecodeResult {
Some(3) => v3::migrate(serde_json::from_slice(bytes)?, limits)?,
Some(4) => DecodeResult {
project: serde_json::from_slice(bytes)?,
migration: None,
},
_ => {
return Err(FileError::Invalid(
"Unsupported or missing schema_version; expected 1, 2 or 3.".into(),
"Unsupported or missing schema_version; expected 1, 2, 3 or 4.".into(),
));
}
}
+8 -18
View File
@@ -64,9 +64,9 @@ pub struct LegacyWorkPortSplitRequest {
pub outgoing_items: Vec<Id>,
}
/// R6 specialization has one explicit seam; current models support identity only.
pub fn item_satisfies(_project: &Project, carried: Id, declared: Id) -> bool {
carried == declared
/// A specialized carried item satisfies a declared base item.
pub fn item_satisfies(project: &Project, carried: Id, declared: Id) -> bool {
crate::data::item_satisfies(project, carried, declared)
}
pub fn items_satisfy(project: &Project, carried: &[Id], declared: &[Id]) -> bool {
carried.iter().all(|item| {
@@ -130,13 +130,7 @@ fn declared_interface_items(p: &Project, port: Id) -> Option<Vec<Id>> {
Some(
interfaces
.into_iter()
.filter_map(|id| p.elements.get(&id))
.filter_map(|e| match e.shared() {
Some(SharedBody::Interface { items }) => Some(items),
_ => None,
})
.flatten()
.copied()
.flat_map(|id| crate::data::interface_items(p, id))
.collect(),
)
}
@@ -903,14 +897,10 @@ fn validate_carried_contract(p: &Project, r: &Relation, port: &Element, out: &mu
..
}) => {
let mut allowed = declared_interface_items(p, port.id);
if let Some(SharedBody::Interface { items }) = legacy
.as_ref()
.and_then(|l| l.interface)
.and_then(|id| p.elements.get(&id))
.and_then(Element::shared)
{
if let Some(interface) = legacy.as_ref().and_then(|l| l.interface) {
let items = crate::data::interface_items(p, interface);
if r.kind() == RelationKind::BoundaryExchange
&& !items_satisfy(p, r.body.items(), items)
&& !items_satisfy(p, r.body.items(), &items)
{
error(
out,
@@ -1173,7 +1163,7 @@ pub(crate) fn validate_boundary_interface_requirements(
if !p.relations.values().any(|role| {
role.kind() == RelationKind::InterfaceProvision
&& role.source() == peer.id
&& role.target() == required.target()
&& crate::data::interface_satisfies(p, role.target(), required.target())
}) {
warning(
out,
+8 -2
View File
@@ -335,6 +335,11 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
.collect();
let mut edges = Vec::new();
for r in p.relations.values() {
// Interface allocations are selectable nested dictionary rows. Their
// independently identified contracts do not add noisy diagram arrows.
if r.kind() == RelationKind::InterfaceItemAllocation {
continue;
}
if d.projection == ProjectionKind::Allocation && r.kind() == RelationKind::Allocation {
continue;
}
@@ -370,7 +375,8 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
}
if let (Some(source), Some(target)) = (anchor(r.source()), anchor(r.target()))
&& (source != target
|| (d.projection.state_machine().is_some()
|| ((d.projection.state_machine().is_some()
|| r.kind() == RelationKind::DataAssociation)
&& r.source() == r.target()
&& nodes
.iter()
@@ -396,7 +402,7 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
RelationBody::BoundaryExchange {
oriented: false,
..
}
} | RelationBody::DataAssociation { .. }
),
source_port: source_port.filter(|id| visible_ports.contains(id)),
target_port: target_port.filter(|id| visible_ports.contains(id)),
+43 -10
View File
@@ -33,8 +33,13 @@ pub fn visit_element_refs(e: &mut Element, mut visit: impl FnMut(&mut Id)) {
type_ref: TypeRef::Named(id),
..
} => visit(id),
SharedBody::Interface { items } => {
for id in items {
SharedBody::Interface { supertype }
| SharedBody::ExchangeItem { supertype, .. }
| SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype },
..
} => {
if let Some(id) = supertype {
visit(id);
}
}
@@ -83,6 +88,9 @@ pub fn visit_element_refs(e: &mut Element, mut visit: impl FnMut(&mut Id)) {
visit(id);
}
for value in values {
for id in &mut value.path {
visit(id);
}
visit(&mut value.field);
}
}
@@ -377,7 +385,12 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
}
if let Some(shared) = e.shared_mut() {
match shared {
SharedBody::Interface { items } => items.retain(|id| !removed.contains(id)),
SharedBody::Interface { supertype }
| SharedBody::ExchangeItem { supertype, .. }
| SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype },
..
} => clear(supertype),
SharedBody::Event {
body: EventBody::Signal { items },
} => items.retain(|id| !removed.contains(id)),
@@ -413,7 +426,10 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
clear(sender);
clear(receiver);
clear(reply_to);
values.retain(|value| !removed.contains(&value.field));
values.retain(|value| {
!removed.contains(&value.field)
&& value.path.iter().all(|id| !removed.contains(id))
});
}
OccurrenceBody::Action { action, lifeline } => {
clear(action);
@@ -485,20 +501,37 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
exchange: Some(id), ..
},
..
}) => p
.relations
.get(id)
.map(|r| (e.id, crate::validation::carried_fields(p, r))),
}) => p.relations.get(id).map(|r| {
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = e.shared()
else {
unreachable!()
};
let retained: Vec<_> = values
.iter()
.filter(|value| {
crate::data::carried_value_path(p, r, &value.path, value.field).is_some()
|| (value.path.is_empty()
&& crate::data::carried_field_paths(p, r)
.iter()
.any(|f| f.field == value.field))
})
.cloned()
.collect();
(e.id, retained)
}),
_ => None,
})
.collect();
for (id, fields) in allowed {
for (id, retained) in allowed {
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = p.elements.get_mut(&id).and_then(Element::shared_mut)
{
values.retain(|value| fields.contains(&value.field));
*values = retained;
}
}
}
+128 -3
View File
@@ -1,7 +1,7 @@
//! Deterministic, bounded diagram geometry. Only authored pins belong in the model;
//! callers share this derived geometry for drawing, picking, fitting and export.
use crate::projection::{self, ProjectedEdge, ProjectedNode, ProjectedView};
use crate::{Diagram, Id, Position, Project, RelationKind, Size};
use crate::{Diagram, Id, Position, Project, Relation, RelationBody, RelationKind, Size};
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use std::fmt;
@@ -55,6 +55,122 @@ pub struct EdgeLabelGeometry {
pub bounds: RoutingBounds,
}
/// Derived labels and navigation markers for the two named association ends.
/// Canvas and SVG consume these same coordinates; no extra diagram state exists.
#[derive(Debug, Clone, PartialEq)]
pub struct AssociationEndGeometry {
pub source_end: bool,
pub label: EdgeLabelGeometry,
pub tip: Position,
pub inward: Position,
pub navigable: bool,
}
pub fn association_end_geometry(
relation: &Relation,
routed: &RoutedEdge,
) -> Vec<AssociationEndGeometry> {
let RelationBody::DataAssociation {
source_navigable,
target_navigable,
..
} = &relation.body
else {
return Vec::new();
};
let mut ends: Vec<AssociationEndGeometry> = Vec::new();
for (source_end, navigable) in [(true, *source_navigable), (false, *target_navigable)] {
let Some(tip) = (if source_end {
routed.points.first()
} else {
routed.points.last()
})
.copied() else {
continue;
};
let inward = if source_end {
routed.points.iter().find(|p| **p != tip)
} else {
routed.points.iter().rev().find(|p| **p != tip)
};
let Some(inward) = inward.copied() else {
continue;
};
let full = crate::data::association_end_label(relation, source_end).unwrap_or_default();
let text = if let Some((role, multiplicity)) = full.rsplit_once(" [") {
let role = if role.chars().count() > 32 {
role.chars()
.take(31)
.chain(std::iter::once('…'))
.collect::<String>()
} else {
role.to_owned()
};
format!("{role} [{multiplicity}")
} else {
full
};
let size = Size {
width: text.chars().count() as f32 * 7.0 + 12.0,
height: 22.0,
};
let dx = inward.x - tip.x;
let dy = inward.y - tip.y;
let length = dx.hypot(dy);
let direction = pos(dx / length, dy / length);
// One normal sign puts opposite endpoints of a straight edge on
// opposite sides because their inward tangent directions are reversed.
let along =
direction.x.abs() * size.width / 2.0 + direction.y.abs() * size.height / 2.0 + 12.0;
let normal =
direction.y.abs() * size.width / 2.0 + direction.x.abs() * size.height / 2.0 + 8.0;
let mut center = pos(
tip.x + direction.x * along - direction.y * normal,
tip.y + direction.y * along + direction.x * normal,
);
if let Some(other) = ends.first()
&& (center.x - other.label.center.x).abs()
< (size.width + other.label.bounds.size.width) / 2.0 + 6.0
&& (center.y - other.label.center.y).abs()
< (size.height + other.label.bounds.size.height) / 2.0 + 6.0
{
// Same-side anchors on a self-loop can still be close. Separate
// their complete bounds along this end's normal in one step.
let perpendicular = pos(-direction.y, direction.x);
let distance = (center.x - other.label.center.x) * perpendicular.x
+ (center.y - other.label.center.y) * perpendicular.y;
let clearance = (perpendicular.x.abs() * (size.width + other.label.bounds.size.width)
+ perpendicular.y.abs() * (size.height + other.label.bounds.size.height))
/ 2.0
+ 8.0;
let shift = if distance < 0.0 {
-clearance - distance
} else {
clearance - distance
};
center.x += perpendicular.x * shift;
center.y += perpendicular.y * shift;
}
ends.push(AssociationEndGeometry {
source_end,
label: EdgeLabelGeometry {
text,
fraction: if source_end { 0.0 } else { 1.0 },
anchor: tip,
center,
bounds: RoutingBounds {
position: pos(center.x - size.width / 2.0, center.y - size.height / 2.0),
size,
},
},
tip,
inward,
navigable,
});
}
ends
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouteWarning {
PinInsideObstacle { pin: usize, obstacle: Id },
@@ -466,6 +582,14 @@ fn route_diagram_impl(
// never changes paths or authored metadata. Previews retain other cached
// labels and avoid the paths actually shown during the gesture.
let mut previous_labels = Vec::new();
for routed in edges.values() {
if let Some(relation) = project.relations.get(&routed.id) {
for end in association_end_geometry(relation, routed) {
bounds.rect(end.label.bounds.position, end.label.bounds.size);
previous_labels.push(end.label.bounds);
}
}
}
for edge in ordered {
let Some(routed) = edges.get_mut(&edge.id) else {
continue;
@@ -579,7 +703,7 @@ fn route_edge(
let mut candidates = Vec::new();
for a in endpoints(source, edge.source_port, view) {
for b in endpoints(target, edge.target_port, view) {
// A real self-transition must leave and return at distinct anchors.
// A real self-relation must leave and return at distinct anchors.
// Reusing one anchor makes the cheapest path a degenerate stub.
if edge.source == edge.target
&& edge.source_port.is_none()
@@ -1107,7 +1231,8 @@ fn label_text(project: &Project, edge: Id) -> String {
let text = match relation.kind() {
RelationKind::Interaction
| RelationKind::FunctionalExchange
| RelationKind::BoundaryExchange => relation.name.as_str(),
| RelationKind::BoundaryExchange
| RelationKind::DataAssociation => relation.name.as_str(),
RelationKind::CapabilityInclude => "«include»",
RelationKind::CapabilityExtend => "«extend»",
RelationKind::CapabilityGeneralization => "specializes",
+17
View File
@@ -114,6 +114,7 @@ pub struct PreparedCommand {
struct IdentityProvenance {
original: BTreeSet<Id>,
current_to_original: BTreeMap<Id, Id>,
explicit_replacement: bool,
}
impl IdentityProvenance {
@@ -123,10 +124,12 @@ impl IdentityProvenance {
Self {
original,
current_to_original,
explicit_replacement: false,
}
}
fn replace(&mut self, project: &Project) {
self.explicit_replacement = true;
let present: BTreeSet<_> = project.identities().into_iter().map(|(id, _)| id).collect();
self.current_to_original = self
.original
@@ -180,6 +183,13 @@ pub fn prepare_command(
)?;
crate::references::finish_deletions(&mut candidate, &pending_deletions);
provenance.retain_present(&candidate);
if !provenance.explicit_replacement {
crate::data::prune_removed_inheritance(
project,
&mut candidate,
&provenance.current_to_original,
);
}
validate_candidate(&candidate)?;
Ok(PreparedCommand {
project: candidate,
@@ -287,6 +297,13 @@ pub fn execute_batch(project: &Project, commands: &[Command]) -> Result<Project,
)?;
}
crate::references::finish_deletions(&mut candidate, &pending_deletions);
if !provenance.explicit_replacement {
crate::data::prune_removed_inheritance(
project,
&mut candidate,
&provenance.current_to_original,
);
}
validate_candidate(&candidate)?;
Ok(candidate)
}
+1 -1
View File
@@ -999,7 +999,7 @@ mod transaction_tests {
let directory = tempfile::tempdir().unwrap();
fs::write(
directory.path().join("project.arcadia"),
"arcadia 3; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
)
.unwrap();
fs::write(directory.path().join("a.arcadia"), "oa_activity a \"A\" {}").unwrap();
+52 -20
View File
@@ -1,9 +1,11 @@
//! Pure, bounded source3 projects. All includes resolve against supplied UTF-8
//! Pure, bounded source projects. All includes resolve against supplied UTF-8
//! documents; this module never reads a filesystem, URL, or process directory.
use crate::{Id, Kind, Project, language, persistence::DecodeResult, validation};
use language::{Diagnostic, ParseLimits, Span};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
#[path = "source_project/source_migration.rs"]
mod source_migration;
#[path = "source_project/source_structure.rs"]
mod source_structure;
@@ -278,21 +280,24 @@ pub fn lint_bundle(bundle: &SourceBundle, limits: ProjectLimits) -> Vec<SourceDi
}
}
/// Compile all reachable files as one source3 model and stabilize omitted UUIDs.
/// Compile reachable source3/4 files, explicitly upgrade data contracts, and stabilize UUIDs.
/// Missing/unreachable files and every admission or engineering error leave the
/// input untouched. V1/V2 single-file migration remains in `language::parse`.
pub fn compile_bundle(
bundle: &SourceBundle,
limits: ProjectLimits,
) -> Result<CompiledSourceProject, Vec<SourceDiagnostic>> {
let (compiled, insertions) = compile_once(bundle, limits)?;
if insertions.is_empty() {
return Ok(compiled);
let (mut compiled, insertions) = compile_once(bundle, limits)?;
if !insertions.is_empty() {
let mut stable = bundle.clone();
apply_edits(&mut stable, insertions)?;
// Re-index actual returned bytes before performing the schema upgrade.
compiled = compile_once(&stable, limits)?.0;
}
let mut stable = bundle.clone();
apply_edits(&mut stable, insertions)?;
// Re-index the actual returned bytes. Never expose offsets into pre-ID text.
compile_once(&stable, limits).map(|(compiled, _)| compiled)
if compiled.decoded.migration.is_some() {
return source_migration::upgrade(&compiled, limits);
}
Ok(compiled)
}
fn compile_once(
@@ -568,7 +573,7 @@ fn compile_once(
span,
}),
};
let project =
let decoded =
language::resolve_declarations(header.project, &declarations, &aliases, limits.model)
.map_err(|(index, error)| {
let path = declaration_paths.get(index).unwrap_or(&bundle.entry);
@@ -578,7 +583,7 @@ fn compile_once(
related: Vec::new(),
}]
})?;
let diagnostics = model_diagnostics(bundle, &index, &project);
let diagnostics = model_diagnostics(bundle, &index, &decoded.project);
let errors: Vec<_> = diagnostics
.iter()
.filter(|issue| issue.diagnostic.severity == validation::Severity::Error)
@@ -590,10 +595,7 @@ fn compile_once(
Ok((
CompiledSourceProject {
bundle: bundle.clone(),
decoded: DecodeResult {
project,
migration: None,
},
decoded,
index,
diagnostics,
},
@@ -718,7 +720,7 @@ fn apply_edits(bundle: &mut SourceBundle, edits: Edits) -> Result<(), Vec<Source
Ok(())
}
/// Canonical, readable source3 export. Like `language::format`, the caller is
/// Canonical, readable source4 export. Like `language::format`, the caller is
/// responsible for supplying a valid model; compilation checks the result.
/// Existing source layout is preserved by `update_bundle`, not this formatter.
pub fn format_bundle(project: &Project) -> SourceBundle {
@@ -734,7 +736,7 @@ pub fn format_bundle(project: &Project) -> SourceBundle {
.push_str(&unindent(&declaration));
}
let mut entry = format!(
"arcadia 3;\n{}{{\n description {};\n",
"arcadia 4;\n{}{{\n description {};\n",
project_header(project),
quote(&project.description)
);
@@ -923,6 +925,7 @@ pub fn update_bundle_with_identity_map(
after: new_text,
old_aliases: &old_aliases,
new_aliases: &new_aliases,
legacy_value_paths: false,
};
let local = edits.entry(path.clone()).or_default();
update.header(&actual.header, &previous.header, &next.header, local);
@@ -951,6 +954,7 @@ pub fn update_bundle_with_identity_map(
after: &after,
old_aliases: &old_aliases,
new_aliases: &new_aliases,
legacy_value_paths: false,
};
let mut local = Vec::new();
update.header(
@@ -1119,6 +1123,9 @@ struct SyntaxUpdate<'a> {
after: &'a str,
old_aliases: &'a BTreeMap<String, String>,
new_aliases: &'a BTreeMap<String, String>,
// Source3 migration only adds path qualification; the existing field identity
// must keep its authored argument trivia during that one-time transformation.
legacy_value_paths: bool,
}
impl SyntaxUpdate<'_> {
fn header(
@@ -1338,11 +1345,11 @@ impl SyntaxUpdate<'_> {
let previous = before.unwrap_or(&[]);
let old_keys: Option<Vec<_>> = previous
.iter()
.map(|item| item_key(item, self.before, self.old_aliases))
.map(|item| item_key(item, self.before, self.old_aliases, self.legacy_value_paths))
.collect();
let new_keys: Option<Vec<_>> = after
.iter()
.map(|item| item_key(item, self.after, self.new_aliases))
.map(|item| item_key(item, self.after, self.new_aliases, self.legacy_value_paths))
.collect();
let keyed = old_keys.zip(new_keys).filter(|(old, new)| {
old.iter().collect::<BTreeSet<_>>().len() == old.len()
@@ -1449,6 +1456,7 @@ fn item_key(
value: &language::EditValue,
source: &str,
aliases: &BTreeMap<String, String>,
legacy_value_paths: bool,
) -> Option<String> {
use language::EditKind;
match &value.kind {
@@ -1462,7 +1470,31 @@ fn item_key(
.find_map(|key| {
fields.get(key).and_then(|field| {
if let EditKind::Reference(alias) = &field.value.kind {
aliases.get(alias).map(|id| format!("{key}:{id}"))
aliases.get(alias).map(|id| {
if key == "field" && !legacy_value_paths {
let path = fields
.get("path")
.and_then(|field| {
if let EditKind::List(path) = &field.value.kind {
path.iter()
.map(|hop| {
if let EditKind::Reference(alias) = &hop.kind {
aliases.get(alias).cloned()
} else {
None
}
})
.collect::<Option<Vec<_>>>()
} else {
None
}
})
.unwrap_or_default();
format!("field:{}:{id}", path.join("/"))
} else {
format!("{key}:{id}")
}
})
} else {
None
}
@@ -0,0 +1,125 @@
//! Source3 data upgrade through token edits; authored modules, nesting and trivia survive.
use super::*;
pub(super) fn upgrade(
current: &CompiledSourceProject,
limits: ProjectLimits,
) -> Result<CompiledSourceProject, Vec<SourceDiagnostic>> {
let report = current
.decoded
.migration
.as_ref()
.expect("an explicit source migration report");
let project = &current.decoded.project;
let canonical: BTreeMap<_, _> = language::format_declarations(project).into_iter().collect();
let changed: BTreeSet<_> = report
.semantic_defaults
.iter()
.map(|default| default.object)
.collect();
let aliases: BTreeMap<_, _> = project
.identities()
.into_iter()
.map(|(id, alias)| (alias.to_owned(), id.to_string()))
.collect();
let mut edits: Edits = BTreeMap::new();
for (path, source) in &current.bundle.files {
let declarations =
language::edit_declarations(source, path == &current.bundle.entry, limits.model)
.map_err(|diagnostic| {
vec![SourceDiagnostic {
path: path.clone(),
diagnostic: *diagnostic,
related: vec![],
}]
})?;
for (id, actual) in declarations {
if !changed.contains(&id) {
continue;
}
let Some(after) = canonical.get(&id) else {
continue;
};
let mut next = language::edit_declaration(after).map_err(|diagnostic| {
vec![SourceDiagnostic {
path: path.clone(),
diagnostic: *diagnostic,
related: vec![],
}]
})?;
if actual.lexical_owner.is_some()
&& let language::EditKind::Record(fields) = &actual.fields.kind
&& !fields.contains_key("parent")
&& let language::EditKind::Record(fields) = &mut next.fields.kind
{
fields.remove("parent");
}
let update = SyntaxUpdate {
source,
before: source,
after,
old_aliases: &aliases,
new_aliases: &aliases,
legacy_value_paths: true,
};
update.value(
&actual.fields,
Some(&actual.fields),
&next.fields,
edits.entry(path.clone()).or_default(),
);
}
}
let source = &current.bundle.files[&current.bundle.entry];
let version = significant(source)
.get(1)
.map(|token| token.span)
.expect("a parsed version token");
edits
.entry(current.bundle.entry.clone())
.or_default()
.push((version, "4".into()));
// New allocation relations are emitted into the allocating interface's
// existing module, outside its lexical element body. Existing source never moves.
let mut added: BTreeMap<String, String> = BTreeMap::new();
for allocation in &report.generated_interface_allocations {
let path = current
.index
.declarations
.get(&allocation.source)
.map(|location| location.path.clone())
.unwrap_or_else(|| current.bundle.entry.clone());
let ending = newline(&current.bundle.files[&path]);
let text = added.entry(path).or_default();
text.push_str(ending);
text.push_str(&canonical[&allocation.id].replace('\n', ending));
}
for (path, text) in added {
let offset = if path == current.bundle.entry {
current.index.project_body.span.end
} else {
current.bundle.files[&path].len()
};
edits.entry(path).or_default().push((
Span {
start: offset,
end: offset,
},
text,
));
}
let mut bundle = current.bundle.clone();
apply_edits(&mut bundle, edits)?;
let (mut result, insertions) = compile_once(&bundle, limits)?;
if !insertions.is_empty() || result.decoded.project != *project {
return Err(vec![problem(
&bundle,
&bundle.entry,
Span::default(),
"migration_source_mismatch",
"Targeted source3 upgrade did not reproduce the migrated project.",
)]);
}
result.decoded.migration = Some(report.clone());
Ok(result)
}
+20
View File
@@ -251,6 +251,8 @@ fn mapped_relation(r: &Relation, direction: TransitionDirection) -> Option<Relat
}
(
RelationBody::Allocation { .. }
| RelationBody::InterfaceItemAllocation { .. }
| RelationBody::DataAssociation { .. }
| RelationBody::ExchangeAllocation { .. }
| RelationBody::CapabilityInvolvement { .. }
| RelationBody::CapabilityInclude { .. }
@@ -421,6 +423,24 @@ pub fn plan_transition(
}
if let Some(e) = project.elements.get(&id) {
selected.extend(crate::references::element_references(e));
// Allocations are owned by interfaces. Independent data
// associations travel only when both endpoint types are
// already required; they do not expand the dictionary.
if matches!(e.kind(), Kind::Interface | Kind::DataType) {
let contracts: Vec<_> = project
.relations
.values()
.filter_map(|r| {
((r.kind() == RelationKind::InterfaceItemAllocation
&& r.source() == id)
|| (r.kind() == RelationKind::DataAssociation
&& selected.contains(&r.source())
&& selected.contains(&r.target())))
.then_some(r.id)
})
.collect();
selected.extend(contracts);
}
// Contextual links are owned by the process/chain shared by
// their endpoint involvements, independently of list order.
if matches!(e.kind(), Kind::Process | Kind::FunctionalChain) {
+120 -94
View File
@@ -388,68 +388,10 @@ pub fn validate(p: &Project) -> Vec<Issue> {
}
if let Some(shared) = e.shared() {
match shared {
SharedBody::DataType {
definition: DataTypeDefinition::Enumeration { literals },
} => {
let mut seen = BTreeSet::new();
for literal in literals {
text(&mut out, e.id, "literals", literal);
if !seen.insert(literal) {
error(
&mut out,
e.id,
"duplicate_literal",
"literals",
"Enumeration literals must be unique.",
);
}
}
}
SharedBody::DataField {
type_ref,
minimum,
maximum,
unit,
} => {
if maximum.is_some_and(|max| max < *minimum) {
error(
&mut out,
e.id,
"invalid_multiplicity",
"maximum",
"Maximum multiplicity must be at least minimum, or unbounded.",
);
}
text(&mut out, e.id, "unit", unit);
if let TypeRef::Named(id) = type_ref {
expect_element(p, &mut out, e.id, *id, "type_ref", |k| k == Kind::DataType);
}
if let Some(parent) = e.parent.and_then(|id| p.elements.get(&id))
&& parent.kind() == Kind::DataType
&& !matches!(
parent.shared(),
Some(SharedBody::DataType {
definition: DataTypeDefinition::Record
})
)
{
error(
&mut out,
e.id,
"field_owner",
"parent",
"Fields under a data type require a Record type.",
);
}
}
SharedBody::Interface { items } => {
check_ids(&mut out, e.id, "items", items);
for id in items {
expect_element(p, &mut out, e.id, *id, "items", |k| {
k == Kind::ExchangeItem
});
}
}
SharedBody::DataType { .. }
| SharedBody::DataField { .. }
| SharedBody::Interface { .. }
| SharedBody::ExchangeItem { .. } => crate::data::validate_element(p, e, &mut out),
SharedBody::Port { .. } => crate::ports::validate_port(p, e, &mut out),
SharedBody::Scenario {
viewpoint,
@@ -643,9 +585,11 @@ pub fn validate(p: &Project) -> Vec<Issue> {
text(&mut out, r.id, "name", &r.name);
text(&mut out, r.id, "description", &r.description);
validate_relation(p, r, &mut out);
crate::data::validate_relation(p, r, &mut out);
crate::ports::validate_boundary_interface_requirements(p, r, &mut out);
validate_relation_context(p, r, &mut out);
}
crate::data::validate_record_cycles(p, &mut out);
for (key, d) in &p.diagrams {
if *key != d.id {
error(
@@ -1436,23 +1380,10 @@ fn enclosing_loops(p: &Project, occurrence: Id) -> BTreeSet<Id> {
}
/// Fields carried by an exchange, including fields of nested named records.
pub fn carried_fields(p: &Project, relation: &Relation) -> BTreeSet<Id> {
let mut pending = relation.body.items().to_vec();
let mut seen = BTreeSet::new();
let mut fields = BTreeSet::new();
while let Some(owner) = pending.pop() {
if !seen.insert(owner) {
continue;
}
for field in p.children(owner) {
if let Some(SharedBody::DataField { type_ref, .. }) = field.shared() {
fields.insert(field.id);
if let TypeRef::Named(id) = type_ref {
pending.push(*id);
}
}
}
}
fields
crate::data::carried_field_paths(p, relation)
.into_iter()
.map(|f| f.field)
.collect()
}
fn occurrence_uses_lifeline(body: &OccurrenceBody, line: Id) -> bool {
match body {
@@ -1683,36 +1614,125 @@ fn validate_message(p: &Project, e: &Element, body: &OccurrenceBody, out: &mut V
}
}
}
let allowed = exchange
.and_then(|id| p.relations.get(&id))
.map(|r| carried_fields(p, r));
let relation = exchange.and_then(|id| p.relations.get(&id));
if message_kind == &MessageKind::Call
&& relation.is_some_and(|r| {
!r.body
.items()
.iter()
.any(|id| crate::data::item_mechanism(p, *id) == Some(ExchangeMechanism::Operation))
})
{
warning(
out,
e.id,
"call_without_operation",
"exchange",
"This generic call carries no Operation item; define an operation contract when appropriate.",
);
}
let mut fields = BTreeSet::new();
for value in values {
expect_element(p, out, e.id, value.field, "values.field", |kind| {
kind == Kind::DataField
});
for hop in &value.path {
expect_element(p, out, e.id, *hop, "values.path", |kind| {
kind == Kind::DataField
});
}
text(out, e.id, "values.expression", &value.expression);
if !fields.insert(value.field) {
if !fields.insert((&value.path, value.field)) {
error(
out,
e.id,
"duplicate_message_value",
"values",
"Each carried field has at most one contextual value annotation in a message.",
"Each qualified carried field has at most one contextual value annotation.",
);
}
if allowed
.as_ref()
.is_some_and(|allowed| !allowed.contains(&value.field))
{
if value.path.len() > crate::data::MAX_VALUE_PATH_DEPTH {
error(
out,
e.id,
"message_value_field",
"values.field",
"Value annotations must reference fields carried by this message's exchange, including nested record fields.",
"message_value_path_limit",
"values.path",
"The value path exceeds the bounded authoring depth.",
);
}
if let Some(r) = relation {
if let Some(path) = crate::data::carried_value_path(p, r, &value.path, value.field) {
if crate::data::item_mechanism(p, path.item) == Some(ExchangeMechanism::Operation) {
let permitted = match message_kind {
MessageKind::Call => matches!(
path.direction,
ParameterDirection::Unspecified
| ParameterDirection::In
| ParameterDirection::InOut
),
MessageKind::Reply => matches!(
path.direction,
ParameterDirection::Unspecified
| ParameterDirection::Out
| ParameterDirection::InOut
| ParameterDirection::Return
),
_ => true,
};
if !permitted {
error(
out,
e.id,
"message_parameter_phase",
"values.path",
"Call values address In/InOut parameters; replies address Out/InOut/Return parameters.",
);
}
if path.direction == ParameterDirection::Unspecified {
warning(
out,
e.id,
"message_parameter_direction",
"values.path",
"The containing operation parameter has no direction yet.",
);
}
}
} else {
let legacy = value
.path
.is_empty()
.then(|| crate::data::resolve_legacy_field_path(p, r, value.field).ok())
.flatten();
if matches!(
legacy,
Some(
crate::data::LegacyFieldPathResolution::Unique(_)
| crate::data::LegacyFieldPathResolution::Ambiguous
)
) {
warning(
out,
e.id,
if legacy == Some(crate::data::LegacyFieldPathResolution::Ambiguous) {
"message_value_ambiguous_path"
} else {
"message_value_missing_path"
},
"values.path",
"This legacy nested field annotation needs an explicit containing parameter path; its expression is preserved.",
);
} else {
error(
out,
e.id,
"message_value_field",
"values.path",
"The qualified field must be carried by the exchange, following Value record fields only.",
);
}
}
}
if value.expression.trim().is_empty() {
warning(
out,
@@ -2130,7 +2150,11 @@ fn validate_relation(p: &Project, r: &Relation, out: &mut Vec<Issue>) {
};
if a.layer() != b.layer()
|| !r.kind().permits(a.kind(), b.kind())
|| (a.id == b.id && r.kind() != RelationKind::StateTransition)
|| (a.id == b.id
&& !matches!(
r.kind(),
RelationKind::StateTransition | RelationKind::DataAssociation
))
{
error(
out,
@@ -2381,8 +2405,10 @@ pub fn can_parent(p: &Project, child_kind: Kind, layer: Layer, parent: Option<Id
owner.layer() == layer
&& parent_permits(owner.kind(), child_kind)
&& match owner.shared() {
Some(SharedBody::DataType { definition }) if child_kind == Kind::DataField => {
*definition == DataTypeDefinition::Record
Some(SharedBody::DataType { definition, .. })
if child_kind == Kind::DataField =>
{
matches!(definition, DataTypeDefinition::Record { .. })
}
Some(SharedBody::Occurrence { body, .. }) if child_kind == Kind::Occurrence => {
matches!(
+38
View File
@@ -0,0 +1,38 @@
// Frozen authored schema3 compatibility input. Do not rewrite as current syntax.
arcadia 3;
project legacy_data "Legacy data contract" id "00000000-0000-0000-0000-000000000001" {
sa_function produce "Produce" id "00000000-0000-0000-0000-000000000002" {}
sa_function consume "Consume" id "00000000-0000-0000-0000-000000000003" {}
sa_exchange_item packet "Position event" id "00000000-0000-0000-0000-000000000004" {
kind Event;
// Reused record parameters retain their own identities.
sa_data_field origin "Origin" id "00000000-0000-0000-0000-000000000007" { type_ref { Named @coordinate; }; }
sa_data_field destination "Destination" id "00000000-0000-0000-0000-000000000008" { type_ref { Named @coordinate; }; }
}
sa_data_type coordinate "Coordinate" id "00000000-0000-0000-0000-000000000005" {
definition Record;
sa_data_field latitude "Latitude" id "00000000-0000-0000-0000-000000000006" { type_ref Real; unit "deg"; }
}
sa_interface sender_contract "Sender contract" id "00000000-0000-0000-0000-000000000009" { items [@packet]; }
sa_interface receiver_contract "Receiver contract" id "00000000-0000-0000-0000-00000000000a" { items [@packet]; }
sa_port output "Output" id "00000000-0000-0000-0000-00000000000b" {
parent @produce; contract { FunctionOutput { outgoing_items [@packet]; }; }; legacy none;
}
sa_port input "Input" id "00000000-0000-0000-0000-00000000000c" {
parent @consume; contract { FunctionInput { incoming_items [@packet]; }; }; legacy none;
}
functional_exchange position_exchange "Position exchange" id "00000000-0000-0000-0000-00000000000d" {
source @produce; target @consume; source_port @output; target_port @input; items [@packet];
}
sa_scenario scenario "Position scenario" id "00000000-0000-0000-0000-00000000000e" {
viewpoint Functional; steps [@message];
sa_lifeline sender "Sender" id "00000000-0000-0000-0000-00000000000f" { represented @produce; }
sa_lifeline receiver "Receiver" id "00000000-0000-0000-0000-000000000010" { represented @consume; }
sa_occurrence message "Position" id "00000000-0000-0000-0000-000000000011" {
body { Exchange {
exchange @position_exchange; sender @sender; receiver @receiver;
values [{ field @latitude; expression "navigation.latitude"; }];
}; };
}
}
}
+312
View File
@@ -0,0 +1,312 @@
{
"schema_version": 3,
"id": "00000000-0000-0000-0000-000000000001",
"alias": "legacy_data",
"name": "Legacy data contract",
"description": "",
"elements": {
"00000000-0000-0000-0000-000000000002": {
"id": "00000000-0000-0000-0000-000000000002",
"alias": "produce",
"name": "Produce",
"description": "",
"parent": null,
"body": {
"Sa": "Function"
}
},
"00000000-0000-0000-0000-000000000003": {
"id": "00000000-0000-0000-0000-000000000003",
"alias": "consume",
"name": "Consume",
"description": "",
"parent": null,
"body": {
"Sa": "Function"
}
},
"00000000-0000-0000-0000-000000000004": {
"id": "00000000-0000-0000-0000-000000000004",
"alias": "packet",
"name": "Position event",
"description": "",
"parent": null,
"body": {
"Sa": {
"Shared": {
"ExchangeItem": {
"kind": "Event"
}
}
}
}
},
"00000000-0000-0000-0000-000000000005": {
"id": "00000000-0000-0000-0000-000000000005",
"alias": "coordinate",
"name": "Coordinate",
"description": "",
"parent": null,
"body": {
"Sa": {
"Shared": {
"DataType": {
"definition": "Record"
}
}
}
}
},
"00000000-0000-0000-0000-000000000006": {
"id": "00000000-0000-0000-0000-000000000006",
"alias": "latitude",
"name": "Latitude",
"description": "",
"parent": "00000000-0000-0000-0000-000000000005",
"body": {
"Sa": {
"Shared": {
"DataField": {
"type_ref": "Real",
"minimum": 1,
"maximum": 1,
"unit": "deg"
}
}
}
}
},
"00000000-0000-0000-0000-000000000007": {
"id": "00000000-0000-0000-0000-000000000007",
"alias": "origin",
"name": "Origin",
"description": "",
"parent": "00000000-0000-0000-0000-000000000004",
"body": {
"Sa": {
"Shared": {
"DataField": {
"type_ref": {
"Named": "00000000-0000-0000-0000-000000000005"
},
"minimum": 1,
"maximum": 1,
"unit": ""
}
}
}
}
},
"00000000-0000-0000-0000-000000000008": {
"id": "00000000-0000-0000-0000-000000000008",
"alias": "destination",
"name": "Destination",
"description": "",
"parent": "00000000-0000-0000-0000-000000000004",
"body": {
"Sa": {
"Shared": {
"DataField": {
"type_ref": {
"Named": "00000000-0000-0000-0000-000000000005"
},
"minimum": 1,
"maximum": 1,
"unit": ""
}
}
}
}
},
"00000000-0000-0000-0000-000000000009": {
"id": "00000000-0000-0000-0000-000000000009",
"alias": "sender_contract",
"name": "Sender contract",
"description": "",
"parent": null,
"body": {
"Sa": {
"Shared": {
"Interface": {
"items": [
"00000000-0000-0000-0000-000000000004"
]
}
}
}
}
},
"00000000-0000-0000-0000-00000000000a": {
"id": "00000000-0000-0000-0000-00000000000a",
"alias": "receiver_contract",
"name": "Receiver contract",
"description": "",
"parent": null,
"body": {
"Sa": {
"Shared": {
"Interface": {
"items": [
"00000000-0000-0000-0000-000000000004"
]
}
}
}
}
},
"00000000-0000-0000-0000-00000000000b": {
"id": "00000000-0000-0000-0000-00000000000b",
"alias": "output",
"name": "Output",
"description": "",
"parent": "00000000-0000-0000-0000-000000000002",
"body": {
"Sa": {
"Shared": {
"Port": {
"contract": {
"FunctionOutput": {
"outgoing_items": [
"00000000-0000-0000-0000-000000000004"
]
}
},
"legacy": null
}
}
}
}
},
"00000000-0000-0000-0000-00000000000c": {
"id": "00000000-0000-0000-0000-00000000000c",
"alias": "input",
"name": "Input",
"description": "",
"parent": "00000000-0000-0000-0000-000000000003",
"body": {
"Sa": {
"Shared": {
"Port": {
"contract": {
"FunctionInput": {
"incoming_items": [
"00000000-0000-0000-0000-000000000004"
]
}
},
"legacy": null
}
}
}
}
},
"00000000-0000-0000-0000-00000000000e": {
"id": "00000000-0000-0000-0000-00000000000e",
"alias": "scenario",
"name": "Position scenario",
"description": "",
"parent": null,
"body": {
"Sa": {
"Shared": {
"Scenario": {
"viewpoint": "Functional",
"context": null,
"precondition": "",
"postcondition": "",
"steps": [
"00000000-0000-0000-0000-000000000011"
]
}
}
}
}
},
"00000000-0000-0000-0000-00000000000f": {
"id": "00000000-0000-0000-0000-00000000000f",
"alias": "sender",
"name": "Sender",
"description": "",
"parent": "00000000-0000-0000-0000-00000000000e",
"body": {
"Sa": {
"Shared": {
"Lifeline": {
"represented": "00000000-0000-0000-0000-000000000002"
}
}
}
}
},
"00000000-0000-0000-0000-000000000010": {
"id": "00000000-0000-0000-0000-000000000010",
"alias": "receiver",
"name": "Receiver",
"description": "",
"parent": "00000000-0000-0000-0000-00000000000e",
"body": {
"Sa": {
"Shared": {
"Lifeline": {
"represented": "00000000-0000-0000-0000-000000000003"
}
}
}
}
},
"00000000-0000-0000-0000-000000000011": {
"id": "00000000-0000-0000-0000-000000000011",
"alias": "message",
"name": "Position",
"description": "",
"parent": "00000000-0000-0000-0000-00000000000e",
"body": {
"Sa": {
"Shared": {
"Occurrence": {
"body": {
"Exchange": {
"exchange": "00000000-0000-0000-0000-00000000000d",
"sender": "00000000-0000-0000-0000-00000000000f",
"receiver": "00000000-0000-0000-0000-000000000010",
"message_kind": "Asynchronous",
"reply_to": null,
"values": [
{
"field": "00000000-0000-0000-0000-000000000006",
"expression": "navigation.latitude"
}
]
}
},
"precondition": "",
"postcondition": ""
}
}
}
}
}
},
"relations": {
"00000000-0000-0000-0000-00000000000d": {
"id": "00000000-0000-0000-0000-00000000000d",
"alias": "position_exchange",
"name": "Position exchange",
"description": "",
"body": {
"FunctionalExchange": {
"source": "00000000-0000-0000-0000-000000000002",
"target": "00000000-0000-0000-0000-000000000003",
"source_port": "00000000-0000-0000-0000-00000000000b",
"target_port": "00000000-0000-0000-0000-00000000000c",
"items": [
"00000000-0000-0000-0000-000000000004"
]
}
}
}
},
"diagrams": {},
"artifact_links": {},
"traces": {}
}
+102 -9
View File
@@ -168,6 +168,20 @@ project mission "Harbor safety — 港 🌊" {
.find(|e| e.alias == "event_record")
.unwrap()
.id;
let associated = p
.add_element(Kind::DataType, Layer::Sa, "Associated record", None)
.unwrap();
if let Some(SharedBody::DataType { definition, .. }) =
p.elements.get_mut(&associated).unwrap().shared_mut()
{
*definition = DataTypeDefinition::Record { supertype: None };
}
p.relate(
RelationKind::DataAssociation,
"Related record",
record,
associated,
);
for (index, type_ref) in [
TypeRef::Boolean,
TypeRef::Integer,
@@ -190,18 +204,30 @@ project mission "Harbor safety — 港 🌊" {
minimum: 1,
maximum: Some(5),
unit: "unit".into(),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
default: None,
};
}
for definition in [
DataTypeDefinition::Boolean,
DataTypeDefinition::Integer,
DataTypeDefinition::String,
DataTypeDefinition::Integer {
minimum: None,
maximum: None,
},
DataTypeDefinition::String {
minimum_length: 0,
maximum_length: None,
},
] {
let id = p
.add_element(Kind::DataType, Layer::Sa, "Primitive type", None)
.unwrap();
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() =
SharedBody::DataType { definition };
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::DataType {
definition,
default: None,
unit: String::new(),
};
}
for kind in [
ExchangeItemKind::Material,
@@ -216,7 +242,11 @@ project mission "Harbor safety — 港 🌊" {
None,
)
.unwrap();
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem { kind };
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem {
kind,
mechanism: ExchangeMechanism::Unspecified,
supertype: None,
};
}
let scenario = p
.elements
@@ -461,7 +491,7 @@ fn authoring_defaults_and_forward_references_remain_strict() {
#[test]
fn typed_unknown_fields_enums_duplicates_and_reference_spelling_are_rejected() {
for (source, expected) in [
("arcadia 4; project mission \"x\" {}", "Unsupported schema"),
("arcadia 5; project mission \"x\" {}", "Unsupported schema"),
(
"arcadia 2; project mission \"x\" { oa_activity a \"A\" { nonsense 1; } }",
"Unknown field",
@@ -765,9 +795,27 @@ fn original_v2_text_and_json_preserve_identity_and_mixed_scenarios_after_extensi
assert_eq!(from_source, from_json);
let original: serde_json::Value = serde_json::from_slice(old_json).unwrap();
let mut retained = serde_json::to_value(&from_json).unwrap();
assert_eq!(retained["schema_version"], 3);
assert_eq!(retained["schema_version"], 4);
retained["schema_version"] = 2.into();
let allocations: Vec<_> = from_json
.relations
.values()
.filter_map(|relation| {
if let RelationBody::InterfaceItemAllocation {
source,
target,
order,
..
} = relation.body
{
Some((source, target, order))
} else {
None
}
})
.collect();
for element in retained["elements"].as_object_mut().unwrap().values_mut() {
let element_id: Id = element["id"].as_str().unwrap().parse().unwrap();
for layer in ["Oa", "Sa"] {
let Some(shared) = element["body"]
.get_mut(layer)
@@ -779,6 +827,46 @@ fn original_v2_text_and_json_preserve_identity_and_mixed_scenarios_after_extensi
assert_eq!(port["contract"], "Legacy");
*port = port["legacy"].clone();
}
if let Some(item) = shared
.get_mut("ExchangeItem")
.and_then(serde_json::Value::as_object_mut)
{
if item["mechanism"] == "Event" {
item.insert("kind".into(), "Event".into());
}
item.remove("mechanism");
item.remove("supertype");
}
if let Some(kind) = shared
.get_mut("DataType")
.and_then(serde_json::Value::as_object_mut)
{
kind.remove("default");
kind.remove("unit");
let definition = &kind["definition"];
if let Some(name) = ["Integer", "Real", "String", "Record"]
.into_iter()
.find(|name| definition.get(name).is_some())
{
kind.insert("definition".into(), name.into());
}
}
if let Some(field) = shared
.get_mut("DataField")
.and_then(serde_json::Value::as_object_mut)
{
for key in ["direction", "storage", "default"] {
field.remove(key);
}
}
if let Some(interface) = shared.get_mut("Interface") {
let mut entries: Vec<_> = allocations
.iter()
.filter(|(source, _, _)| *source == element_id)
.collect();
entries.sort_by_key(|(_, _, order)| *order);
*interface = serde_json::json!({"items":entries.into_iter().map(|(_,target,_)|target).collect::<Vec<_>>()});
}
if let Some(scenario) = shared
.get_mut("Scenario")
.and_then(serde_json::Value::as_object_mut)
@@ -797,6 +885,10 @@ fn original_v2_text_and_json_preserve_identity_and_mixed_scenarios_after_extensi
}
}
}
retained["relations"]
.as_object_mut()
.unwrap()
.retain(|_, relation| relation["body"].get("InterfaceItemAllocation").is_none());
for relation in retained["relations"].as_object_mut().unwrap().values_mut() {
if let Some(boundary) = relation["body"].get_mut("BoundaryExchange") {
assert_eq!(boundary["oriented"], true);
@@ -826,7 +918,7 @@ fn original_v2_text_and_json_preserve_identity_and_mixed_scenarios_after_extensi
);
assert_eq!(
from_json.relations.len(),
original["relations"].as_object().unwrap().len()
original["relations"].as_object().unwrap().len() + allocations.len()
);
assert_eq!(
from_json.diagrams.len(),
@@ -899,7 +991,7 @@ fn v1_text_and_json_migrate_deterministically_without_losing_legacy_semantics()
assert_eq!(from_text, from_json);
assert_eq!(read(text), from_text);
assert_eq!(persistence::decode(json).unwrap(), from_json);
assert_eq!(from_text.schema_version, 3);
assert_eq!(from_text.schema_version, 4);
assert!(!from_text.elements.values().any(|e| e.layer() == Layer::Sa));
let raw: serde_json::Value = serde_json::from_slice(json).unwrap();
for (id, record) in raw["elements"].as_object().unwrap() {
@@ -1100,6 +1192,7 @@ fn complete_normative_examples_are_accepted_by_the_real_parser() {
}
if code.trim_start().starts_with("arcadia 2;")
|| code.trim_start().starts_with("arcadia 3;")
|| code.trim_start().starts_with("arcadia 4;")
{
read(&code);
examples += 1;
+12 -5
View File
@@ -39,7 +39,7 @@ fn frozen_original_v2_reader_preserves_every_original_record() {
assert_eq!(decoded.project, from_source.project);
assert_eq!(decoded.migration, from_source.migration);
let report = decoded.migration.unwrap();
assert_eq!((report.from_schema, report.to_schema), (2, 3));
assert_eq!((report.from_schema, report.to_schema), (2, 4));
assert_eq!(report.preserved_ports.len(), 4);
assert!(report.generated_endpoints.is_empty());
assert_eq!(report.orientation_defaults.len(), 1);
@@ -56,6 +56,7 @@ fn frozen_original_v2_reader_preserves_every_original_record() {
+ old["traces"].as_object().unwrap().len()
+ old["artifact_links"].as_object().unwrap().len()
+ 1
+ report.generated_interface_allocations.len()
);
let mut current = serde_json::to_value(&decoded.project).unwrap();
for diagram in current["diagrams"].as_object_mut().unwrap().values_mut() {
@@ -143,7 +144,7 @@ fn missing_v2_endpoints_are_deterministic_reported_and_independently_typed() {
}
}
let canonical = language::format(&first.project);
assert!(canonical.starts_with("arcadia 3;"));
assert!(canonical.starts_with("arcadia 4;"));
let reopened = persistence::decode_with_report(canonical.as_bytes()).unwrap();
assert!(reopened.migration.is_none());
assert_eq!(reopened.project, first.project);
@@ -223,7 +224,13 @@ fn migration_admission_counts_generated_objects_records_and_references() {
_ => 0,
})
})
.sum::<usize>();
.sum::<usize>()
+ decode(&old)
.migration
.unwrap()
.generated_interface_allocations
.len()
* 2;
for limits in [
ParseLimits {
max_graph_objects: graph + 1,
@@ -244,7 +251,7 @@ fn migration_admission_counts_generated_objects_records_and_references() {
));
}
let accepted = ParseLimits {
max_graph_objects: graph + 2,
max_graph_objects: migrated.elements.len() + migrated.relations.len(),
max_records: records,
max_step_references: reference_count,
..ParseLimits::UNLIMITED
@@ -267,7 +274,7 @@ fn old_contract_is_validated_before_new_shapes_and_v1_flows_through_v2() {
assert!(error.contains("V2") && error.contains(&fe), "{error}");
let v1 = include_bytes!("../../../examples/legacy-v1-coastal-rescue.oa.json");
let result = persistence::decode_with_report(v1).unwrap();
assert_eq!(result.project.schema_version, 3);
assert_eq!(result.project.schema_version, 4);
assert_eq!(result.migration.unwrap().from_schema, 1);
assert_eq!(persistence::decode(v1).unwrap(), result.project);
}
+6 -5
View File
@@ -1,6 +1,6 @@
use oa_core::{language, persistence, *};
const SOURCE: &str = r#"arcadia 3;
const SOURCE: &str = r#"arcadia 4;
project typed_ports "Typed ports" {
sa_system producer "Producer" {}
sa_actor consumer "Consumer" {}
@@ -9,7 +9,8 @@ project typed_ports "Typed ports" {
allocation sends "Produces" { source @producer; target @send; }
allocation receives "Consumes" { source @consumer; target @receive; }
sa_exchange_item data "Data" {}
sa_interface service "Service" { items [@data]; }
sa_interface service "Service" {}
interface_item_allocation service_data "Service data" { source @service; target @data; }
sa_port output "Output" { parent @send; contract { FunctionOutput { outgoing_items [@data]; }; }; }
sa_port input "Input" { parent @receive; contract { FunctionInput { incoming_items [@data]; }; }; }
sa_port provider "Provider port" { parent @producer; contract { Component { kind Standard; orientation Unset; }; }; }
@@ -26,7 +27,7 @@ project typed_ports "Typed ports" {
"#;
#[test]
fn source3_covers_typed_contracts_roles_allocations_and_nested_legacy_references() {
fn source4_covers_typed_contracts_roles_allocations_and_nested_legacy_references() {
let decoded = language::parse_with_report(SOURCE).unwrap();
assert!(decoded.migration.is_none());
let canonical = language::format(&decoded.project);
@@ -69,7 +70,7 @@ fn source3_covers_typed_contracts_roles_allocations_and_nested_legacy_references
}
#[test]
fn source3_requires_explicit_port_contract_and_fe_endpoints_without_generation() {
fn source4_requires_explicit_port_contract_and_fe_endpoints_without_generation() {
for (remove, expected) in [
("source_port @output; ", "source_port"),
("target_port @input; ", "target_port"),
@@ -90,7 +91,7 @@ fn source3_requires_explicit_port_contract_and_fe_endpoints_without_generation()
}
#[test]
fn source3_rejects_mixed_component_kinds_and_nested_reference_typos() {
fn source4_rejects_mixed_component_kinds_and_nested_reference_typos() {
let mixed = SOURCE.replace(
"parent @consumer; contract { Component { kind Standard; orientation Unset;",
"parent @consumer; contract { Component { kind Flow; orientation Unset;",
File diff suppressed because it is too large Load Diff
+228
View File
@@ -0,0 +1,228 @@
use oa_core::{language, persistence, *};
use serde_json::{Value, json};
const SOURCE3: &str = include_str!("fixtures/v3-data-contract.arcadia");
fn id(n: u128) -> Id {
Id::from_u128(n)
}
// Frozen JSON uses the same authored schema3 contract as the source fixture;
// this helper never serializes current defaults under version3.
fn original3() -> Value {
serde_json::from_str(include_str!("fixtures/v3-data-contract.json")).unwrap()
}
#[test]
fn genuine_v3_preserves_typed_ports_and_allocates_deterministic_relationships() {
let old = original3();
let decoded = persistence::decode_with_report(&serde_json::to_vec(&old).unwrap()).unwrap();
let source = language::parse_with_report(SOURCE3).unwrap();
assert_eq!(decoded.project, source.project);
assert_eq!(decoded.migration, source.migration);
let project = &decoded.project;
let report = decoded.migration.as_ref().unwrap();
assert_eq!((report.from_schema, report.to_schema), (3, 4));
assert_eq!(project.identities().len(), 19);
assert!(report.preserved_ports.is_empty());
assert!(report.generated_endpoints.is_empty());
assert_eq!(report.generated_interface_allocations.len(), 2);
for allocation in &report.generated_interface_allocations {
assert_eq!(
allocation.id,
Id::new_v5(
&id(1),
format!(
"v2-interface-item:{}:{}",
allocation.source, allocation.target
)
.as_bytes()
)
);
assert_eq!(allocation.target, id(4));
assert_eq!(allocation.order, 0);
assert!(matches!(
project.relations[&allocation.id].body,
RelationBody::InterfaceItemAllocation {
transmission: TransmissionProtocol::Unspecified,
acquisition: AcquisitionProtocol::Unspecified,
..
}
));
}
let now = serde_json::to_value(project).unwrap();
for port in [id(11), id(12)] {
assert_eq!(
now["elements"][port.to_string()],
old["elements"][port.to_string()]
);
}
assert!(matches!(
project.elements[&id(4)].shared(),
Some(SharedBody::ExchangeItem {
kind: ExchangeItemKind::Information,
mechanism: ExchangeMechanism::Event,
supertype: None
})
));
assert_eq!(report.unresolved_message_values.len(), 1);
assert!(
validation::validate(project)
.iter()
.any(|issue| issue.code == "message_value_ambiguous_path")
);
let canonical = language::format(project);
assert!(canonical.starts_with("arcadia 4;"));
let reopened = language::parse_with_report(&canonical).unwrap();
assert_eq!(&reopened.project, project);
assert!(reopened.migration.is_none());
assert_eq!(canonical, language::format(&reopened.project));
}
#[test]
fn v3_changed_payloads_reject_schema4_fields_and_new_constructor_names() {
let mut old = original3();
old["elements"][id(4).to_string()]["body"]["Sa"]["Shared"]["ExchangeItem"]["mechanism"] =
json!("Flow");
assert!(persistence::decode(&serde_json::to_vec(&old).unwrap()).is_err());
let mut old = original3();
old["elements"][id(5).to_string()]["body"]["Sa"]["Shared"]["DataType"]["definition"] =
json!({"Record":{"supertype":null}});
assert!(persistence::decode(&serde_json::to_vec(&old).unwrap()).is_err());
let mut old = original3();
old["elements"][id(17).to_string()]["body"]["Sa"]["Shared"]["Occurrence"]["body"]["Exchange"]
["values"][0]["path"] = json!([]);
assert!(persistence::decode(&serde_json::to_vec(&old).unwrap()).is_err());
let source = SOURCE3.replace("kind Event;", "kind Information; mechanism Flow;");
assert!(language::parse(&source).is_err());
let source = SOURCE3.replace(
"functional_exchange position_exchange",
"interface_item_allocation position_exchange",
);
assert!(language::parse(&source).is_err());
}
#[test]
fn deterministic_allocation_id_collision_is_located_without_overwriting_any_object() {
let mut old = original3();
let collision = Id::new_v5(
&id(1),
format!("v2-interface-item:{}:{}", id(9), id(4)).as_bytes(),
);
old["artifact_links"][collision.to_string()] = json!({"id":collision,"alias":"retained_artifact","name":"Retain","description":"","owner":id(1),"relation":"References","uri":"docs/contract.md","revision":null,"fragment":null});
let error = persistence::decode(&serde_json::to_vec(&old).unwrap()).unwrap_err();
match error {
persistence::FileError::Model { issues, .. } => {
assert_eq!(issues[0].code, "identity_collision");
assert_eq!(issues[0].element, Some(id(9)));
assert_eq!(issues[0].field.as_deref(), Some("items"));
}
other => panic!("unexpected error {other}"),
}
}
#[test]
fn unique_legacy_nested_value_is_qualified_and_physical_nature_is_not_guessed() {
let source = SOURCE3.replace("kind Event;", "kind Material;").replace(
"type_ref { Named @coordinate; }; }\n }",
"type_ref String; }\n }",
);
let decoded = language::parse_with_report(&source).unwrap();
assert!(matches!(
decoded.project.elements[&id(4)].shared(),
Some(SharedBody::ExchangeItem {
kind: ExchangeItemKind::Material,
mechanism: ExchangeMechanism::Unspecified,
..
})
));
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = decoded.project.elements[&id(17)].shared()
else {
panic!()
};
assert_eq!(values[0].path, vec![id(7)]);
assert_eq!(values[0].expression, "navigation.latitude");
}
#[test]
fn v1_and_frozen_v2_inputs_reach_four_through_the_shared_data_upgrade() {
let v2 =
persistence::decode_with_report(include_bytes!("fixtures/v2-coastal-rescue.json")).unwrap();
let text =
language::parse_with_report(include_str!("fixtures/v2-coastal-rescue.arcadia")).unwrap();
assert_eq!(v2.project, text.project);
assert_eq!(v2.migration, text.migration);
assert_eq!(v2.migration.unwrap().to_schema, 4);
let v1 = language::parse_with_report(
"arcadia 1; project \"Old\" id \"00000000-0000-0000-0000-000000000001\" {}",
)
.unwrap();
assert_eq!(v1.project.schema_version, 4);
assert_eq!(v1.migration.unwrap().from_schema, 1);
}
#[test]
fn allocation_alias_collisions_are_stable_and_duplicate_legacy_payload_fields_reject() {
let mut old = original3();
let first = persistence::decode_with_report(&serde_json::to_vec(&old).unwrap()).unwrap();
let alias = first.migration.unwrap().generated_interface_allocations[0]
.alias
.clone();
old["artifact_links"][id(100).to_string()] = json!({"id":id(100),"alias":alias,"name":"Existing alias","description":"","owner":id(1),"relation":"References","uri":"docs/contract.md","revision":null,"fragment":null});
let bytes = serde_json::to_vec(&old).unwrap();
let migrated = persistence::decode_with_report(&bytes).unwrap();
let generated = &migrated
.migration
.as_ref()
.unwrap()
.generated_interface_allocations[0];
assert_ne!(generated.alias, alias);
assert!(generated.alias.starts_with(&alias));
assert_eq!(
migrated.project,
persistence::decode_with_report(&bytes).unwrap().project
);
let duplicate = include_str!("fixtures/v3-data-contract.json").replace(
"\"kind\": \"Event\"",
"\"kind\": \"Event\", \"kind\": \"Material\"",
);
assert!(
persistence::decode(duplicate.as_bytes())
.unwrap_err()
.to_string()
.contains("Duplicate field 'kind'")
);
}
#[test]
fn recursive_legacy_record_paths_remain_ambiguous_instead_of_becoming_one_argument() {
let mut old = original3();
old["elements"][id(8).to_string()]["body"]["Sa"]["Shared"]["DataField"]["type_ref"] =
json!("String");
old["elements"][id(100).to_string()] = json!({"id":id(100),"alias":"next_coordinate","name":"Next coordinate","description":"","parent":id(5),"body":{"Sa":{"Shared":{"DataField":{"type_ref":{"Named":id(5)},"minimum":0,"maximum":1,"unit":""}}}}});
let decoded = persistence::decode_with_report(&serde_json::to_vec(&old).unwrap()).unwrap();
assert_eq!(
decoded
.migration
.as_ref()
.unwrap()
.unresolved_message_values
.len(),
1
);
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = decoded.project.elements[&id(17)].shared()
else {
panic!()
};
assert!(values[0].path.is_empty());
assert!(
validation::validate(&decoded.project)
.iter()
.any(|issue| issue.code == "message_value_ambiguous_path")
);
}
+215
View File
@@ -0,0 +1,215 @@
use oa_core::{language, source_project::*, *};
use std::collections::BTreeMap;
fn id(n: u128) -> Id {
Id::from_u128(n)
}
#[test]
fn authored_v3_bundle_upgrade_preserves_includes_nested_ownership_comments_and_identity() {
let original = include_str!("fixtures/v3-data-contract.arcadia");
let header = original.find(" sa_function").unwrap();
let close = original.rfind('}').unwrap();
let entry = format!(
"{} // Contracts stay in their original module.\n include \"contracts.arcadia\";\n}}\n",
&original[..header]
);
let fragment = original[header..close].replace(
"items [@packet];",
"items [@ // interface contract decision\npacket];",
);
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), entry),
("contracts.arcadia".into(), fragment),
]),
};
let compiled = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
assert_eq!(compiled.bundle.files.len(), 2);
assert!(compiled.bundle.files["project.arcadia"].contains("arcadia 4;"));
assert!(compiled.bundle.files["project.arcadia"].contains("include \"contracts.arcadia\";"));
for text in [
"// Contracts stay in their original module.",
"// Reused record parameters retain their own identities.",
"// interface contract decision",
] {
assert!(
compiled
.bundle
.files
.values()
.any(|source| source.contains(text)),
"Lost {text}"
);
}
assert_eq!(compiled.index.lexical_owners[&id(6)], id(5));
assert_eq!(compiled.index.lexical_owners[&id(7)], id(4));
assert_eq!(compiled.index.lexical_owners[&id(8)], id(4));
assert_eq!(compiled.index.lexical_owners[&id(17)], id(14));
let report = compiled.decoded.migration.as_ref().unwrap();
assert_eq!(report.from_schema, 3);
for allocation in &report.generated_interface_allocations {
assert_eq!(
compiled.index.declarations[&allocation.id].path,
"contracts.arcadia"
);
}
assert!(
compiled
.diagnostics
.iter()
.any(|d| d.diagnostic.code == "message_value_ambiguous_path")
);
let second = compile_bundle(&compiled.bundle, ProjectLimits::default()).unwrap();
assert_eq!(second.bundle, compiled.bundle);
assert_eq!(second.decoded.project, compiled.decoded.project);
assert!(second.decoded.migration.is_none());
let mut renamed = compiled.decoded.project.clone();
renamed.elements.get_mut(&id(6)).unwrap().name = "Latitude degrees".into();
let updated = update_bundle(&compiled, &renamed, ProjectLimits::default()).unwrap();
assert_eq!(updated.index.lexical_owners, compiled.index.lexical_owners);
assert!(updated.bundle.files["contracts.arcadia"].contains("Latitude degrees"));
assert!(
bundle.files["project.arcadia"].contains("arcadia 3;"),
"Migration does not mutate the caller's draft"
);
}
#[test]
fn schema4_typed_values_supertype_paths_and_protocols_roundtrip() {
let source = r#"arcadia 4; project data_contract "Data contract" {
sa_data_type bounded "Bounded" { definition { Integer { minimum -9223372036854775808; maximum 9223372036854775807; }; }; default { Integer -9223372036854775808; }; unit "m"; }
sa_data_type label_type "Label" { definition { String { minimum_length 1; maximum_length 4; }; }; default { String "航海"; }; }
sa_data_type base "Base" { definition { Record { supertype none; }; }; }
sa_data_type derived "Derived" { definition { Record { supertype @base; }; }; }
sa_exchange_item operation "Operation" { mechanism Operation;
sa_data_field value "Value" { type_ref { Named @bounded; }; direction In; storage Value; default [{ Integer 42; }]; }
}
sa_interface contract "Contract" { supertype none; }
interface_item_allocation member "Operation member" { source @contract; target @operation; transmission Synchronous; acquisition Accept; order 3; }
data_association association "Related records" { source @base; target @derived; source_role "parent"; target_role "children"; source_minimum 0; source_maximum 1; target_minimum 0; target_maximum none; source_navigable true; target_navigable true; }
}"#;
let parsed = language::parse(source).unwrap();
let formatted = language::format(&parsed);
assert!(formatted.contains("supertype @base"));
assert!(formatted.contains("transmission Synchronous"));
assert_eq!(language::parse(&formatted).unwrap(), parsed);
let compiled = compile_bundle(&format_bundle(&parsed), ProjectLimits::default()).unwrap();
assert_eq!(compiled.decoded.project, parsed);
assert!(compiled.decoded.migration.is_none());
}
#[test]
fn omitted_ids_are_stabilized_before_allocation_identity_generation() {
let bundle=SourceBundle{entry:"project.arcadia".into(),files:BTreeMap::from([("project.arcadia".into(),"arcadia 3; project old_model \"Old\" { sa_exchange_item event_item \"Event\" { kind Event; } sa_interface contract \"Contract\" { items [@event_item]; } }".into())])};
let compiled = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
let report = compiled.decoded.migration.as_ref().unwrap();
let allocation = &report.generated_interface_allocations[0];
assert_eq!(
allocation.id,
Id::new_v5(
&compiled.decoded.project.id,
format!(
"v2-interface-item:{}:{}",
allocation.source, allocation.target
)
.as_bytes()
)
);
let reopened = compile_bundle(&compiled.bundle, ProjectLimits::default()).unwrap();
assert_eq!(reopened.decoded.project, compiled.decoded.project);
assert_eq!(reopened.bundle, compiled.bundle);
}
#[test]
fn inferring_a_legacy_path_keeps_rationale_inside_its_argument() {
let source = include_str!("fixtures/v3-data-contract.arcadia")
.replace(
"type_ref { Named @coordinate; }; }\n }",
"type_ref String; }\n }",
)
.replace(
"field @latitude; expression",
"field @latitude; // original argument rationale\nexpression",
);
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([("project.arcadia".into(), source)]),
};
let compiled = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
let source = &compiled.bundle.files["project.arcadia"];
let argument = &source[source.find("values [{").unwrap()..];
let argument = &argument[..argument.find('}').unwrap()];
assert!(
argument.contains("// original argument rationale"),
"{source}"
);
assert!(argument.contains("path [@origin]"), "{source}");
assert_eq!(compiled.index.lexical_owners[&id(17)], id(14));
}
#[test]
fn qualified_value_reordering_and_path_reidentification_keep_each_arguments_comments() {
let mut project = language::parse(include_str!("fixtures/v3-data-contract.arcadia")).unwrap();
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = project.elements.get_mut(&id(17)).unwrap().shared_mut()
else {
panic!()
};
*values = vec![
MessageValue {
path: vec![id(7)],
field: id(6),
expression: "origin value".into(),
},
MessageValue {
path: vec![id(8)],
field: id(6),
expression: "destination value".into(),
},
];
let mut bundle = format_bundle(&project);
for source in bundle.files.values_mut() {
*source = source
.replace(
"expression \"origin value\";",
"expression \"origin value\"; // origin argument rationale",
)
.replace(
"expression \"destination value\";",
"expression \"destination value\"; // destination argument rationale",
);
}
let current = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = project.elements.get_mut(&id(17)).unwrap().shared_mut()
else {
panic!()
};
values.reverse();
let renamed = Id::from_u128(100);
let mut identities: BTreeMap<_, _> = project
.identities()
.into_iter()
.map(|(id, _)| (id, id))
.collect();
identities.insert(id(7), renamed);
reidentify(&mut project, id(7), renamed).unwrap();
project.elements.get_mut(&renamed).unwrap().alias = "revised_origin".into();
let result =
update_bundle_with_identity_map(&current, &project, &identities, ProjectLimits::default())
.unwrap();
let source = &result.bundle.files[&result.index.declarations[&id(17)].path];
let destination = source.find("// destination argument rationale").unwrap();
let origin = source.find("// origin argument rationale").unwrap();
assert!(
destination < origin,
"Distinct uses of the same terminal field must reorder as complete argument annotations: {source}"
);
assert!(source[origin..].contains("path [@revised_origin]"));
assert_eq!(result.decoded.project, project);
}
+18 -15
View File
@@ -447,11 +447,12 @@ fn standard_interface_roles_do_not_follow_message_direction_and_kind_mixing_is_r
p = execute_batch(&p, &plan_component_exchange(&p, &req).unwrap()).unwrap();
let (source, target) = p.relations[&boundary].body.endpoints();
let interface = add(&mut p, Kind::Interface, Layer::Sa, "Service");
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface { items: vec![item] };
p.relate(
RelationKind::InterfaceItemAllocation,
"Interface payload",
interface,
item,
);
let requirement = p.relate(
RelationKind::InterfaceRequirement,
"Caller requires service",
@@ -499,11 +500,12 @@ fn legacy_split_preserves_original_identity_prose_interface_artifact_constraint_
let (mut p, a, b, item, forward) = fixture();
let (old, _) = endpoints(&p, forward);
let interface = add(&mut p, Kind::Interface, Layer::Sa, "Original interface");
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface { items: vec![item] };
p.relate(
RelationKind::InterfaceItemAllocation,
"Interface payload",
interface,
item,
);
p.elements.get_mut(&old).unwrap().description = "Original bidirectional rationale".into();
*p.elements.get_mut(&old).unwrap().shared_mut().unwrap() = SharedBody::Port {
contract: PortContract::Legacy,
@@ -659,11 +661,12 @@ fn directed_legacy_resolution_retains_unclassified_interface_and_role_identity()
let (mut p, _, _, item, fe) = fixture();
let output = endpoints(&p, fe).0;
let interface = add(&mut p, Kind::Interface, Layer::Sa, "Original service");
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface { items: vec![item] };
p.relate(
RelationKind::InterfaceItemAllocation,
"Interface payload",
interface,
item,
);
*p.elements.get_mut(&output).unwrap().shared_mut().unwrap() = SharedBody::Port {
contract: PortContract::Legacy,
legacy: Some(LegacyPortContract {
+4 -1
View File
@@ -94,7 +94,9 @@ fn fixture(layer: Layer) -> Fixture {
.add_element(Kind::DataType, layer, "Request record", None)
.unwrap();
*p.elements.get_mut(&record).unwrap().shared_mut().unwrap() = SharedBody::DataType {
definition: DataTypeDefinition::Record,
definition: DataTypeDefinition::Record { supertype: None },
default: None,
unit: String::new(),
};
let field = p
.add_element(Kind::DataField, layer, "Requested level", Some(record))
@@ -160,6 +162,7 @@ fn fixture(layer: Layer) -> Fixture {
}) = p.elements.get_mut(&call).unwrap().shared_mut()
{
values.push(MessageValue {
path: vec![payload],
field,
expression: "requested_level".into(),
});
+6 -6
View File
@@ -5,7 +5,7 @@ fn setup() -> tempfile::TempDir {
let directory = tempfile::tempdir().unwrap();
fs::write(
directory.path().join("project.arcadia"),
"arcadia 3; project p \"P\" { include \"parts/a.arcadia\"; }\n",
"arcadia 4; project p \"P\" { include \"parts/a.arcadia\"; }\n",
)
.unwrap();
fs::create_dir(directory.path().join("parts")).unwrap();
@@ -59,7 +59,7 @@ fn loading_keeps_original_no_uuid_bytes_and_saving_stabilizes_exactly_once() {
fn invalid_and_missing_includes_keep_editable_text_and_located_diagnostics() {
let directory = setup();
let entry = directory.path().join("project.arcadia");
fs::write(&entry, "arcadia 3; project p \"P\" {\n include \"missing.arcadia\";\n include \"parts/a.arcadia\";\n}\n").unwrap();
fs::write(&entry, "arcadia 4; project p \"P\" {\n include \"missing.arcadia\";\n include \"parts/a.arcadia\";\n}\n").unwrap();
fs::write(
directory.path().join("parts/a.arcadia"),
"oa_activity a \"A\" { invalid",
@@ -102,7 +102,7 @@ fn discovery_never_refreshes_drafts_and_preserves_detached_buffers() {
let overlays = BTreeMap::from([
(
"project.arcadia".into(),
"arcadia 3; project p \"P\" { include \"new.arcadia\"; }".into(),
"arcadia 4; project p \"P\" { include \"new.arcadia\"; }".into(),
),
(
"parts/a.arcadia".into(),
@@ -176,7 +176,7 @@ fn new_destinations_require_explicit_missing_expectations_and_reject_collisions(
files: BTreeMap::from([
(
"project.arcadia".into(),
"arcadia 3; project p \"P\" { include \"child.arcadia\"; }".into(),
"arcadia 4; project p \"P\" { include \"child.arcadia\"; }".into(),
),
("child.arcadia".into(), "oa_activity a \"A\" {}".into()),
]),
@@ -256,7 +256,7 @@ fn physical_hard_link_aliases_are_rejected() {
.unwrap();
fs::write(
directory.path().join("project.arcadia"),
"arcadia 3; project p \"P\" { include \"parts/a.arcadia\"; include \"alias.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"parts/a.arcadia\"; include \"alias.arcadia\"; }",
)
.unwrap();
assert!(matches!(
@@ -286,7 +286,7 @@ fn symlinks_to_outside_or_inside_project_are_rejected() {
std::os::unix::fs::symlink(&destination, &link).unwrap();
fs::write(
directory.path().join("project.arcadia"),
"arcadia 3; project p \"P\" { include \"alias.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"alias.arcadia\"; }",
)
.unwrap();
let loaded = load_project(
@@ -6,10 +6,10 @@ fn source() -> CompiledSourceProject {
&SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), "arcadia 3; project p \"Identity review\" { include \"team/first.arcadia\"; include \"team/second.arcadia\"; include \"contracts.arcadia\"; }".into()),
("project.arcadia".into(), "arcadia 4; project p \"Identity review\" { include \"team/first.arcadia\"; include \"team/second.arcadia\"; include \"contracts.arcadia\"; }".into()),
("team/first.arcadia".into(), "// Rationale for first\nsa_exchange_item first \"First\" { description \"First rationale\"; }\n".into()),
("team/second.arcadia".into(), "// Rationale for second\nsa_exchange_item second \"Second\" {}\n".into()),
("contracts.arcadia".into(), "sa_interface contract \"Contract\" { items [\n @first // first item rationale\n ,\n @second // second item rationale\n ]; }\n".into()),
("contracts.arcadia".into(), "sa_event contract \"Contract\" { body { Signal { items [\n @first // first item rationale\n ,\n @second // second item rationale\n ]; }; }; }\n".into()),
]),
},
ProjectLimits::default(),
@@ -91,8 +91,9 @@ fn identity_swap_and_reorder_keep_both_declarations_and_item_comments_with_origi
reidentify(&mut candidate, second, first).unwrap();
reidentify(&mut candidate, temporary, second).unwrap();
let contract = find(&candidate, "contract");
let Some(SharedBody::Interface { items }) =
candidate.elements.get_mut(&contract).unwrap().shared_mut()
let Some(SharedBody::Event {
body: EventBody::Signal { items },
}) = candidate.elements.get_mut(&contract).unwrap().shared_mut()
else {
panic!("interface")
};
@@ -5,7 +5,7 @@ fn compile(a: &str, b: &str) -> CompiledSourceProject {
compile_bundle(&SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), "arcadia 3; project p \"Nested writeback\" { include \"a.arcadia\"; include \"b.arcadia\"; }\n".into()),
("project.arcadia".into(), "arcadia 4; project p \"Nested writeback\" { include \"a.arcadia\"; include \"b.arcadia\"; }\n".into()),
("a.arcadia".into(), a.into()), ("b.arcadia".into(), b.into()),
]),
}, ProjectLimits::default()).unwrap()
+35 -33
View File
@@ -30,7 +30,7 @@ fn id(project: &Project, alias: &str) -> Id {
#[test]
fn route_edits_keep_diagram_file_ownership_and_comments_with_edge_identity() {
let input = bundle(
"arcadia 3; project p \"Routing\" { include \"views.arcadia\"; include \"work.arcadia\"; }",
"arcadia 4; project p \"Routing\" { include \"views.arcadia\"; include \"work.arcadia\"; }",
&[
(
"work.arcadia",
@@ -95,7 +95,7 @@ diagram review "Review" {
#[test]
fn invalid_cross_file_route_references_and_geometry_locate_the_authored_view() {
let mut input = bundle(
"arcadia 3; project p \"Routing\" { include \"views.arcadia\"; include \"work.arcadia\"; }",
"arcadia 4; project p \"Routing\" { include \"views.arcadia\"; include \"work.arcadia\"; }",
&[
(
"work.arcadia",
@@ -127,7 +127,7 @@ fn invalid_cross_file_route_references_and_geometry_locate_the_authored_view() {
fn typed() -> SourceBundle {
bundle(
"arcadia 3; project test_model \"航海\" {\n include \"exchanges.arcadia\";\n include \"work/send.arcadia\";\n include \"work/receive.arcadia\";\n include \"types.arcadia\";\n}",
"arcadia 4; project test_model \"航海\" {\n include \"exchanges.arcadia\";\n include \"work/send.arcadia\";\n include \"work/receive.arcadia\";\n include \"types.arcadia\";\n}",
&[
(
"exchanges.arcadia",
@@ -194,7 +194,7 @@ fn cross_file_typed_ports_global_forward_references_and_stable_ids() {
#[test]
fn advisory_lint_locations_refer_to_raw_drafts_before_identity_stabilization() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"work.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"work.arcadia\"; }",
&[(
"work.arcadia",
"sa_function first \"First\" {}\nsa_function second \"Second\" {}\n",
@@ -228,7 +228,7 @@ fn advisory_lint_locations_refer_to_raw_drafts_before_identity_stabilization() {
#[test]
fn source_errors_keep_exact_fragment_unicode_positions() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"child.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"child.arcadia\"; }",
&[(
"child.arcadia",
"// Пример\nsa_function child \"航海\" { parent @missing; }",
@@ -274,7 +274,7 @@ fn duplicate_alias_and_identity_report_both_files_including_project_identity() {
),
] {
let input = bundle(
"arcadia 3; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
&[("a.arcadia", left), ("b.arcadia", right)],
);
let error = compile_bundle(&input, ProjectLimits::default())
@@ -285,7 +285,7 @@ fn duplicate_alias_and_identity_report_both_files_including_project_identity() {
assert_eq!(error.related[0].path, "a.arcadia");
}
let input = bundle(
"arcadia 3; project p \"P\" { include \"child.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"child.arcadia\"; }",
&[("child.arcadia", "oa_activity p \"Collision\" {}")],
);
let error = compile_bundle(&input, ProjectLimits::default())
@@ -297,7 +297,7 @@ fn duplicate_alias_and_identity_report_both_files_including_project_identity() {
#[test]
fn includes_are_once_only_and_cycles_missing_and_unreachable_files_are_located() {
let mut input = bundle(
"arcadia 3; project p \"P\" { include \"sub/a.arcadia\"; include \"sub/b.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"sub/a.arcadia\"; include \"sub/b.arcadia\"; }",
&[
("sub/a.arcadia", "include \"../shared.arcadia\";"),
("sub/b.arcadia", "include \"../shared.arcadia\";"),
@@ -356,7 +356,7 @@ fn portable_paths_reject_escapes_devices_urls_and_case_collisions() {
);
assert!(resolve_include("../bad.arcadia", "a.arcadia").is_err());
let input = bundle(
"arcadia 3; project p \"P\" {}",
"arcadia 4; project p \"P\" {}",
&[("A.arcadia", ""), ("a.arcadia", "")],
);
assert_eq!(
@@ -370,7 +370,7 @@ fn portable_paths_reject_escapes_devices_urls_and_case_collisions() {
#[test]
fn project_admission_is_aggregate_and_precedes_global_resolution() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
&[
("a.arcadia", "oa_activity one \"One\" { parent @missing; }"),
("b.arcadia", "oa_activity two \"Two\" {}"),
@@ -591,7 +591,7 @@ fn failed_update_preserves_candidate_and_rejects_stale_index() {
#[test]
fn single_string_and_legacy_apis_remain_explicit_and_filesystem_free() {
let source = "arcadia 3; project p \"P\" { include \"missing.arcadia\"; }";
let source = "arcadia 4; project p \"P\" { include \"missing.arcadia\"; }";
assert!(
language::parse(source).unwrap_err()[0]
.message
@@ -681,7 +681,7 @@ fn json_bundle_rejects_duplicate_file_keys_and_unknown_fields() {
#[test]
fn generated_id_insertion_handles_adjacent_header_tokens_and_remains_exactly_indexed() {
let input = bundle(
"arcadia 3;project p\"P\"{include \"child.arcadia\";}",
"arcadia 4;project p\"P\"{include \"child.arcadia\";}",
&[(
"child.arcadia",
"oa_activity a\"A\"{}diagram d\"D\"{}node n{diagram @d;element @a;}",
@@ -703,7 +703,7 @@ fn generated_id_insertion_handles_adjacent_header_tokens_and_remains_exactly_ind
#[test]
fn duplicate_include_edges_count_toward_admission_and_ordered_references_are_aggregate() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"a.arcadia\"; include \"a.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"a.arcadia\"; include \"a.arcadia\"; }",
&[("a.arcadia", "")],
);
assert_eq!(
@@ -720,7 +720,7 @@ fn duplicate_include_edges_count_toward_admission_and_ordered_references_are_agg
"project_limit"
);
let input = bundle(
"arcadia 3; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"a.arcadia\"; include \"b.arcadia\"; }",
&[
(
"a.arcadia",
@@ -763,7 +763,7 @@ fn include_inspection_reuses_strict_entry_fragment_syntax_and_real_spans() {
&source[span.start..span.end],
"include \"../shared.arcadia\";"
);
let entry = "arcadia 3; project p \"P\" { include \"sub/work.arcadia\"; }";
let entry = "arcadia 4; project p \"P\" { include \"sub/work.arcadia\"; }";
assert_eq!(
inspect_includes("project.arcadia", entry, true, ProjectLimits::default()).unwrap()[0]
.target,
@@ -829,7 +829,7 @@ fn comments(source: &str) -> Vec<String> {
#[test]
fn scalar_header_guard_and_project_edits_preserve_exact_crlf_trivia_and_escape_spelling() {
let entry = "arcadia 3;\r\nproject p // project title\r\n \"Original project\" {\r\n description // project reason\r\n \"Before\";\r\n include \"behavior.arcadia\";\r\n}\r\n";
let entry = "arcadia 4;\r\nproject p // project title\r\n \"Original project\" {\r\n description // project reason\r\n \"Before\";\r\n include \"behavior.arcadia\";\r\n}\r\n";
let source = "oa_state_machine machine \"Machine\" {}\r\noa_region region_one \"Region\" { parent @machine; }\r\noa_state first \"First\" { parent @region_one; }\r\noa_state second \"Second\" { parent @region_one; }\r\nstate_transition route // route title\r\n \"Original transition\" {\r\n\tguard // feasibility\r\n\t \"old guard\"; // retain explanation\r\n\tdescription \"Keep\\u0020spelling\";\r\n\tsource @ // endpoint proof\r\n first; target @second;\r\n}\r\n";
let current = compile(&bundle(entry, &[("behavior.arcadia", source)]));
let mut project = current.decoded.project.clone();
@@ -864,7 +864,7 @@ fn scalar_header_guard_and_project_edits_preserve_exact_crlf_trivia_and_escape_s
#[test]
fn alias_updates_touch_only_header_and_reference_tokens_even_with_comments_after_at() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"work.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"work.arcadia\"; }",
&[(
"work.arcadia",
"oa_activity root_work // root rationale\n \"Root\\u0020name\" { description \"root_work is prose\"; }\noa_activity child \"Child\" { parent @ // parent proof\n root_work; }\n",
@@ -887,7 +887,7 @@ fn alias_updates_touch_only_header_and_reference_tokens_even_with_comments_after
#[test]
fn omitted_defaults_stay_omitted_and_new_fields_do_not_reformat_surviving_fields() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"work.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"work.arcadia\"; }",
&[(
"work.arcadia",
"oa_activity work \"Work\" {\r\n\t// owner rationale\r\n\tparent none ; // preserve spacing\r\n}\r\n",
@@ -913,7 +913,7 @@ fn omitted_defaults_stay_omitted_and_new_fields_do_not_reformat_surviving_fields
#[test]
fn kind_change_removes_field_syntax_but_keeps_its_comments_and_other_fields() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"item.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"item.arcadia\"; }",
&[(
"item.arcadia",
"oa_exchange_item item \"Item\" {\n description \"Keep\\u0020this\" ; // description note\n kind // classification rationale\n Information ;\n parent none;\n}\n",
@@ -953,7 +953,7 @@ fn significant_words(source: &str) -> Vec<String> {
#[test]
fn constructor_tag_changes_retain_shared_nested_fields_and_removed_field_comments() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"event.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"event.arcadia\"; }",
&[(
"event.arcadia",
"oa_event timer \"Timer\" { body { Time // time rationale\n { expression // expression rationale\n \"before\" ; kind After; // clock rationale\n }; }; }\n",
@@ -986,7 +986,7 @@ fn constructor_tag_changes_retain_shared_nested_fields_and_removed_field_comment
#[test]
fn scalar_record_constructor_changes_keep_comments_inside_removed_values() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"ports.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"ports.arcadia\"; }",
&[(
"ports.arcadia",
"sa_function work \"Work\" {}\nsa_port input \"Input\" { parent @work; contract Legacy; // contract rationale\n legacy { direction In; // direction rationale\n interface none; // interface rationale\n }; }\n",
@@ -1017,10 +1017,10 @@ fn scalar_record_constructor_changes_keep_comments_inside_removed_values() {
#[test]
fn reference_list_reordering_carries_item_comments_and_alias_spelling_with_identity() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"types.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"types.arcadia\"; }",
&[(
"types.arcadia",
"sa_exchange_item a \"A\" {} sa_exchange_item b \"B\" {}\nsa_interface service \"Service\" { items [\n // before A\n @ // A reference rationale\n a // after A\n ,\n // before B\n @b // after B\n ]; }\n",
"sa_exchange_item a \"A\" {} sa_exchange_item b \"B\" {}\nsa_event service \"Service\" { body { Signal { items [\n // before A\n @ // A reference rationale\n a // after A\n ,\n // before B\n @b // after B\n ]; }; }; }\n",
)],
);
let current = compile(&input);
@@ -1029,8 +1029,9 @@ fn reference_list_reordering_carries_item_comments_and_alias_spelling_with_ident
let b = id(&project, "b");
let service = id(&project, "service");
project.elements.get_mut(&a).unwrap().alias = "renamed_a".into();
if let Some(SharedBody::Interface { items }) =
project.elements.get_mut(&service).unwrap().shared_mut()
if let Some(SharedBody::Event {
body: EventBody::Signal { items },
}) = project.elements.get_mut(&service).unwrap().shared_mut()
{
*items = vec![b, a];
} else {
@@ -1051,10 +1052,10 @@ fn reference_list_reordering_carries_item_comments_and_alias_spelling_with_ident
#[test]
fn removed_list_items_and_declarations_keep_comments_as_enclosing_annotations() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"types.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"types.arcadia\"; }",
&[(
"types.arcadia",
"sa_exchange_item a \"A\" { // declaration explanation\n } sa_exchange_item b \"B\" {}\nsa_interface service \"Service\" { items [\n // explanation for removed A\n @a,\n // explanation for retained B\n @b ]; }\n",
"sa_exchange_item a \"A\" { // declaration explanation\n } sa_exchange_item b \"B\" {}\nsa_event service \"Service\" { body { Signal { items [\n // explanation for removed A\n @a,\n // explanation for retained B\n @b ]; }; }; }\n",
)],
);
let current = compile(&input);
@@ -1063,8 +1064,9 @@ fn removed_list_items_and_declarations_keep_comments_as_enclosing_annotations()
let b = id(&project, "b");
let service = id(&project, "service");
project.elements.remove(&a);
if let Some(SharedBody::Interface { items }) =
project.elements.get_mut(&service).unwrap().shared_mut()
if let Some(SharedBody::Event {
body: EventBody::Signal { items },
}) = project.elements.get_mut(&service).unwrap().shared_mut()
{
*items = vec![b];
} else {
@@ -1102,7 +1104,7 @@ oa_occurrence message "Message" { parent @conversation; body { Exchange {
}; }; }
"#;
let current = compile(&bundle(
"arcadia 3; project p \"P\" { include \"conversation.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"conversation.arcadia\"; }",
&[("conversation.arcadia", source)],
));
let mut project = current.decoded.project.clone();
@@ -1151,7 +1153,7 @@ oa_occurrence message "Message" { parent @conversation; body { Exchange {
#[test]
fn added_list_items_empty_lists_and_literal_changes_preserve_existing_annotations() {
let input = bundle(
"arcadia 3; project p \"P\" { include \"types.arcadia\"; }",
"arcadia 4; project p \"P\" { include \"types.arcadia\"; }",
&[(
"types.arcadia",
"oa_data_type values \"Values\" { definition { Enumeration { literals [ // enumeration rationale\n ]; }; }; }\n",
@@ -1160,7 +1162,7 @@ fn added_list_items_empty_lists_and_literal_changes_preserve_existing_annotation
let empty = compile(&input);
let mut project = empty.decoded.project.clone();
let values = id(&project, "values");
if let Some(SharedBody::DataType { definition }) =
if let Some(SharedBody::DataType { definition, .. }) =
project.elements.get_mut(&values).unwrap().shared_mut()
{
*definition = DataTypeDefinition::Enumeration {
@@ -1185,7 +1187,7 @@ fn added_list_items_empty_lists_and_literal_changes_preserve_existing_annotation
.replace("\"Beta\"", "\"Beta\" // beta explanation\n"),
);
let annotated = compile(&annotated);
if let Some(SharedBody::DataType { definition }) =
if let Some(SharedBody::DataType { definition, .. }) =
project.elements.get_mut(&values).unwrap().shared_mut()
{
*definition = DataTypeDefinition::Enumeration {
+47 -9
View File
@@ -328,11 +328,12 @@ fn items_ports_interfaces_and_exchange_allocation_are_typed() {
let f2 = add(&mut p, Kind::Function, Layer::Sa, "Receive", None);
let item = add(&mut p, Kind::ExchangeItem, Layer::Sa, "Message", None);
let interface = add(&mut p, Kind::Interface, Layer::Sa, "Link interface", None);
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface { items: vec![item] };
p.relate(
RelationKind::InterfaceItemAllocation,
"Interface payload",
interface,
item,
);
let port = |p: &mut Project, name: &str, parent, direction| {
let id = Id::new_v4();
let contract = if p.elements[&parent].kind() == Kind::Function {
@@ -740,6 +741,9 @@ fn reidentifying_data_types_and_function_ports_updates_every_typed_reference() {
minimum: 0,
maximum: None,
unit: "items".into(),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
default: None,
};
let function = add(&mut p, Kind::Function, Layer::Sa, "Function", None);
let other = add(&mut p, Kind::Function, Layer::Sa, "Other", None);
@@ -804,8 +808,40 @@ fn every_demo_identity_can_be_remapped_and_deleted_without_dangling_references()
"Reidentification must preserve all values and order"
);
if id != p.id {
let deleted = execute_batch(&p, &[Command::Delete(id)])
.unwrap_or_else(|err| panic!("Delete {id}: {err}"));
let deleted = if p
.relations
.get(&id)
.is_some_and(|r| r.kind() == RelationKind::InterfaceItemAllocation)
{
// An explicitly empty interface cannot silently accept the
// still-carried payload. Removing its definition needs a
// reviewed edit of that dependent contract in the same batch.
let mut session = Session::new(p.clone());
assert!(
session
.execute(Command::Delete(id))
.unwrap_err()
.0
.contains("port_interface_items")
);
assert_eq!(session.project(), &p);
assert_eq!(session.revision(), 0);
let item = p.relations[&id].target();
let mut commands = vec![Command::Delete(id)];
commands.extend(
p.relations
.values()
.filter(|r| {
r.kind() == RelationKind::BoundaryExchange
&& r.body.items().contains(&item)
})
.map(|r| Command::Delete(r.id)),
);
execute_batch(&p, &commands).unwrap()
} else {
execute_batch(&p, &[Command::Delete(id)])
.unwrap_or_else(|err| panic!("Delete {id}: {err}"))
};
accepted(&deleted);
}
}
@@ -890,13 +926,15 @@ fn demo_has_both_layers_complete_contracts_and_no_checks() {
assert!(p.elements.values().any(|e| matches!(
e.shared(),
Some(SharedBody::ExchangeItem {
kind: ExchangeItemKind::Material
kind: ExchangeItemKind::Material,
..
})
)));
assert!(p.elements.values().any(|e| matches!(
e.shared(),
Some(SharedBody::ExchangeItem {
kind: ExchangeItemKind::Energy
kind: ExchangeItemKind::Energy,
..
})
)));
}
+534 -5
View File
@@ -12,6 +12,216 @@ use oa_core::{
use serde_json::{Value, json};
use std::{collections::BTreeSet, path::PathBuf, sync::Arc};
#[cfg(test)]
mod direct_scenario_tests {
use super::*;
use crate::behavior::{
self,
scenario::{self, CanvasEvent, Event, MessageStyle, Slot},
};
fn setup() -> (App, scenario::direct_tests::Fixture) {
let f = scenario::direct_tests::fixture();
let mut app = App::with_project(f.project.clone());
let _ = app.update(Message::Select(f.owner));
let _ = app.update(Message::Page(Page::Behavior));
assert_eq!(app.scenario_context().unwrap().scenario, f.owner);
(app, f)
}
fn form(app: &mut App, event: Event) {
let _ = app.update(Message::Behavior(behavior::Event::Scenario(event)));
}
fn begin(app: &App, f: &scenario::direct_tests::Fixture) -> CanvasEvent {
CanvasEvent::Begin {
context: app.scenario_context().unwrap(),
slot: Slot {
parent: f.owner,
before: None,
},
sender: f.sender,
receiver: f.receiver,
style: MessageStyle::Asynchronous,
}
}
#[test]
fn direct_scenario_scroll_and_real_resize_invalidate_only_pointer_context() {
let (mut app, f) = setup();
let original = app.document.bundle().clone();
let event = begin(&app, &f);
let context = app.scenario_context().unwrap();
let size = app.window_size;
let _ = app.update(Message::WindowResized(size));
assert_eq!(app.scenario_context(), Some(context));
let _ = app.update(Message::WindowResized(iced::Size::new(
size.width + 20.,
size.height,
)));
assert_ne!(app.scenario_context(), Some(context));
let _ = app.update(Message::ScenarioCanvas(event));
assert!(!app.behavior.has_pending());
let context = app.scenario_context().unwrap();
for (area, offset) in [
(scenario::ScrollArea::Canvas, iced::Vector::new(30., 150.)),
(scenario::ScrollArea::Page, iced::Vector::new(0., 90.)),
] {
let before = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Scrolled(
context, area, offset,
)));
assert_ne!(app.scenario_context(), Some(before));
let current = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Scrolled(
context, area, offset,
)));
assert_eq!(
app.scenario_context(),
Some(current),
"unchanged redraw notification retains context"
);
}
let event = begin(&app, &f);
let _ = app.update(Message::ScenarioCanvas(event));
form(&mut app, Event::Name("Keep my draft".into()));
let context = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Scrolled(
context,
scenario::ScrollArea::Page,
iced::Vector::new(0., 200.),
)));
assert!(app.behavior.has_pending());
assert_eq!(app.document.bundle(), &original);
let current = app.scenario_context().unwrap();
for dimension in 0..3 {
let mut stale = current;
match dimension {
0 => stale.document = Id::new_v4(),
1 => stale.scenario = Id::new_v4(),
_ => stale.revision += 1,
}
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Scrolled(
stale,
scenario::ScrollArea::Canvas,
iced::Vector::new(0., 900.),
)));
assert_eq!(app.scenario_context(), Some(current));
}
assert!(!app.document.can_undo());
}
#[test]
fn direct_scenario_rejects_every_stale_context_and_preserves_property_drafts() {
let (mut app, f) = setup();
let before = app.document.snapshot();
for dimension in 0..4 {
let mut event = begin(&app, &f);
let CanvasEvent::Begin { context, .. } = &mut event else {
unreachable!()
};
match dimension {
0 => context.document = Id::new_v4(),
1 => context.scenario = Id::new_v4(),
2 => context.revision += 1,
_ => context.epoch += 1,
}
let _ = app.update(Message::ScenarioCanvas(event));
assert!(!app.behavior.has_pending());
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
}
let _ = app.update(Message::Field(
"/name".into(),
"Pending scenario name".into(),
));
assert!(app.draft_dirty());
let event = begin(&app, &f);
let _ = app.update(Message::ScenarioCanvas(event));
assert!(!app.behavior.has_pending());
assert!(app.draft_dirty());
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
}
#[test]
fn direct_scenario_creation_and_reorder_preserve_selection_and_each_undo_once() {
let (mut app, f) = setup();
let original = app.document.bundle().clone();
let event = begin(&app, &f);
let _ = app.update(Message::ScenarioCanvas(event));
form(
&mut app,
Event::Exchange(Choice {
id: f.exchange,
label: "Contract".into(),
}),
);
form(&mut app, Event::Submit);
assert!(!app.behavior.has_pending());
let created = app.selected;
assert_ne!(created, f.owner);
assert_eq!(
app.project().elements[&f.owner].steps().unwrap(),
&[f.call, f.reply, created]
);
let before_reorder = app.document.bundle().clone();
let context = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Select(
context, f.sender,
)));
assert_eq!(
app.scenario_context(),
Some(context),
"same-owner selection retains gesture context"
);
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Reorder {
context,
occurrence: created,
slot: Slot {
parent: f.owner,
before: Some(f.call),
},
}));
assert_eq!(app.selected, created);
assert_eq!(
app.project().elements[&f.owner].steps().unwrap(),
&[created, f.call, f.reply]
);
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before_reorder);
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &original);
assert_eq!(app.project(), &f.project);
assert!(!app.document.can_undo());
}
#[test]
fn direct_scenario_source_failure_and_navigation_keep_form_until_success() {
let (mut app, f) = setup();
let bundle = app.document.bundle().clone();
let mut limits = oa_core::source_project::ProjectLimits::default();
limits.model.max_source_bytes =
bundle.files.values().map(String::len).sum::<usize>() + 4000;
app.document = Document::from_bundle(bundle.clone(), limits).unwrap();
app.sync();
let event = begin(&app, &f);
let _ = app.update(Message::ScenarioCanvas(event));
form(
&mut app,
Event::Exchange(Choice {
id: f.exchange,
label: "Contract".into(),
}),
);
form(&mut app, Event::Name("Long message".repeat(1024)));
let _ = app.update(Message::Page(Page::Catalog));
assert_eq!(app.page, Page::Behavior);
form(&mut app, Event::Submit);
assert!(app.behavior.has_pending());
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo());
form(&mut app, Event::Name("Recovered message".into()));
form(&mut app, Event::Submit);
assert!(!app.behavior.has_pending());
assert_eq!(app.project().named(app.selected), "Recovered message");
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo());
}
}
#[cfg(test)]
mod behavior_lifecycle_tests;
mod state_diagram;
@@ -115,6 +325,7 @@ pub enum Message {
BrowseGroup(crate::explorer::Group),
ExplorerPage(usize),
CreateKind(Kind),
Data(crate::data_view::Event),
Add(bool),
AddRelation,
PortAction(crate::port_workflow::Action),
@@ -127,6 +338,9 @@ pub enum Message {
Field(String, String),
FieldText(String, text_editor::Action),
FieldShape(String, Value),
FieldAppend(String, Value),
FieldValuePath(String, crate::data_values::FieldPathKey),
FieldValueBrowse(String, Option<crate::data_values::FieldPathKey>, usize),
FieldVariant(String, Value),
FieldArray(String, Option<usize>, i32),
Apply,
@@ -144,6 +358,7 @@ pub enum Message {
BehaviorOwner(Choice),
BehaviorDiagram(Choice),
StateDiagram(crate::behavior::state_edit::Event),
ScenarioCanvas(crate::behavior::scenario::CanvasEvent),
PlaceSelected,
HideSelected,
ToggleCollapse,
@@ -204,6 +419,7 @@ pub struct App {
pub page: Page,
pub guide: crate::guide::State,
pub behavior: crate::behavior::State,
pub data_state: crate::data_view::State,
pub inspector_tab: crate::navigation::InspectorTab,
pub layer: Layer,
pub selected: Id,
@@ -292,6 +508,7 @@ impl App {
page: Page::Diagram,
guide: crate::guide::State::default(),
behavior: Default::default(),
data_state: Default::default(),
inspector_tab: Default::default(),
layer,
selected,
@@ -574,9 +791,10 @@ impl App {
}
fn execute(&mut self, command: Command) -> bool {
let command = crate::port_edit::repair_owner_change(self.project(), command);
let scenario_selection = self.behavior.scenario.created_selection(&command);
match self.document.execute(command) {
Ok(selected) => {
if let Some(id) = selected {
if let Some(id) = scenario_selection.or(selected) {
self.selected = id;
}
self.sync();
@@ -732,6 +950,15 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
// Scrollable geometry can change while async work or an overlay blocks
// commands. Keep the observed translation current; its passive handler
// still validates document, scenario and revision before accepting it.
if matches!(
&message,
Message::ScenarioCanvas(crate::behavior::scenario::CanvasEvent::Scrolled(..))
) {
return self.handle(message);
}
// Global subscriptions also receive keys consumed by an overlay.
if self.model_menu.is_some() && matches!(message, Message::Escape) {
self.model_menu = None;
@@ -764,6 +991,8 @@ impl App {
Message::Field(..)
| Message::FieldText(..)
| Message::FieldShape(..)
| Message::FieldAppend(..)
| Message::FieldValuePath(..)
| Message::FieldVariant(..)
| Message::FieldArray(..)
| Message::ElementKind(_)
@@ -896,6 +1125,7 @@ impl App {
self.connection = None;
}
if previous_layer != self.layer {
self.data_state = Default::default();
self.explorer_index = crate::explorer::Index::new(self.project(), self.layer);
self.explorer_focus = None;
self.explorer_group = None;
@@ -928,8 +1158,115 @@ impl App {
task
}
}
pub(crate) fn scenario_context(&self) -> Option<crate::behavior::scenario::Context> {
let scenario = crate::behavior::selected_owner(self)?;
(self.page == Page::Behavior
&& self.project().elements.get(&scenario)?.kind() == Kind::Scenario)
.then_some(crate::behavior::scenario::Context {
document: self.canvas_document,
scenario,
revision: self.document.revision(),
epoch: self.canvas_epoch,
})
}
fn handle(&mut self, message: Message) -> Task<Message> {
match message {
Message::ScenarioCanvas(event) => {
use crate::behavior::scenario::{self, CanvasEvent};
let context = event.context();
if let CanvasEvent::Scrolled(_, area, offset) = event {
// Inner and outer scroll notifications may come from the
// same frame. Accept both across the first epoch bump,
// while still rejecting another owner/document/revision.
if self.scenario_context().is_some_and(|current| {
current.document == context.document
&& current.scenario == context.scenario
&& current.revision == context.revision
}) && self.behavior.scenario.scrolled(area, offset)
{
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
return Task::none();
}
if self.scenario_context() != Some(context) {
return Task::none();
}
match event {
CanvasEvent::Select(_, id) => {
if !self.behavior.has_pending()
&& crate::behavior::selected_behavior(self.project(), id)
== Some(context.scenario)
{
self.select(id);
self.selected_node = None;
}
}
CanvasEvent::Choose(_, tool) => {
if self.behavior.has_pending() || !self.apply() {
return Task::none();
}
self.behavior.scenario.choose_tool(context.scenario, tool);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
mutation => {
if self.behavior.has_pending() || self.draft_dirty() || self.source_dirty()
{
self.status =
"Apply or cancel pending edits before changing the scenario."
.into();
return Task::none();
}
match mutation {
CanvasEvent::Begin {
slot,
sender,
receiver,
style,
..
} => {
let mut state = std::mem::take(&mut self.behavior.scenario);
let result = state.begin_message(
self.project(),
context,
slot,
sender,
receiver,
style,
);
self.behavior.scenario = state;
match result {
Ok(()) => {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
self.status = "Choose the message exchange and apply at the highlighted sequence position.".into();
}
Err(error) => self.status = error,
}
}
CanvasEvent::Reorder {
occurrence, slot, ..
} => {
match scenario::reorder(
self.project(),
context.scenario,
occurrence,
slot,
) {
Ok(command) => {
if self.execute(command) {
self.selected = occurrence;
self.selected_node = None;
self.refresh_draft();
self.status = "Occurrence reordered within its sequence · Undo restores the previous order".into();
}
}
Err(error) => self.status = error,
}
}
_ => unreachable!(),
}
}
}
}
Message::StateDiagram(event) => return self.edit_state_diagram(event),
Message::BehaviorOwner(choice) => {
if self.apply()
@@ -1124,6 +1461,32 @@ impl App {
self.status = e;
}
}
Message::FieldAppend(path, value) => {
if let Some(draft) = &mut self.draft
&& let Err(error) = draft.append(&path, value)
{
self.status = error;
}
}
Message::FieldValueBrowse(path, scope, page) => {
if let Some(draft) = &mut self.draft
&& draft
.value
.pointer(&path)
.is_some_and(|row| row.get("expression").is_some())
{
draft
.value_browsers
.insert(path, crate::forms::ValueBrowser { scope, page });
}
}
Message::FieldValuePath(path, key) => {
if let Some(draft) = &mut self.draft
&& let Err(error) = draft.value_path(&path, key)
{
self.status = error;
}
}
Message::FieldVariant(path, value) => {
if let Some(d) = &mut self.draft {
let result = d.materialize().and_then(|current| {
@@ -1384,6 +1747,19 @@ impl App {
self.fit();
}
}
Message::Data(event) => {
if self.data_state.update(&event) {
return Task::none();
}
if self.apply() {
match crate::data_view::command(self.project(), self.layer, event) {
Ok(command) => {
self.execute(command);
}
Err(error) => self.status = error,
}
}
}
Message::CreateKind(kind) => self.create_kind = kind,
Message::Add(child) => {
if self.apply() {
@@ -2203,7 +2579,14 @@ impl App {
Err(e) => e,
};
}
Message::WindowResized(size) => self.window_size = size,
Message::WindowResized(size) => {
// The canvas can retain its capped size during a real window
// resize. Invalidate any scenario pointer/slot gesture anyway.
if self.window_size != size && self.scenario_context().is_some() {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
self.window_size = size;
}
Message::CanvasResized(size) => {
let first_measurement = self.canvas_size.is_none();
let size_changed = self.canvas_size != Some(size);
@@ -2577,8 +2960,14 @@ impl App {
.discovered(&disk.bundle, disk.reachable.clone());
self.show_source_file(false);
self.source_diagnostics = self.document.compiled().diagnostics.clone();
self.status =
"Source project opened. Included files and comments are preserved.".into();
self.migration = self.document.compiled().decoded.migration.clone();
if self.migration.is_some() {
self.status = "Imported earlier source schema. Review Model checks; Save all explicitly writes the upgraded source while retaining comments and includes.".into();
self.page = Page::Validation;
} else {
self.status =
"Source project opened. Included files and comments are preserved.".into();
}
}
Err(error) => {
self.canvas_document = Id::new_v4();
@@ -3208,7 +3597,9 @@ fn read_snapshot(path: PathBuf) -> Result<LoadedSnapshot, String> {
&& let Some(source_files::DiskExpectation::Bytes(bytes)) =
disk.expectations.get(&disk.bundle.entry)
&& let Ok(decoded) = persistence::decode_with_report_limited(bytes, LIMITS.model)
&& decoded.migration.is_some()
// Source1/2 require the historical single-document adapters.
// Source3+ must retain its authored bundle and token migration.
&& decoded.migration.as_ref().is_some_and(|report| report.from_schema <= 2)
{
return Ok(LoadedSnapshot::Legacy(
path,
@@ -3293,6 +3684,97 @@ mod source_project_tests {
Ok(())
}
#[test]
fn source3_native_open_preserves_report_comments_nesting_and_save_reopen() {
let original = include_str!("../../oa-core/tests/fixtures/v3-data-contract.arcadia");
for split in [false, true] {
let directory = Directory::new();
let path = directory.0.join("project.arcadia");
let mut authored = std::collections::BTreeMap::new();
if split {
let start = original.find("{\n").unwrap() + 2;
let end = original.rfind('}').unwrap();
authored.insert(
"project.arcadia",
format!(
"{} include \"dictionary.arcadia\";\n}}\n",
&original[..start]
),
);
authored.insert("dictionary.arcadia", original[start..end].to_owned());
} else {
authored.insert("project.arcadia", original.to_owned());
}
for (file, source) in &authored {
std::fs::write(directory.0.join(file), source).unwrap();
}
let mut app = App::with_project(Project::empty());
send(
&mut app,
Message::Loaded(Ok(Some(read_snapshot(path.clone()).unwrap()))),
);
assert_eq!(app.migration.as_ref().unwrap().from_schema, 3);
assert_eq!(app.page, Page::Validation);
assert_eq!(app.path, Some(path.clone()));
assert_eq!(app.document.bundle().files.len(), authored.len());
assert!(
app.dirty(),
"accepted source migration needs explicit saving"
);
for (file, source) in &authored {
assert_eq!(
std::fs::read_to_string(directory.0.join(file)).unwrap(),
*source
);
}
let text = app
.document
.bundle()
.files
.values()
.cloned()
.collect::<String>();
assert!(text.contains("// Reused record parameters retain their own identities."));
assert!(text.contains("// Frozen authored schema3 compatibility input."));
let packet = app
.project()
.elements
.values()
.find(|e| e.alias == "packet")
.unwrap()
.id;
let origin = app
.project()
.elements
.values()
.find(|e| e.alias == "origin")
.unwrap()
.id;
assert_eq!(
app.document.compiled().index.lexical_owners.get(&origin),
Some(&packet)
);
let before = app.document.snapshot();
save(&mut app, path.clone()).unwrap();
assert!(!app.dirty());
for (file, source) in &before.bundle.files {
assert_eq!(
std::fs::read_to_string(directory.0.join(file)).unwrap(),
*source
);
}
let mut reopened = App::with_project(Project::empty());
send(
&mut reopened,
Message::Loaded(Ok(Some(read_snapshot(path).unwrap()))),
);
assert!(reopened.migration.is_none());
assert_eq!(reopened.project(), app.project());
assert_eq!(reopened.document.bundle(), app.document.bundle());
assert!(!reopened.dirty());
}
}
fn pending_journal(directory: &Directory, before: Option<&str>) -> (PathBuf, PathBuf) {
let path = directory.0.join("project.arcadia");
let journal = directory.0.join(".arcadia-save-project.arcadia.journal");
@@ -3847,3 +4329,50 @@ mod lint_tests {
assert!(app.project().elements.is_empty());
}
}
#[cfg(test)]
mod data_paging_lifecycle_tests {
use super::*;
#[test]
fn paging_preserves_same_context_and_resets_on_layer_or_document_replacement() {
let mut p = Project::empty();
let mut oa = None;
for layer in [Layer::Oa, Layer::Sa] {
for index in 0..70 {
let id = p
.add_element(
Kind::Interface,
layer,
&format!("Interface {layer} {index}"),
None,
)
.unwrap();
if layer == Layer::Oa {
oa = Some(id);
}
}
}
let mut app = App::with_project(p.clone());
let page = Message::Data(crate::data_view::Event::Page {
section: crate::data_view::Section::Catalog,
owner: None,
page: 2,
});
let _ = app.update(Message::Page(Page::Data));
let _ = app.update(page.clone());
let retained = app.data_state.clone();
let _ = app.update(Message::Page(Page::Catalog));
let _ = app.update(Message::Page(Page::Data));
let _ = app.update(Message::Layer(Layer::Oa));
assert_eq!(app.data_state, retained);
let _ = app.update(Message::Layer(Layer::Sa));
assert_eq!(app.data_state, crate::data_view::State::default());
let _ = app.update(page.clone());
let _ = app.update(Message::Select(oa.unwrap()));
assert_eq!(app.layer, Layer::Oa);
assert_eq!(app.data_state, crate::data_view::State::default());
let _ = app.update(page);
app.reset(p, None);
assert_eq!(app.data_state, crate::data_view::State::default());
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+6 -5
View File
@@ -432,11 +432,12 @@ mod tests {
let provided = element(&mut p, Kind::Interface, Layer::Sa, "Reporting");
let required = element(&mut p, Kind::Interface, Layer::Sa, "Results");
for (interface, item) in [(provided, report), (required, result)] {
*p.elements
.get_mut(&interface)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Interface { items: vec![item] };
p.relate(
RelationKind::InterfaceItemAllocation,
"Allocated item",
interface,
item,
);
}
p.relate(
RelationKind::InterfaceProvision,
+559
View File
@@ -0,0 +1,559 @@
//! One address for a carried value, shared by scenario creation and property editing.
use oa_core::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldPathKey {
pub path: Vec<Id>,
pub field: Id,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldPathChoice {
pub key: FieldPathKey,
pub label: String,
pub picker_label: String,
}
impl std::fmt::Display for FieldPathChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.picker_label)
}
}
fn phase_allows(project: &Project, entry: &data::CarriedFieldPath, phase: &MessageKind) -> bool {
data::item_mechanism(project, entry.item) != Some(ExchangeMechanism::Operation)
|| match phase {
MessageKind::Call => matches!(
entry.direction,
ParameterDirection::Unspecified
| ParameterDirection::In
| ParameterDirection::InOut
),
MessageKind::Reply => matches!(
entry.direction,
ParameterDirection::Unspecified
| ParameterDirection::Out
| ParameterDirection::InOut
| ParameterDirection::Return
),
_ => true,
}
}
fn named_choice(project: &Project, entry: data::CarriedFieldPath) -> FieldPathChoice {
let qualified = entry
.path
.iter()
.chain(std::iter::once(&entry.field))
.map(|id| {
project
.elements
.get(id)
.map(|e| format!("{} (@{})", e.name, e.alias))
.unwrap_or_else(|| id.to_string())
})
.collect::<Vec<_>>();
let direction =
if data::item_mechanism(project, entry.item) == Some(ExchangeMechanism::Operation) {
match entry.direction {
ParameterDirection::Unspecified => " · direction unspecified — review",
ParameterDirection::In => " · In",
ParameterDirection::Out => " · Out",
ParameterDirection::InOut => " · InOut",
ParameterDirection::Return => " · Return",
}
} else {
""
};
let terminal = qualified
.last()
.expect("A field path always has a terminal");
let owner_path = qualified[..qualified.len() - 1].join(" → ");
let picker_label = format!(
"{terminal}{direction} — {}{}",
project.named(entry.item),
if owner_path.is_empty() {
String::new()
} else {
format!(" / {owner_path}")
},
);
FieldPathChoice {
key: FieldPathKey {
path: entry.path,
field: entry.field,
},
label: format!(
"{} / {}{direction}",
project.named(entry.item),
qualified.join(" → ")
),
picker_label,
}
}
// A bounded picker must expose its distinguishing field before a long path.
// Keep the full address separately for the wrapping detail text.
fn sorted_choices(mut choices: Vec<FieldPathChoice>) -> Vec<FieldPathChoice> {
choices.sort_by_cached_key(|choice| choice.picker_label.to_lowercase());
choices
}
#[cfg(test)]
pub fn choices(
project: &Project,
exchange: &Relation,
phase: &MessageKind,
) -> Result<Vec<FieldPathChoice>, String> {
Ok(sorted_choices(
data::try_carried_field_paths(project, exchange)?
.into_iter()
.filter(|entry| phase_allows(project, entry, phase))
.map(|entry| named_choice(project, entry))
.collect(),
))
}
/// Direct carried fields only: an unrelated deep branch must not prevent
/// browsing a root field. Preserve the core resolver's first carried owner.
pub fn roots(project: &Project, exchange: &Relation, phase: &MessageKind) -> Vec<FieldPathChoice> {
let mut seen = std::collections::BTreeSet::new();
sorted_choices(
exchange
.body
.items()
.iter()
.flat_map(|item| {
data::effective_fields(project, *item)
.into_iter()
.filter_map(|field| {
let SharedBody::DataField { direction, .. } = field.shared()? else {
return None;
};
Some(data::CarriedFieldPath {
item: *item,
path: vec![],
field: field.id,
direction: *direction,
})
})
})
.filter(|entry| seen.insert(entry.field))
.filter(|entry| phase_allows(project, entry, phase))
.map(|entry| named_choice(project, entry))
.collect(),
)
}
/// Browse one record at a time, including explicitly chosen recursive hops.
pub fn at_scope(
project: &Project,
exchange: &Relation,
phase: &MessageKind,
scope: Option<&FieldPathKey>,
) -> Result<Vec<FieldPathChoice>, String> {
match scope {
Some(key) => children(project, exchange, phase, key),
None => Ok(roots(project, exchange, phase)),
}
}
/// Resolve authored finite paths as well as the finite representative picker list.
/// In particular, optional recursive Value records may be traversed repeatedly.
pub fn resolve(
project: &Project,
exchange: &Relation,
phase: &MessageKind,
key: &FieldPathKey,
) -> Option<FieldPathChoice> {
data::carried_value_path(project, exchange, &key.path, key.field)
.filter(|entry| phase_allows(project, entry, phase))
.map(|entry| named_choice(project, entry))
}
pub fn parent(key: &FieldPathKey) -> Option<FieldPathKey> {
let (&field, path) = key.path.split_last()?;
Some(FieldPathKey {
path: path.to_vec(),
field,
})
}
/// Expand exactly one selected record. This keeps recursive authoring explicit
/// and finite, and never traverses Reference storage or manufactures value paths.
pub fn children(
project: &Project,
exchange: &Relation,
phase: &MessageKind,
key: &FieldPathKey,
) -> Result<Vec<FieldPathChoice>, String> {
let Some(entry) = data::carried_value_path(project, exchange, &key.path, key.field)
.filter(|entry| phase_allows(project, entry, phase))
else {
return Ok(vec![]);
};
let Some(SharedBody::DataField {
type_ref: TypeRef::Named(record),
storage: FieldStorage::Value,
..
}) = project.elements.get(&key.field).and_then(Element::shared)
else {
return Ok(vec![]);
};
if !data::is_record(project, *record) {
return Ok(vec![]);
}
if key.path.len() >= data::MAX_VALUE_PATH_DEPTH {
return Err(format!(
"A value path can contain at most {} enclosing fields.",
data::MAX_VALUE_PATH_DEPTH
));
}
let mut path = key.path.clone();
path.push(key.field);
Ok(sorted_choices(
data::effective_fields(project, *record)
.into_iter()
.map(|field| {
named_choice(
project,
data::CarriedFieldPath {
item: entry.item,
path: path.clone(),
field: field.id,
direction: entry.direction,
},
)
})
.collect(),
))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub struct Payload {
pub project: Project,
pub exchange: Id,
pub item: Id,
pub leaf: Id,
pub origin: Id,
pub destination: Id,
pub scenario: Id,
}
pub fn payload() -> Payload {
let mut p = Project::empty();
let item = p
.add_element(Kind::ExchangeItem, Layer::Oa, "Move", None)
.unwrap();
*p.elements.get_mut(&item).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem {
kind: ExchangeItemKind::Information,
mechanism: ExchangeMechanism::Operation,
supertype: None,
};
let record = p
.add_element(Kind::DataType, Layer::Oa, "Coordinate", None)
.unwrap();
*p.elements.get_mut(&record).unwrap().shared_mut().unwrap() = SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype: None },
default: None,
unit: String::new(),
};
let leaf = p
.add_element(Kind::DataField, Layer::Oa, "latitude", Some(record))
.unwrap();
let origin = p
.add_element(Kind::DataField, Layer::Oa, "origin", Some(item))
.unwrap();
let destination = p
.add_element(Kind::DataField, Layer::Oa, "destination", Some(item))
.unwrap();
for (id, type_ref, direction) in [
(leaf, TypeRef::Real, ParameterDirection::Unspecified),
(origin, TypeRef::Named(record), ParameterDirection::In),
(destination, TypeRef::Named(record), ParameterDirection::Out),
] {
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::DataField {
type_ref,
direction,
minimum: 1,
maximum: Some(1),
unit: String::new(),
storage: FieldStorage::Value,
default: None,
};
}
let source = p
.add_element(Kind::Activity, Layer::Oa, "Request", None)
.unwrap();
let target = p
.add_element(Kind::Activity, Layer::Oa, "Perform", None)
.unwrap();
let exchange = p.relate(RelationKind::Interaction, "Movement", source, target);
p.relations.get_mut(&exchange).unwrap().body = RelationBody::Interaction {
source,
target,
items: vec![item],
};
let scenario = p
.add_element(Kind::Scenario, Layer::Oa, "Conversation", None)
.unwrap();
validate_candidate(&p).unwrap();
Payload {
project: p,
exchange,
item,
leaf,
origin,
destination,
scenario,
}
}
#[test]
fn phase_choices_keep_reused_record_addresses_distinct() {
let mut f = payload();
assert_eq!(
data::item_mechanism(&f.project, f.item),
Some(ExchangeMechanism::Operation)
);
let call = choices(
&f.project,
&f.project.relations[&f.exchange],
&MessageKind::Call,
)
.unwrap();
assert!(
call.iter()
.any(|c| c.key.path == [f.origin] && c.key.field == f.leaf)
);
assert!(!call.iter().any(|c| c.key.path == [f.destination]));
let reply = choices(
&f.project,
&f.project.relations[&f.exchange],
&MessageKind::Reply,
)
.unwrap();
assert!(
reply
.iter()
.any(|c| c.key.path == [f.destination] && c.key.field == f.leaf)
);
assert!(!reply.iter().any(|c| c.key.path == [f.origin]));
if let Some(SharedBody::DataField { direction, .. }) = f
.project
.elements
.get_mut(&f.destination)
.unwrap()
.shared_mut()
{
*direction = ParameterDirection::InOut;
}
let both = choices(
&f.project,
&f.project.relations[&f.exchange],
&MessageKind::Call,
)
.unwrap();
let leaves = both
.iter()
.filter(|c| c.key.field == f.leaf)
.collect::<Vec<_>>();
assert_eq!(leaves.len(), 2);
assert_ne!(leaves[0].key, leaves[1].key);
assert_ne!(leaves[0].label, leaves[1].label);
let values = leaves
.into_iter()
.map(|c| (c.key.clone(), "1".to_string()))
.collect::<std::collections::BTreeMap<_, _>>();
assert_eq!(values.len(), 2);
}
#[test]
fn reference_parameter_stops_descent_and_unspecified_direction_remains_visible() {
let mut f = payload();
if let Some(SharedBody::DataField {
storage, direction, ..
}) = f.project.elements.get_mut(&f.origin).unwrap().shared_mut()
{
*storage = FieldStorage::Reference;
*direction = ParameterDirection::Unspecified;
}
let call = choices(
&f.project,
&f.project.relations[&f.exchange],
&MessageKind::Call,
)
.unwrap();
let direct = call.iter().find(|c| c.key.field == f.origin).unwrap();
assert!(direct.key.path.is_empty());
assert!(direct.label.contains("unspecified"));
assert!(!call.iter().any(|c| c.key.path.contains(&f.origin)));
}
pub fn recursive_payload() -> (Payload, Id) {
let mut f = payload();
let record = f.project.elements[&f.leaf].parent.unwrap();
let next = f
.project
.add_element(Kind::DataField, Layer::Oa, "next", Some(record))
.unwrap();
*f.project
.elements
.get_mut(&next)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::DataField {
type_ref: TypeRef::Named(record),
minimum: 0,
maximum: Some(1),
unit: String::new(),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
default: None,
};
validate_candidate(&f.project).unwrap();
(f, next)
}
pub fn wide_payload() -> Payload {
let mut f = payload();
let record = f.project.elements[&f.leaf].parent.unwrap();
for (owner, template, count) in [(f.item, f.origin, 95), (record, f.leaf, 127)] {
for index in 0..count {
let body = f.project.elements[&template].shared().unwrap().clone();
let id = f
.project
.add_element(
Kind::DataField,
Layer::Oa,
&format!("Field {template} {index}"),
Some(owner),
)
.unwrap();
*f.project
.elements
.get_mut(&id)
.unwrap()
.shared_mut()
.unwrap() = body;
}
}
f
}
#[test]
fn roots_and_one_hop_children_do_not_expand_unrelated_payload_branches() {
let mut f = wide_payload();
let exchange = &f.project.relations[&f.exchange];
let direct = roots(&f.project, exchange, &MessageKind::Call);
assert_eq!(direct.len(), 96);
assert!(direct.iter().all(|choice| choice.key.path.is_empty()));
let representative = choices(&f.project, exchange, &MessageKind::Call).unwrap();
assert_eq!(representative.len(), 96 * 129);
for root in &direct {
assert_eq!(
resolve(&f.project, exchange, &MessageKind::Call, &root.key),
Some(root.clone())
);
}
let nested = children(&f.project, exchange, &MessageKind::Call, &direct[0].key).unwrap();
assert_eq!(nested.len(), 128);
for child in &nested {
assert_eq!(
resolve(&f.project, exchange, &MessageKind::Call, &child.key),
Some(child.clone())
);
assert!(child.label.ends_with(" · In"));
}
// A temporarily over-limit model still exposes its unrelated root fields;
// the editor must not expand the whole graph before showing a choice.
for index in 0..32 {
let body = f.project.elements[&f.origin].shared().unwrap().clone();
let id = f
.project
.add_element(
Kind::DataField,
Layer::Oa,
&format!("Extra {index}"),
Some(f.item),
)
.unwrap();
*f.project
.elements
.get_mut(&id)
.unwrap()
.shared_mut()
.unwrap() = body;
}
let exchange = &f.project.relations[&f.exchange];
assert!(choices(&f.project, exchange, &MessageKind::Call).is_err());
assert_eq!(roots(&f.project, exchange, &MessageKind::Call).len(), 128);
assert_eq!(
children(&f.project, exchange, &MessageKind::Call, &direct[0].key)
.unwrap()
.len(),
128
);
}
#[test]
fn recursive_records_can_be_drilled_into_and_valid_imported_paths_resolve() {
let (f, next) = recursive_payload();
let exchange = &f.project.relations[&f.exchange];
let record = FieldPathKey {
path: vec![f.origin],
field: next,
};
let nested = children(&f.project, exchange, &MessageKind::Call, &record).unwrap();
let leaf = nested.iter().find(|c| c.key.field == f.leaf).unwrap();
assert_eq!(leaf.key.path, vec![f.origin, next]);
assert!(
!choices(&f.project, exchange, &MessageKind::Call)
.unwrap()
.iter()
.any(|c| c.key == leaf.key)
);
assert_eq!(
resolve(&f.project, exchange, &MessageKind::Call, &leaf.key),
Some(leaf.clone())
);
assert_eq!(parent(&leaf.key), Some(record));
let deepest = FieldPathKey {
path: std::iter::once(f.origin)
.chain(std::iter::repeat_n(next, data::MAX_VALUE_PATH_DEPTH - 1))
.collect(),
field: next,
};
assert!(resolve(&f.project, exchange, &MessageKind::Call, &deepest).is_some());
assert!(
children(&f.project, exchange, &MessageKind::Call, &deepest)
.unwrap_err()
.contains("128")
);
}
#[test]
fn recursive_picker_starts_with_distinct_leaf_names_and_sorts_them() {
let (f, next) = recursive_payload();
let exchange = &f.project.relations[&f.exchange];
let context = FieldPathKey {
path: vec![f.origin, next, next],
field: next,
};
let visible = children(&f.project, exchange, &MessageKind::Call, &context).unwrap();
let leaf = visible
.iter()
.find(|choice| choice.key.field == f.leaf)
.unwrap();
assert!(leaf.to_string().starts_with("latitude (@latitude)"));
assert!(leaf.label.contains("origin (@origin) → next (@next)"));
assert!(
visible.windows(2).all(
|pair| pair[0].to_string().to_lowercase() <= pair[1].to_string().to_lowercase()
)
);
assert_ne!(
visible[0].to_string().chars().take(24).collect::<String>(),
visible[1].to_string().chars().take(24).collect::<String>()
);
assert_eq!(
resolve(&f.project, exchange, &MessageKind::Call, &leaf.key),
Some(leaf.clone())
);
}
}
File diff suppressed because it is too large Load Diff
+181 -1
View File
@@ -292,6 +292,7 @@ impl DiagramCanvas<'_> {
request.placement = Some(node);
} else if let Some(edge) = self
.hit_label(&scene.routed, local)
.or_else(|| self.hit_association_label(&scene.routed, local))
.or_else(|| self.hit_edge(&scene.routed, local).map(|(id, _)| id))
{
request.object = edge;
@@ -369,6 +370,33 @@ impl DiagramCanvas<'_> {
})
.map(|edge| edge.id)
}
fn hit_association_label(&self, routed: &RoutedView, p: Point) -> Option<Id> {
let p = self.world(p);
routed
.edges
.values()
.flat_map(|edge| {
self.project
.relations
.get(&edge.id)
.into_iter()
.flat_map(move |relation| routing::association_end_geometry(relation, edge))
.map(move |end| (edge.id, end.label))
})
.filter(|(_, label)| {
Rectangle::new(
point(label.bounds.position),
Size::new(label.bounds.size.width, label.bounds.size.height),
)
.contains(p)
})
.min_by(|a, b| {
p.distance(point(a.1.center))
.total_cmp(&p.distance(point(b.1.center)))
.then(a.0.cmp(&b.0))
})
.map(|(id, _)| id)
}
fn preview_diagram(&self, state: &State) -> Diagram {
let mut diagram = self.project.diagrams[&self.diagram].clone();
if let (Some((id, _, original)), Some(preview)) = (state.drag, state.preview) {
@@ -725,7 +753,10 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
state.drag = Some((id, p, position));
state.preview = Some(position);
Some(Action::publish(Message::SelectNode(id)).and_capture())
} else if let Some(id) = self.hit_label(&scene.routed, p) {
} else if let Some(id) = self
.hit_label(&scene.routed, p)
.or_else(|| self.hit_association_label(&scene.routed, p))
{
Some(Action::publish(Message::Select(id)).and_capture())
} else if let Some((id, segment)) = self.hit_edge(&scene.routed, p) {
if id == self.selected
@@ -1010,6 +1041,37 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
..Default::default()
});
}
if let Some(relation) = self.project.relations.get(&edge.id) {
for end in routing::association_end_geometry(relation, routed) {
if end.navigable {
let [a, tip, b] = navigation_mark(end.tip, end.inward);
f.stroke(
&Path::new(|p| {
p.move_to(a);
p.line_to(tip);
p.line_to(b);
}),
Stroke::default().with_color(color).with_width(1.7),
);
}
let label = &end.label;
f.fill_rectangle(
point(label.bounds.position),
Size::new(label.bounds.size.width, label.bounds.size.height),
Color::WHITE,
);
f.fill_text(Text {
content: label.text.clone(),
position: point(label.center),
color: if active { style::TEAL } else { style::MUTED },
size: 13.into(),
align_x: iced::widget::text::Alignment::Center,
align_y: iced::alignment::Vertical::Center,
max_width: f32::INFINITY,
..Default::default()
});
}
}
}
for n in &view.nodes {
if !containers.contains(&n.id) {
@@ -1257,6 +1319,17 @@ fn endpoint_position(view: &ProjectedView, id: Id) -> Option<Position> {
})
})
}
fn navigation_mark(tip: Position, inward: Position) -> [Point; 3] {
let tip = point(tip);
let delta = point(inward) - tip;
let direction = delta / delta.x.hypot(delta.y).max(0.001);
let normal = Vector::new(-direction.y, direction.x) * 4.;
[
tip + direction * 9. + normal,
tip,
tip + direction * 9. - normal,
]
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PortGlyph {
Function,
@@ -1544,6 +1617,21 @@ pub fn export_svg(p: &Project, diagram: Id) -> String {
if !label.text.is_empty() {
svg.push_str(&format!("<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"white\"/><text x=\"{}\" y=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\" font-family=\"sans-serif\" font-size=\"13\" fill=\"#637487\">{}</text>",label.bounds.position.x,label.bounds.position.y,label.bounds.size.width,label.bounds.size.height,label.center.x,label.center.y,escape(&label.text)));
}
if let Some(relation) = p.relations.get(&edge.id) {
for end in routing::association_end_geometry(relation, route) {
let side = if end.source_end { "source" } else { "target" };
svg.push_str(&format!(
"<g data-association=\"{}\" data-end=\"{side}\">",
edge.id
));
if end.navigable {
let [a, tip, b] = navigation_mark(end.tip, end.inward);
svg.push_str(&format!("<path data-navigation=\"{side}\" d=\"M {} {} L {} {} L {} {}\" fill=\"none\" stroke=\"#8999a9\" stroke-width=\"1.7\"/>",a.x,a.y,tip.x,tip.y,b.x,b.y));
}
let label = &end.label;
svg.push_str(&format!("<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"white\"/><text x=\"{}\" y=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\" font-family=\"sans-serif\" font-size=\"13\" fill=\"#637487\">{}</text></g>",label.bounds.position.x,label.bounds.position.y,label.bounds.size.width,label.bounds.size.height,label.center.x,label.center.y,escape(&label.text)));
}
}
}
for n in &view.nodes {
if !containers.contains(&n.id) {
@@ -2353,6 +2441,98 @@ mod tests {
assert!(geometry.bounds.position.y <= route.label.bounds.position.y);
}
#[test]
fn association_end_contracts_share_svg_geometry_and_select_without_moving_name_label() {
for self_loop in [false, true] {
let mut p = Project::empty();
let a = p.add(Kind::DataType, "Tree", 100., 100.);
let b = if self_loop {
a
} else {
p.add(Kind::DataType, "Branch", 650., 100.)
};
for id in BTreeSet::from([a, b]) {
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype: None },
default: None,
unit: String::new(),
};
}
let edge = p.relate(RelationKind::DataAssociation, "Hierarchy", a, b);
p.relations.get_mut(&edge).unwrap().body = RelationBody::DataAssociation {
source: a,
target: b,
source_role: "parent".into(),
target_role: "children".into(),
source_minimum: 0,
source_maximum: Some(1),
target_minimum: 0,
target_maximum: None,
source_navigable: false,
target_navigable: true,
};
let diagram = p.ensure_diagram(Layer::Oa);
let projected = project_view(&p, diagram);
assert!(
!projected
.edges
.iter()
.find(|e| e.id == edge)
.unwrap()
.oriented
);
let routed = route_diagram(&p, &p.diagrams[&diagram], &projected);
let ends = routing::association_end_geometry(&p.relations[&edge], &routed.edges[&edge]);
assert_eq!(ends.len(), 2);
let svg = export_svg(&p, diagram);
assert!(svg.contains("parent [0..1]</text>"));
assert!(svg.contains("children [0..*]</text>"));
assert!(!svg.contains("data-navigation=\"source\""));
assert!(svg.contains("data-navigation=\"target\""));
let mut canvas = DiagramCanvas {
project: &p,
diagram,
selected: edge,
zoom: 0.7,
pan: Vector::new(350., 350.),
context: Context {
document: p.id,
diagram,
revision: 0,
epoch: 0,
},
selected_bend: None,
editable: true,
connection: None,
};
for end in ends {
assert!(svg.contains(&format!(
"x=\"{}\" y=\"{}\" text-anchor",
end.label.center.x, end.label.center.y
)));
let at = Point::new(
end.label.center.x * canvas.zoom + canvas.pan.x,
end.label.center.y * canvas.zoom + canvas.pan.y,
);
let mut state = State::default();
assert_eq!(canvas.hit_association_label(&routed, at), Some(edge));
assert!(
matches!(pointer(&canvas,&mut state,mouse::Event::ButtonPressed(mouse::Button::Left),at),Some(Message::Select(id)) if id==edge)
);
assert!(
state.route_drag.is_none(),
"Endpoint contract labels never drag the association name"
);
assert_eq!(
canvas
.context_request(&state, at, Rectangle::with_size(Size::new(1800., 1200.)))
.object,
edge
);
canvas.selected = p.id;
}
}
}
#[test]
fn detached_label_selects_connection_and_occluding_card_owns_its_hit() {
let (mut p, diagram, edge) = route_fixture();
p.diagrams.get_mut(&diagram).unwrap().routes[0].label = Some(EdgeLabel {
+142 -13
View File
@@ -14,6 +14,7 @@ use iced::{
use oa_core::*;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
mod data_fields;
mod port_fields;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -31,6 +32,12 @@ pub struct Input {
pub raw: String,
pub editor: text_editor::Content,
}
#[derive(Clone, Default)]
pub struct ValueBrowser {
pub scope: Option<crate::data_values::FieldPathKey>,
pub page: usize,
}
pub struct Draft {
pub kind: RecordKind,
pub original: Id,
@@ -39,6 +46,7 @@ pub struct Draft {
pub inputs: BTreeMap<String, Input>,
pub exact_strings: bool,
port_contract_drafts: BTreeMap<String, Value>,
pub value_browsers: BTreeMap<String, ValueBrowser>,
}
impl Draft {
@@ -76,11 +84,14 @@ impl Draft {
inputs: BTreeMap::new(),
exact_strings: false,
port_contract_drafts: BTreeMap::new(),
value_browsers: BTreeMap::new(),
};
draft.rebuild();
Some(draft)
}
fn rebuild(&mut self) {
// Array/variant edits can change the meaning of a row path.
self.value_browsers.clear();
self.inputs.clear();
fn visit(value: &Value, path: &str, out: &mut BTreeMap<String, Input>) {
match value {
@@ -218,7 +229,7 @@ impl Draft {
} else if path.ends_with("bindings") {
json!({"referenced": Id::nil(), "local": Id::nil()})
} else if path.ends_with("values") {
json!({"field": Id::nil(), "expression": ""})
json!({"path": [], "field": Id::nil(), "expression": ""})
} else if path.ends_with("routes") {
json!({"edge": Id::nil(), "waypoints": [], "label": null})
} else if path.ends_with("waypoints") {
@@ -242,6 +253,33 @@ impl Draft {
self.rebuild();
Ok(())
}
pub fn append(&mut self, path: &str, value: Value) -> Result<(), String> {
let mut candidate = self.materialize()?;
candidate
.pointer_mut(path)
.and_then(Value::as_array_mut)
.ok_or("List no longer exists.")?
.push(value);
self.value = candidate;
self.rebuild();
Ok(())
}
pub fn value_path(
&mut self,
path: &str,
key: crate::data_values::FieldPathKey,
) -> Result<(), String> {
let mut candidate = self.materialize()?;
let row = candidate
.pointer_mut(path)
.and_then(Value::as_object_mut)
.ok_or("Message value no longer exists.")?;
row.insert("path".into(), json!(key.path));
row.insert("field".into(), json!(key.field));
self.value = candidate;
self.rebuild();
Ok(())
}
pub fn command(&self) -> Result<Command, String> {
let mut value = self.materialize()?;
let decode = |e: serde_json::Error| e.to_string();
@@ -411,6 +449,7 @@ fn reference(path: &str) -> bool {
| "Named"
| "diagram"
| "machine"
| "supertype"
) || matches!(
parent,
"items"
@@ -440,6 +479,7 @@ fn optional_reference(path: &str) -> bool {
| "reply_to"
| "lifeline"
| "state"
| "supertype"
)
}
fn multiline(path: &str) -> bool {
@@ -462,9 +502,11 @@ fn free_string(path: &str) -> bool {
multiline(path)
|| matches!(
path.rsplit('/').next(),
Some("name" | "uri" | "revision" | "fragment" | "unit")
Some("name" | "uri" | "revision" | "fragment" | "unit" | "source_role" | "target_role")
)
|| path.split('/').rev().nth(1) == Some("literals")
|| (path.contains("/default/")
&& matches!(path.rsplit('/').next(), Some("String" | "Enumeration")))
}
// These are choices for the closed model, not a second validation boundary.
@@ -662,21 +704,42 @@ fn reference_ids(draft: &Draft, project: &Project, path: &str) -> Vec<Id> {
.collect();
}
if field == "field" {
let address_path = path
.strip_suffix("/field")
.and_then(|row| value.pointer(&format!("{row}/path")))
.and_then(|v| serde_json::from_value::<Vec<Id>>(v.clone()).ok())
.unwrap_or_default();
return element
.as_ref()
.and_then(|e| match e.shared()? {
SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
exchange: Some(id), ..
exchange: Some(id),
message_kind,
..
},
..
} => project.relations.get(id),
} => project.relations.get(id).and_then(|r| {
let scope = address_path.split_last().map(|(&field, path)| {
crate::data_values::FieldPathKey {
path: path.to_vec(),
field,
}
});
crate::data_values::at_scope(project, r, message_kind, scope.as_ref()).ok()
}),
_ => None,
})
.map(|r| validation::carried_fields(project, r).into_iter().collect())
.unwrap_or_default();
.unwrap_or_default()
.into_iter()
.filter(|choice| choice.key.path == address_path)
.map(|choice| choice.key.field)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
}
let scenario = element
.as_ref()
.and_then(|e| e.parent)
@@ -707,6 +770,40 @@ fn reference_ids(draft: &Draft, project: &Project, path: &str) -> Vec<Id> {
return false;
}
match field {
"supertype" => element.as_ref().is_some_and(|owner| {
if candidate.id == owner.id
|| candidate.kind() != owner.kind()
|| (candidate.kind() == Kind::DataType
&& !data::is_record(project, candidate.id))
{
return false;
}
if let (
Some(SharedBody::ExchangeItem {
kind, mechanism, ..
}),
Some(SharedBody::ExchangeItem {
kind: base_kind,
mechanism: base_mechanism,
..
}),
) = (owner.shared(), candidate.shared())
&& (kind != base_kind
|| (*base_mechanism != ExchangeMechanism::Unspecified
&& mechanism != base_mechanism))
{
return false;
}
let mut next = Some(candidate.id);
let mut seen = BTreeSet::new();
while let Some(id) = next {
if id == owner.id || !seen.insert(id) {
return false;
}
next = project.elements.get(&id).and_then(data::supertype);
}
true
}),
"machine" => candidate.kind() == Kind::StateMachine,
"parent" => element.as_ref().is_some_and(|child| {
if candidate.id == draft.original
@@ -1058,6 +1155,20 @@ fn variants(path: &str, value: &Value, kind: RecordKind) -> Vec<(String, Value)>
let words: &[&str] = match field {
"side" if path.starts_with("/port_anchors/") => &["Left", "Right", "Top", "Bottom"],
"layer" => &["Oa", "Sa"],
"mechanism" => &["Unspecified", "Flow", "Event", "Operation", "SharedData"],
"storage" => &["Value", "Reference"],
"direction" if path.contains("DataField") => {
&["Unspecified", "In", "Out", "InOut", "Return"]
}
"transmission" => &[
"Unspecified",
"Synchronous",
"Asynchronous",
"Unicast",
"Multicast",
"Broadcast",
],
"acquisition" => &["Unspecified", "Read", "Accept"],
"operator" => &["Alternative", "Parallel", "Loop", "Optional"],
"viewpoint" if path.contains("/Oa/") => &[
"OperationalActivity",
@@ -1066,7 +1177,7 @@ fn variants(path: &str, value: &Value, kind: RecordKind) -> Vec<(String, Value)>
],
"viewpoint" => &["Functional", "BoundaryInterface", "MixedLegacy"],
"phase" => &["Entry", "Do", "Exit"],
"kind" if path.contains("ExchangeItem") => &["Information", "Material", "Energy", "Event"],
"kind" if path.contains("ExchangeItem") => &["Information", "Material", "Energy"],
"kind" if path.contains("Control") => &["Choice", "Merge", "Fork", "Join", "Loop"],
"kind" if path.contains("State") => &[
"State",
@@ -1132,11 +1243,20 @@ fn variants(path: &str, value: &Value, kind: RecordKind) -> Vec<(String, Value)>
if field == "definition" {
return vec![
("Boolean".into(), json!("Boolean")),
("Integer".into(), json!("Integer")),
("Real".into(), json!("Real")),
("Text".into(), json!("String")),
(
"Integer".into(),
json!({"Integer":{"minimum":null,"maximum":null}}),
),
(
"Real".into(),
json!({"Real":{"minimum":null,"maximum":null}}),
),
(
"Text".into(),
json!({"String":{"minimum_length":0,"maximum_length":null}}),
),
("Enumeration".into(), json!({"Enumeration":{"literals":[]}})),
("Record".into(), json!("Record")),
("Record".into(), json!({"Record":{"supertype":null}})),
];
}
if field == "type_ref" {
@@ -1273,6 +1393,9 @@ fn property<'a>(
label: &str,
skip_variant: bool,
) -> View<'a, Message> {
if let Some(view) = data_fields::property(draft, project, value, path) {
return view;
}
let label_view = || text(label.to_owned()).size(11).color(style::MUTED);
if path.ends_with("/Port/legacy") {
let mut content = column![].spacing(4);
@@ -2075,6 +2198,8 @@ mod tests {
Layer::Oa,
SharedBody::ExchangeItem {
kind: ExchangeItemKind::Energy,
mechanism: ExchangeMechanism::Flow,
supertype: None,
},
);
let mut draft = Draft::from_project(&p, item).unwrap();
@@ -2091,8 +2216,12 @@ mod tests {
let interface = p
.add_element(Kind::Interface, Layer::Oa, "Power contract", None)
.unwrap();
p.elements.get_mut(&interface).unwrap().body =
ElementBody::shared_in(Layer::Oa, SharedBody::Interface { items: vec![item] });
p.relate(
RelationKind::InterfaceItemAllocation,
"Allocated item",
interface,
item,
);
assert!(execute_batch(&p, &[draft.command().unwrap()]).is_err());
assert!(draft.dirty());
assert_eq!(p.elements[&item].layer(), Layer::Oa);
+813
View File
@@ -0,0 +1,813 @@
//! Typed data contracts use the same draft and command boundary as other properties.
use super::*;
use iced::widget::column;
fn element(draft: &Draft, project: &Project) -> Option<Element> {
serde_json::from_value(draft.materialize().unwrap_or_else(|_| draft.value.clone()))
.ok()
.or_else(|| project.elements.get(&draft.original).cloned())
}
fn definition(project: &Project, reference: &TypeRef) -> Option<DataTypeDefinition> {
Some(match reference {
TypeRef::Boolean => DataTypeDefinition::Boolean,
TypeRef::Integer => DataTypeDefinition::Integer {
minimum: None,
maximum: None,
},
TypeRef::Real => DataTypeDefinition::Real {
minimum: None,
maximum: None,
},
TypeRef::String => DataTypeDefinition::String {
minimum_length: 0,
maximum_length: None,
},
TypeRef::Named(id) => match project.elements.get(id)?.shared()? {
SharedBody::DataType { definition, .. } => definition.clone(),
_ => return None,
},
})
}
fn literal(definition: &DataTypeDefinition) -> Option<Value> {
Some(match definition {
DataTypeDefinition::Boolean => json!({"Boolean": false}),
DataTypeDefinition::Integer { minimum, .. } => json!({"Integer": minimum.unwrap_or(0)}),
DataTypeDefinition::Real { minimum, .. } => json!({"Real": minimum.unwrap_or(0.)}),
DataTypeDefinition::String { .. } => json!({"String": ""}),
DataTypeDefinition::Enumeration { literals } => json!({"Enumeration": literals.first()?}),
DataTypeDefinition::Record { .. } => return None,
})
}
pub(super) fn property<'a>(
draft: &'a Draft,
project: &'a Project,
value: &'a Value,
path: &str,
) -> Option<View<'a, Message>> {
if path.split('/').rev().nth(1) == Some("values") && value.is_object() {
return Some(message_value(draft, project, value, path));
}
let leaf = path.rsplit('/').next()?;
if leaf == "direction" && path.contains("/DataField/") {
let operation = element(draft, project)
.and_then(|e| e.parent)
.and_then(|id| data::item_mechanism(project, id))
== Some(ExchangeMechanism::Operation);
if !operation {
let mut out = column![
text("Parameter direction").size(11).color(style::MUTED),
text("Unspecified · direction applies to direct Operation parameters.").size(11)
]
.spacing(5);
if value.as_str() != Some("Unspecified") {
out = out
.push(
text(format!(
"Current {:?} requires review.",
value.as_str().unwrap_or_default()
))
.size(11),
)
.push(
button(text("Use Unspecified").size(11))
.style(style::nav)
.on_press(Message::FieldShape(path.into(), json!("Unspecified"))),
);
}
return Some(out.into());
}
}
let bounded = (path.contains("/definition/Integer/") || path.contains("/definition/Real/"))
&& matches!(leaf, "minimum" | "maximum");
let count_max = matches!(leaf, "maximum_length" | "source_maximum" | "target_maximum")
|| (leaf == "maximum" && path.contains("/DataField/"));
if bounded || count_max {
let label = match leaf {
"minimum" => "Inclusive lower bound",
"maximum" if bounded => "Inclusive upper bound",
"maximum_length" => "Maximum Unicode characters",
"source_maximum" => "Source maximum count",
"target_maximum" => "Target maximum count",
_ => "Maximum count",
};
let mut out = column![text(label).size(11).color(style::MUTED)].spacing(5);
if value.is_null() {
out = out.push(
button(
text(if bounded {
"Unbounded · set bound"
} else {
"Unlimited · set maximum"
})
.size(12),
)
.style(style::nav)
.on_press(Message::FieldShape(
path.into(),
if path.contains("/Real/") {
json!(0.)
} else if count_max {
let minimum_path = path.replace("maximum", "minimum");
json!(
draft
.materialize()
.ok()
.and_then(|v| v.pointer(&minimum_path).and_then(Value::as_u64))
.unwrap_or(1)
.max(1)
)
} else {
json!(0)
},
)),
);
} else if let Some(input) = draft.inputs.get(path) {
let owned = path.to_owned();
out = out
.push(
text_input("", &input.raw)
.on_input(move |s| Message::Field(owned.clone(), s))
.size(12)
.padding(8),
)
.push(
button(text("Clear bound").size(10))
.style(style::nav)
.on_press(Message::FieldShape(path.into(), Value::Null)),
);
}
return Some(out.into());
}
if leaf == "default" && (path.contains("/DataField/") || path.contains("/DataType/")) {
let owner = element(draft, project);
let (definition, collection, reference, minimum) =
match owner.as_ref().and_then(Element::shared) {
Some(SharedBody::DataType { definition, .. }) => {
(Some(definition.clone()), false, false, 0)
}
Some(SharedBody::DataField {
type_ref,
storage,
minimum,
..
}) => (
definition(project, type_ref),
true,
*storage == FieldStorage::Reference,
*minimum,
),
_ => (None, false, false, 0),
};
let initial = definition.as_ref().and_then(literal);
let mut out = column![text("Default").size(11).color(style::MUTED)].spacing(6);
if reference {
out = out.push(
text("References have no literal default; they identify an existing record.")
.size(11)
.color(style::MUTED),
);
}
if value.is_null() {
out = out.push(text("Absent · no authored default").size(12));
if !reference {
if let Some(initial) = initial {
out = out.push(
button(text("Set literal default").size(11))
.style(style::nav)
.on_press(Message::FieldShape(
path.into(),
if collection {
json!([initial])
} else {
initial
},
)),
);
}
if collection && minimum == 0 {
out = out.push(
button(text("Set explicit empty collection").size(11))
.style(style::nav)
.on_press(Message::FieldShape(path.into(), json!([]))),
);
}
}
} else {
out = out.push(
button(text("Clear default · make absent").size(11))
.style(style::nav)
.on_press(Message::FieldShape(path.into(), Value::Null)),
);
if let Some(values) = value.as_array() {
if values.is_empty() {
out = out.push(text("Explicit empty collection []").size(12));
}
for (i, value) in values.iter().enumerate() {
out = out
.push(literal_editor(
draft,
project,
value,
&format!("{path}/{i}"),
definition.as_ref(),
))
.push(
button(text("Remove value").size(10))
.style(style::nav)
.on_press(Message::FieldArray(path.into(), Some(i), 0)),
);
}
if let Some(initial) = initial
&& !reference
{
out = out.push(
button(text("+ Add literal").size(11))
.style(style::nav)
.on_press(Message::FieldAppend(path.into(), initial)),
);
}
} else {
out = out.push(literal_editor(
draft,
project,
value,
path,
definition.as_ref(),
));
}
}
return Some(out.into());
}
None
}
fn literal_editor<'a>(
draft: &'a Draft,
project: &'a Project,
value: &'a Value,
path: &str,
definition: Option<&DataTypeDefinition>,
) -> View<'a, Message> {
if let Some(DataTypeDefinition::Enumeration { literals }) = definition {
let current = draft
.materialize()
.ok()
.and_then(|v| {
v.pointer(&format!("{path}/Enumeration"))
.and_then(Value::as_str)
.map(str::to_owned)
})
.or_else(|| {
value
.get("Enumeration")
.and_then(Value::as_str)
.map(str::to_owned)
});
let mut choices = literals.clone();
if let Some(current) = &current
&& !choices.contains(current)
{
choices.push(current.clone());
}
let path = path.to_owned();
let picker = pick_list(choices, current, move |s| {
Message::FieldShape(path.clone(), json!({"Enumeration": s}))
})
.text_size(12)
.padding(8)
.width(Fill);
return if value.get("Enumeration").is_none() {
column![text("Current default uses another literal type. Choose an enumeration literal or clear the default.").size(11).color(style::MUTED),picker].spacing(5).into()
} else {
picker.into()
};
}
let mut out = column![].spacing(5);
if let Some(fields) = value.as_object() {
for (tag, payload) in fields {
out = out.push(super::property(
draft,
project,
payload,
&format!("{path}/{tag}"),
&friendly(tag),
true,
));
}
} else {
out = out.push(
text("Current literal requires review; clear it to choose a typed value.").size(11),
);
}
out.into()
}
fn message_value<'a>(
draft: &'a Draft,
project: &'a Project,
value: &'a Value,
path: &str,
) -> View<'a, Message> {
let edited = draft.materialize().unwrap_or_else(|_| draft.value.clone());
let row = edited.pointer(path).unwrap_or(value).clone();
let current = serde_json::from_value::<MessageValue>(row.clone()).ok();
let owner = element(draft, project);
let context = owner
.as_ref()
.and_then(Element::shared)
.and_then(|body| match body {
SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
exchange: Some(id),
message_kind,
..
},
..
} => project.relations.get(id).map(|r| (r, message_kind)),
_ => None,
});
let current_key = current
.as_ref()
.map(|value| crate::data_values::FieldPathKey {
path: value.path.clone(),
field: value.field,
});
let selected = context.and_then(|(exchange, phase)| {
current_key
.as_ref()
.and_then(|key| crate::data_values::resolve(project, exchange, phase, key))
});
let browser = draft
.value_browsers
.get(path)
.cloned()
.unwrap_or_else(|| ValueBrowser {
scope: selected
.as_ref()
.and_then(|choice| crate::data_values::parent(&choice.key)),
page: 0,
});
let mut out = column![text("Qualified carried field").size(11).color(style::MUTED)].spacing(6);
if let Some(choice) = &selected {
out = out.push(text(choice.label.clone()).size(11));
} else if let Some(key) = &current_key
&& !key.field.is_nil()
{
out = out.push(
text(format!(
"Current address needs review: {} / {}. Choose an explicit field.",
key.path
.iter()
.map(|id| project.named(*id))
.collect::<Vec<_>>()
.join(" → "),
project.named(key.field)
))
.size(11)
.color(style::MUTED),
);
}
if let Some((exchange, phase)) = context {
let location = browser
.scope
.as_ref()
.and_then(|key| crate::data_values::resolve(project, exchange, phase, key))
.map(|choice| choice.label)
.unwrap_or_else(|| "Root carried fields".into());
out = out.push(
text(format!("Browse: {location}"))
.size(11)
.color(style::MUTED),
);
if let Some(scope) = &browser.scope {
let mut navigation = row![button(text("↑ Up").size(11)).style(style::nav).on_press(
Message::FieldValueBrowse(path.into(), crate::data_values::parent(scope), 0)
)]
.spacing(4);
if !scope.path.is_empty() {
navigation = navigation.push(
button(text("Root fields").size(11))
.style(style::nav)
.on_press(Message::FieldValueBrowse(path.into(), None, 0)),
);
}
out = out.push(navigation);
}
match crate::data_values::at_scope(project, exchange, phase, browser.scope.as_ref()) {
Ok(choices) => {
let count = choices.len();
let (visible, page, pages) = field_page(choices, browser.page);
// Selection detail stays visible independently of browser location/page.
let visible_selection = selected
.clone()
.filter(|choice| visible.iter().any(|c| c.key == choice.key));
let owned = path.to_owned();
out = out.push(
pick_list(visible, visible_selection, move |choice| {
Message::FieldValuePath(owned.clone(), choice.key)
})
.placeholder("Choose a field here…")
.text_size(12)
.padding(8)
.width(Fill),
);
if pages > 1 {
out = out.push(
row![
button(text("Previous").size(11))
.style(style::nav)
.on_press_maybe((page > 0).then(|| Message::FieldValueBrowse(
path.into(),
browser.scope.clone(),
page - 1
))),
text(format!("{} / {pages} · {count} fields", page + 1)).size(11),
button(text("Next").size(11))
.style(style::nav)
.on_press_maybe((page + 1 < pages).then(|| {
Message::FieldValueBrowse(
path.into(),
browser.scope.clone(),
page + 1,
)
}))
]
.spacing(4)
.align_y(iced::Alignment::Center),
);
} else if count == 0 {
out = out.push(
text("No compatible fields at this location.")
.size(11)
.color(style::MUTED),
);
}
}
Err(error) => out = out.push(text(error).size(11).color(style::MUTED)),
}
if let Some(choice) = &selected
&& browser.scope.as_ref() != Some(&choice.key)
&& crate::data_values::children(project, exchange, phase, &choice.key)
.is_ok_and(|children| !children.is_empty())
{
out = out.push(
button(
text(format!(
"Browse fields in {} →",
project.named(choice.key.field)
))
.size(11),
)
.style(style::nav)
.on_press(Message::FieldValueBrowse(
path.into(),
Some(choice.key.clone()),
0,
)),
);
}
} else {
out = out.push(
text("Choose a message exchange to browse its carried fields.")
.size(11)
.color(style::MUTED),
);
}
if let Some(expression) = value.get("expression") {
out = out.push(super::property(
draft,
project,
expression,
&format!("{path}/expression"),
"Value expression",
false,
));
}
out.into()
}
const FIELDS_PER_PAGE: usize = 24;
fn field_page(
choices: Vec<crate::data_values::FieldPathChoice>,
requested: usize,
) -> (Vec<crate::data_values::FieldPathChoice>, usize, usize) {
let pages = choices.len().div_ceil(FIELDS_PER_PAGE).max(1);
let page = requested.min(pages - 1);
(
choices
.into_iter()
.skip(page * FIELDS_PER_PAGE)
.take(FIELDS_PER_PAGE)
.collect(),
page,
pages,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selecting_qualified_path_preserves_expression_typed_before_the_next_render() {
let (mut f, next) = crate::data_values::tests::recursive_payload();
if let Some(SharedBody::DataField { direction, .. }) = f
.project
.elements
.get_mut(&f.destination)
.unwrap()
.shared_mut()
{
*direction = ParameterDirection::InOut;
}
let call = f
.project
.add_element(Kind::Occurrence, Layer::Oa, "Call", Some(f.scenario))
.unwrap();
*f.project
.elements
.get_mut(&call)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange: Some(f.exchange),
sender: None,
receiver: None,
message_kind: MessageKind::Call,
reply_to: None,
values: vec![MessageValue {
path: vec![f.origin],
field: f.leaf,
expression: "old".into(),
}],
},
precondition: String::new(),
postcondition: String::new(),
};
f.project
.elements
.get_mut(&f.scenario)
.unwrap()
.steps_mut()
.unwrap()
.push(call);
let mut app = crate::app::App::with_project(f.project.clone());
let path = "/body/Oa/Shared/Occurrence/body/Exchange/values/0";
let _ = app.update(Message::Select(call));
let _ = app.update(Message::Field(
format!("{path}/expression"),
"newly typed".into(),
));
let before_browse = app.draft.as_ref().unwrap().materialize().unwrap();
for (scope, page) in [
(None, 0),
(
Some(crate::data_values::FieldPathKey {
path: vec![f.origin],
field: next,
}),
999,
),
] {
let _ = app.update(Message::FieldValueBrowse(path.into(), scope, page));
let _ = super::super::view(app.draft.as_ref().unwrap(), app.project());
assert_eq!(
app.draft.as_ref().unwrap().materialize().unwrap(),
before_browse
);
assert_eq!(app.project(), &f.project);
}
let _ = app.update(Message::FieldValuePath(
path.into(),
crate::data_values::FieldPathKey {
path: vec![f.destination],
field: f.leaf,
},
));
let _ = app.update(Message::Apply);
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = app.project().elements[&call].shared()
else {
panic!()
};
assert_eq!(
values,
&vec![MessageValue {
path: vec![f.destination],
field: f.leaf,
expression: "newly typed".into()
}],
"{}",
app.status
);
let _ = app.update(Message::Undo);
assert_eq!(app.project(), &f.project);
let nested = crate::data_values::children(
app.project(),
&app.project().relations[&f.exchange],
&MessageKind::Call,
&crate::data_values::FieldPathKey {
path: vec![f.origin],
field: next,
},
)
.unwrap()
.into_iter()
.find(|c| c.key.field == f.leaf)
.unwrap();
let _ = app.update(Message::Select(call));
let _ = app.update(Message::FieldValuePath(path.into(), nested.key.clone()));
let _ = app.update(Message::Apply);
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = app.project().elements[&call].shared()
else {
panic!()
};
assert_eq!(values[0].path, vec![f.origin, next], "{}", app.status);
assert!(
crate::data_values::resolve(
app.project(),
&app.project().relations[&f.exchange],
&MessageKind::Call,
&nested.key
)
.is_some()
);
let _ = super::super::view(app.draft.as_ref().unwrap(), app.project());
}
#[test]
fn field_browser_pages_every_direct_field_without_flattening_other_records() {
let f = crate::data_values::tests::wide_payload();
let exchange = &f.project.relations[&f.exchange];
let roots =
crate::data_values::at_scope(&f.project, exchange, &MessageKind::Call, None).unwrap();
assert!(roots.len() > FIELDS_PER_PAGE);
assert!(roots.iter().all(|choice| choice.key.path.is_empty()));
let scope = crate::data_values::FieldPathKey {
path: vec![],
field: f.origin,
};
let children =
crate::data_values::at_scope(&f.project, exchange, &MessageKind::Call, Some(&scope))
.unwrap();
assert!(children.len() > FIELDS_PER_PAGE);
assert!(
children
.iter()
.all(|choice| choice.key.path == vec![f.origin])
);
for choices in [roots, children] {
let (_, _, pages) = field_page(choices.clone(), 0);
let visited: Vec<_> = (0..pages)
.flat_map(|page| {
let (visible, actual, _) = field_page(choices.clone(), page);
assert_eq!(actual, page);
assert!(visible.len() <= FIELDS_PER_PAGE);
visible
})
.collect();
assert_eq!(visited, choices);
assert_eq!(field_page(choices, usize::MAX).1, pages - 1);
}
assert_eq!(field_page(vec![], usize::MAX), (vec![], 0, 1));
}
#[test]
fn numeric_bound_drafts_keep_partial_and_full_precision_values_out_of_accepted_state() {
let mut p = Project::empty();
let id = p
.add_element(Kind::DataType, Layer::Oa, "Counter", None)
.unwrap();
let mut draft = Draft::from_project(&p, id).unwrap();
let definition = "/body/Oa/Shared/DataType/definition";
draft
.shape(
definition,
json!({"Integer":{"minimum":null,"maximum":i64::MAX}}),
)
.unwrap();
let maximum = format!("{definition}/Integer/maximum");
draft.input(&maximum, "-".into());
assert!(draft.command().is_err());
assert!(draft.shape(&maximum, Value::Null).is_err());
assert_eq!(draft.inputs[&maximum].raw, "-");
draft.input(&maximum, "9223372036854775808".into());
assert!(draft.command().is_err());
draft.input(&maximum, i64::MAX.to_string());
draft
.shape(
"/body/Oa/Shared/DataType/default",
json!({"Integer":i64::MAX}),
)
.unwrap();
let accepted = execute_batch(&p, &[draft.command().unwrap()]).unwrap();
assert!(matches!(
accepted.elements[&id].shared(),
Some(SharedBody::DataType {
definition: DataTypeDefinition::Integer {
maximum: Some(i64::MAX),
..
},
default: Some(DataValue::Integer(i64::MAX)),
..
})
));
draft.input(&maximum, "10".into());
assert!(execute_batch(&accepted, &[draft.command().unwrap()]).is_err());
assert_eq!(draft.inputs[&maximum].raw, "10");
}
#[test]
fn defaults_distinguish_absent_empty_and_typed_literals_with_escaped_unicode() {
let mut p = Project::empty();
let item = p
.add_element(Kind::ExchangeItem, Layer::Oa, "Payload", None)
.unwrap();
let id = p
.add_element(Kind::DataField, Layer::Oa, "Optional names", Some(item))
.unwrap();
let mut draft = Draft::from_project(&p, id).unwrap();
let root = "/body/Oa/Shared/DataField";
draft.shape(&format!("{root}/minimum"), json!(0)).unwrap();
draft
.shape(&format!("{root}/maximum"), Value::Null)
.unwrap();
draft.shape(&format!("{root}/default"), json!([])).unwrap();
let empty = execute_batch(&p, &[draft.command().unwrap()]).unwrap();
assert!(
matches!(empty.elements[&id].shared(),Some(SharedBody::DataField {default:Some(v),..}) if v.is_empty())
);
draft
.shape(&format!("{root}/default"), Value::Null)
.unwrap();
let absent = execute_batch(&empty, &[draft.command().unwrap()]).unwrap();
assert!(matches!(
absent.elements[&id].shared(),
Some(SharedBody::DataField { default: None, .. })
));
draft
.shape(&format!("{root}/default"), json!([{"String":"é🙂\n"}]))
.unwrap();
draft.input(&format!("{root}/default/0/String"), "é🙂\n".into());
draft
.append(&format!("{root}/default"), json!({"String":"next"}))
.unwrap();
assert_eq!(
draft
.materialize()
.unwrap()
.pointer(&format!("{root}/default/0/String")),
Some(&json!("é🙂\n"))
);
draft.array(&format!("{root}/default"), Some(1), 0).unwrap();
draft.set_exact(true).unwrap();
let saved = execute_batch(&absent, &[draft.command().unwrap()]).unwrap();
assert!(
matches!(saved.elements[&id].shared(),Some(SharedBody::DataField {default:Some(v),..}) if v == &vec![DataValue::String("é🙂\n".into())])
);
let _ = super::super::view(&draft, &saved);
draft
.shape(&format!("{root}/storage"), json!("Reference"))
.unwrap();
assert!(execute_batch(&saved, &[draft.command().unwrap()]).is_err());
}
#[test]
fn supertype_picker_excludes_descendants_and_keeps_original_inherited_field_identity() {
let mut p = Project::empty();
let base = p
.add_element(Kind::DataType, Layer::Oa, "Base", None)
.unwrap();
let child = p
.add_element(Kind::DataType, Layer::Oa, "Child", None)
.unwrap();
for (id, supertype) in [(base, None), (child, Some(base))] {
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype },
default: None,
unit: String::new(),
};
}
let field = p
.add_element(Kind::DataField, Layer::Oa, "Owned by base", Some(base))
.unwrap();
let draft = Draft::from_project(&p, base).unwrap();
let path = "/body/Oa/Shared/DataType/definition/Record/supertype";
assert!(!reference_ids(&draft, &p, path).contains(&child));
let child_draft = Draft::from_project(&p, child).unwrap();
assert!(reference_ids(&child_draft, &p, path).contains(&base));
assert_eq!(data::effective_fields(&p, child)[0].id, field);
assert_eq!(p.elements[&field].parent, Some(base));
}
}
+7 -9
View File
@@ -144,13 +144,7 @@ fn component_items_fit(project: &Project, port: Id, items: &[Id]) -> bool {
}
let declared: Vec<_> = interfaces
.iter()
.filter_map(|id| project.elements.get(id))
.filter_map(|e| match e.shared() {
Some(SharedBody::Interface { items }) => Some(items),
_ => None,
})
.flatten()
.copied()
.flat_map(|id| data::interface_items(project, *id))
.collect();
items_satisfy(project, items, &declared)
}
@@ -714,8 +708,12 @@ mod tests {
interface,
);
assert!(reference_ids(&draft, &project, target).is_empty());
project.elements.get_mut(&interface).unwrap().body =
ElementBody::shared_in(Layer::Sa, SharedBody::Interface { items: vec![item] });
project.relate(
RelationKind::InterfaceItemAllocation,
"Allocated item",
interface,
item,
);
assert_eq!(reference_ids(&draft, &project, target), vec![output]);
}
+24 -7
View File
@@ -369,7 +369,7 @@ fn article(topic: Topic) -> Article {
&[
"Create the source and target activities/functions in one perspective. Give each an engineering name and allocate leaf work to its responsible participant.",
"Choose Interaction or Functional exchange in the diagram palette. Click the source, then a highlighted compatible target, or drag between them. Functional exchanges connect output ports to input ports; function cards create or reuse real ports in the same transaction. Middle-button drag pans while keeping the source; arrow keys also pan when the drawing canvas has focus. Click empty space to restart, or Escape to cancel.",
"Create an Exchange item under Data & interfaces. Choose its kind (Information, Material, Energy or Event) and describe its payload.",
"Create an Exchange item under Data & interfaces. Choose its nature (Information, Material or Energy) and its mechanism (Flow, Event, Operation or Shared data). Describe the payload independently of the connection.",
"Select the exchange in Model explorer or the diagram. Edit its properties to reference the appropriate exchange items and available ports; Apply changes validates the complete record.",
"Choose Boundary exchange and connect compatible component ports. Flow goes from Out to In; Standard is unoriented. Select / move returns to arranging. Exchange allocation associates a boundary exchange with the functional exchange it carries.",
],
@@ -380,7 +380,7 @@ fn article(topic: Topic) -> Article {
),
explain(
"Use engineering payloads",
"Choose Information for data such as a distress report, Energy for delivered power, Material for a transferred substance and Event for a notification. Data types and fields can make structured payloads precise. URI artifact links can point to detailed interface-control documents.",
"Choose Information for data such as a distress report, Energy for delivered power and Material for a transferred substance. Mechanism separately describes how it is exchanged: an Event is a notification, an Operation has parameters, and a Flow carries values or a physical quantity. Data types and fields make payloads precise. Artifact links can point to interface-control documents.",
),
],
related: &[
@@ -510,17 +510,34 @@ fn article(topic: Topic) -> Article {
const {
Article {
summary: "Define exchanged payloads independently of the ports and participants that carry them. Reuse the same data definitions in related exchanges.",
keywords: "data interface port direction input output inout contract provision requirement exchange item enum enumeration record primitive field value type multiplicity minimum maximum",
keywords: "data interface port direction input output inout return contract provision requirement exchange item enum enumeration record primitive field value type multiplicity minimum maximum bounds default unit specialization inheritance association storage reference recursive path transmission acquisition protocol",
sections: &[
walkthrough(
"Define a reusable payload",
&[
"Open Data & interfaces and create an Exchange item. Select Information, Material, Energy or Event to describe the nature of the exchange.",
"Create a Data type where the payload needs a named definition. Choose its Data type definition and edit the corresponding values in Properties.",
"For structured definitions, create Data fields under a legal Data type or Exchange item owner. Set Value type and the minimum/maximum count as required by the contract.",
"Open Data & interfaces and create an Exchange item. Choose Information, Material or Energy for nature; choose Flow, Event, Operation or Shared data for mechanism. Keep Unspecified when the engineering decision is still open.",
"Create a Data type for a reusable definition. Choose Boolean, Integer, Real, String, Enumeration or Record. Numeric bounds are inclusive; String bounds count Unicode characters. A typed default must satisfy those bounds or enumeration literals. Units annotate quantities without converting them.",
"Create fields within an Exchange item or Record type. Set Value type, minimum/maximum count, unit and optional default. A default can be absent, explicitly empty when minimum is zero, or a list of typed scalar values. A type default describes one element; it does not create a required collection.",
"Select the exchange and reference the payload items. Apply changes and check the result in Model checks.",
],
),
explain(
"Operation parameters and message values",
"An Operation's direct fields are parameters. In and InOut supply call values; Out, InOut and Return supply reply values, from the provider's perspective. There is at most one Return parameter. Qualified paths distinguish origin.latitude from destination.latitude when both use the same Coordinate record. Nested fields inherit the parameter direction. Message expressions are annotations, not evaluated values.",
),
explain(
"Reuse, ownership and references",
"A Record or Exchange item can specialize one compatible base. Inherited fields keep their original owner and identity; edit the base to change them. Value fields compose a payload. Reference fields refer to separately identified Record objects and stop payload expansion. Optional recursive values and reference cycles are valid; a mandatory value cycle warns that no finite complete value exists. Data associations describe named reference ends, multiplicities and navigation between Record types without creating contained fields.",
),
walkthrough(
"Allocate an item to interfaces",
&[
"Create an Interface and allocate an Exchange item. Select its allocation row to edit transmission, acquisition and order; Open item navigates to the shared payload definition.",
"Two interfaces may allocate the same item with different protocols. Attach CAD, code or document evidence to the allocation when it concerns that particular contract.",
"Removing an allocation keeps the shared item and other allocations. If a live boundary depends on it, first revise that boundary contract. Undo restores an accepted removal.",
"An Interface may specialize one base and inherit its allocations. Duplicate allocation of an already inherited item is rejected. A specialized item satisfies its base contract; a base item does not satisfy a more specific contract.",
],
),
walkthrough(
"Connect participant boundaries",
&[
@@ -723,7 +740,7 @@ fn article(topic: Topic) -> Article {
),
explain(
"Open and migration",
"Open reads and validates a complete candidate before replacing the current project. Supported legacy files are migrated explicitly; save the resulting current format under a new name if the legacy original must remain available. Unsupported or invalid input does not replace the accepted project.",
"Open validates a complete candidate before replacing the project. Versions 1, 2 and 3 migrate explicitly to version 4; Model checks shows preserved ports, supplied data defaults, generated interface allocations and unresolved message paths. Old Event items become Information notifications; unknown physical mechanisms remain Unspecified. Source3 upgrades retain files, includes, nested ownership and comments. Opening does not overwrite the original: use Save as if it must remain in its older format. Invalid input leaves the accepted project unchanged.",
),
],
related: &[Topic::Source, Topic::Recovery, Topic::Artifacts],
+2
View File
@@ -4,6 +4,8 @@ mod behavior;
mod connection_edit;
mod connection_tool;
mod context_menu;
mod data_values;
mod data_view;
mod diagram;
mod document;
mod explorer;
+20 -13
View File
@@ -157,12 +157,9 @@ pub fn port_context_rows(project: &Project, port: Id) -> Vec<String> {
}
if let Some(legacy) = legacy {
rows.push(legacy_line(&context, legacy));
if let Some(interface) = legacy.interface
&& let Some(SharedBody::Interface { items }) =
context.element(interface).and_then(Element::shared)
{
for item in items {
origins.entry(*item).or_default().push(format!(
if let Some(interface) = legacy.interface {
for item in data::interface_items(project, interface) {
origins.entry(item).or_default().push(format!(
"preserved interface {} (suggestion only; not an active typed contract)",
context.label(interface)
));
@@ -711,11 +708,17 @@ mod tests {
let (other_fe, commands) = exchange(&mut project, source, target, vec![second]);
project = execute_batch(&project, &commands).unwrap();
let interface = add(&mut project, Kind::Interface, "Incident service");
project.elements.get_mut(&interface).unwrap().body = ElementBody::shared_in(
Layer::Sa,
SharedBody::Interface {
items: vec![first, second],
},
project.relate(
RelationKind::InterfaceItemAllocation,
"First item",
interface,
first,
);
project.relate(
RelationKind::InterfaceItemAllocation,
"Second item",
interface,
second,
);
let connection = &project.relations[&boundary];
let (a, b) = (connection.source(), connection.target());
@@ -790,8 +793,12 @@ mod tests {
..
} = fixture();
let interface = add(&mut project, Kind::Interface, "Preserved contract");
project.elements.get_mut(&interface).unwrap().body =
ElementBody::shared_in(Layer::Sa, SharedBody::Interface { items: vec![first] });
project.relate(
RelationKind::InterfaceItemAllocation,
"Allocated item",
interface,
first,
);
let legacy = port(
&mut project,
source,
+3 -6
View File
@@ -168,12 +168,9 @@ impl State {
_ => {}
}
}
if let Some(SharedBody::Interface { items }) = old
.and_then(|old| old.interface)
.and_then(|id| p.elements.get(&id))
.and_then(|e| e.shared())
{
incoming.extend(items);
if let Some(interface) = old.and_then(|old| old.interface) {
let items = data::interface_items(p, interface);
incoming.extend(items.iter().copied());
outgoing.extend(items);
}
for r in p.relations.values() {
+1 -1
View File
@@ -250,7 +250,7 @@ fn opening_legacy_source_surfaces_report_without_modifying_original_bytes() {
assert_eq!(app.page, Page::Validation);
assert_eq!(app.project(), &original);
assert!(!app.dirty());
assert!(app.source_snapshot.starts_with("arcadia 3;"));
assert!(app.source_snapshot.starts_with("arcadia 4;"));
assert!(serde_json::from_slice::<serde_json::Value>(&bytes).unwrap()["schema_version"] == 2);
}
+46 -63
View File
@@ -703,69 +703,7 @@ fn inspector(app: &App) -> View<'_, Message> {
}
fn data_catalog(app: &App) -> View<'_, Message> {
let p = app.project();
let mut content = column![heading(
"Data & interfaces",
"Define information, material and energy at the system boundary."
)]
.spacing(15);
for kind in Kind::ALL {
let is_data = matches!(
kind,
Kind::ExchangeItem | Kind::DataType | Kind::DataField | Kind::Interface | Kind::Port
);
if !is_data {
continue;
}
let elements = p
.elements
.values()
.filter(|e| e.layer() == app.layer && e.kind() == kind)
.collect::<Vec<_>>();
if elements.is_empty() {
continue;
}
content = content.push(
text(format!("{} · {}", kind.label(), elements.len()))
.size(15)
.color(style::kind_color(kind)),
);
for e in elements {
content = content.push(crate::context_menu::Area::new(
button(
row![
column![
text(&e.name).size(14),
label(format!(
"@{}{}",
e.alias,
e.parent
.map(|id| format!(" · in {}", p.named(id)))
.unwrap_or_default()
)),
text(short(&e.description, 125))
.size(12)
.color(style::MUTED)
]
.spacing(5)
.width(Fill),
text("→").size(17)
]
.align_y(iced::Center),
)
.padding(14)
.width(Fill)
.style(if e.id == app.selected {
style::selected
} else {
style::nav
})
.on_press(Message::Select(e.id)),
move |anchor| crate::model_menu::open(e.id, anchor),
));
}
}
scrollable(content.padding(24)).into()
crate::data_view::view(app)
}
fn traces(app: &App) -> View<'_, Message> {
@@ -1099,6 +1037,51 @@ fn checks(app: &App) -> View<'_, Message> {
app.project().named(endpoint.exchange)
)));
}
card=card.push(label(format!("Data migration: {} semantic defaults · {} interface allocations · {} unresolved value addresses",report.semantic_defaults.len(),report.generated_interface_allocations.len(),report.unresolved_message_values.len())));
for default in report.semantic_defaults.iter().take(6) {
card = card
.push(action(
&format!(
"{} · {}",
app.project().named(default.object),
default.field
),
Message::Select(default.object),
))
.push(label(&default.description));
}
for allocation in report.generated_interface_allocations.iter().take(6) {
card = card
.push(action(
&format!(
"Created item allocation · @{} · order {}",
allocation.alias, allocation.order
),
Message::Select(allocation.id),
))
.push(label(format!(
"{} → {}",
app.project().named(allocation.source),
app.project().named(allocation.target)
)));
}
for value in report.unresolved_message_values.iter().take(6) {
card = card
.push(action(
&format!(
"Review qualified value · {}",
app.project().named(value.occurrence)
),
Message::EditProperties(value.occurrence),
))
.push(label(&value.reason));
}
if report.semantic_defaults.len() > 6
|| report.generated_interface_allocations.len() > 6
|| report.unresolved_message_values.len() > 6
{
card=card.push(label("Showing the first six entries in each data migration category. Model checks below link remaining unresolved contracts."));
}
for boundary in &report.orientation_defaults {
card = card.push(action(
&format!(
+10 -8
View File
@@ -231,7 +231,7 @@ fn parse_source(body: &[u8]) -> ApiResult<oa_core::persistence::DecodeResult> {
}
fn import_json(body: &[u8]) -> ApiResult<oa_core::persistence::DecodeResult> {
// Format is chosen by HTTP. The shared decoder owns explicit schema-1 and schema-2 migration.
// Format is chosen by HTTP. The shared decoder owns supported older-schema migration.
let _: Value = json_body(body)?;
oa_core::persistence::decode_with_report_limited(body, MODEL_LIMITS).map_err(
|error| match error {
@@ -525,7 +525,7 @@ async fn put_source_project(
StatusCode::OK,
json!({
"revision": stored.revision, "changed": changed, "issues": diagnostics,
"source_project": stored.source_project
"source_project": stored.source_project, "migration": stored.migration
}),
))
})
@@ -947,14 +947,16 @@ async fn validate_candidate(
// Advisory locations refer to submitted bytes, before Apply
// would insert missing persistent identities.
let diagnostics: Vec<_> = source_project::lint_bundle(&source_project, SOURCE_LIMITS).into_iter().map(source_issue).collect();
if !diagnostics.iter().any(|issue| issue.severity == "error") {
PreparedProject::from_bundle(source_project)?;
}
Ok(diagnostics)
let migration = if !diagnostics.iter().any(|issue| issue.severity == "error") {
PreparedProject::from_bundle(source_project)?.migration().cloned()
} else {
None
};
Ok((diagnostics, migration))
});
let diagnostics = result.unwrap_or_else(candidate_issues);
let (diagnostics, migration) = result.unwrap_or_else(|error| (candidate_issues(error), None));
let valid = !diagnostics.iter().any(|issue| issue.severity == "error");
return Ok(response(stored, StatusCode::OK, json!({"revision":stored.revision,"valid":valid,"issues":diagnostics,"migration":null})));
return Ok(response(stored, StatusCode::OK, json!({"revision":stored.revision,"valid":valid,"issues":diagnostics,"migration":migration})));
}
_ => return Err(ApiError::bad_request("Validation requires one matching format/payload: json with model, arcadia with source, or source-project with source_project.")),
};
+13 -3
View File
@@ -128,9 +128,10 @@ impl PreparedProject {
fn from_compiled(compiled: CompiledSourceProject) -> ApiResult<Self> {
check_model_size(&compiled.decoded.project)?;
check_source_size(&compiled.bundle)?;
let migration = compiled.decoded.migration.clone();
Ok(Self {
compiled,
migration: None,
migration,
})
}
@@ -173,6 +174,10 @@ impl PreparedProject {
&self.compiled.bundle
}
pub(crate) fn migration(&self) -> Option<&MigrationReport> {
self.migration.as_ref()
}
pub(crate) fn source_issues(&self) -> Vec<crate::error::IssueDto> {
self.compiled
.diagnostics
@@ -329,7 +334,12 @@ impl Store {
let prepared = if let Some(bundle) = envelope.source_project {
let prepared = PreparedProject::from_bundle(bundle.clone())
.map_err(|error| corrupt(error.detail))?;
if prepared.bundle() != &bundle || prepared.model() != &decoded.project {
// Explicit source upgrades may change tokens and generate new
// records. They must still agree with independently migrated
// JSON. Current-format unstabilized/inconsistent pairs reject.
if (prepared.bundle() != &bundle && prepared.migration.is_none())
|| prepared.model() != &decoded.project
{
return Err(corrupt(
"Stored source and model disagree, or source lacks stable identities."
.into(),
@@ -347,7 +357,7 @@ impl Store {
revision: envelope.revision,
model: decoded.project,
source_project: prepared.compiled.bundle,
migration: decoded.migration,
migration: decoded.migration.or(prepared.migration),
};
if stored.resource_id != filename_id || stored.revision == 0 {
return Err(corrupt(
+8 -6
View File
@@ -8,6 +8,8 @@ use serde_json::{Value, json};
use std::{path::Path, sync::Arc};
use tokio::{sync::oneshot, task::JoinHandle};
#[path = "http/data_contracts.rs"]
mod data_contracts;
#[path = "http/port_anchors.rs"]
mod port_anchors;
#[path = "http/source_projects.rs"]
@@ -1929,7 +1931,7 @@ async fn legacy_json_import_and_model_reidentification_keep_the_service_address(
}
#[tokio::test]
async fn schema3_migration_reports_and_invalid_typed_transaction_preserve_http_state() {
async fn current_migration_reports_and_invalid_typed_transaction_preserve_http_state() {
let directory = tempfile::tempdir().unwrap();
let server = TestServer::start(directory.path(), None).await;
let old = v2_missing_ports();
@@ -1945,7 +1947,7 @@ async fn schema3_migration_reports_and_invalid_typed_transaction_preserve_http_s
assert_eq!(imported.status(), StatusCode::CREATED);
let etag = imported.headers()["etag"].to_str().unwrap().to_owned();
let summary: Value = imported.json().await.unwrap();
assert_eq!(summary["schema_version"], 3);
assert_eq!(summary["schema_version"], oa_core::SCHEMA_VERSION);
assert_eq!(
summary["migration"],
serde_json::to_value(&expected.migration).unwrap()
@@ -1958,7 +1960,7 @@ async fn schema3_migration_reports_and_invalid_typed_transaction_preserve_http_s
let before = std::fs::read(&filename).unwrap();
let envelope: Value = serde_json::from_slice(&before).unwrap();
assert!(envelope.get("migration").is_none());
assert_eq!(envelope["model"]["schema_version"], 3);
assert_eq!(envelope["model"]["schema_version"], oa_core::SCHEMA_VERSION);
let validation = server
.client
.post(server.url(&format!("/projects/{id}/validation")))
@@ -2000,7 +2002,7 @@ async fn schema3_migration_reports_and_invalid_typed_transaction_preserve_http_s
.text()
.await
.unwrap();
assert!(source.starts_with("arcadia 3;"));
assert!(source.starts_with("arcadia 4;"));
assert_eq!(oa_core::language::parse(&source).unwrap(), stored.model);
let no_op = server
.client
@@ -2049,7 +2051,7 @@ async fn reopening_v2_envelope_reports_migration_without_saving_or_advancing_rev
let migrated = server.get(id).await;
assert_eq!(migrated.resource_id, id);
assert_eq!(migrated.revision, 7);
assert_eq!(migrated.model.schema_version, 3);
assert_eq!(migrated.model.schema_version, oa_core::SCHEMA_VERSION);
assert_eq!(
migrated
.migration
@@ -2074,7 +2076,7 @@ async fn reopening_v2_envelope_reports_migration_without_saving_or_advancing_rev
assert_eq!(current.model.name, "Reviewed migrated model");
let saved: Value = serde_json::from_slice(&std::fs::read(&filename).unwrap()).unwrap();
assert_eq!(saved["revision"], 8);
assert_eq!(saved["model"]["schema_version"], 3);
assert_eq!(saved["model"]["schema_version"], oa_core::SCHEMA_VERSION);
assert!(saved.get("migration").is_none());
server.stop().await;
}
@@ -0,0 +1,734 @@
//! Transport evidence for the published R6 contract, not a second model fixture.
use super::*;
use oa_core::source_project::{ProjectLimits, SourceBundle, compile_bundle};
use oa_core::{DataTypeDefinition, DataValue, SharedBody, TransmissionProtocol};
use std::collections::BTreeMap;
fn documented_data() -> Project {
let contract = include_str!("../../../../docs/language.rst");
let example = contract
.split("This complete data contract example is also exercised through the REST API:")
.nth(1)
.unwrap()
.split(".. code-block:: text")
.nth(1)
.unwrap();
let source = example
.lines()
.skip_while(|line| line.trim().is_empty())
.take_while(|line| line.starts_with(" ") || line.is_empty())
.map(|line| line.strip_prefix(" ").unwrap_or(line))
.collect::<Vec<_>>()
.join("\n");
let model = oa_core::language::parse(&source).unwrap();
oa_core::validate_candidate(&model).unwrap();
model
}
fn id(model: &Project, alias: &str) -> Id {
model
.identities()
.into_iter()
.find(|(_, a)| *a == alias)
.unwrap()
.0
}
fn assert_pair(stored: &StoredProject) {
let compiled = compile_bundle(&stored.source_project, ProjectLimits::default()).unwrap();
assert_eq!(compiled.decoded.project, stored.model);
assert_eq!(compiled.bundle, stored.source_project);
}
async fn commands(
server: &TestServer,
current: &StoredProject,
commands: Vec<Command>,
) -> reqwest::Response {
server
.client
.post(server.url(&format!("/projects/{}/transactions", current.resource_id)))
.header("if-match", current.etag())
.json(&json!({"commands":commands}))
.send()
.await
.unwrap()
}
#[tokio::test]
async fn published_data_contract_queries_atomic_edits_identity_and_restart() {
let directory = tempfile::tempdir().unwrap();
let server = TestServer::start(directory.path(), None).await;
let model = documented_data();
let (resource, _) = server.import(&model).await;
let before = server.get(resource).await;
assert_eq!(before.model, model);
assert_pair(&before);
for (kind, count) in [("InterfaceItemAllocation", 2), ("DataAssociation", 1)] {
let result: Value = server
.client
.get(server.url(&format!("/projects/{resource}/relations?kind={kind}")))
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.json()
.await
.unwrap();
assert_eq!(result["items"].as_array().unwrap().len(), count);
}
let voltage = id(&model, "voltage");
let mut invalid = model.elements[&voltage].clone();
let Some(SharedBody::DataType {
definition: DataTypeDefinition::Real { maximum, .. },
..
}) = invalid.shared_mut()
else {
panic!()
};
*maximum = Some(12.0); // Existing default24V is outside this bound.
let filename = directory.path().join(format!("{resource}.json"));
let disk_before = std::fs::read(&filename).unwrap();
assert_eq!(
commands(
&server,
&before,
vec![Command::EditElement(voltage, invalid.clone())]
)
.await
.status(),
StatusCode::UNPROCESSABLE_ENTITY
);
assert_eq!(server.get(resource).await.etag(), before.etag());
assert_eq!(std::fs::read(&filename).unwrap(), disk_before);
let Some(SharedBody::DataType { default, .. }) = invalid.shared_mut() else {
panic!()
};
*default = Some(DataValue::Real(12.0));
let nav = id(&model, "nav_operation");
let other = id(&model, "monitor_operation");
let mut allocation = model.relations[&nav].clone();
let oa_core::RelationBody::InterfaceItemAllocation { transmission, .. } = &mut allocation.body
else {
panic!()
};
*transmission = TransmissionProtocol::Unicast;
let artifact = oa_core::ArtifactLink {
id: Id::new_v4(),
alias: "navigation_evidence".into(),
name: "Navigation CAD evidence".into(),
description: "Independent allocation evidence".into(),
owner: nav,
relation: oa_core::ArtifactRelation::Verifies,
uri: "cad://navigation/connector".into(),
revision: Some("review-17".into()),
fragment: Some("pin-3".into()),
};
let response = commands(
&server,
&before,
vec![
Command::EditElement(voltage, invalid),
Command::EditRelation(nav, allocation.clone()),
Command::CreateArtifact(artifact.clone()),
],
)
.await;
assert_eq!(
response.status(),
StatusCode::OK,
"{}",
response.text().await.unwrap()
);
let changed = server.get(resource).await;
assert_eq!(changed.revision, before.revision + 1);
assert_eq!(changed.model.relations[&other], model.relations[&other]);
assert_eq!(changed.model.relations[&nav], allocation);
assert_eq!(changed.model.artifact_links[&artifact.id], artifact);
assert_pair(&changed);
assert_eq!(
commands(&server, &before, vec![Command::Rename(nav, "Stale".into())])
.await
.status(),
StatusCode::PRECONDITION_FAILED
);
let renamed = Id::new_v4();
assert_eq!(
commands(&server, &changed, vec![Command::Reidentify(nav, renamed)])
.await
.status(),
StatusCode::OK
);
let reidentified = server.get(resource).await;
assert_eq!(
reidentified.model.artifact_links[&artifact.id].owner,
renamed
);
// This allocation is not enforcing a live boundary, so removal is valid.
assert_eq!(
commands(&server, &reidentified, vec![Command::Delete(renamed)])
.await
.status(),
StatusCode::OK
);
let removed = server.get(resource).await;
assert!(removed.model.elements.contains_key(&id(&model, "navigate")));
assert_eq!(removed.model.relations[&other], model.relations[&other]);
assert!(!removed.model.artifact_links.contains_key(&artifact.id));
assert_pair(&removed);
let source = server
.client
.get(server.url(&format!("/projects/{resource}/source")))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert!(source.starts_with("arcadia 4;"));
assert_eq!(oa_core::language::parse(&source).unwrap(), removed.model);
server.stop().await;
let server = TestServer::start(directory.path(), None).await;
let reopened = server.get(resource).await;
assert_eq!(reopened.model, removed.model);
assert_eq!(reopened.etag(), removed.etag());
assert_pair(&reopened);
server.stop().await;
}
#[tokio::test]
async fn authored_schema3_bundle_upgrade_reports_data_defaults_and_preserves_files() {
let directory = tempfile::tempdir().unwrap();
let server = TestServer::start(directory.path(), None).await;
let old = SourceBundle {
entry: "legacy.arcadia".into(), files: BTreeMap::from([
("legacy.arcadia".into(), "// Entry rationale\narcadia 3; project old_data \"Old data\" { include \"dictionary.arcadia\"; }\n".into()),
("dictionary.arcadia".into(), "// Event rationale\nsa_exchange_item notification \"Notification\" { kind Event; }\n// Interface rationale\nsa_interface contract \"Contract\" { items [@notification]; }\n".into())
])
};
let response = server
.client
.post(server.url("/projects/import-source-project"))
.json(&old)
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let summary: Value = response.json().await.unwrap();
let resource = summary["resource_id"].as_str().unwrap().parse().unwrap();
let stored = server.get(resource).await;
let report = stored.migration.as_ref().unwrap();
assert_eq!((report.from_schema, report.to_schema), (3, 4));
assert_eq!(report.generated_interface_allocations.len(), 1);
assert!(!report.semantic_defaults.is_empty());
let validated: Value = server
.client
.post(server.url(&format!("/projects/{resource}/validation")))
.json(&json!({"format":"source-project","source_project":old}))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(validated["valid"], true);
assert_eq!(validated["migration"]["from_schema"], 3);
assert_eq!(
validated["migration"]["generated_interface_allocations"]
.as_array()
.unwrap()
.len(),
1
);
assert_eq!(stored.source_project.files.len(), 2);
assert!(stored.source_project.files["legacy.arcadia"].contains("arcadia 4;"));
for text in [
"// Event rationale",
"// Interface rationale",
"interface_item_allocation",
] {
assert!(stored.source_project.files["dictionary.arcadia"].contains(text));
}
assert_pair(&stored);
let filename = directory.path().join(format!("{resource}.json"));
let bytes = std::fs::read(&filename).unwrap();
server.stop().await;
let server = TestServer::start(directory.path(), None).await;
let reopened = server.get(resource).await;
assert_eq!(reopened.model, stored.model);
assert_eq!(reopened.source_project, stored.source_project);
assert!(reopened.migration.is_none());
assert_eq!(std::fs::read(filename).unwrap(), bytes);
server.stop().await;
}
#[tokio::test]
async fn existing_schema3_coupled_envelope_upgrades_in_memory_until_explicit_save() {
let directory = tempfile::tempdir().unwrap();
let resource = Id::new_v4();
let filename = directory.path().join(format!("{resource}.json"));
let old_model: Value = serde_json::from_str(include_str!(
"../../../oa-core/tests/fixtures/v3-data-contract.json"
))
.unwrap();
let old_bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([(
"project.arcadia".into(),
include_str!("../../../oa-core/tests/fixtures/v3-data-contract.arcadia").into(),
)]),
};
let original = serde_json::to_vec(&json!({"resource_id":resource,"revision":17,"model":old_model,"source_project":old_bundle})).unwrap();
std::fs::write(&filename, &original).unwrap();
let server = TestServer::start(directory.path(), None).await;
let opened = server.get(resource).await;
assert_eq!(opened.revision, 17);
assert_eq!(opened.model.schema_version, 4);
assert_eq!(opened.migration.as_ref().unwrap().from_schema, 3);
assert!(opened.source_project.files["project.arcadia"].contains("arcadia 4;"));
assert_pair(&opened);
assert_eq!(std::fs::read(&filename).unwrap(), original);
assert_eq!(
commands(
&server,
&opened,
vec![Command::Rename(
opened.model.id,
"Reviewed data migration".into()
)]
)
.await
.status(),
StatusCode::OK
);
let saved = server.get(resource).await;
assert_eq!(saved.revision, 18);
let bytes = std::fs::read(&filename).unwrap();
assert_ne!(bytes, original);
server.stop().await;
let server = TestServer::start(directory.path(), None).await;
let reopened = server.get(resource).await;
assert_eq!(reopened.model, saved.model);
assert_eq!(reopened.source_project, saved.source_project);
assert_eq!(reopened.etag(), saved.etag());
assert!(reopened.migration.is_none());
assert_eq!(std::fs::read(&filename).unwrap(), bytes);
server.stop().await;
}
#[tokio::test]
async fn qualified_call_reply_values_reject_invalid_edits_and_survive_identity_source_and_restart()
{
use oa_core::{
Element, FieldStorage, MessageKind, MessageValue, OccurrenceBody, ParameterDirection,
PortContract, RelationBody, ScenarioViewpoint, TypeRef,
};
fn values(model: &Project, occurrence: Id) -> &[MessageValue] {
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = model.elements[&occurrence].shared()
else {
panic!("Expected message");
};
values
}
fn edited_values(model: &Project, occurrence: Id, next: Vec<MessageValue>) -> Element {
let mut element = model.elements[&occurrence].clone();
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { values, .. },
..
}) = element.shared_mut()
else {
panic!("Expected message");
};
*values = next;
element
}
let mut model = documented_data();
let operation = id(&model, "navigate");
let coordinate = id(&model, "coordinate");
let located = id(&model, "located");
let latitude = id(&model, "latitude");
let origin = id(&model, "origin");
let destination = id(&model, "destination");
let accepted = id(&model, "accepted");
// The second parameter inherits the very same latitude identity.
let Some(SharedBody::DataField { type_ref, .. }) =
model.elements.get_mut(&destination).unwrap().shared_mut()
else {
panic!();
};
*type_ref = TypeRef::Named(located);
let next = model
.add_element(
Kind::DataField,
Layer::Sa,
"Next coordinate",
Some(coordinate),
)
.unwrap();
*model.elements.get_mut(&next).unwrap().shared_mut().unwrap() = SharedBody::DataField {
type_ref: TypeRef::Named(coordinate),
minimum: 0,
maximum: Some(1),
direction: ParameterDirection::Unspecified,
storage: FieldStorage::Value,
unit: String::new(),
default: None,
};
let requester = model
.add_element(Kind::Function, Layer::Sa, "Request navigation", None)
.unwrap();
let provider = model
.add_element(Kind::Function, Layer::Sa, "Provide navigation", None)
.unwrap();
let output = Id::new_v4();
let input = Id::new_v4();
for (port, contract) in [
(
output,
PortContract::FunctionOutput {
outgoing_items: vec![operation],
},
),
(
input,
PortContract::FunctionInput {
incoming_items: vec![operation],
},
),
] {
let (owner, name) = if port == output {
(requester, "Navigation output")
} else {
(provider, "Navigation input")
};
let element = oa_core::ports::make_port(&model, port, owner, name, contract).unwrap();
model.elements.insert(port, element);
}
let exchange = model.relate(
RelationKind::FunctionalExchange,
"Navigation request",
requester,
provider,
);
model.relations.get_mut(&exchange).unwrap().body = RelationBody::FunctionalExchange {
source: requester,
target: provider,
source_port: output,
target_port: input,
items: vec![operation],
};
let scenario = model
.add_element(Kind::Scenario, Layer::Sa, "Navigation conversation", None)
.unwrap();
let Some(SharedBody::Scenario { viewpoint, .. }) =
model.elements.get_mut(&scenario).unwrap().shared_mut()
else {
panic!();
};
*viewpoint = ScenarioViewpoint::Functional;
let sender = model
.add_element(Kind::Lifeline, Layer::Sa, "Requester line", Some(scenario))
.unwrap();
let receiver = model
.add_element(Kind::Lifeline, Layer::Sa, "Provider line", Some(scenario))
.unwrap();
for (line, represented) in [(sender, requester), (receiver, provider)] {
*model.elements.get_mut(&line).unwrap().shared_mut().unwrap() = SharedBody::Lifeline {
represented: Some(represented),
};
}
let call = model
.add_element(
Kind::Occurrence,
Layer::Sa,
"Navigation call",
Some(scenario),
)
.unwrap();
let reply = model
.add_element(
Kind::Occurrence,
Layer::Sa,
"Navigation reply",
Some(scenario),
)
.unwrap();
for (occurrence, message_kind, from, to, reply_to) in [
(call, MessageKind::Call, sender, receiver, None),
(reply, MessageKind::Reply, receiver, sender, Some(call)),
] {
*model
.elements
.get_mut(&occurrence)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange: Some(exchange),
sender: Some(from),
receiver: Some(to),
message_kind,
reply_to,
values: vec![],
},
precondition: String::new(),
postcondition: String::new(),
};
}
model
.elements
.get_mut(&scenario)
.unwrap()
.steps_mut()
.unwrap()
.extend([call, reply]);
oa_core::validate_candidate(&model).unwrap();
let directory = tempfile::tempdir().unwrap();
let server = TestServer::start(directory.path(), None).await;
let (resource, _) = server.import(&model).await;
let before = server.get(resource).await;
let call_values = vec![
MessageValue {
path: vec![origin],
field: latitude,
expression: " origin.latitude\n+ 0.25 ".into(),
},
MessageValue {
path: vec![destination],
field: latitude,
expression: "destination.latitude".into(),
},
MessageValue {
path: vec![origin, next],
field: latitude,
expression: "previous.latitude".into(),
},
];
let reply_values = vec![MessageValue {
path: vec![],
field: accepted,
expression: "true".into(),
}];
let response = commands(
&server,
&before,
vec![
Command::EditElement(call, edited_values(&model, call, call_values.clone())),
Command::EditElement(reply, edited_values(&model, reply, reply_values.clone())),
],
)
.await;
assert_eq!(
response.status(),
StatusCode::OK,
"{}",
response.text().await.unwrap()
);
let authored = server.get(resource).await;
assert_eq!(authored.revision, before.revision + 1);
assert_eq!(values(&authored.model, call), call_values);
assert_eq!(values(&authored.model, reply), reply_values);
assert_eq!(
authored.model.elements[&latitude],
model.elements[&latitude]
);
assert_pair(&authored);
let filename = directory.path().join(format!("{resource}.json"));
let bytes = std::fs::read(&filename).unwrap();
for (occurrence, value, code) in [
(
call,
MessageValue {
path: vec![],
field: accepted,
expression: "wrong call phase".into(),
},
"message_parameter_phase",
),
(
reply,
MessageValue {
path: vec![origin],
field: latitude,
expression: "wrong reply phase".into(),
},
"message_parameter_phase",
),
(
call,
MessageValue {
path: vec![origin, accepted],
field: latitude,
expression: "unrelated hop".into(),
},
"message_value_field",
),
] {
let invalid = edited_values(&authored.model, occurrence, vec![value]);
let mut invalid_model = authored.model.clone();
invalid_model.elements.insert(occurrence, invalid.clone());
let response = commands(
&server,
&authored,
vec![Command::EditElement(occurrence, invalid)],
)
.await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let problem: Value = response.json().await.unwrap();
assert_eq!(problem["code"], "command_rejected", "{problem}");
assert!(
problem["detail"].as_str().unwrap().starts_with(code),
"{problem}"
);
// Transactions report the first rejection; validation supplies located issues.
let validation: Value = server
.client
.post(server.url(&format!("/projects/{resource}/validation")))
.json(&json!({"format":"json", "model":invalid_model}))
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.json()
.await
.unwrap();
assert_eq!(validation["valid"], false);
assert!(
validation["issues"]
.as_array()
.unwrap()
.iter()
.any(|issue| issue["code"] == code
&& issue["object_id"] == json!(occurrence)
&& issue["field"] == "values.path"),
"{problem}"
);
let unchanged = server.get(resource).await;
assert_eq!(unchanged.etag(), authored.etag());
assert_eq!(unchanged.model, authored.model);
assert_eq!(unchanged.source_project, authored.source_project);
assert_eq!(std::fs::read(&filename).unwrap(), bytes);
}
// Source transport changes one argument without conflating the shared leaf.
let source = server
.client
.get(server.url(&format!("/projects/{resource}/source")))
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.text()
.await
.unwrap();
let edited_source = source.replace(
"\"destination.latitude\"",
"\"destination.corrected_latitude\"",
);
assert_ne!(edited_source, source);
let response = server
.client
.put(server.url(&format!("/projects/{resource}/source")))
.header("if-match", authored.etag())
.header("content-type", "text/plain")
.body(edited_source)
.send()
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::OK,
"{}",
response.text().await.unwrap()
);
let source_edited = server.get(resource).await;
assert_eq!(source_edited.revision, authored.revision + 1);
let mut expected_call = call_values.clone();
expected_call[1].expression = "destination.corrected_latitude".into();
assert_eq!(values(&source_edited.model, call), expected_call);
assert_eq!(values(&source_edited.model, reply), reply_values);
assert_pair(&source_edited);
// Reidentify every kind of enclosing hop, the shared terminal, and its base type.
let mapping = [origin, destination, next, latitude, coordinate]
.into_iter()
.map(|old| (old, Id::new_v4()))
.collect::<BTreeMap<_, _>>();
let response = commands(
&server,
&source_edited,
mapping
.iter()
.map(|(old, new)| Command::Reidentify(*old, *new))
.collect(),
)
.await;
assert_eq!(
response.status(),
StatusCode::OK,
"{}",
response.text().await.unwrap()
);
let changed = server.get(resource).await;
assert_eq!(changed.revision, source_edited.revision + 1);
for value in &mut expected_call {
value.path = value.path.iter().map(|hop| mapping[hop]).collect();
value.field = mapping[&value.field];
}
assert_eq!(values(&changed.model, call), expected_call);
assert_eq!(values(&changed.model, reply), reply_values);
assert_eq!(
changed.model.elements[&mapping[&latitude]].parent,
Some(mapping[&coordinate])
);
assert!(
matches!(changed.model.elements[&located].shared(), Some(SharedBody::DataType {
definition: DataTypeDefinition::Record { supertype: Some(base) }, ..
}) if *base == mapping[&coordinate])
);
assert!(
oa_core::data::effective_fields(&changed.model, located)
.iter()
.any(|field| field.id == mapping[&latitude])
);
for old in mapping.keys() {
assert!(!changed.model.contains(*old));
}
assert!(
matches!(changed.model.elements[&reply].shared(), Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { reply_to: Some(correlation), .. }, ..
}) if *correlation == call)
);
assert_pair(&changed);
let source = server
.client
.get(server.url(&format!("/projects/{resource}/source")))
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.text()
.await
.unwrap();
assert!(source.starts_with("arcadia 4;"));
assert_eq!(oa_core::language::parse(&source).unwrap(), changed.model);
let saved = std::fs::read(&filename).unwrap();
server.stop().await;
let server = TestServer::start(directory.path(), None).await;
let reopened = server.get(resource).await;
assert_eq!(reopened.etag(), changed.etag());
assert_eq!(reopened.model, changed.model);
assert_eq!(reopened.source_project, changed.source_project);
assert_eq!(values(&reopened.model, call), expected_call);
assert_eq!(values(&reopened.model, reply), reply_values);
assert_pair(&reopened);
assert_eq!(std::fs::read(&filename).unwrap(), saved);
server.stop().await;
}
@@ -6,10 +6,10 @@ fn authored() -> SourceBundle {
let bundle = SourceBundle {
entry: "harbor.arcadia".into(),
files: BTreeMap::from([
("harbor.arcadia".into(), "// Harbor engineering rationale 航海\r\narcadia 3; project harbor \"Harbor rescue\" {\r\n include \"team/first.arcadia\";\r\n include \"team/second.arcadia\";\r\n include \"contracts.arcadia\";\r\n include \"work.arcadia\";\r\n}\r\n".into()),
("harbor.arcadia".into(), "// Harbor engineering rationale 航海\r\narcadia 4; project harbor \"Harbor rescue\" {\r\n include \"team/first.arcadia\";\r\n include \"team/second.arcadia\";\r\n include \"contracts.arcadia\";\r\n include \"work.arcadia\";\r\n}\r\n".into()),
("team/first.arcadia".into(), "// First payload rationale\r\nsa_exchange_item first \"First payload\" { description \"Reviewed first\"; }\r\n".into()),
("team/second.arcadia".into(), "// Second payload rationale\r\nsa_exchange_item second \"Second payload\" {}\r\n".into()),
("contracts.arcadia".into(), "// Contract ownership stays here\r\nsa_interface contract \"Contract\" { items [\r\n @first // first reference rationale\r\n ,\r\n @second // second reference rationale\r\n ]; }\r\n".into()),
("contracts.arcadia".into(), "// Contract ownership stays here\r\nsa_interface contract \"Contract\" {}\r\ninterface_item_allocation first_allocation \"First allocation\" { source @contract; target @first // first reference rationale\r\n; order 0; }\r\ninterface_item_allocation second_allocation \"Second allocation\" { source @contract; target @second // second reference rationale\r\n; order 1; }\r\n".into()),
("work.arcadia".into(), "// Operational rationale\r\noa_activity assess \"Assess assistance\" {}\r\n".into()),
]),
};
+32 -8
View File
@@ -784,8 +784,8 @@ candidate validation reports the same diagnostic in its 200 response.
Parsing, validation and query processing use snapshot workers, so this work
does not hold the catalog lock or serialize unrelated model preparation.</p>
<p>Import accepts schema-1 JSON through the shared explicit migration adapter,
as well as schema-2 native JSON. Source import uses the shared language parser
and its supported migrations. Export uses schema 3 / arcadia 3. Native JSON
as well as schema-2, schema-3 and current schema-4 JSON. Source import uses the shared language parser
and its supported migrations. Export uses schema 4 / arcadia 4. Native JSON
replacement accepts supported older schemas through the same explicit migration.
Only documented query parameters are accepted. In particular, appending
<span class="docutils literal"><span class="pre">?revision=...</span></span> to model/source export is an error, not historical retrieval.</p>
@@ -796,7 +796,7 @@ Only documented query parameters are accepted. In particular, appending
<pre class="literal-block">{
&quot;entry&quot;: &quot;rescue.arcadia&quot;,
&quot;files&quot;: {
&quot;rescue.arcadia&quot;: &quot;arcadia 3; project rescue \&quot;Rescue\&quot; { include \&quot;oa/work.arcadia\&quot;; }\n&quot;,
&quot;rescue.arcadia&quot;: &quot;arcadia 4; project rescue \&quot;Rescue\&quot; { include \&quot;oa/work.arcadia\&quot;; }\n&quot;,
&quot;oa/work.arcadia&quot;: &quot;// Engineering rationale\noa_activity assess \&quot;Assess assistance\&quot; {}\n&quot;
}
}</pre>
@@ -807,8 +807,9 @@ targets or another hosted resource. All submitted files must be reachable;
missing files, cycles, duplicate keys, case collisions and escaping paths are
rejected. The bundle permits at most 256 files, 32 include edges along a path,
and 1,024 include edges in total. Model and source-byte budgets apply across
the complete bundle, not separately per file. Bundle syntax is source3;
single-file legacy migration remains available through interchange import.</p>
the complete bundle, not separately per file. Current bundle syntax is source4; source3 bundles migrate explicitly while
preserving their files/includes/comments. V1/V2 single-file migration remains
available through interchange import.</p>
<p>Compilation inserts UUIDs into headers that omit them. Import returns 201 with
Location/ETag; GET source-project retrieves the stabilized accepted bundle.
PUT returns <span class="docutils literal">revision</span>, <span class="docutils literal">changed</span>, located <span class="docutils literal">issues</span> and that accepted
@@ -965,8 +966,11 @@ does not execute conditions or simulate a process.</p>
store <span class="docutils literal">message_kind</span>, optional correlated-call <span class="docutils literal">reply_to</span> and contextual
<span class="docutils literal">values</span>. Message kinds are Asynchronous, Call, Reply, Create, Delete, or
<span class="docutils literal"><span class="pre">{&quot;Timer&quot;:{&quot;expression&quot;:&quot;after</span> 5 <span class="pre">s&quot;}}</span></span>. Each value record contains a
carried DataField UUID in <span class="docutils literal">field</span> and its textual <span class="docutils literal">expression</span>; expressions
do not change the shared exchange item's type or evaluate server-side.</p>
carried DataField UUID in <span class="docutils literal">field</span>, enclosing field UUID list <span class="docutils literal">path</span> (default
[]) and textual <span class="docutils literal">expression</span>. Identity is (path, field), allowing repeated uses
of a Record. Operation Call/Reply direction checks use the direct parameter;
Reference storage stops nested payload traversal. Expressions do not change the
shared exchange item's type or evaluate server-side.</p>
<p><span class="docutils literal">ScenarioUse</span> contains a referenced <span class="docutils literal">scenario</span> and one-to-one lifeline
<span class="docutils literal">bindings</span> records with <span class="docutils literal">referenced</span> and <span class="docutils literal">local</span> UUIDs. The core validates
viewpoint/layer compatibility, call/reply order and reversal, lifetime order,
@@ -978,6 +982,26 @@ exports make those compatibility defaults explicit. This preserves original V2
models while the release schema is being integrated; it does not silently
reinterpret old mixed lifelines as a strict new viewpoint.</p>
</section>
<section id="data-and-interface-contracts">
<h2>Data and interface contracts</h2>
<p>Schema4 uses typed bounded DataTypeDefinition and DataValue constructors, field
storage/defaults/directions, and single specialization. Exact JSON shapes are in
<span class="docutils literal">openapi.json</span> and semantic rules and runnable source in <span class="docutils literal">language.rst</span> section 4.5.
Interface membership is an identified InterfaceItemAllocation relation with
independent order/transmission/acquisition. DataAssociation relates Record types
with named, navigable, multiplicity-bearing ends; it does not add carried fields.</p>
<p>Use ordinary relation queries, transactions and artifact links, for example
<span class="docutils literal">GET <span class="pre">/api/v1/projects/{id}/relations?kind=InterfaceItemAllocation</span></span>. The service
and desktop use the same inheritance/path/default validation. Invalid bounds,
defaults, directions, cycles or contract-breaking deletions reject atomically,
preserving the accepted source/model, revision and stored bytes. Correct a related
contract in the same transaction when removing a used interface allocation.</p>
<p>Explicit schema1/2/3 migration preserves prior identities and typed ports. Reports
add semantic defaults, generated interface allocations and unresolved message
values. Old source3 bundles retain files/includes/comments during upgrade; all
current exports use schema4/source4. Reading an old envelope does not write it or
advance its ETag. Canonical exports omit transient migration reports.</p>
</section>
<section id="validation">
<h2>Validation</h2>
<p>GET returns current-model diagnostics. POST accepts either:</p>
@@ -985,7 +1009,7 @@ reinterpret old mixed lifelines as a strict new viewpoint.</p>
<p>or:</p>
<pre class="literal-block">{&quot;format&quot;:&quot;arcadia&quot;, &quot;source&quot;:&quot;complete source document&quot;}</pre>
<p>or:</p>
<pre class="literal-block">{&quot;format&quot;:&quot;source-project&quot;, &quot;source_project&quot;:{&quot;entry&quot;:&quot;rescue.arcadia&quot;, &quot;files&quot;:{&quot;rescue.arcadia&quot;:&quot;arcadia 3; project rescue \&quot;Rescue\&quot; {}&quot;}}}</pre>
<pre class="literal-block">{&quot;format&quot;:&quot;source-project&quot;, &quot;source_project&quot;:{&quot;entry&quot;:&quot;rescue.arcadia&quot;, &quot;files&quot;:{&quot;rescue.arcadia&quot;:&quot;arcadia 4; project rescue \&quot;Rescue\&quot; {}&quot;}}}</pre>
<p>A well-formed validation request returns 200 with <span class="docutils literal">valid</span> and <span class="docutils literal">issues</span> even
if its candidate is invalid, including a model record that fails typed decoding.
Malformed request JSON or an invalid format/payload envelope is a 400.
+35 -8
View File
@@ -146,8 +146,8 @@ Parsing, validation and query processing use snapshot workers, so this work
does not hold the catalog lock or serialize unrelated model preparation.
Import accepts schema-1 JSON through the shared explicit migration adapter,
as well as schema-2 native JSON. Source import uses the shared language parser
and its supported migrations. Export uses schema 3 / arcadia 3. Native JSON
as well as schema-2, schema-3 and current schema-4 JSON. Source import uses the shared language parser
and its supported migrations. Export uses schema 4 / arcadia 4. Native JSON
replacement accepts supported older schemas through the same explicit migration.
Only documented query parameters are accepted. In particular, appending
``?revision=...`` to model/source export is an error, not historical retrieval.
@@ -160,7 +160,7 @@ A source bundle contains ``entry`` and a map of ``files``. For example::
{
"entry": "rescue.arcadia",
"files": {
"rescue.arcadia": "arcadia 3; project rescue \"Rescue\" { include \"oa/work.arcadia\"; }\n",
"rescue.arcadia": "arcadia 4; project rescue \"Rescue\" { include \"oa/work.arcadia\"; }\n",
"oa/work.arcadia": "// Engineering rationale\noa_activity assess \"Assess assistance\" {}\n"
}
}
@@ -172,8 +172,9 @@ targets or another hosted resource. All submitted files must be reachable;
missing files, cycles, duplicate keys, case collisions and escaping paths are
rejected. The bundle permits at most 256 files, 32 include edges along a path,
and 1,024 include edges in total. Model and source-byte budgets apply across
the complete bundle, not separately per file. Bundle syntax is source3;
single-file legacy migration remains available through interchange import.
the complete bundle, not separately per file. Current bundle syntax is source4; source3 bundles migrate explicitly while
preserving their files/includes/comments. V1/V2 single-file migration remains
available through interchange import.
Compilation inserts UUIDs into headers that omit them. Import returns 201 with
Location/ETag; GET source-project retrieves the stabilized accepted bundle.
@@ -355,8 +356,11 @@ Scenario bodies store an explicit ``viewpoint``. Occurrence Exchange bodies
store ``message_kind``, optional correlated-call ``reply_to`` and contextual
``values``. Message kinds are Asynchronous, Call, Reply, Create, Delete, or
``{"Timer":{"expression":"after 5 s"}}``. Each value record contains a
carried DataField UUID in ``field`` and its textual ``expression``; expressions
do not change the shared exchange item's type or evaluate server-side.
carried DataField UUID in ``field``, enclosing field UUID list ``path`` (default
[]) and textual ``expression``. Identity is (path, field), allowing repeated uses
of a Record. Operation Call/Reply direction checks use the direct parameter;
Reference storage stops nested payload traversal. Expressions do not change the
shared exchange item's type or evaluate server-side.
``ScenarioUse`` contains a referenced ``scenario`` and one-to-one lifeline
``bindings`` records with ``referenced`` and ``local`` UUIDs. The core validates
@@ -370,6 +374,29 @@ exports make those compatibility defaults explicit. This preserves original V2
models while the release schema is being integrated; it does not silently
reinterpret old mixed lifelines as a strict new viewpoint.
Data and interface contracts
----------------------------
Schema4 uses typed bounded DataTypeDefinition and DataValue constructors, field
storage/defaults/directions, and single specialization. Exact JSON shapes are in
``openapi.json`` and semantic rules and runnable source in ``language.rst`` section 4.5.
Interface membership is an identified InterfaceItemAllocation relation with
independent order/transmission/acquisition. DataAssociation relates Record types
with named, navigable, multiplicity-bearing ends; it does not add carried fields.
Use ordinary relation queries, transactions and artifact links, for example
``GET /api/v1/projects/{id}/relations?kind=InterfaceItemAllocation``. The service
and desktop use the same inheritance/path/default validation. Invalid bounds,
defaults, directions, cycles or contract-breaking deletions reject atomically,
preserving the accepted source/model, revision and stored bytes. Correct a related
contract in the same transaction when removing a used interface allocation.
Explicit schema1/2/3 migration preserves prior identities and typed ports. Reports
add semantic defaults, generated interface allocations and unresolved message
values. Old source3 bundles retain files/includes/comments during upgrade; all
current exports use schema4/source4. Reading an old envelope does not write it or
advance its ETag. Canonical exports omit transient migration reports.
Validation
----------
@@ -383,7 +410,7 @@ or::
or::
{"format":"source-project", "source_project":{"entry":"rescue.arcadia", "files":{"rescue.arcadia":"arcadia 3; project rescue \"Rescue\" {}"}}}
{"format":"source-project", "source_project":{"entry":"rescue.arcadia", "files":{"rescue.arcadia":"arcadia 4; project rescue \"Rescue\" {}"}}}
A well-formed validation request returns 200 with ``valid`` and ``issues`` even
if its candidate is invalid, including a model record that fails typed decoding.
+219 -45
View File
@@ -623,7 +623,7 @@ a { text-decoration: none; }
<h1 class="title">Arcadia Studio OA / SA Language and Editing Contract</h1>
<dl class="docinfo simple">
<dt class="version">Version<span class="colon">:</span></dt>
<dd class="version">3</dd>
<dd class="version">4</dd>
<dt class="status">Status<span class="colon">:</span></dt>
<dd class="status">Normative current implementation contract; first-release integration</dd>
<dt class="core-implementation">Core implementation<span class="colon">:</span></dt>
@@ -637,14 +637,13 @@ a { text-decoration: none; }
<h2>1. Scope and conformance</h2>
<p>This specification defines the shared Operational Analysis (OA) and System
Analysis (SA) model, its textual language, graphical editing obligations,
validation, persistence, and explicit migration from versions 1 and 2. MUST, MUST NOT,
validation, persistence, and explicit migration from versions 1, 2 and 3. MUST, MUST NOT,
and MAY indicate requirements, prohibitions, and permitted choices.</p>
<p>Schema 3 introduces typed function and component ports, required functional
exchange endpoints, independently oriented boundary exchanges, and explicit
PortAllocation relations. First-release scenario/state additions remain in
scope; this schema change does not declare native acceptance or the wider
release complete. The preserved schema-2 reader validates the original
contract before migration.</p>
<p>Schema 4 adds bounded reusable data types, typed scalar defaults, exchange
mechanisms, qualified message values, specialization, identified interface
allocations and reference associations. It retains schema 3 typed ports and
state views. Explicit older readers preserve existing meanings and identities.
This contract does not by itself establish native acceptance or release completion.</p>
<p>OA describes stakeholders, operational work and needs. SA describes the
selected system boundary, external actors, functions, services and expected
behavior. SA permits at most one System of Interest; its absence is an
@@ -662,7 +661,7 @@ Actual verification evidence is separate from this contract.</p>
</section>
<section id="one-authoritative-model">
<h2>2. One authoritative model</h2>
<p>A Project stores <span class="docutils literal">schema_version</span> (3), <span class="docutils literal">id</span>, <span class="docutils literal">alias</span>, <span class="docutils literal">name</span>,
<p>A Project stores <span class="docutils literal">schema_version</span> (4), <span class="docutils literal">id</span>, <span class="docutils literal">alias</span>, <span class="docutils literal">name</span>,
<span class="docutils literal">description</span>, and maps named <span class="docutils literal">elements</span>, <span class="docutils literal">relations</span>, <span class="docutils literal">diagrams</span>,
<span class="docutils literal">artifact_links</span>, and <span class="docutils literal">traces</span>. Each map is keyed by the UUID contained in
its record. Duplicate map keys and mismatching keys/identities are errors.</p>
@@ -722,20 +721,20 @@ lists all additional fields. <span class="docutils literal">ref</span> means <sp
<td><p><span class="docutils literal">[]</span></p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_exchange_item</span>, <span class="docutils literal">sa_exchange_item</span></p></td>
<td><p><span class="docutils literal">kind</span>: Information, Material, Energy, Event</p></td>
<td><p>Information</p></td>
<td><p><span class="docutils literal">kind</span>: Information, Material, Energy; <span class="docutils literal">mechanism</span>: ExchangeMechanism; <span class="docutils literal">supertype</span>: item ref?</p></td>
<td><p>Information; Unspecified; none</p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_data_type</span>, <span class="docutils literal">sa_data_type</span></p></td>
<td><p><span class="docutils literal">definition</span>: Boolean, Integer, Real, String, Record, or Enumeration constructor</p></td>
<td><p>String</p></td>
<td><p><span class="docutils literal">definition</span>: DataTypeDefinition; <span class="docutils literal">default</span>: DataValue?; <span class="docutils literal">unit</span>: string</p></td>
<td><p>String with minimum_length 0 / maximum_length none; none; <span class="docutils literal">&quot;&quot;</span></p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_data_field</span>, <span class="docutils literal">sa_data_field</span></p></td>
<td><p><span class="docutils literal">type_ref</span>; <span class="docutils literal">minimum</span>: u32; <span class="docutils literal">maximum</span>: optional u32; <span class="docutils literal">unit</span>: string</p></td>
<td><p>String; 1; 1; <span class="docutils literal">&quot;&quot;</span></p></td>
<td><p><span class="docutils literal">type_ref</span>; <span class="docutils literal">minimum</span>: u32; <span class="docutils literal">maximum</span>: optional u32; <span class="docutils literal">unit</span>: string; <span class="docutils literal">direction</span>: ParameterDirection; <span class="docutils literal">storage</span>: FieldStorage; <span class="docutils literal">default</span>: DataValue list?</p></td>
<td><p>String; 1; 1; <span class="docutils literal">&quot;&quot;</span>; Unspecified; Value; none</p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_interface</span>, <span class="docutils literal">sa_interface</span></p></td>
<td><p><span class="docutils literal">items</span>: exchange-item refs</p></td>
<td><p><span class="docutils literal">[]</span></p></td>
<td><p><span class="docutils literal">supertype</span>: interface ref?</p></td>
<td><p>none; membership is an identified interface_item_allocation relation</p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_port</span>, <span class="docutils literal">sa_port</span></p></td>
<td><p><span class="docutils literal">contract</span>: required PortContract; <span class="docutils literal">legacy</span>: optional LegacyPortContract</p></td>
@@ -883,6 +882,14 @@ references. Their kind is the declaration keyword:</p>
<td><p>Same-layer participant → leaf activity/function</p></td>
<td><p>None</p></td>
</tr>
<tr><td><p><span class="docutils literal">interface_item_allocation</span></p></td>
<td><p>Same-layer Interface → ExchangeItem</p></td>
<td><p><span class="docutils literal">order</span> u32 / 0; <span class="docutils literal">transmission</span> TransmissionProtocol / Unspecified; <span class="docutils literal">acquisition</span> AcquisitionProtocol / Unspecified</p></td>
</tr>
<tr><td><p><span class="docutils literal">data_association</span></p></td>
<td><p>Same-layer Record DataType → Record DataType</p></td>
<td><p><span class="docutils literal">source_role</span>, <span class="docutils literal">target_role</span> / &quot;&quot;; <span class="docutils literal">source_minimum</span>, <span class="docutils literal">target_minimum</span> / 0; <span class="docutils literal">source_maximum</span>, <span class="docutils literal">target_maximum</span> / none; <span class="docutils literal">source_navigable</span>, <span class="docutils literal">target_navigable</span> / false</p></td>
</tr>
<tr><td><p><span class="docutils literal">interaction</span></p></td>
<td><p>OA activity → OA activity</p></td>
<td><p><span class="docutils literal">items</span> refs / []</p></td>
@@ -963,7 +970,8 @@ references. Their kind is the declaration keyword:</p>
</table>
<p>Relation endpoints and carried ExchangeItems stay in the same layer. Parallel
exchanges with distinct identities are permitted. Self-relations are invalid
except for a state transition that returns to its source state.</p>
except for a state transition that returns to its source state or an explicit
DataAssociation between two ends of the same Record type.</p>
<p>Direct Allocation has at most one performer per leaf. Role sharing is a
different relationship: several OA participants can realize a Role. A direct
allocation inconsistent with its role's realized performers produces an
@@ -976,9 +984,10 @@ declares <span class="docutils literal">outgoing_items</span>; <span class="docu
The lists contain distinct same-layer ExchangeItem references. A functional
exchange MUST reference output/input ports owned by its respective functions,
and each carried item MUST fit both declarations. Empty declarations accept
no items. Item compatibility is identity equality; future specialization is
not inferred from names. Port declarations remain independent of incident
exchanges after creation.</p>
no items. A carried item satisfies an identical declaration or a declaration
of one of its explicit base items. A base item does not satisfy a more
specialized declaration; names imply no compatibility. Port declarations
remain independent of incident exchanges after creation.</p>
<p>A <span class="docutils literal">Component</span> contract belongs to an SA System or SystemActor and stores
<span class="docutils literal">kind</span> (Standard or Flow) and <span class="docutils literal">orientation</span> (Unset, In, Out, InOut).
Standard requires Unset. Flow Unset is an incomplete draft, not InOut. Typed
@@ -1011,12 +1020,13 @@ not create endpoints. Graphical/command FE creation plans ports atomically,
using unique compatible typed-port reuse or deterministic new endpoints.
Port deletion cascades to incident FEs; FE deletion retains independent ports.</p>
<p>For example:</p>
<pre class="literal-block">arcadia 3;
<pre class="literal-block">arcadia 4;
project ports_example &quot;Typed function contract&quot; {
sa_function send &quot;Send&quot; {}
sa_function receive &quot;Receive&quot; {}
sa_exchange_item payload &quot;Payload&quot; {}
sa_interface old_service &quot;Preserved service&quot; { items [&#64;payload]; }
sa_interface old_service &quot;Preserved service&quot; {}
interface_item_allocation service_payload &quot;Service payload&quot; { source &#64;old_service; target &#64;payload; }
sa_port output &quot;Output&quot; {
parent &#64;send;
contract { FunctionOutput { outgoing_items [&#64;payload]; }; };
@@ -1125,11 +1135,19 @@ local to its sender lifeline, has no global exchange or values, and has either
no receiver or the same receiver as sender. Its nonempty expression describes
the delay/deadline; an empty expression warns. Conditions and expressions are
stored engineering annotations, not an executable simulation language.</p>
<p>Each MessageValue is <span class="docutils literal">{ field &#64;data_field; expression &quot;value expression&quot;; }</span>.
The field MUST be a DataField carried by the message exchange, including fields
inside named nested records. At most one annotation for a given field is
allowed in one message. Values do not overwrite the referenced type or global
exchange item. Expression text is preserved exactly; an empty expression warns.</p>
<p>Each MessageValue is <span class="docutils literal">{ path [&#64;parameter]; field &#64;data_field; expression &quot;value expression&quot;; }</span>.
Its identity is the pair (path, field), so two uses of one Record can have
different values for the same terminal field. Path contains enclosing DataField
references, excluding the terminal field; direct parameters use <span class="docutils literal">[]</span>. Every
hop MUST follow Value storage through a named Record's effective fields. Reference
storage stops traversal. Operation Call accepts In/InOut and Reply accepts
Out/InOut/Return, interpreted from the provider's perspective. Nested field paths
inherit their direct parameter's direction. Unspecified direction warns.
At most one annotation for a pair is allowed. Omitted path defaults to <span class="docutils literal">[]</span>;
an ambiguous preserved legacy nested annotation warns <span class="docutils literal">message_value_ambiguous_path</span>
until an explicit path is selected. New graphical choices always identify a path.
Values never overwrite types or items. Expression text is descriptive, preserved
exactly and not evaluated; an empty expression warns.</p>
<p>ScenarioUse references an existing same-layer scenario and maps its lifelines
with <span class="docutils literal">bindings [ { referenced &#64;callee_line; local &#64;caller_line; } ];</span>.
Each binding is one-to-one and references a direct lifeline of the appropriate
@@ -1280,6 +1298,137 @@ DeepHistory remembers nested configuration. Fallback applies when no resumable
history exists. History is per Region, including top-level Regions in this
Studio profile; no running history state is persisted or synthesized.</p>
</section>
<section id="data-contracts-specialization-and-interface-allocation">
<h3>4.5. Data contracts, specialization and interface allocation</h3>
<p>ExchangeItem <span class="docutils literal">kind</span> describes nature: Information, Material or Energy.
<span class="docutils literal">mechanism</span> is Unspecified, Flow, Event, Operation or SharedData. Unknown
mechanisms remain explicit Unspecified drafts with a warning. Material/Energy
with Event/Operation/SharedData warns for engineering review; it is not silently
reclassified. Empty Event notifications and void Operations are valid. An empty
carried/allocated Flow, SharedData or Unspecified item warns.</p>
<p>An Operation's directly owned DataFields are parameters. <span class="docutils literal">direction</span> is
Unspecified, In, Out, InOut or Return, from the provider's perspective. At most
one effective parameter is Return. Unspecified parameters warn; non-operation
fields MUST use Unspecified. Nested record fields inherit direction from their
direct parameter when used in message paths, rather than storing context on a
shared type. <span class="docutils literal">storage</span> is Value or Reference. Reference requires a named Record,
has no explicit default, and does not convey ownership or deletion of the type.</p>
<p>DataTypeDefinition has exactly the following constructors:</p>
<table>
<caption>Reusable definitions</caption>
<thead>
<tr><th class="head"><p>Constructor</p></th>
<th class="head"><p>Required fields</p></th>
</tr>
</thead>
<tbody>
<tr><td><p>Boolean</p></td>
<td><p>None</p></td>
</tr>
<tr><td><p>Integer</p></td>
<td><p><span class="docutils literal">minimum</span>, <span class="docutils literal">maximum</span>: optional signed 64-bit integers</p></td>
</tr>
<tr><td><p>Real</p></td>
<td><p><span class="docutils literal">minimum</span>, <span class="docutils literal">maximum</span>: optional finite IEEE-754 binary64 values</p></td>
</tr>
<tr><td><p>String</p></td>
<td><p><span class="docutils literal">minimum_length</span>: u32; <span class="docutils literal">maximum_length</span>: optional u32</p></td>
</tr>
<tr><td><p>Enumeration</p></td>
<td><p><span class="docutils literal">literals</span>: unique nonempty, case-sensitive strings</p></td>
</tr>
<tr><td><p>Record</p></td>
<td><p><span class="docutils literal">supertype</span>: same-layer Record ref?</p></td>
</tr>
</tbody>
</table>
<p>Bounds are inclusive and ordered; an absent bound means unbounded within the
represented numeric domain. Integer comparisons MUST NOT convert to binary64.
NaN, infinities, overflow and reversed bounds reject. String length counts Unicode
scalar values, not UTF-8 bytes or grapheme clusters. Enum defaults match exact
literals. Empty enum definitions remain incomplete drafts with a warning.</p>
<p>DataValue is a tagged scalar: <span class="docutils literal">{ Boolean true; }</span>, <span class="docutils literal">{ Integer 42; }</span>,
<span class="docutils literal">{ Real 1.5; }</span>, <span class="docutils literal">{ String &quot;value&quot;; }</span> or <span class="docutils literal">{ Enumeration &quot;Ready&quot;; }</span>.
There is no implicit numeric or string coercion. A type default is one compatible
scalar within its bounds. Record type defaults and record/object instance literals
are unsupported. A field default is absent (<span class="docutils literal">none</span>) or a list of compatible
scalars with length inside its multiplicity. <span class="docutils literal">[]</span> explicitly supplies an empty
collection and requires minimum 0, including Value Record fields; a nonempty
Record literal rejects. Reference fields MUST use <span class="docutils literal">none</span>. A one-valued scalar
field uses a one-value list. A named type default supplies an individual element's
default, not a collection or an implicit instance of a mandatory field.</p>
<p>Numeric types may carry unit text. Empty field units inherit the named type unit;
an explicit different unit warns when that type has a unit. Units on nonnumeric
fields/types warn and remain preserved. Unit strings never convert values or
establish dimensional compatibility. Expressions are not executed.</p>
<p>Record, ExchangeItem and Interface each permit one same-family, same-layer
supertype. Specialization is acyclic and separate from containment. Effective
fields are base fields followed by local fields, preserving original field UUIDs
and owners. Local names MUST NOT shadow inherited names. Item specialization
preserves base nature and any specified mechanism; an Unspecified base mechanism
may be refined. Deleting a derived record never deletes its base. Mandatory
Value-field cycles warn <span class="docutils literal">record_no_finite_value</span>; optional or Reference cycles
are valid without that warning. Traversal is cycle guarded and bounded; a payload
path budget failure is an explicit diagnostic, not silent truncation.</p>
<p>InterfaceItemAllocation is an ordinary identified relation from Interface to
ExchangeItem. It stores <span class="docutils literal">order</span> and independent transmission/acquisition
protocols. Transmission is Unspecified, Synchronous, Asynchronous, Unicast,
Multicast or Broadcast; acquisition is Unspecified, Read or Accept. No protocol
combination is inferred from mechanism. Effective allocations are base-first,
then local ordered by (order, alias, UUID). A local item already allocated locally
or inherited is an error. Removing an allocation keeps its item and other
allocations; if live boundary compatibility would break, the transaction MUST
repair the affected contract explicitly or reject atomically. Artifacts can
reference the allocation identity independently of the global item.</p>
<p>An exchange carrying a specialized item satisfies a declaration of its base,
never the reverse. Standard provided/required compatibility uses explicit
interface ancestry. Identity/ancestry, not matching names, defines conformance.
The current typed function/component port contracts remain unchanged.</p>
<p>DataAssociation connects Record types without adding fields or transitively
carrying payload. Each named end has role, multiplicity and navigability. Source
multiplicity counts source instances per target instance and vice versa; it is
not a count of model elements. An end's navigable flag permits navigation toward
that end. Self-associations are valid; if both ends are navigable they require
distinct nonempty roles. Empty roles and duplicate role contracts warn, whereas
invalid ranges reject. Composition/shared aggregation, multiple inheritance,
redefinition, instance literals and arbitrary-precision decimal arithmetic are
outside this bounded contract.</p>
<p>This complete data contract example is also exercised through the REST API:</p>
<pre class="code text literal-block"><code>arcadia 4;
project engineering_data &quot;Engineering data&quot; {
sa_data_type voltage &quot;Voltage&quot; {
definition { Real { minimum 0.0; maximum 48.0; }; };
default { Real 24.0; }; unit &quot;V&quot;;
}
sa_data_type coordinate &quot;Coordinate&quot; {
definition { Record { supertype none; }; };
sa_data_field latitude &quot;Latitude&quot; { type_ref Real; }
}
sa_data_type located &quot;Located asset&quot; {
definition { Record { supertype &#64;coordinate; }; };
sa_data_field supply &quot;Supply&quot; { type_ref { Named &#64;voltage; }; }
}
sa_exchange_item navigate &quot;Navigate&quot; {
mechanism Operation;
sa_data_field origin &quot;Origin&quot; { type_ref { Named &#64;coordinate; }; direction In; }
sa_data_field destination &quot;Destination&quot; { type_ref { Named &#64;coordinate; }; direction In; }
sa_data_field accepted &quot;Accepted&quot; { type_ref Boolean; direction Return; }
}
sa_interface navigation &quot;Navigation&quot; {}
sa_interface monitoring &quot;Monitoring&quot; {}
interface_item_allocation nav_operation &quot;Navigation operation&quot; {
source &#64;navigation; target &#64;navigate; transmission Synchronous; acquisition Accept;
}
interface_item_allocation monitor_operation &quot;Monitoring operation&quot; {
source &#64;monitoring; target &#64;navigate; transmission Asynchronous; acquisition Read;
}
data_association location_link &quot;Location relationship&quot; {
source &#64;coordinate; target &#64;located;
source_role &quot;location&quot;; target_role &quot;assets&quot;;
source_maximum 1;
}
}</code></pre>
</section>
</section>
<section id="diagrams-artifacts-and-cross-layer-traceability">
<h2>5. Diagrams, artifacts, and cross-layer traceability</h2>
@@ -1308,7 +1457,7 @@ remove or relocate incompatible placements in the same transaction. Context
errors use <span class="docutils literal">state_diagram_context</span>; incompatible placements use
<span class="docutils literal">state_diagram_member</span>. Neither case silently hides invalid members.</p>
<p>This complete source example places one state from an existing machine:</p>
<pre class="code text literal-block"><code>arcadia 3;
<pre class="code text literal-block"><code>arcadia 4;
project operating &quot;Operating modes&quot; {
oa_entity crew &quot;Crew&quot; {}
oa_state_machine modes &quot;Modes&quot; { parent &#64;crew; }
@@ -1517,7 +1666,7 @@ spellings can be used in alias positions because references begin with <span cla
<span class="docutils literal"><span class="pre">element-kind</span></span> and <span class="docutils literal"><span class="pre">relation-kind</span></span> are exactly the corresponding declaration
keywords listed above. Typed field
sets and enum constructors are closed by sections 3–5.</p>
<pre class="code text literal-block"><code>document = &quot;arcadia&quot; &quot;3&quot; &quot;;&quot; project
<pre class="code text literal-block"><code>document = &quot;arcadia&quot; &quot;4&quot; &quot;;&quot; project
project = &quot;project&quot; alias string identity? &quot;{&quot; project-entry* &quot;}&quot;
project-entry = &quot;description&quot; string &quot;;&quot; | declaration
declaration = element
@@ -1554,16 +1703,16 @@ Ordinary string fields require quoted strings and cannot contain an unquoted
<span class="docutils literal">&#64;alias</span> reference. Enum fields require unquoted named values or their typed
constructor records. Typed values MUST NOT nest more than 64 levels; malformed
deeply nested drafts produce a diagnostic instead of exhausting the parser stack.</p>
<section id="modular-source3-projects">
<h3>6.1. Modular source3 projects</h3>
<section id="modular-source-projects">
<h3>6.1. Modular source projects</h3>
<p>The pure <span class="docutils literal">source_project</span> core API compiles a virtual source bundle, containing
<span class="docutils literal">entry</span> and a <span class="docutils literal">files</span> map from logical paths to UTF-8 strings. Its entry is a
root-level <span class="docutils literal">.arcadia</span> file with the source3 project header above. A project entry
root-level <span class="docutils literal">.arcadia</span> file with the source4 project header above. A project entry
MAY also be <span class="docutils literal">include string &quot;;&quot;</span>. An included fragment consists only of ordinary
declarations and include statements; it MUST NOT contain another version header,
project wrapper, or project description. Includes MUST occur at document level,
never inside an element body or typed field value. For example:</p>
<pre class="literal-block">arcadia 3;
<pre class="literal-block">arcadia 4;
project rescue &quot;Rescue&quot; id &quot;00000000-0000-4000-8000-000000000001&quot; {
description &quot;Operational model&quot;;
include &quot;oa/participants.arcadia&quot;;
@@ -1621,9 +1770,12 @@ the source index. Columns remain one-based Unicode scalars within the real file;
spans never refer to concatenated or synthetic source.</p>
<p>Single-string parse/lint APIs remain filesystem-free and reject include
statements with an explicit source-bundle requirement. V1/V2 single-file imports
continue through their existing migration readers and reports. Modular projects
require source3; migration is performed before modular export, not independently
on included fragments. Modular source does not change the semantic JSON schema.</p>
continue through explicit migration. Modular projects accept source3 and source4;
source3 is upgraded as one project, preserving file paths, includes, nested
ownership and comments through targeted token edits. Generated allocation
declarations stay in their interface's existing file. Individual include fragments
are not independently migrated. Missing UUIDs stabilize before migration so new
allocation identities are deterministic on subsequent compilation.</p>
</section>
<section id="nested-element-ownership">
<h3>6.2. Nested element ownership</h3>
@@ -1827,9 +1979,31 @@ explicitly before Apply succeeds.</p>
<h2>9. Persistence and explicit migration</h2>
<p>Loading detects JSON from its first non-whitespace <span class="docutils literal">{</span>; other input is parsed
as Arcadia source regardless of filename. Saving an <span class="docutils literal">.arcadia</span> suffix uses
the accepted V3 source bundle (<span class="docutils literal">arcadia 3</span>); other suffixes use V3 JSON. Both forms preserve the same
the accepted V4 source bundle (<span class="docutils literal">arcadia 4</span>); other suffixes use V4 JSON. Both forms preserve the same
complete model. JSON rejects unknown fields throughout typed payloads,
duplicate maps, unsupported versions, and structural errors.</p>
<p>The schema-3 reader freezes the changed data payloads and old constructor catalog;
schema-4 fields/constructors MUST NOT be silently accepted as schema 3. Existing
typed PortContract records remain unchanged. Information/Material/Energy retain
their nature with Unspecified mechanism; old Event becomes Information with Event
mechanism. Old bounds/defaults/supertypes are absent, String length is 0..unbounded,
and fields retain type/multiplicity/unit with Unspecified direction, Value storage
and no explicit default. No physical mechanism or direction is guessed.</p>
<p>Each old Interface.items entry generates one InterfaceItemAllocation with its
original zero-based order and Unspecified protocols. UUID v5 uses the project UUID
namespace and name <span class="docutils literal"><span class="pre">v2-interface-item:&lt;interface-uuid&gt;:&lt;item-uuid&gt;</span></span> consistently
for schema-2 and schema-3 inputs. Aliases are deterministic and collision-free;
collision with any existing identity is an error rather than an overwrite. Existing
interface/item identities remain intact. Old nested message values acquire a path
only when exactly one valid path exists. Ambiguous paths, including recursive
reuse, retain the old annotation with a located warning rather than guessing.</p>
<p>Migration reports additionally contain <span class="docutils literal">semantic_defaults</span> (object, field,
description), <span class="docutils literal">generated_interface_allocations</span> (id, source, target, alias,
order) and <span class="docutils literal">unresolved_message_values</span> (occurrence, field, reason). These new
report arrays default empty when reading older responses. Version 1 normalizes
through V2, then the typed-port V3 adapter and this shared V4 data upgrade. Original
V2 and real V3 fixtures remain unchanged compatibility inputs. Current exports
always use version 4; reading/migrating alone never saves or changes revisions.</p>
<p>Native source Save All checks the original contents of observed dependencies
before staging writes. Existing target files are replaced individually and the
entry is installed last. A transaction journal records originals and intended
@@ -1853,7 +2027,7 @@ defaults without changing any prior identity, name, reference, order, geometry,
artifact or trace field. The original V2 golden source/JSON in
<span class="docutils literal"><span class="pre">crates/oa-core/tests/fixtures</span></span> MUST NOT be regenerated from the newer demo;
they verify that every old persistent field survives. Canonical output writes
the added defaults through the explicit schema-3 migration.</p>
the added defaults through the explicit schema-3 and schema-4 migrations.</p>
<p>The V2 adapter preserves every original identity, alias, prose, parent,
placement, trace and artifact. Generic ports become Legacy with their original
direction/interface record. Existing FE endpoint IDs remain unchanged. For
@@ -1870,13 +2044,13 @@ IDs, required resolutions, generated endpoint IDs/aliases/owners, and boundary
orientation defaults. REST import, replacement, candidate validation and
project snapshots surface the same report. Opening an old server envelope
preserves its resource ID/revision and bytes; the next explicit edit writes
schema 3. Model/source exports contain only the canonical model. Migration
schema 4. Model/source exports contain only the canonical model. Migration
reports are transient response metadata, not persisted model facts.</p>
<p>Admission checks account for generated objects and their references before
construction. Both the old V2 contract and the resulting V3 graph are
construction. Both the old V2 contract and the resulting V4 graph are
validated. Migration itself does not save or increase a stored revision.
Canonical second saves are stable. V1 normalization produces the frozen V2
model and then uses this same V2-to-3 stage.</p>
model and then uses these same V2-to-3-to-4 stages.</p>
<p>Save validates a snapshot, writes a sibling temporary file, flushes it, and
atomically replaces the destination. Failed serialization or validation must
not truncate a previous file. External concurrent-writer conflict resolution
@@ -1892,20 +2066,20 @@ step becomes a distinct occurrence element owned by its process. Generated
diagram, node, and occurrence identities use UUID v5 with the old Project ID
as namespace and deterministic role/index names. If such an identity collides,
a deterministic suffix is tried. Reimporting the same fully identified V1
input therefore yields the same V3 result, including repeated occurrences.
input therefore yields the same V4 result, including repeated occurrences.
No System or SA content is invented during an OA-only migration.</p>
<p>V1 source aliases are retained when valid in V2. JSON imports generate the old
canonical aliases deterministically. Any alias newly reserved in V2 is changed
by a deterministic suffix; aliases were not persistent V1 semantic data.
A project alias and aliases for new records are generated without colliding
with retained aliases. The existing bundled V1 text and JSON migrate to equal
V3 projects. Future versions remain errors until a separate migration exists.</p>
V4 projects. Future versions remain errors until a separate migration exists.</p>
</section>
<section id="complete-authoring-example">
<h2>10. Complete authoring example</h2>
<p>This document intentionally omits IDs for new authoring. Apply and Save write
the assigned UUIDs explicitly.</p>
<pre class="code text literal-block"><code>arcadia 3;
<pre class="code text literal-block"><code>arcadia 4;
project harbor &quot;Harbor assistance&quot; {
oa_entity control &quot;Harbor control&quot; {}
oa_activity assess &quot;Assess assistance&quot; {}
+223 -44
View File
@@ -1,7 +1,7 @@
Arcadia Studio OA / SA Language and Editing Contract
====================================================
:Version: 3
:Version: 4
:Status: Normative current implementation contract; first-release integration
:Core implementation: ``crates/oa-core``
:Text suffix: ``.arcadia``
@@ -11,15 +11,14 @@ Arcadia Studio OA / SA Language and Editing Contract
This specification defines the shared Operational Analysis (OA) and System
Analysis (SA) model, its textual language, graphical editing obligations,
validation, persistence, and explicit migration from versions 1 and 2. MUST, MUST NOT,
validation, persistence, and explicit migration from versions 1, 2 and 3. MUST, MUST NOT,
and MAY indicate requirements, prohibitions, and permitted choices.
Schema 3 introduces typed function and component ports, required functional
exchange endpoints, independently oriented boundary exchanges, and explicit
PortAllocation relations. First-release scenario/state additions remain in
scope; this schema change does not declare native acceptance or the wider
release complete. The preserved schema-2 reader validates the original
contract before migration.
Schema 4 adds bounded reusable data types, typed scalar defaults, exchange
mechanisms, qualified message values, specialization, identified interface
allocations and reference associations. It retains schema 3 typed ports and
state views. Explicit older readers preserve existing meanings and identities.
This contract does not by itself establish native acceptance or release completion.
OA describes stakeholders, operational work and needs. SA describes the
selected system boundary, external actors, functions, services and expected
@@ -40,7 +39,7 @@ Actual verification evidence is separate from this contract.
2. One authoritative model
--------------------------
A Project stores ``schema_version`` (3), ``id``, ``alias``, ``name``,
A Project stores ``schema_version`` (4), ``id``, ``alias``, ``name``,
``description``, and maps named ``elements``, ``relations``, ``diagrams``,
``artifact_links``, and ``traces``. Each map is keyed by the UUID contained in
its record. Duplicate map keys and mismatching keys/identities are errors.
@@ -96,17 +95,17 @@ lists all additional fields. ``ref`` means ``@alias``; ``ref?`` also accepts
- ``steps``: occurrence refs
- ``[]``
* - ``oa_exchange_item``, ``sa_exchange_item``
- ``kind``: Information, Material, Energy, Event
- Information
- ``kind``: Information, Material, Energy; ``mechanism``: ExchangeMechanism; ``supertype``: item ref?
- Information; Unspecified; none
* - ``oa_data_type``, ``sa_data_type``
- ``definition``: Boolean, Integer, Real, String, Record, or Enumeration constructor
- String
- ``definition``: DataTypeDefinition; ``default``: DataValue?; ``unit``: string
- String with minimum_length 0 / maximum_length none; none; ``""``
* - ``oa_data_field``, ``sa_data_field``
- ``type_ref``; ``minimum``: u32; ``maximum``: optional u32; ``unit``: string
- String; 1; 1; ``""``
- ``type_ref``; ``minimum``: u32; ``maximum``: optional u32; ``unit``: string; ``direction``: ParameterDirection; ``storage``: FieldStorage; ``default``: DataValue list?
- String; 1; 1; ``""``; Unspecified; Value; none
* - ``oa_interface``, ``sa_interface``
- ``items``: exchange-item refs
- ``[]``
- ``supertype``: interface ref?
- none; membership is an identified interface_item_allocation relation
* - ``oa_port``, ``sa_port``
- ``contract``: required PortContract; ``legacy``: optional LegacyPortContract
- No implicit contract; ``legacy`` defaults none. OA admits Legacy only.
@@ -230,6 +229,12 @@ references. Their kind is the declaration keyword:
* - ``allocation``
- Same-layer participant → leaf activity/function
- None
* - ``interface_item_allocation``
- Same-layer Interface → ExchangeItem
- ``order`` u32 / 0; ``transmission`` TransmissionProtocol / Unspecified; ``acquisition`` AcquisitionProtocol / Unspecified
* - ``data_association``
- Same-layer Record DataType → Record DataType
- ``source_role``, ``target_role`` / ""; ``source_minimum``, ``target_minimum`` / 0; ``source_maximum``, ``target_maximum`` / none; ``source_navigable``, ``target_navigable`` / false
* - ``interaction``
- OA activity → OA activity
- ``items`` refs / []
@@ -290,7 +295,8 @@ references. Their kind is the declaration keyword:
Relation endpoints and carried ExchangeItems stay in the same layer. Parallel
exchanges with distinct identities are permitted. Self-relations are invalid
except for a state transition that returns to its source state.
except for a state transition that returns to its source state or an explicit
DataAssociation between two ends of the same Record type.
Direct Allocation has at most one performer per leaf. Role sharing is a
different relationship: several OA participants can realize a Role. A direct
@@ -305,9 +311,10 @@ declares ``outgoing_items``; ``FunctionInput`` declares ``incoming_items``.
The lists contain distinct same-layer ExchangeItem references. A functional
exchange MUST reference output/input ports owned by its respective functions,
and each carried item MUST fit both declarations. Empty declarations accept
no items. Item compatibility is identity equality; future specialization is
not inferred from names. Port declarations remain independent of incident
exchanges after creation.
no items. A carried item satisfies an identical declaration or a declaration
of one of its explicit base items. A base item does not satisfy a more
specialized declaration; names imply no compatibility. Port declarations
remain independent of incident exchanges after creation.
A ``Component`` contract belongs to an SA System or SystemActor and stores
``kind`` (Standard or Flow) and ``orientation`` (Unset, In, Out, InOut).
@@ -347,12 +354,13 @@ Port deletion cascades to incident FEs; FE deletion retains independent ports.
For example::
arcadia 3;
arcadia 4;
project ports_example "Typed function contract" {
sa_function send "Send" {}
sa_function receive "Receive" {}
sa_exchange_item payload "Payload" {}
sa_interface old_service "Preserved service" { items [@payload]; }
sa_interface old_service "Preserved service" {}
interface_item_allocation service_payload "Service payload" { source @old_service; target @payload; }
sa_port output "Output" {
parent @send;
contract { FunctionOutput { outgoing_items [@payload]; }; };
@@ -474,11 +482,19 @@ no receiver or the same receiver as sender. Its nonempty expression describes
the delay/deadline; an empty expression warns. Conditions and expressions are
stored engineering annotations, not an executable simulation language.
Each MessageValue is ``{ field @data_field; expression "value expression"; }``.
The field MUST be a DataField carried by the message exchange, including fields
inside named nested records. At most one annotation for a given field is
allowed in one message. Values do not overwrite the referenced type or global
exchange item. Expression text is preserved exactly; an empty expression warns.
Each MessageValue is ``{ path [@parameter]; field @data_field; expression "value expression"; }``.
Its identity is the pair (path, field), so two uses of one Record can have
different values for the same terminal field. Path contains enclosing DataField
references, excluding the terminal field; direct parameters use ``[]``. Every
hop MUST follow Value storage through a named Record's effective fields. Reference
storage stops traversal. Operation Call accepts In/InOut and Reply accepts
Out/InOut/Return, interpreted from the provider's perspective. Nested field paths
inherit their direct parameter's direction. Unspecified direction warns.
At most one annotation for a pair is allowed. Omitted path defaults to ``[]``;
an ambiguous preserved legacy nested annotation warns ``message_value_ambiguous_path``
until an explicit path is selected. New graphical choices always identify a path.
Values never overwrite types or items. Expression text is descriptive, preserved
exactly and not evaluated; an empty expression warns.
ScenarioUse references an existing same-layer scenario and maps its lifelines
with ``bindings [ { referenced @callee_line; local @caller_line; } ];``.
@@ -620,6 +636,141 @@ DeepHistory remembers nested configuration. Fallback applies when no resumable
history exists. History is per Region, including top-level Regions in this
Studio profile; no running history state is persisted or synthesized.
4.5. Data contracts, specialization and interface allocation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ExchangeItem ``kind`` describes nature: Information, Material or Energy.
``mechanism`` is Unspecified, Flow, Event, Operation or SharedData. Unknown
mechanisms remain explicit Unspecified drafts with a warning. Material/Energy
with Event/Operation/SharedData warns for engineering review; it is not silently
reclassified. Empty Event notifications and void Operations are valid. An empty
carried/allocated Flow, SharedData or Unspecified item warns.
An Operation's directly owned DataFields are parameters. ``direction`` is
Unspecified, In, Out, InOut or Return, from the provider's perspective. At most
one effective parameter is Return. Unspecified parameters warn; non-operation
fields MUST use Unspecified. Nested record fields inherit direction from their
direct parameter when used in message paths, rather than storing context on a
shared type. ``storage`` is Value or Reference. Reference requires a named Record,
has no explicit default, and does not convey ownership or deletion of the type.
DataTypeDefinition has exactly the following constructors:
.. list-table:: Reusable definitions
:header-rows: 1
* - Constructor
- Required fields
* - Boolean
- None
* - Integer
- ``minimum``, ``maximum``: optional signed 64-bit integers
* - Real
- ``minimum``, ``maximum``: optional finite IEEE-754 binary64 values
* - String
- ``minimum_length``: u32; ``maximum_length``: optional u32
* - Enumeration
- ``literals``: unique nonempty, case-sensitive strings
* - Record
- ``supertype``: same-layer Record ref?
Bounds are inclusive and ordered; an absent bound means unbounded within the
represented numeric domain. Integer comparisons MUST NOT convert to binary64.
NaN, infinities, overflow and reversed bounds reject. String length counts Unicode
scalar values, not UTF-8 bytes or grapheme clusters. Enum defaults match exact
literals. Empty enum definitions remain incomplete drafts with a warning.
DataValue is a tagged scalar: ``{ Boolean true; }``, ``{ Integer 42; }``,
``{ Real 1.5; }``, ``{ String "value"; }`` or ``{ Enumeration "Ready"; }``.
There is no implicit numeric or string coercion. A type default is one compatible
scalar within its bounds. Record type defaults and record/object instance literals
are unsupported. A field default is absent (``none``) or a list of compatible
scalars with length inside its multiplicity. ``[]`` explicitly supplies an empty
collection and requires minimum 0, including Value Record fields; a nonempty
Record literal rejects. Reference fields MUST use ``none``. A one-valued scalar
field uses a one-value list. A named type default supplies an individual element's
default, not a collection or an implicit instance of a mandatory field.
Numeric types may carry unit text. Empty field units inherit the named type unit;
an explicit different unit warns when that type has a unit. Units on nonnumeric
fields/types warn and remain preserved. Unit strings never convert values or
establish dimensional compatibility. Expressions are not executed.
Record, ExchangeItem and Interface each permit one same-family, same-layer
supertype. Specialization is acyclic and separate from containment. Effective
fields are base fields followed by local fields, preserving original field UUIDs
and owners. Local names MUST NOT shadow inherited names. Item specialization
preserves base nature and any specified mechanism; an Unspecified base mechanism
may be refined. Deleting a derived record never deletes its base. Mandatory
Value-field cycles warn ``record_no_finite_value``; optional or Reference cycles
are valid without that warning. Traversal is cycle guarded and bounded; a payload
path budget failure is an explicit diagnostic, not silent truncation.
InterfaceItemAllocation is an ordinary identified relation from Interface to
ExchangeItem. It stores ``order`` and independent transmission/acquisition
protocols. Transmission is Unspecified, Synchronous, Asynchronous, Unicast,
Multicast or Broadcast; acquisition is Unspecified, Read or Accept. No protocol
combination is inferred from mechanism. Effective allocations are base-first,
then local ordered by (order, alias, UUID). A local item already allocated locally
or inherited is an error. Removing an allocation keeps its item and other
allocations; if live boundary compatibility would break, the transaction MUST
repair the affected contract explicitly or reject atomically. Artifacts can
reference the allocation identity independently of the global item.
An exchange carrying a specialized item satisfies a declaration of its base,
never the reverse. Standard provided/required compatibility uses explicit
interface ancestry. Identity/ancestry, not matching names, defines conformance.
The current typed function/component port contracts remain unchanged.
DataAssociation connects Record types without adding fields or transitively
carrying payload. Each named end has role, multiplicity and navigability. Source
multiplicity counts source instances per target instance and vice versa; it is
not a count of model elements. An end's navigable flag permits navigation toward
that end. Self-associations are valid; if both ends are navigable they require
distinct nonempty roles. Empty roles and duplicate role contracts warn, whereas
invalid ranges reject. Composition/shared aggregation, multiple inheritance,
redefinition, instance literals and arbitrary-precision decimal arithmetic are
outside this bounded contract.
This complete data contract example is also exercised through the REST API:
.. code-block:: text
arcadia 4;
project engineering_data "Engineering data" {
sa_data_type voltage "Voltage" {
definition { Real { minimum 0.0; maximum 48.0; }; };
default { Real 24.0; }; unit "V";
}
sa_data_type coordinate "Coordinate" {
definition { Record { supertype none; }; };
sa_data_field latitude "Latitude" { type_ref Real; }
}
sa_data_type located "Located asset" {
definition { Record { supertype @coordinate; }; };
sa_data_field supply "Supply" { type_ref { Named @voltage; }; }
}
sa_exchange_item navigate "Navigate" {
mechanism Operation;
sa_data_field origin "Origin" { type_ref { Named @coordinate; }; direction In; }
sa_data_field destination "Destination" { type_ref { Named @coordinate; }; direction In; }
sa_data_field accepted "Accepted" { type_ref Boolean; direction Return; }
}
sa_interface navigation "Navigation" {}
sa_interface monitoring "Monitoring" {}
interface_item_allocation nav_operation "Navigation operation" {
source @navigation; target @navigate; transmission Synchronous; acquisition Accept;
}
interface_item_allocation monitor_operation "Monitoring operation" {
source @monitoring; target @navigate; transmission Asynchronous; acquisition Read;
}
data_association location_link "Location relationship" {
source @coordinate; target @located;
source_role "location"; target_role "assets";
source_maximum 1;
}
}
5. Diagrams, artifacts, and cross-layer traceability
----------------------------------------------------
@@ -654,7 +805,7 @@ This complete source example places one state from an existing machine:
.. code-block:: text
arcadia 3;
arcadia 4;
project operating "Operating modes" {
oa_entity crew "Crew" {}
oa_state_machine modes "Modes" { parent @crew; }
@@ -875,7 +1026,7 @@ sets and enum constructors are closed by sections 3–5.
.. code-block:: text
document = "arcadia" "3" ";" project
document = "arcadia" "4" ";" project
project = "project" alias string identity? "{" project-entry* "}"
project-entry = "description" string ";" | declaration
declaration = element
@@ -917,18 +1068,18 @@ Ordinary string fields require quoted strings and cannot contain an unquoted
constructor records. Typed values MUST NOT nest more than 64 levels; malformed
deeply nested drafts produce a diagnostic instead of exhausting the parser stack.
6.1. Modular source3 projects
6.1. Modular source projects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The pure ``source_project`` core API compiles a virtual source bundle, containing
``entry`` and a ``files`` map from logical paths to UTF-8 strings. Its entry is a
root-level ``.arcadia`` file with the source3 project header above. A project entry
root-level ``.arcadia`` file with the source4 project header above. A project entry
MAY also be ``include string ";"``. An included fragment consists only of ordinary
declarations and include statements; it MUST NOT contain another version header,
project wrapper, or project description. Includes MUST occur at document level,
never inside an element body or typed field value. For example::
arcadia 3;
arcadia 4;
project rescue "Rescue" id "00000000-0000-4000-8000-000000000001" {
description "Operational model";
include "oa/participants.arcadia";
@@ -994,9 +1145,12 @@ spans never refer to concatenated or synthetic source.
Single-string parse/lint APIs remain filesystem-free and reject include
statements with an explicit source-bundle requirement. V1/V2 single-file imports
continue through their existing migration readers and reports. Modular projects
require source3; migration is performed before modular export, not independently
on included fragments. Modular source does not change the semantic JSON schema.
continue through explicit migration. Modular projects accept source3 and source4;
source3 is upgraded as one project, preserving file paths, includes, nested
ownership and comments through targeted token edits. Generated allocation
declarations stay in their interface's existing file. Individual include fragments
are not independently migrated. Missing UUIDs stabilize before migration so new
allocation identities are deterministic on subsequent compilation.
6.2. Nested element ownership
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1228,10 +1382,35 @@ explicitly before Apply succeeds.
Loading detects JSON from its first non-whitespace ``{``; other input is parsed
as Arcadia source regardless of filename. Saving an ``.arcadia`` suffix uses
the accepted V3 source bundle (``arcadia 3``); other suffixes use V3 JSON. Both forms preserve the same
the accepted V4 source bundle (``arcadia 4``); other suffixes use V4 JSON. Both forms preserve the same
complete model. JSON rejects unknown fields throughout typed payloads,
duplicate maps, unsupported versions, and structural errors.
The schema-3 reader freezes the changed data payloads and old constructor catalog;
schema-4 fields/constructors MUST NOT be silently accepted as schema 3. Existing
typed PortContract records remain unchanged. Information/Material/Energy retain
their nature with Unspecified mechanism; old Event becomes Information with Event
mechanism. Old bounds/defaults/supertypes are absent, String length is 0..unbounded,
and fields retain type/multiplicity/unit with Unspecified direction, Value storage
and no explicit default. No physical mechanism or direction is guessed.
Each old Interface.items entry generates one InterfaceItemAllocation with its
original zero-based order and Unspecified protocols. UUID v5 uses the project UUID
namespace and name ``v2-interface-item:<interface-uuid>:<item-uuid>`` consistently
for schema-2 and schema-3 inputs. Aliases are deterministic and collision-free;
collision with any existing identity is an error rather than an overwrite. Existing
interface/item identities remain intact. Old nested message values acquire a path
only when exactly one valid path exists. Ambiguous paths, including recursive
reuse, retain the old annotation with a located warning rather than guessing.
Migration reports additionally contain ``semantic_defaults`` (object, field,
description), ``generated_interface_allocations`` (id, source, target, alias,
order) and ``unresolved_message_values`` (occurrence, field, reason). These new
report arrays default empty when reading older responses. Version 1 normalizes
through V2, then the typed-port V3 adapter and this shared V4 data upgrade. Original
V2 and real V3 fixtures remain unchanged compatibility inputs. Current exports
always use version 4; reading/migrating alone never saves or changes revisions.
Native source Save All checks the original contents of observed dependencies
before staging writes. Existing target files are replaced individually and the
entry is installed last. A transaction journal records originals and intended
@@ -1256,7 +1435,7 @@ defaults without changing any prior identity, name, reference, order, geometry,
artifact or trace field. The original V2 golden source/JSON in
``crates/oa-core/tests/fixtures`` MUST NOT be regenerated from the newer demo;
they verify that every old persistent field survives. Canonical output writes
the added defaults through the explicit schema-3 migration.
the added defaults through the explicit schema-3 and schema-4 migrations.
The V2 adapter preserves every original identity, alias, prose, parent,
placement, trace and artifact. Generic ports become Legacy with their original
@@ -1275,14 +1454,14 @@ IDs, required resolutions, generated endpoint IDs/aliases/owners, and boundary
orientation defaults. REST import, replacement, candidate validation and
project snapshots surface the same report. Opening an old server envelope
preserves its resource ID/revision and bytes; the next explicit edit writes
schema 3. Model/source exports contain only the canonical model. Migration
schema 4. Model/source exports contain only the canonical model. Migration
reports are transient response metadata, not persisted model facts.
Admission checks account for generated objects and their references before
construction. Both the old V2 contract and the resulting V3 graph are
construction. Both the old V2 contract and the resulting V4 graph are
validated. Migration itself does not save or increase a stored revision.
Canonical second saves are stable. V1 normalization produces the frozen V2
model and then uses this same V2-to-3 stage.
model and then uses these same V2-to-3-to-4 stages.
Save validates a snapshot, writes a sibling temporary file, flushes it, and
atomically replaces the destination. Failed serialization or validation must
@@ -1301,7 +1480,7 @@ step becomes a distinct occurrence element owned by its process. Generated
diagram, node, and occurrence identities use UUID v5 with the old Project ID
as namespace and deterministic role/index names. If such an identity collides,
a deterministic suffix is tried. Reimporting the same fully identified V1
input therefore yields the same V3 result, including repeated occurrences.
input therefore yields the same V4 result, including repeated occurrences.
No System or SA content is invented during an OA-only migration.
V1 source aliases are retained when valid in V2. JSON imports generate the old
@@ -1309,7 +1488,7 @@ canonical aliases deterministically. Any alias newly reserved in V2 is changed
by a deterministic suffix; aliases were not persistent V1 semantic data.
A project alias and aliases for new records are generated without colliding
with retained aliases. The existing bundled V1 text and JSON migrate to equal
V3 projects. Future versions remain errors until a separate migration exists.
V4 projects. Future versions remain errors until a separate migration exists.
10. Complete authoring example
------------------------------
@@ -1319,7 +1498,7 @@ the assigned UUIDs explicitly.
.. code-block:: text
arcadia 3;
arcadia 4;
project harbor "Harbor assistance" {
oa_entity control "Harbor control" {}
oa_activity assess "Assess assistance" {}
+652 -63
View File
@@ -3,7 +3,7 @@
"info": {
"title": "Arcadia Studio model API",
"version": "1.0.0",
"description": "Current schema-3 snapshots and conditional atomic writes. Request body limit: 8 MiB; at most 200 nested commands; no retained revisions, request receipts, automatic retries or persistent transition plans. See docs/api.rst. Fixed store capacity: 128 models / 256 MiB serialized envelopes. Stateless transition preview/apply. Artifact URI/revision strings remain opaque core fields. Model admission before structural validation: 5,000 graph objects, 20,000 total records and 50,000 ordered references. Preparation uses snapshots outside the catalog lock; final commits recheck the exact ETag. Each accepted envelope couples model and authored source under one revision. Source-only edits advance the shared ETag. Source bundles resolve logical paths only, preserve authored files/comments, and have a stabilized JSON cap of 8 MiB, 256 files, 32 include edges along a path and 1,024 include edges overall."
"description": "Current schema-4 snapshots and conditional atomic writes. Request body limit: 8 MiB; at most 200 nested commands; no retained revisions, request receipts, automatic retries or persistent transition plans. See docs/api.rst. Fixed store capacity: 128 models / 256 MiB serialized envelopes. Stateless transition preview/apply. Artifact URI/revision strings remain opaque core fields. Model admission before structural validation: 5,000 graph objects, 20,000 total records and 50,000 ordered references. Preparation uses snapshots outside the catalog lock; final commits recheck the exact ETag. Each accepted envelope couples model and authored source under one revision. Source-only edits advance the shared ETag. Source bundles resolve logical paths only, preserve authored files/comments, and have a stabilized JSON cap of 8 MiB, 256 files, 32 include edges along a path and 1,024 include edges overall."
},
"servers": [
{
@@ -389,7 +389,7 @@
}
}
},
"description": "Schema-3 native JSON is described below. Schema-1 and schema-2 JSON/source are accepted through explicit frozen readers and migration, also on replacement and candidate validation. Reports list preserved Legacy contracts, generated FE endpoint IDs/aliases and boundary orientation defaults. Export emits schema 3 / arcadia 3. See docs/language.rst."
"description": "Schema-4 native JSON is described below. Schema-1, schema-2 and schema-3 JSON/source are accepted through explicit frozen readers and migration, also on replacement and candidate validation. Reports list preserved Legacy contracts, generated FE endpoint IDs/aliases and boundary orientation defaults. Export emits schema 4 / arcadia 4. See docs/language.rst."
}
},
"/api/v1/projects/{id}": {
@@ -1902,7 +1902,9 @@
"CapabilityGeneralization",
"MissionInvolvement",
"SequenceLink",
"PortAllocation"
"PortAllocation",
"InterfaceItemAllocation",
"DataAssociation"
]
},
"Position": {
@@ -2004,40 +2006,185 @@
{
"type": "string",
"enum": [
"Boolean",
"Integer",
"Real",
"String",
"Record"
"Boolean"
]
},
{
"oneOf": [
{
"type": "object",
"properties": {
"Integer": {
"type": "object",
"properties": {
"Enumeration": {
"type": "object",
"properties": {
"literals": {
"type": "array",
"items": {
"type": "string"
}
"minimum": {
"anyOf": [
{
"type": "integer",
"format": "int64",
"minimum": -9223372036854775808,
"maximum": 9223372036854775807
},
{
"type": "null"
}
},
"required": [
"literals"
],
"additionalProperties": false
]
},
"maximum": {
"anyOf": [
{
"type": "integer",
"format": "int64",
"minimum": -9223372036854775808,
"maximum": 9223372036854775807
},
{
"type": "null"
}
]
}
},
"required": [
"Enumeration"
"minimum",
"maximum"
],
"additionalProperties": false
}
]
},
"required": [
"Integer"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Real": {
"type": "object",
"properties": {
"minimum": {
"anyOf": [
{
"type": "number",
"format": "double",
"description": "Finite IEEE-754 binary64; no coercion from typed Integer values."
},
{
"type": "null"
}
]
},
"maximum": {
"anyOf": [
{
"type": "number",
"format": "double",
"description": "Finite IEEE-754 binary64; no coercion from typed Integer values."
},
{
"type": "null"
}
]
}
},
"required": [
"minimum",
"maximum"
],
"additionalProperties": false
}
},
"required": [
"Real"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"String": {
"type": "object",
"properties": {
"minimum_length": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"maximum_length": {
"anyOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
{
"type": "null"
}
]
}
},
"required": [
"minimum_length",
"maximum_length"
],
"additionalProperties": false
}
},
"required": [
"String"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Enumeration": {
"type": "object",
"properties": {
"literals": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"literals"
],
"additionalProperties": false
}
},
"required": [
"Enumeration"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Record": {
"type": "object",
"properties": {
"supertype": {
"anyOf": [
{
"type": "string",
"format": "uuid"
},
{
"type": "null"
}
]
}
},
"required": [
"supertype"
],
"additionalProperties": false
}
},
"required": [
"Record"
],
"additionalProperties": false
}
]
},
@@ -2402,17 +2549,27 @@
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": [
"Information",
"Material",
"Energy",
"Event"
"$ref": "#/components/schemas/ExchangeItemKind"
},
"mechanism": {
"$ref": "#/components/schemas/ExchangeMechanism"
},
"supertype": {
"anyOf": [
{
"type": "string",
"format": "uuid"
},
{
"type": "null"
}
]
}
},
"required": [
"kind"
"kind",
"mechanism",
"supertype"
],
"additionalProperties": false
}
@@ -2430,10 +2587,25 @@
"properties": {
"definition": {
"$ref": "#/components/schemas/DataTypeDefinition"
},
"default": {
"anyOf": [
{
"$ref": "#/components/schemas/DataValue"
},
{
"type": "null"
}
]
},
"unit": {
"type": "string"
}
},
"required": [
"definition"
"definition",
"default",
"unit"
],
"additionalProperties": false
}
@@ -2454,13 +2626,15 @@
},
"minimum": {
"type": "integer",
"minimum": 0
"minimum": 0,
"maximum": 4294967295
},
"maximum": {
"anyOf": [
{
"type": "integer",
"minimum": 0
"minimum": 0,
"maximum": 4294967295
},
{
"type": "null"
@@ -2469,13 +2643,35 @@
},
"unit": {
"type": "string"
},
"direction": {
"$ref": "#/components/schemas/ParameterDirection"
},
"storage": {
"$ref": "#/components/schemas/FieldStorage"
},
"default": {
"anyOf": [
{
"type": "array",
"items": {
"$ref": "#/components/schemas/DataValue"
}
},
{
"type": "null"
}
]
}
},
"required": [
"type_ref",
"minimum",
"maximum",
"unit"
"unit",
"direction",
"storage",
"default"
],
"additionalProperties": false
}
@@ -2491,16 +2687,20 @@
"Interface": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "string",
"format": "uuid"
}
"supertype": {
"anyOf": [
{
"type": "string",
"format": "uuid"
},
{
"type": "null"
}
]
}
},
"required": [
"items"
"supertype"
],
"additionalProperties": false
}
@@ -3581,6 +3781,128 @@
"PortAllocation"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"InterfaceItemAllocation": {
"type": "object",
"properties": {
"source": {
"type": "string",
"format": "uuid"
},
"target": {
"type": "string",
"format": "uuid"
},
"order": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"transmission": {
"$ref": "#/components/schemas/TransmissionProtocol"
},
"acquisition": {
"$ref": "#/components/schemas/AcquisitionProtocol"
}
},
"required": [
"source",
"target",
"order",
"transmission",
"acquisition"
],
"additionalProperties": false
}
},
"required": [
"InterfaceItemAllocation"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"DataAssociation": {
"type": "object",
"properties": {
"source": {
"type": "string",
"format": "uuid"
},
"target": {
"type": "string",
"format": "uuid"
},
"source_role": {
"type": "string"
},
"target_role": {
"type": "string"
},
"source_minimum": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"source_maximum": {
"anyOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
{
"type": "null"
}
]
},
"target_minimum": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"target_maximum": {
"anyOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
{
"type": "null"
}
]
},
"source_navigable": {
"type": "boolean"
},
"target_navigable": {
"type": "boolean"
}
},
"required": [
"source",
"target",
"source_role",
"target_role",
"source_minimum",
"source_maximum",
"target_minimum",
"target_maximum",
"source_navigable",
"target_navigable"
],
"additionalProperties": false
}
},
"required": [
"DataAssociation"
],
"additionalProperties": false
}
]
},
@@ -3617,7 +3939,12 @@
},
"PortAnchorSide": {
"type": "string",
"enum": ["Left", "Right", "Top", "Bottom"],
"enum": [
"Left",
"Right",
"Top",
"Bottom"
],
"description": "Presentation side of the owner placement; independent of semantic port direction."
},
"PortAnchor": {
@@ -3638,7 +3965,11 @@
"description": "Finite binary32 fraction of the complete owner edge, measured from top on Left/Right and from left on Top/Bottom."
}
},
"required": ["port", "side", "offset"],
"required": [
"port",
"side",
"offset"
],
"additionalProperties": false
},
"NodePlacement": {
@@ -3956,7 +4287,7 @@
"properties": {
"schema_version": {
"type": "integer",
"const": 3
"const": 4
},
"id": {
"type": "string",
@@ -4070,7 +4401,7 @@
"source_project"
],
"additionalProperties": false,
"description": "Accepted coupled model/source snapshot. Compiling source_project reproduces model; revision changes once if either representation changes. Old model-only envelopes acquire source in memory without a write or revision change."
"description": "Accepted coupled model/source snapshot. Compiling source_project reproduces model; revision changes once if either representation changes. Older model-only or schema3 coupled envelopes migrate in memory without a write or revision change; both representations must independently migrate to the same graph."
},
"ProjectSummary": {
"type": "object",
@@ -4814,15 +5145,29 @@
"type": "object",
"description": "Upsert manual port position by port identity on an existing owner placement, preserving unrelated entries. Port must be a direct child of the placement's semantic element.",
"properties": {
"diagram": { "type": "string", "format": "uuid" },
"node": { "type": "string", "format": "uuid" },
"anchor": { "$ref": "#/components/schemas/PortAnchor" }
"diagram": {
"type": "string",
"format": "uuid"
},
"node": {
"type": "string",
"format": "uuid"
},
"anchor": {
"$ref": "#/components/schemas/PortAnchor"
}
},
"required": ["diagram", "node", "anchor"],
"required": [
"diagram",
"node",
"anchor"
],
"additionalProperties": false
}
},
"required": ["SetPortAnchor"],
"required": [
"SetPortAnchor"
],
"additionalProperties": false
},
{
@@ -4832,15 +5177,30 @@
"type": "object",
"description": "Restore automatic positioning for an existing direct child Port. No-op when that valid owner placement has no manual anchor for the port; wrong or stale ownership is rejected.",
"properties": {
"diagram": { "type": "string", "format": "uuid" },
"node": { "type": "string", "format": "uuid" },
"port": { "type": "string", "format": "uuid" }
"diagram": {
"type": "string",
"format": "uuid"
},
"node": {
"type": "string",
"format": "uuid"
},
"port": {
"type": "string",
"format": "uuid"
}
},
"required": ["diagram", "node", "port"],
"required": [
"diagram",
"node",
"port"
],
"additionalProperties": false
}
},
"required": ["RemovePortAnchor"],
"required": [
"RemovePortAnchor"
],
"additionalProperties": false
},
{
@@ -5809,6 +6169,14 @@
"MessageValue": {
"type": "object",
"properties": {
"path": {
"type": "array",
"items": {
"type": "string",
"format": "uuid"
},
"default": []
},
"field": {
"type": "string",
"format": "uuid"
@@ -5821,7 +6189,8 @@
"field",
"expression"
],
"additionalProperties": false
"additionalProperties": false,
"description": "Identity is (path, field). Path lists enclosing DataField UUIDs, excluding the terminal field. Value storage traverses named Records; Reference storage stops traversal. Operation Call accepts In/InOut and Reply accepts Out/InOut/Return. Unspecified direction and retained ambiguous legacy empty paths warn. Expressions are descriptive, never executed."
},
"LifelineBinding": {
"type": "object",
@@ -6083,12 +6452,13 @@
"type": "integer",
"enum": [
1,
2
2,
3
]
},
"to_schema": {
"type": "integer",
"const": 3
"const": 4
},
"preserved_ports": {
"type": "array",
@@ -6179,6 +6549,91 @@
"type": "string",
"format": "uuid"
}
},
"semantic_defaults": {
"type": "array",
"items": {
"type": "object",
"properties": {
"object": {
"type": "string",
"format": "uuid"
},
"field": {
"type": "string"
},
"description": {
"type": "string"
}
},
"required": [
"object",
"field",
"description"
],
"additionalProperties": false
}
},
"generated_interface_allocations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"source": {
"type": "string",
"format": "uuid"
},
"target": {
"type": "string",
"format": "uuid"
},
"alias": {
"type": "string"
},
"order": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"id",
"source",
"target",
"alias",
"order"
],
"additionalProperties": false
}
},
"unresolved_message_values": {
"type": "array",
"items": {
"type": "object",
"properties": {
"occurrence": {
"type": "string",
"format": "uuid"
},
"field": {
"type": "string",
"format": "uuid"
},
"reason": {
"type": "string"
}
},
"required": [
"occurrence",
"field",
"reason"
],
"additionalProperties": false
}
}
},
"required": [
@@ -6190,11 +6645,11 @@
"required_resolutions"
],
"additionalProperties": false,
"description": "Transient observations from explicit V1→V2→V3 or V2→V3 migration. No save or revision increase occurs merely by reading an old envelope."
"description": "Transient observations from explicit V1/V2/V3 to V4 migration. New report lists default to empty when reading older responses. Reading an old envelope neither saves nor changes its revision. Allocation UUIDv5 uses project namespace and v2-interface-item:<interface>:<item>."
},
"SourceBundle": {
"type": "object",
"description": "Complete source3 workspace. The entry is a root filename. Files use canonical portable slash-separated relative .arcadia paths and all must be reachable. Includes resolve only against this map, never the service filesystem. Up to 256 files, 32 include edges along a path and 1,024 include edges overall. Serialized bundle JSON is at most 8 MiB, checked again after missing UUIDs are inserted. GET returns exact accepted stable text.",
"description": "Complete source4 workspace (source3 migrates explicitly). The entry is a root filename. Files use canonical portable slash-separated relative .arcadia paths and all must be reachable. Includes resolve only against this map, never the service filesystem. Up to 256 files, 32 include edges along a path and 1,024 include edges overall. Serialized bundle JSON is at most 8 MiB, checked again after missing UUIDs are inserted. GET returns exact accepted stable text.",
"properties": {
"entry": {
"type": "string"
@@ -6267,15 +6722,149 @@
},
"source_project": {
"$ref": "#/components/schemas/SourceBundle"
},
"migration": {
"anyOf": [
{
"$ref": "#/components/schemas/MigrationReport"
},
{
"type": "null"
}
]
}
},
"required": [
"revision",
"changed",
"issues",
"source_project"
"source_project",
"migration"
],
"additionalProperties": false
},
"ExchangeItemKind": {
"type": "string",
"enum": [
"Information",
"Material",
"Energy"
]
},
"ExchangeMechanism": {
"type": "string",
"enum": [
"Unspecified",
"Flow",
"Event",
"Operation",
"SharedData"
]
},
"ParameterDirection": {
"type": "string",
"enum": [
"Unspecified",
"In",
"Out",
"InOut",
"Return"
]
},
"FieldStorage": {
"type": "string",
"enum": [
"Value",
"Reference"
]
},
"TransmissionProtocol": {
"type": "string",
"enum": [
"Unspecified",
"Synchronous",
"Asynchronous",
"Unicast",
"Multicast",
"Broadcast"
]
},
"AcquisitionProtocol": {
"type": "string",
"enum": [
"Unspecified",
"Read",
"Accept"
]
},
"DataValue": {
"oneOf": [
{
"type": "object",
"properties": {
"Boolean": {
"type": "boolean"
}
},
"required": [
"Boolean"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Integer": {
"type": "integer",
"format": "int64",
"minimum": -9223372036854775808,
"maximum": 9223372036854775807
}
},
"required": [
"Integer"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Real": {
"type": "number",
"format": "double",
"description": "Finite IEEE-754 binary64; no coercion from typed Integer values."
}
},
"required": [
"Real"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"String": {
"type": "string"
}
},
"required": [
"String"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"Enumeration": {
"type": "string"
}
},
"required": [
"Enumeration"
],
"additionalProperties": false
}
]
}
}
}
+3 -3
View File
@@ -8,12 +8,12 @@ Arcadia Studio implements a systems-engineering workbench spanning Operational A
|---|---|
| Operational Analysis | Entities, actors, roles, activities, missions, capabilities and processes; entity/work decomposition; leaf allocation; role realization/assignment; interactions and capability/process involvement |
| System Analysis | One System of Interest, external Actors, functions, missions, capabilities and functional chains; functional decomposition independent of the system boundary; allocation, functional/boundary exchanges and mission-capability links |
| Data and interfaces | Information/material/energy/event exchange items, primitive/enum/record data types, typed fields with multiplicity/units, separate function input/output and Standard/Flow component ports, interface provision/requirement, port and exchange allocations |
| Data and interfaces | Information/material/energy nature and Flow/Event/Operation/SharedData mechanisms, bounded primitive/enum/record types, typed defaults, field multiplicity/units/direction/storage, specialization, identified interface allocations and reference associations, separate function input/output and Standard/Flow component ports, interface provision/requirement, port and exchange allocations |
| Behavior | Process/chain work and exchange contributions, control topology and sequence reuse; scenario lifelines, correlated calls/replies, timers, action/state occurrences, ALT/PAR/LOOP/OPTIONAL fragments, scenario reuse and pre/postconditions |
| States and conditions | Participant-owned state machines, nested regions, states/modes and typed pseudostates, signal/time/change events, trigger/guard/effect transitions, linked entry/do/exit work, availability and constraints |
| Perspectives and evidence | Bidirectional counterpart creation/linking, reviewed name/description updates, many-to-many typed/manual traces, arbitrary artifact URI/revision/fragment references |
| Views and editing | Independent diagrams, decomposition/allocation nesting, collapse, pan/zoom/Fit/Arrange, editable connection routes and labels, four-side port positioning, direct interaction/functional/boundary exchange tools, contextual menus, SVG export, model explorer and typed properties |
| Text and storage | `arcadia 3` source projects with relative includes and nested declarations, stable aliases/UUIDs, a source-file tree, per-file drafts and diagnostics, comment-preserving graphical updates, exact model/source Undo/Redo, legacy migration, atomic saves and interrupted source-save recovery |
| Text and storage | `arcadia 4` source projects with relative includes and nested declarations, stable aliases/UUIDs, a source-file tree, per-file drafts and diagnostics, comment-preserving graphical updates, exact model/source Undo/Redo, legacy migration, atomic saves and interrupted source-save recovery |
| Automation | Rust REST service for project/source-bundle/query/validation/transaction/transition/artifact workflows, ETag preconditions, bounded requests and atomic current-revision storage |
Graphical and textual parity applies to the persistent fields of this profile. Diagram placements are model data; camera, selection, source cursor and undo history are session state. Canvas gestures need not match textual operations one for one: typed inspectors and explicit commands expose precise semantics. Full source replacement must repair dependencies in its candidate, while graphical delete/reidentify commands maintain references automatically.
@@ -45,7 +45,7 @@ These are concrete design responses, not claims that every Capella user experien
## Required first-release work
Direct state/scenario/process canvas authoring, semantic-content drift and reviewed counterpart reconciliation, expanded data contracts, persistent coverage/filter views, Home/recent-project and unsaved-work recovery, hosted desktop editing, guidance and final acceptance remain in the [release plan](../harness/PLAN.md). These are unfinished requirements, not exclusions from the release. Interrupted source-save recovery restores a save transaction; it does not checkpoint unsaved models or drafts.
Direct scenario/process canvas authoring, semantic-content drift and reviewed counterpart reconciliation, native acceptance of expanded data contracts, persistent coverage/filter views, Home/recent-project and unsaved-work recovery, hosted desktop editing, guidance and final acceptance remain in the [release plan](../harness/PLAN.md). These are unfinished requirements, not exclusions from the release. Direct state editing has scoped Windows/Linux acceptance recorded in [state evidence](../harness/release-state-editing.md). Interrupted source-save recovery restores a save transaction; it does not checkpoint unsaved models or drafts.
## Remaining boundaries
+2 -2
View File
@@ -1,6 +1,6 @@
# Arcadia Studio server
`arcadia-server` is a headless Rust REST service for the same schema-3 model, commands, source language, validation, artifacts and OA/SA traces used by the desktop. It stores each model and its authored source project together in an atomic JSON envelope. The service provides a deployment artifact and configuration examples; this repository does not assert that a remote instance has been deployed.
`arcadia-server` is a headless Rust REST service for the same schema-4 model, commands, source language, validation, artifacts and OA/SA traces used by the desktop. It stores each model and its authored source project together in an atomic JSON envelope. The service provides a deployment artifact and configuration examples; this repository does not assert that a remote instance has been deployed.
The complete HTTP contract is [api.rst](api.rst); machine-readable schemas are in [openapi.json](openapi.json), also served at `/api/v1/openapi.json`. The original [service research](research-v2-service.md) discusses broader alternatives; retained history, SQLite, idempotency receipts and stored transition plans from that research are **not** the implemented storage contract.
@@ -44,7 +44,7 @@ The data directory contains `.arcadia.lock` and one `<resource-id>.json` file pe
Startup validates every committed envelope, its filename/UUID, revision, size and complete model. Any corrupt or unsupported envelope stops startup; the service does not silently skip bad data or invent an empty replacement. Sibling `.arcadia-write-*` files from an interrupted pre-commit write are not committed models and are ignored on startup.
Earlier model-only envelopes are accepted through the existing model migrations and receive deterministic source files in memory. Opening, reading or an exact no-op neither rewrites those envelopes nor advances their revision. The next changed edit persists the coupled representation. Already-coupled envelopes must contain stable source IDs and matching model/source; inconsistent pairs are rejected at startup. Capacity accounting includes source generated in memory for old envelopes, so an over-capacity old store fails explicitly without rewriting or pruning it.
Earlier model-only envelopes are accepted through the existing model migrations and receive deterministic source files in memory. Opening, reading or an exact no-op neither rewrites those envelopes nor advances their revision. The next changed edit persists the coupled representation. Already-coupled schema3 envelopes explicitly migrate both representations in memory; the independently migrated graphs must agree. Current-format source must contain stable IDs. Inconsistent pairs are rejected at startup. Migration reports remain visible until a current-format edit/save; opening alone never rewrites the envelope. Capacity accounting includes source generated in memory for old envelopes, so an over-capacity old store fails explicitly without rewriting or pruning it.
Parsing, validation and blocking disk operations run on blocking workers. A shared store mutex captures snapshots and serializes final revision checks and writes. Parsing, semantic validation, source writeback and query processing use the captured snapshot outside that lock; an expensive candidate does not block the catalog or another model's preparation. Commit rechecks the exact ETag, so a candidate prepared against a superseded snapshot returns `412 revision_conflict`. A successful changed update increments revision once. Both model and source bundle must be unchanged for `changed: false`; comment-only edits advance the same revision. Each write serializes the whole envelope to a sibling temporary file, syncs it, and atomically replaces the destination. Unix also syncs the directory. The in-memory snapshot changes only after the replacement succeeds. A directory-sync error after replacement is reported as an uncertain write outcome while the in-memory head still matches the installed file.
+6
View File
@@ -63,3 +63,9 @@ State camera/tool lifetime follows effective machine and diagram identity, even
when selection changes through Catalog or Layer outside Behavior. Reset only on
actual context change; preserve same-view return. Independent review reproduced
the leak and native Windows/Linux tests verified the correction in316dc55.
- Carried-value property browsing follows one exact record scope at a time, with
bounded pages and a separate read-only browser location. Flattened representative
paths were proven ambiguous in native recursive/reused data. Browsing does not
change the selected field or expression; choosing a field remains an explicit
draft edit through the ordinary validated command. No persistent browser schema.
+1 -1
View File
@@ -4,7 +4,7 @@
Deliver the first release of Arcadia Studio for system engineers: complete Operational Analysis and System Analysis/System Architecture workflows, equivalent graphical and textual models, clear artifact traceability and a deployable/programmatically accessible Rust service. Logical/Physical Architecture and later Arcadia layers are future releases, as the new objective explicitly states.
The authoritative objective is attachment07aee762-7d27-4cbe-81c3-2e82c7170711/goal-objective.md. It retains first-release scope and source/include, drag-selection and direct behavior editing requirements, and strengthens domain coherence, alternative evaluation and target-user task evidence. TASK_LEDGER.md separates given/verified facts, assumptions and open candidates; STATE.md records progress. The accepted0.2.0 prototype is the baseline, not proof of release completeness. Its source is preserved at D:/CodexBuilds/Capella2-release1-01a06e2e/v2-source-baseline.zip and existing archives remain in dist until replacement passes acceptance.
The authoritative objective is attachment10134df9-bea2-4c02-a820-67b53d6b86f7/goal-objective.md. It retains first-release scope and source/include, drag-selection and direct behavior editing requirements, and strengthens domain coherence, alternative evaluation and target-user task evidence. TASK_LEDGER.md separates given/verified facts, assumptions and open candidates; STATE.md records progress. The accepted0.2.0 prototype is the baseline, not proof of release completeness. Its source is preserved at D:/CodexBuilds/Capella2-release1-01a06e2e/v2-source-baseline.zip and existing archives remain in dist until replacement passes acceptance.
## Existing architecture and retained decisions
+177 -32
View File
@@ -1,38 +1,183 @@
# First release continuation pointer — 2026-09-06
# First release — current engineering state
The goal is active and incomplete. This C: checkout remains a continuation pointer
with older production code. Do substantial work in the active integration checkout,
not here; read its STATE, PLAN and TASK_LEDGER before continuing:
## Objective and phase
D:/CodexBuilds/Capella2-data-integration (codex/data-contract-integration).
Current production cf04ff1, root native/evidence checkpoint follows it.
Linux peer D:/CodexBuilds/Capella2-data-linux-review, b5db730.
Authoritative objective: attachment10134df9-bea2-4c02-a820-67b53d6b86f7/goal-objective.md.
Direct scenario work is now in isolated `codex/scenario-direct`, checkout
`D:/CodexBuilds/Capella2-scenario-direct`, base ab661f2, dedicated target
`D:/CodexBuilds/Capella2-scenario-target`. Scope and acceptance are recorded in
release-scenario-editing.md. Existing scene/order semantics and typed drafts are
retained; direct drawing, explicit insertion, same-parent reorder and correlated
activation rendering are implemented in d1d8f0b, with independent-review fixes
in 7a66607 for stale scroll slots, actual Iced scroll coordinates, operand-specific
activation segments and repeated picker cost, plus e7e37d4 for passive scroll
observations during async save. DATA b35dede is integrated in dfd2e41 without
conflicts. Combined Windows desktop tests pass 286/286, strict all-target desktop
Clippy and optimized build pass; a copied artifact/manifest is frozen under
`D:/CodexBuilds/Capella2-release1-01a06e2e/ui-scenario-data-windows-dfd2e41`. Exact artifact
hash, before/after failures and timings are in release-scenario-editing.md.
Focused independent recheck reports no remaining medium/high finding. Native
Windows/Linux trials remain pending and root-owned; this branch claims no native
acceptance and does not close process/chain work.
R6 contracts, direct behavior, source5/core/REST/scalar and closed constructor GUI
are integrated. Full Windows767/Linux770 workspace tests, strict checks and release
builds passed before newest desktop constructor/help slice; its platform gates run.
REST live184schemas/19typed values/9 malformed rejections passed earlier. No remote
service was deployed. Native Windows hosted publish, exact includes/comments,
graph/text Save, invalid-draft rejection, API artifact review/Reload/Undo/Redo,
revision conflicts, offline recovery, local copy and catalog Open were exercised.
That trial closed0/empty stderr. Source/history/ports/routing/explorer/state and
basic advanced behavior have scoped native Windows/Linux evidence in active ledgers.
The first-release goal remains active and incomplete. Deliver usable Rust/Iced
Operational Analysis and System Analysis/System Architecture, equivalent graphical,
textual and REST semantics, artifact traceability, directly editable behavior,
offline guidance, and Windows/Linux release evidence. Later Arcadia layers remain
future releases. The full authoritative objective was reread on 2026-09-06:
attachment10134df9-bea2-4c02-a820-67b53d6b86f7/goal-objective.md.
PLAN.md retains the entire release scope; no subsystem acceptance completes it.
Current high-impact issue: installed invalid local repair source retained a previous
hosted handle, allowing repaired source to save to the old resource. Actual-App/HTTP
red reproduction exists; HOST owns minimal fix and fresh reviewer. A separate stale
empty catalog UX fix follows. Native verification is required after both fixes.
GUI worker owns independent reset/member/literal decisions in SEM; other keyed/order/
artifact/multi-source decisions remain. Whole release coverage, advanced native cases,
Home/recovery/help and final cross-disciplinary acceptance/packaging are unfinished.
Direct state-machine editing is accepted through production316dc55. The main
checkout was fast-forwarded to acceptance a8f451e. R6 data/interface contracts
through b35dede are now integrated into the isolated direct-scenario checkout.
Root retains final main integration and acceptance; the combined direct scenario
has not yet completed native trials.
Meaningful implementation and runtime progress continues; no external blocker exists.
Root is sole native operator; authorization persists. Isolated loopback test server
20984 at127.0.0.1:8787 uses Temp/capella2-hosted-native-20260906/store, resource
d28b2fc9-fbbd-456b-8ba8-a1195d1c8f33 revision6. No desktop trial is currently active.
Original Capella remains available; re-inventory native windows before input.
## Accepted foundations
Linux is WSL Ubuntu-24.04, not the separate unconfigured Ubuntu distro. Optional
X11 needs libxkbcommon-x11-0 and the user's sudo password; the user already has the
exact apt command. Wayland/Windows/REST work is not blocked. Do not bypass auth.
No remote push, usage reset or broad target cleanup authorized.
- Core typed OA/SA semantics, validated atomic commands and ordinary history are
shared by three Rust crates. Typed ports, explicit unresolved migration and
original Capella observations: release-port-{contract,core,migration}.md and
release-capella-workflow-benchmark.md.
- Explorer/port discovery d364d3c: Add port on participants, grouped roots, focused
children, breadcrumbs, contextual paging/search and full-depth outline. Actual
Windows creation,251-root/12-level trials,1100x700 and Linux reopen/font fixes:
release-explorer-usability.md.
- Routing23535b4, viewport366ce44, labels65fa9ab: authored bends/labels, group
movement, fold restoration, Undo/Redo, save/reopen and SVG, including minimum-size
native trials. Dense full solve measured119ms; arbitrary crossings remain possible.
See release-routing-verification.md and release-routing-linux.md.
- Source4e8575b: nested lexical ownership/includes, provenance-aware token writes,
exact accepted source/model history, retained drafts, Save All/recovery and coupled
hosted source/model revisions. Windows/Linux native and actual REST restart,
stale ETag, comment-only edit and cross-file reparent passed. Full422 Windows /
425 Linux tests at that checkpoint. See release-source-integration.md.
- Direct drawing fef2e0d plus tooltip ad7feb5: OA Interaction, SA Functional and
Boundary Exchange by palette click-click or drag; compatible highlights, automatic
function ports, four-side draggable anchors, contextual menus and source folders.
Independent pointer/tooltip findings fixed and native retested. Windows193 desktop
and Linux189+4 focused tests followed earlier full485/488 suites. Scoped native
Windows/Linux acceptance: release-port-drawing.md and release-context-menus.md.
## Newly accepted state workspace
Production316dc55 includes typed machine views, shared persisted geometry, atomic
region/symbol/state creation, group movement, direct transitions and reconnection,
Internal rows, Local edges, typed detail forms, folding, placement and navigation.
Architecture and Behavior view selections are separate. Drafts survive rejected
source/model commits; passive camera events never apply a form.
Independent/native findings fixed: covered GPU shapes, pseudo-label/edge collision,
selection-relayout drag displacement, missing typed form access, folded-content
access, wrong-view placement Apply, and camera/tool leakage on machine navigation.
An actual owner/view change resets gesture state and fits; returning to the same
view preserves camera/tool. Exact evidence and limitations: release-state-editing.md.
Verification: full551 Windows /554 Linux workspace tests and strict workspace
Clippy at e0b2210. Final316dc55:241 desktop tests, strict all-target desktop Clippy,
and desktop builds on each platform; five new navigation tests included. Two guide
tests passed after help changes. Source/reST/API state contracts and actual HTTP
rejection/revision/source/restart tests passed earlier in the integration.
Root and independent Windows native trials covered1440x900 and1100x700 creation,
nested movement, first-drag transition, endpoint/menu reconnect, invalid target,
Escape, timed Internal, Local/EntryPoint, placement Apply, Undo/Redo and save/reopen.
Linux native covered1440x900 creation, first transition/move, Undo/Redo, fold and
saved collapsed reopen. Final316dc55 native on both platforms proved same-view
camera/tool preservation and different-machine Fit/Select reset. Logs are empty.
## Active R6 implementation and next actions
Checkout D:/CodexBuilds/Capella2-data-integration; branch
codex/data-contract-integration, base5ce3eef+plan2bf4c54+navigation9118218.
Dedicated target D:/CodexBuilds/Capella2-data-target. Contract freeze is schema/source4
with full data payload and dictionary slices together; existing typed ports remain.
See release-data-implementation.md and release-data-contract.md in that checkout.
R6 core/source/desktop are frozen at ab661f2. Full Windows607 tests and Linux610
tests pass (one explicit benchmark ignored on each platform); strict workspace
all-target Clippy passes on both. Optimized desktop/server Linux build also passed.
Windows desktop261 tests include the bounded scenario value editor. Exact logs,
binaries and runtime evidence: release-data-verification.md.
All4 R6 actual HTTP workflows pass, covering data protocols/artifact identity,
rejected defaults, qualified Call/Reply paths, validation locations, source edits,
reidentification, source3 migration and restart persistence. The published example's
actual server responses passed served/local OpenAPI validation; obsolete shapes
reject. Strict reST rendering and81 OpenAPI schemas passed.
Independent core review found association transition closure pulling unrelated
types and missing empty-enum warning; both corrected and focused tests passed.
Repeated per-ancestor full scans were simplified to one scan per helper call.
Explicit optimized inheritance timings250/500/1000: Windows21.070/89.088/391.590ms,
Linux22.381/111.662/408.129ms. These single-run empty-chain fixtures measure core
validation, not general UI latency. A1000-deep chain remains a pathological cost.
Independent desktop review fixes now pass tests: a focused dictionary with24-row
pages replaces unbounded inherited rows; recursive paths support explicit drill-down
and imported finite paths; same-phase styles/same-exchange reselection preserve
valid drafts. Read-only follow-up found no new path/style defect. Paging resets
only on actual layer/document changes; its regression failed before and passes now.
The bounded scenario editor replaces whole-recursion enumeration and per-field
inputs with24-row browsing and a single focused value draft. The reply call picker
no longer filters alternative calls using values belonging to the old exchange.
Automated and independent checks pass; native scenario checks are next.
Root exclusively operates native R6. The Windows13-object data model has saved
native bounds/default repair, a typed physical flow/field, allocation protocol
edit, allocation removal/Undo, and inherited-owner navigation. Association endpoint
labels/selectability were exercised. The1100x700 data layout has been inspected.
A separate53-object recursive-operation fixture was prepared with core APIs and
round-tripped for upcoming native scenario trials; fixture construction is not
claimed as native authoring. See the verification note for remaining gates.
Parallel isolated work: drawing_correctness implements direct scenario gestures in
Capella2-scenario-direct. data_core owns typed semantic review core and
state_architecture_review owns source5/migration in Capella2-semantic-review.
The typed facet C design won the bounded experiment/criticism round; its production
plan and decision are recorded in that checkout. No overlapping writers or targets.
1. State evidence is committed and main fast-forwarded to a8f451e; DATA received
the same evidence in c5276b1. Finish native data-authoring acceptance and bounded
scenario-value authoring, then full integrated Windows/Linux verification.
2. Finish R6 core/source/desktop, integrate actual REST/schema/reST, independent
semantic/correctness/UX review, Windows/Linux checks and real data authoring.
3. Implement R3 typed semantic drift/reconciliation after R6 freezes. Current
baselines/reconciliation only cover prose. Use the experimentally selected typed facet review design C; the semantic
integration checkout records the full scope and source5 migration plan.
4. Complete direct scenario/process gestures, persistent coverage/filters,
Home/recent/recovery, hosted desktop ETag workflows and offline guidance.
5. Fresh final requirements/domain/correctness/native UX/architecture review; full
Windows/Linux/MSRV checks, real runtime, reproducible docs and release packaging.
## Environment and native ownership
The user explicitly reauthorized native testing after Escape. Root's f5467e5 R6
window3476204 and exec93768 closed normally after verified source migration and
55-object recursive scenario reopen; no runtime output. The property-browser
replacement build b35dede has passed the root's Windows native retest. The
combined direct-scenario binary is frozen for its separate pending native trial.
Original Capella is present. Older protected user7210312/6228978 were absent;
do not reset/save/close them if they return. Re-inventory before switching apps.
Evidence: D:/CodexBuilds/Capella2-release1-01a06e2e. State source checkout/target:
D:/CodexBuilds/Capella2-state-integration and -target. Linux source/target:
D:/CodexBuilds/Capella2-state-linux-review and -target. Use distinct Cargo targets
per checkout; shared-cache results were previously caught and excluded.
Windows: cargo test --locked --workspace; cargo clippy --locked --workspace
--all-targets -- -D warnings; cargo build --locked -p oa-desktop -p oa-server.
WSL Ubuntu24.04 uses target/linux-cargo.toml and Mesa software Vulkan for native
WSLg. No remote push or usage reset authorized. No broad recursive target deletion.
Latest R6 checkpoint: b35dede Windows264 desktop tests, strict Clippy, optimized
build and root-owned native retest pass for the one-record property browser. Paging and
location changes retain accepted model and typed expressions. f5467e5 Windows
and Linux263 desktop tests, strict Clippy and optimized release passed. Native
Windows source3 migration preserved comments/nesting through explicit Save All
and clean source4 reopen. Native recursive55-object scenario values and paired
Call/Reply history were verified; flat property paths prompted the latest fix.
The independent bounded-browser review reports no remaining medium/high finding.
Linux native R6 workflows remain a root-owned acceptance gate. See
release-data-verification.md. Main remains a8f451e; R6 is not yet accepted.
+13 -3
View File
@@ -1,6 +1,6 @@
# Task Ledger — first release
Authoritative objective: attachment07aee762-7d27-4cbe-81c3-2e82c7170711/
Authoritative objective: attachment10134df9-bea2-4c02-a820-67b53d6b86f7/
goal-objective.md, read fully2026-09-06. STATE.md records execution; PLAN.md retains
scope; DECISIONS.md and linked contracts preserve rationale.
@@ -39,6 +39,13 @@ requires native workflows, semantic evaluators and fresh independent review.
whole-model equality or flat reformatting. Independent counterexamples were fixed.
- R3 existing-target reconciliation remains name/description only. R6 data shape
expansion is active implementation, not accepted functionality.
- R6 ab661f2 full suites passed Windows607/Linux610; f5467e5 desktop263 and
strict Clippy/release passed on both platforms. Native Windows data editing,
typed defaults, allocations, recursive qualified Call/Reply values, history and
saved reopening passed. Source3 migration now preserves comments and nesting.
Native found flat property browsing still ambiguous; one-record browsing with
bounded pages now passes264 desktop tests/Clippy, pending rebuilt native checks.
Linux native R6 acceptance remains outstanding.
## Assumptions and open questions
@@ -48,8 +55,11 @@ requires native workflows, semantic evaluators and fresh independent review.
gestures still need their own occurrence/order semantics and task verification.
- Routing offers a usable initial path plus manual pins; arbitrary dense diagrams
are not guaranteed crossing-free. Measured dense full solve119ms remains a limit.
- R3 typed historical bodies plus finite proposals appear simpler than a separate
recursive semantic-value schema. This candidate awaits R6 freeze and review.
- R3 selected design C uses finite self-tagged typed facets, separate membership
and order acknowledgements, and transient constructor groups. Source5 historical
references are implemented in the isolated semantic checkout. Independent review
found narrow-acknowledgement/canonical-agreement/rollup defects; the worker has
added regressions and fixes. Full catalog, GUI/API/spec and acceptance remain.
## Decisions and current strategy
+6
View File
@@ -1,5 +1,11 @@
# R6 data and interface contract proposal
Implementation freeze (2026-09-06): `release-data-implementation.md` supersedes
the earlier version-number and generic-port proposals below. Current contract is
schema/source4 with explicit1/2/3 migration; existing typed PortContract remains
authoritative. Value Record default `[]` is allowed at minimum0; Reference fields
have no explicit default. See docs/language.rst4.5 for the implemented specification.
Status: read-only design, 2026-09-05. No implementation, test pass, or native Studio acceptance is claimed here. This is the recommended integration contract for the lead to freeze before the R6 worker changes exhaustive enums. It extends the current typed model and transaction path; it does not introduce an instance database, expression evaluator, units engine, or plugin metamodel.
## Evidence and scope
+59
View File
@@ -0,0 +1,59 @@
# R6 implementation freeze — schema/source 4
Status: active implementation in isolated D:/CodexBuilds/Capella2-data-integration.
State editing is accepted in main a8f451e; DATA includes its navigation fix and evidence.
The full first-release goal remains incomplete.
## Outcome and contract
Implement the complete data/interface contract in release-data-contract.md before
accepting schema/source4 artifacts: nature/mechanism, bounded scalar types/defaults,
field direction/storage, qualified scenario value paths, single specialization,
identified interface-item allocations/protocols and binary reference associations.
Use its exact types and validation rules. Existing PortContract and legacy
resolution/split behavior are authoritative; the old R6 InOut paragraph is superseded
by release-port-contract.md. R6 never creates a new InOut functional contract.
Retain three crates, Project and validated atomic Command/Document boundaries.
Use data.rs shared helpers for effective fields, item ancestry, inherited interface
allocations, carried field paths and value validation. Reference visitors own live
references; no second model or mutation API. Inherited rows expose original identity.
Scenario paths disambiguate reused records and stop at Reference storage.
## Sequence and ownership
1. Core owner freezes public shapes/helpers, implements typed data validation,
reference/removal/transition maintenance and focused meaningful regressions.
2. Source/migration owner preserves V1/V2/current3 inputs through an explicit4
reader; updates parser/source-project migration without flattening nesting,
includes or comments. Frozen strict DTOs only for changed old payloads plus a
closed old constructor catalog avoid cloning the whole metamodel.
3. Desktop owner integrates typed forms, path pickers, readable nested dictionary
and interface-allocation rows. Root integrates OpenAPI/spec and actual REST.
4. Full tests/strict checks, source/JSON/HTTP roundtrips, invalid/stale transactions,
Windows/Linux native authoring, compact UI and fresh independent review.
Separate files per owner; communicate model/helper signatures before dependent edits.
Use a dedicated target for this worktree. No simultaneous Cargo mutations.
Do not publish or accept intermediate4 files until both payload and dictionary
slices are complete. R3 semantic reconciliation follows this shape/reference freeze.
## Required evidence
- Physical flow and Operation parameters use bounded reusable types and defaults.
- Two parameters using one Record retain distinct value paths through calls/replies,
reidentify/delete, graphical/source edits and initial transitions.
- Two interfaces allocate one item with independent protocols/artifact links; removing
one allocation retains the item and the other allocation, and Undo restores it.
- Specialization/inherited fields and associations preserve ownership and identity;
invalid cycles/defaults/paths/ranges reject atomically, incomplete drafts warn.
- V1/V2/current3 migration preserves identities, typed ports, comments, includes and
nested ownership; deterministic allocation IDs and unresolved legacy annotations
have explicit diagnostics. GUI/source/REST save/reopen agree.
Alternatives: silent changes under schema3 rejected because existing saved3 projects
are real compatibility inputs. Whole-model frozen DTO/validator duplication rejected
in favor of strict changed-payload compatibility adapters. Generic JSON diff or
opaque body replacement is not the R3 solution. Instance literals, unit conversion,
expression execution and multiple inheritance remain explicitly outside this
bounded contract; the release requirements for categories/filters are separate.
+119
View File
@@ -0,0 +1,119 @@
# R6 data contracts — native verification in progress
R6 is not accepted. Main remains at a8f451e. The full first-release goal remains
active and incomplete. User explicitly reauthorized native testing after Escape.
## Frozen production and automated evidence
Data integration ab661f2: Windows607 and Linux610 workspace tests pass, one explicit
benchmark ignored each; strict workspace all-target Clippy passes on both.
Windows261 desktop tests include the focused bounded scenario editor; Linux release
desktop/server build passed. Logs under D:/CodexBuilds/Capella2-release1-01a06e2e:
r6-workspace-windows-ab661f2.log and r6-workspace-windows-clippy-ab661f2.log.
Linux logs in Capella2-data-linux-review/target/linux-verification:
workspace-ab661f2.log, workspace-clippy-ab661f2.log, release-ab661f2.log.
Windows frozen executable ui-r6-windows/arcadia-studio.exe SHA256
C3ABD9E550E1AD6824DFE273EB27A3ABB35C5C0DA97C819DCB0AB2586AF5450C.
Current native window1835476, process session37598. No output observed; runtime.log
has not been created by Tee-Object (do not claim an empty log file).
All4 actual R6 HTTP tests pass with strict server Clippy: published data example,
protocol/artifact identity, rejected defaults, qualified reused/inherited/recursive
Call/Reply paths, phase/path422 with unchanged ETag/model/source/disk, source edits,
hop/terminal/base reidentification, correlation and restart persistence. Source3
coupled/source bundle migrations report correctly and opening alone does not write.
Logs: r6-http-paths-final.log, r6-http-all-data.log, r6-http-paths-clippy.log.
Initial fixture errors (untyped Port and transaction-error envelope assumption)
were corrected before passing. Published example responses from server32033FFE
passed served/local OpenAPI validation; obsolete shapes rejected. Strict reST HTML
and81 OpenAPI schemas passed. One stale port compatibility paragraph was corrected.
Optimized empty inheritance chains250/500/1000: Windows21.070/89.088/391.590ms;
Linux22.381/111.662/408.129ms. Single-run core validation timings, not UI latency.
## Personally observed Windows native workflows
Loaded the isolated Engineering data source fixture. Its architecture view shows
nested fields, association role/multiplicity labels, self-reference navigation and
selectable endpoint labels. No selection-induced dirty state observed.
Voltage maximum48→12 with default24 rejects when navigating; entered12 survives,
accepted summary remains0..48/default24, and a located default error is shown.
Repair default→12 applies together; Undo restores both old values, Redo restores
both new values. Created Cooling water with Material/Flow and contained Mass flow
rate Real1..1, unit kg/s, explicit default0.0. Save All wrote an included sa/types.arcadia
file with matching typed values, leaving13objects/4links/1 expected missing-System
warning. Navigation allocation changed Synchronous→Asynchronous; Monitoring's
separate Asynchronous/Read allocation is preserved. Removing Monitoring allocation
keeps Navigate; Undo restores the allocation and original checks. Followed inherited
Latitude from Located asset to Coordinate. Saved all edits. Data layout inspected
at1440x900 and1100x700; no overlapping controls observed.
Separate ui-r6-scenario-windows/model/project.arcadia was constructed with the core
API from the saved native data, adding functional ports/exchange, correlated
Call/Reply, reused/inherited/recursive records and30 extra fields.53objects/5links
validate and source round-trip exactly. fixture-generator.rs retained as evidence;
temporary project example removed. Initial generator compile/load errors were
fixture-only and fixed using the bundle-aware loader; final build has no warnings.
This preparation is not native scenario authoring evidence.
## Remaining acceptance gates
Native scenario focused/path/phase/draft behavior and paging; actual saved reopen;
source3 migration diagnostics; Linux native data/scenario workflows. Closure of
material findings before R6 acceptance. Independent semantic/correctness/spec
reviews already drove fixes; final native observations may require further review.
The broader release still needs semantic reconciliation, direct scenario/process
editing, lifecycle/hosted/help work and fresh cross-disciplinary end-state review.
## Native findings and follow-up fixes (2026-09-06)
At1100x700, the53-object recursive fixture exposed32/33 nested fields in two pages.
Native Call+Reply creation stored distinct Origin/Latitude and Destination/Latitude
expressions despite their shared terminal UUID. One Undo removed the pair; Redo
restored it. Save All wrote55objects/5links; source confirms both paths and reply
correlation. Three expected checks concern the absent SA System and two unallocated
functions. The saved evidence is ui-r6-scenario-windows/model/project.arcadia.
A third-hop popup exposed a material UI defect: repeated long path prefixes hid
all terminal field names. Fix74989b6 shows the terminal name first, sorts choices,
and retains the full address as wrapping detail text.262 desktop tests, strict
Clippy and release build passed; native retest is pending. Intermediate fixed hash
E592165A6FFFAEC64B67FF0A33FB4E78571527EE3C8F2CC457666DA6C277D5CB.
Native source3 import showed8semantic defaults,2generated allocations,1unresolved
value address and left the original hash305F19D1B79F99F8D4CF627BA2E9CA6836BB7959CC0070227815937A699EAFEA unchanged.
Its old desktop Save All path requested a new file and preserved the original, but
canonical regeneration discarded comments/nesting in the upgraded copy. This is a
material desktop/source parity defect, not a core bundle migration defect. The fix
keeps the historical single-document adapter only for source1/2; source3+ follows
bundle migration and propagates its report into Model checks. A regression passes
for actual disk single-file and included-file open, no write until explicit save,
comments, lexical ownership, report, exact saved source and clean reopened state.
Full desktop/Clippy/build and native retest are in progress; do not accept R6 yet.
The old Windows native window1835476 closed normally; exec37598 exited0 with no
runtime output beyond a newline. Re-inventory before opening the rebuilt binary.
## Migration retest and bounded property browsing
f5467e5 passed263 desktop tests, strict all-target desktop Clippy and optimized
release on Windows/Linux. Frozen Windows SHA256
33D1B2B6709BBC734E265568C7F93CB86A506497DEF3F4531669E5ABF8B2F039.
Native fresh legacy.arcadia import preserved original bytes until Save All,
displayed8defaults/2allocations/1unresolved address, and retained comments and
nested fields in its text editor. Save All kept the same file and source4 wording;
reopen was clean15objects/3links/4checks without a migration report. Saved SHA256
A8C0A689FEA6CC352007ACB127DE4A45E05290830DE815385CFFBAB777255543.
Evidence: ui-r6-final-windows/migration/legacy.arcadia.
The55-object recursive scenario reopened with both qualified expressions intact.
Leaf-first labels fixed the hidden terminal names, but existing-value properties
still flattened every representative path, causing repeated indistinguishable
leaf names. The follow-up browses one record at a time, with24-choice pages and
wrapping current address/location text. Up/root/page actions change only browser
state; draft field and expression are preserved.264 desktop tests and strict
Clippy passed, including wide-record page coverage and draft preservation across
recursive browsing. Optimized build and native retest remain pending. Frozen
f5467e5 window3476204 closed normally; exec93768 had no runtime output.
+236
View File
@@ -0,0 +1,236 @@
# Direct scenario editing — bounded implementation plan
Status: implementation and automated Windows checks passed in the isolated
`codex/scenario-direct` checkout, based on ab661f2. Initial production is d1d8f0b;
independent-review fixes are in 7a66607 and e7e37d4. The focused independent
recheck reports no remaining medium/high finding. Root-owned Windows/Linux native
trials remain pending. DATA b35dede is integrated in dfd2e41 with 286 desktop
tests, strict Clippy and a fresh frozen Windows release artifact. This does not
complete the release or process/chain work.
## Decisions
Extend the existing `behavior::Scene`; retain its derived lifeline columns and
ordered occurrence rows. No model/schema/layout records are added. Lifeline and
occurrence UUIDs remain distinct from represented work and global exchanges.
Select mode selects headers, stems, messages and occurrence boxes. A selected
occurrence has a reorder handle; dragging it chooses a visible slot in its same
parent sequence. It never reparents or changes lifeline columns. A Message tool
uses the existing MessageStyle, with Call + correlated reply initially selected.
Click-click or drag between represented lifelines captures a highlighted explicit
insertion slot `(parent, before occurrence or append)` and opens the existing
typed draft with those endpoints. Exchanges are filtered by layer, viewpoint and
the core's represented-endpoint compatibility. Earlier calls retain complete
exact-slot validation, cached by document revision, owner, slot and endpoints.
Choices use search plus 24-item pages; every final creation still validates the
complete ordinary command at the captured insertion slot.
No compatible exchange produces an actionable retained draft, not a new global
exchange or a silently changed endpoint. Timer remains available as a local tool.
The canvas remains rendered while a bounded, independently scrollable form is
open. Values keep the existing qualified-path editor and lifecycle. Final creation
uses ordinary CreateElement plus SetSteps in one Batch; paired call/reply are
inserted together and undo together. Reordering uses SetSteps within the captured
parent. Existing core validation decides reply order, branch dominance, lifetime,
phase and endpoint compatibility. Failed preparation/source writes retain drafts.
Transient events capture document/scenario/revision/epoch, and the App validates
the current Behavior owner before handling them. Selection does not invalidate a
gesture within the same scenario. Escape, unfocus, context/tool change and pending
drafts cancel gestures. Scroll, bounds changes and actual window resize also
cancel the captured source/slot. Ordered raw pointer events are translated by the
actual combined inner/page Scrollable offsets. No geometry is persisted.
Execution bars derive their ends from actual correlated reply positions; separate
conditional reply branches render their corresponding spans. Calls without a
visible reply use a short explicitly open activation, not a fabricated reply.
## Acceptance checks
Production-event tests cover hit priority, click-click/drag, scroll-origin changes,
Escape/unfocus/stale contexts and exactly one result per gesture. Planner/App tests
cover middle/operand insertion, paired identities, complete SetSteps ordering,
same-parent reorder, rejected reply-before-call, unchanged global exchanges, exact
source/model Undo, draft retention and bounded exchange/call controls. Run focused
and full desktop tests, strict all-target desktop Clippy and optimized build with
the dedicated `D:/CodexBuilds/Capella2-scenario-target` target.
Root native tasks (not yet performed):
1. Draw an existing exchange again into the middle of a scenario as Call+Reply;
enter a qualified value, select both occurrences, Undo/Redo, save/reopen.
2. Insert inside an ALT/LOOP operand, reorder within it, reject a reply before its
call, and inspect correlated execution bars and preserved occurrence identities.
3. Cancel drawing after scrolling/layout change, retry, retain typed values while
navigation is blocked, and open/return from a referenced scenario. Verify at
1440x900 and 1100x700 on Windows and Linux before scoped acceptance.
## Initial automated evidence — 2026-09-06 (superseded by review fixes)
Source checkout: `D:/CodexBuilds/Capella2-scenario-direct`, production commit
`d1d8f0bbed5aa0112189138a1cc025affe26c09b`. Changes are confined to desktop
`app.rs`, `behavior.rs` and `behavior/scenario.rs`; no core model, persisted layout
or schema changes are included.
All commands used the dedicated `D:/CodexBuilds/Capella2-scenario-target` target
with `--locked --offline`:
- `cargo check -p oa-desktop --all-targets`: passed.
- `cargo test -p oa-desktop direct_`: 19 passed, including 13 new direct-scenario
tests and six existing matching tests.
- `cargo test -p oa-desktop`: final source passed all 274 tests, zero failures or
ignored tests. This includes exact source/model Undo, creation and reorder
selection, rejected stale contexts, retained failed-write drafts, bounded
contextual controls, scroll-origin cancellation and correlated activation spans.
- `cargo clippy -p oa-desktop --all-targets -- -D warnings`: passed.
- `cargo build -p oa-desktop --release`: passed.
- `git diff --check`: passed before the production commit.
Logs are under `D:/CodexBuilds/`: `Capella2-scenario-check.log`,
`Capella2-scenario-direct-tests.log`, `Capella2-scenario-desktop-final-tests.log`,
`Capella2-scenario-desktop-clippy.log` and `Capella2-scenario-desktop-release.log`.
Windows artifact:
`D:/CodexBuilds/Capella2-scenario-target/release/arcadia-studio.exe`,
20,345,856 bytes, SHA-256
`7CC6DCDB7ECC0C6B144137D31DB0BE9BC1555FEFAE6B465DAEABCF52DFE1A166`.
This artifact has not been native-tested. Widget-tree/event tests do not establish
visual usability, scrolling behavior or GPU rendering acceptance; the three native
tasks above remain required. Process/chain direct editing remains outside this
bounded implementation.
## Independent-review fixes and final automated evidence — 2026-09-06
Production commit: `7a666076bfcfd1f2258d2f5508328db5adf40825`, same isolated
checkout and dedicated target. Only the three previously owned desktop source
files changed. No core/source/schema or process/chain features were added.
The new event regressions failed on the prior implementation: a bounds shift kept
the first click's source/slot armed, and a held drag could still publish its old
slot after the bounds changed. Both now cancel. After scrolling, resizing or
clipping changes, the next click starts a fresh gesture. App tests also verify
unchanged-size notifications retain context, actual resize invalidates it, and
scrolling preserves property/source history and the pending behavior form.
Local Iced inspection established that Scrollable translates its supplied cursor
but leaves raw CursorMoved coordinates and the canvas layout unchanged. The
existing inner and outer scrollables now have a local, passive observer which
reads their actual translation through Widget::operate. Ordinary on_scroll cannot
report initial/remounted state or passive content-size clamping. The observer
forwards layout, drawing, overlays and event capture, and publishes only changed
translations or document/owner context. Reporting before child input makes a
result using an old slot stale before App processes it; reporting after input
captures wheel/scrollbar changes. The real Iced Scrollable test uses its debug
null renderer and verifies 0 → 180 wheel offset → 50 passive clamp → 180 on
expansion → 0 after remount, with no repeated messages on unchanged redraws.
The reported ALT fixture also failed before the fix: a root Call, Reply then
Action in operand one, another Reply in operand two, and a third operand without
a Reply. Derived execution geometry now splits at operand boundaries, stops each
returned operand at its own correlated Reply, leaves its following Action outside
that segment, and marks the reply-free operand open. It does not imply chronology
between alternative operands or add persistent execution records.
Picker measurement on the same Windows debug target:
| Probe | Before | After |
| --- | --- | --- |
| 500 compatible exchange choices | 7.87 s | 1.46 ms |
| Same choices after one name edit | 8.14 s | 1.48 ms |
| 100 exact-slot earlier calls, initial validation | not measured | 595 ms |
| Those calls after name/value/search/page edits | not measured | 34–39 µs |
The exchange list no longer clones and validates the entire project per candidate.
Final Apply still rejects a Delete inserted before a later Call on that lifeline;
the new regression confirms appending that same Delete succeeds. Reply choices
retain exact validation, invalidate for changed slot/document/revision/endpoints,
and do not lose their cached eligibility while expressions are being typed.
These are bounded picker measurements, not complete native-frame timings.
Final checks (`--locked --offline`): 27 focused matching tests passed; all 282
desktop tests passed, zero failures/ignored tests; strict desktop all-target
Clippy passed; optimized desktop build passed; git diff --check passed. Clippy
requested one test-only nested-if cleanup, which was applied before the final
clean Clippy/build.
Logs under `D:/CodexBuilds/`:
`Capella2-scenario-review-before-tests.log`, `Capella2-scenario-alt-before.log`,
`Capella2-scenario-scroll-observer-tests.log`,
`Capella2-scenario-review-desktop-tests.log`,
`Capella2-scenario-review-clippy.log`, `Capella2-scenario-review-release.log`.
Current Windows binary:
`D:/CodexBuilds/Capella2-scenario-target/release/arcadia-studio.exe`,
20,349,952 bytes, SHA-256
`1AE729097F267DE596AE0970D3A62AE06C0C89CE2FDE70DF980AD785A0E0A8E6`.
It supersedes the initial artifact above. Native acceptance is still pending.
Root should repeat the three primary native tasks, including inner/outer wheel
and scrollbar cancellation at a middle slot, resize/remount/clamp recovery, and
the three-operand ALT fixture. The broader release objective remains incomplete.
## Final passive-scroll save correction — 2026-09-06
Production `e7e37d485d842731d270781bd4e60a323fe4cdba` addresses the focused review's remaining App lifecycle
finding. During an async save, Iced can change its scroll position while App's busy
gate rejects ordinary messages. The observer had already recorded its report,
so dropping that notice left App's offset stale after save completion. The new
regression failed before the fix: App retained offset (0, 0) instead of (25, 140).
App now dispatches only the passive Scrolled event before interaction gates. Its
existing handler still validates document, scenario and revision. Mutation input
remains gated. The test checks current offsets and cancellation epoch while busy,
rejects an old-document observation, delivers a successful Saved receipt, then
uses production Canvas pointer events to create the intended sender/receiver/slot
draft without a model or source-history mutation.
The independent reviewer rechecked this exact production change and regression;
no remaining medium/high finding was reported in the focused review. Final full
desktop tests pass 283/283, strict all-target desktop Clippy passes, optimized
desktop build passes, and git diff --check passes. Logs under D:/CodexBuilds are
`Capella2-scenario-busy-scroll-before.log`,
`Capella2-scenario-busy-scroll-after.log`,
`Capella2-scenario-busy-scroll-desktop-tests.log`,
`Capella2-scenario-busy-scroll-clippy.log` and
`Capella2-scenario-busy-scroll-release.log`.
Latest Windows artifact, superseding both builds above:
`D:/CodexBuilds/Capella2-scenario-target/release/arcadia-studio.exe`,
20,349,952 bytes, SHA-256 `CEEB8E277DFC47C0D55DA43F903FCA45AFBF902AFA418B3924375910D699373A`.
Native acceptance is pending. Include scrolling while saving in the root's native
recovery task before accepting the direct scenario milestone.
## Combined DATA/scenario integration — 2026-09-06
Merge `dfd2e41259e73ef10a4e29a426569c08eaae215f` integrates `codex/data-contract-integration` at
`b35dede75fc8778ea695b9b2c023cfa2a1e49e09` into the isolated scenario branch.
The merge applied without conflicts and needed no manual code resolutions or new
semantic design. Direct scenario geometry/planners/tests and the existing
scenario evidence were unchanged by the merge. App's early passive-scroll handler
remains intact alongside DATA's source migration and property-browser handling.
The shared field-path API remains compatible: compact leaf-first labels and
deterministic sorting now feed the existing bounded scenario value picker, while
full qualified labels remain available for detail text.
Combined verification on the dedicated scenario target: all 286 desktop tests
passed, no failures or ignored tests; strict desktop all-target Clippy passed;
optimized desktop build passed; staged diff --check passed. All commands used
`--locked --offline`. DATA's three new regressions are present together with the
283-test scenario suite, including source3 save/reopen and direct gesture/save
lifecycle coverage. No DATA checkout, Linux checkout or native application was
modified or operated in this integration task.
Frozen artifact directory: `D:/CodexBuilds/Capella2-release1-01a06e2e/ui-scenario-data-windows-dfd2e41`.
It contains `arcadia-studio.exe`, the three combined verification logs and a
`manifest.json` identifying the source checkout, merge commit, target and hash.
The copied binary hash was checked against the release target binary.
Binary size: 20,411,392 bytes. SHA-256: `8BC031CF6124859D31082BB0FFB0335C406D54E12ECAD8493CE50A23923E5589`.
Root reports DATA b35dede's Windows native trial and independent focused review
passed. This does not transfer native acceptance to the combined direct-scenario
workflow. Its Windows/Linux native tasks remain pending, including scroll/resize
cancellation, middle/operand insertion, execution spans and save recovery. Root
owns final integration into main and native acceptance; process editing remains
outside this task.