Spaces:
Running
Running
chore: phase 6.3 architecture and LFS media tracking
Browse filesFiles changed (22)
- .gitattributes+2
- ARCHITECTURE.md+14-3
- js/app.js+918-144
- js/i18n.js+105-3
- js/renderers/mermaid-adapter.js+147-12
- js/renderers/vis-adapter.js+165-10
- js/scenarios/scenario-vanishing-crack.jsAdded+280
- js/smim/bfo.js+209-40
- js/smim/iso15926.js+372-90
- js/smim/naive.js+238
- js/smrm/actions.js+96-66
- js/smrm/definitions.js+30
- js/sms/lpg-generator.js+28-13
- js/sms/rdf-generator.js+133-44
- js/sms/sms-graph-generator.jsAdded+172
- js/state.js+46-9
- js/urmsm/bom-view.js+44-4
- js/urmsm/smrm-view.jsAdded+106
- narratives/Ontologies_-_Disappearing_Crack.mp3Added+3
- narratives/Ontologies_-_Disappearing_Crack.srtAdded+149
- styles/Twemoji-16.0.1.ttfAdded+3
- styles/main.css+336-2
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text
15 unmodified lines16171819202122232425262728293015 unmodified lines### The Pipeline Modules* `/js/smrm/` (System Model Reference Model) - **Domain Logic & Actions.*** `actions.js`: Validates user input and pushes strict Event objects to `state.js`. Never touches the UI.* `/js/smim/` (Information Elements & Rules) - **Ontology Adapters.*** `bfo.js`, `iso15926.js`: Pure functions. They take the Event Log and Current Time, and return a standardised `SemanticGraph` object `{ nodes: [], edges: [] }`.* `/js/sms/` (Data in Tool) - **Storage Generators.*** `lpg-generator.js`, `rdf-generator.js`: Generate database-specific table views and queries (Cypher, SPARQL/Turtle) from the `SemanticGraph`.* `/js/urmsm/` (Dimension & Aspect) - **User Viewpoints.*** `bom-view.js`: Generates the engineering Bill of Materials tree abstracting away database/ontology mechanics.* `/js/renderers/` - **Visualisation.*** `vis-adapter.js`, `mermaid-adapter.js`: Pure painters. They take the `SemanticGraph` and map node/edge types to colours, shapes, and physics.## 3. The Data Contract: Semantic Graph ObjectAll `smim/` adapters must return an object in this format to decouple ontologies from renderers:15 unmodified lines161718192021222324252627282930313233343536373839404115 unmodified lines### The Pipeline Modules* `/js/smrm/` (System Model Reference Model) - **Domain Logic & Actions.*** `definitions.js`: Standard manufacturing domain vocabulary (Entity Classes, Relationship Types).* `actions.js`: Validates user input and pushes strict Event objects to `state.js`. Never touches the UI.* `/js/smim/` (Information Elements & Rules) - **Ontology Adapters.*** `bfo.js`, `iso15926.js`, `naive.js`: Pure functions. They take the Event Log and Current Time, and return a standardised `SemanticGraph` object `{ nodes: [], edges: [] }`. `naive.js` acts as an unconstrained property graph adapter without 3D/4D formalisms.* `/js/sms/` (Data in Tool) - **Storage Generators.*** `sms-graph-generator.js`: Transforms the canonical `SemanticGraph` (SMIM) into a physical storage graph (SMS), implementing W3C Reification for RDF and `TRANSITION_TO` state chains for LPG.* `lpg-generator.js`, `rdf-generator.js`: Generate database-specific table views and queries (Cypher, SPARQL/Turtle) from the `SemanticGraph`.* `/js/urmsm/` (Dimension & Aspect) - **User Viewpoints.*** `bom-view.js`: Generates the engineering Bill of Materials tree abstracting away database/ontology mechanics with strict Parent -> Slot -> Child traversal.* `smrm-view.js`: Transforms the canonical SMIM Semantic Graph into the SMRM Engineer View by mathematically collapsing contextual Slot nodes into direct transitive Parent -> Child relationships while preserving edge properties/defects.* `/js/scenarios/` - **Interactive Scenarios & Narratives.*** `scenario-vanishing-crack.js`: Defines temporal subtitles and chronological Event Sourcing timeline actions for the "Vanishing Crack" narrative demonstration across `NAIVE_NODE`, `NAIVE_EDGE`, and `ISO15926`.* `/js/renderers/` - **Visualisation.*** `vis-adapter.js`, `mermaid-adapter.js`: Pure painters. They take the `SemanticGraph` and map node/edge types to colours, shapes, and physics. `mermaid-adapter.js` serialises relationship properties directly onto edge labels.## 3. The Perspectives Architecture (IEC 63339)The application provides three distinct viewpoints:1. **SMRM Perspective (`state.perspective = 'SMRM'`):** Engineering viewpoint. Contextual Slots are collapsed via `smrm-view.js`, presenting a direct part-to-part hierarchy with defects transferred to transitive edges.2. **SMIM Perspective (`state.perspective = 'SMIM'`):** Canonical ontology layer. Preserves full ontological topology (Parent -> Slot -> Child, BFO MaterialEntity/Quality, ISO 15926 4D Extent/State).3. **SMS Perspective (`state.perspective = 'SMS'`):** Physical database storage layer (LPG states and `TRANSITION_TO` edges, W3C RDF statement reification and literals).## 3. The Data Contract: Semantic Graph ObjectAll `smim/` adapters must return an object in this format to decouple ontologies from renderers:
5 unmodified lines67891011121314151617181920212231 unmodified lines54555657585960616263646566671 unmodified line697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151162 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417532 unmodified lines20820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526640 unmodified lines3073083093103113123133143153163173183193203213223233243251 unmodified line3273283293303313323333343 unmodified lines33833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340469 unmodified lines4744754764774784795 unmodified lines* passes data between the Event Log, Domain Actions, Ontologies, and Renderers.*/import { createApp, computed, watch, onMounted, ref, reactive } from 'vue';import { state, advanceTime } from './state.js';import { i18n } from './i18n.js';import { createAddPartEvent, createRemoveEdgeEvent } from './smrm/actions.js';import * as bfoAdapter from './smim/bfo.js';import * as isoAdapter from './smim/iso15926.js';import { initVisNetwork, updateVisNetwork } from './renderers/vis-adapter.js';import { updateMermaidNetwork } from './renderers/mermaid-adapter.js';import { generateBomTree } from './urmsm/bom-view.js';import { generateLpgStorage, generateLpgQuery } from './sms/lpg-generator.js';import { generateRdfStorage, generateRdfQuery } from './sms/rdf-generator.js';/*** RECURSIVE BOM TREE NODE COMPONENT31 unmodified lines// 1. Local UI Settings (Isolated from domain state)const settings = reactive({language: 'sv', // Available options: 'sv', 'en', 'ru'ontology: 'BFO', // SMIM Top-Level Ontology: 'BFO' or 'ISO15926'storage: 'LPG', // SMS Storage Paradigm: 'LPG' or 'RDF'engine: 'vis' // Renderer: 'vis' (Vis.js) or 'mermaid'});// DOM References for renderersconst visContainer = ref(null);const mermaidContainer = ref(null);// Form inputsconst partNameInput = ref('');1 unmodified lineconst selectedEdgeToRemove = ref('');const showHistory = ref(true);// Layout State (Flex percentages for resizers)const layout = reactive({ leftWidth: 66, bomHeight: 25, storageHeight: 40 });// Active dictionary based on local settingsconst t = computed(() => i18n[settings.language]);// Computed views over the Event Logconst activeEdges = computed(() => {return state.eventLog.filter(e =>e.valid_from <= state.currentTime &&(e.valid_to === null || e.valid_to > state.currentTime));});const activeNodes = computed(() => {const nodes = new Set(['System_A']);activeEdges.value.forEach(e => {if (e.from) nodes.add(e.from);if (e.to) nodes.add(e.to);});return Array.from(nodes);});// Dynamic entity projection: Reconstruct base entities from the event logconst baseNodes = computed(() => {const nodeMap = new Map();// Root continuant system entitynodeMap.set('System_A', { id: 'System_A', label: 'System_A', type: 'system' });const events = showHistory.value ? state.eventLog : activeEdges.value;events.forEach(event => {if (event.from && !nodeMap.has(event.from)) {nodeMap.set(event.from, { id: event.from, label: event.from, type: 'element' });}if (event.to && !nodeMap.has(event.to)) {nodeMap.set(event.to, { id: event.to, label: event.to, type: 'element' });}});return Array.from(nodeMap.values());});/*** Central Event Dispatcher* ------------------------2 unmodified lines** @param {Object} event - The domain event object to dispatch.*/function dispatch(event) {if (!event) return;if (event.type === 'EDGE_REMOVED' || event.type === 'REMOVE_EDGE') {const targetEdge = state.eventLog.find(e => e.id === event.edgeId);if (!targetEdge) {console.error(`[Dispatcher] Cannot sever relation. Edge ${event.edgeId} not found.`);return;}if (targetEdge.valid_to !== null) {console.warn(`[Dispatcher] Relation ${event.edgeId} is already closed.`);return;}targetEdge.valid_to = event.valid_to ?? state.currentTime;return;}// Relationship creation eventif (!event.id) {event.id = `e${state.edgeSequence++}`;} else {const match = String(event.id).match(/^e(\d+)$/);if (match) {const num = parseInt(match[1], 10);if (num >= state.edgeSequence) {state.edgeSequence = num + 1;}}}const edgeExists = state.eventLog.some(e =>e.from === event.from &&e.to === event.to &&e.valid_to === null);if (edgeExists) {console.warn(`[Dispatcher] Active edge already exists between ${event.from} and ${event.to}`);return;}state.eventLog.push(event);}// The core transformation pipeline: Event Log -> Ontology -> Semantic Graphconst semanticGraph = computed(() => {const eventsToProcess = showHistory.value ? state.eventLog : activeEdges.value;if (settings.ontology === 'BFO') {return bfoAdapter.generateSemanticGraph(eventsToProcess, baseNodes.value, state.currentTime);} else {return isoAdapter.generateSemanticGraph(eventsToProcess, baseNodes.value, state.currentTime);}});32 unmodified lines}});// Watch for graph or engine changes to trigger re-renderswatch([semanticGraph, () => settings.engine], () => {renderGraph();}, { deep: true });function renderGraph() {if (settings.engine === 'vis') {const isComplex = settings.ontology === 'ISO15926';updateVisNetwork(semanticGraph.value, isComplex);} else if (mermaidContainer.value) {updateMermaidNetwork(semanticGraph.value, mermaidContainer.value);}}// Lifecycle hooksonMounted(() => {if (visContainer.value) {initVisNetwork(visContainer.value);}// Inject initial seed data via pure factories and central dispatcherdispatch(createAddPartEvent('System_A', 'SubAssembly_1', state.currentTime, state.edgeSequence, state.eventLog));dispatch(createAddPartEvent('System_A', 'Part_A', state.currentTime, state.edgeSequence, state.eventLog));dispatch(createAddPartEvent('SubAssembly_1', 'Sensor_X', state.currentTime, state.edgeSequence, state.eventLog));renderGraph();});// UI Event Handlersfunction handleAdd() {const event = createAddPartEvent(selectedParent.value,partNameInput.value,state.currentTime,state.edgeSequence,state.eventLog);if (event) {dispatch(event);partNameInput.value = '';}}function handleRemove() {if (selectedEdgeToRemove.value) {const event = createRemoveEdgeEvent(selectedEdgeToRemove.value,state.currentTime,state.eventLog);if (event) {dispatch(event);}}}40 unmodified linesdocument.body.classList.add('no-select');}return {state, settings, t, layout, advanceTime, dispatch,handleAdd, handleRemove,partNameInput, selectedParent, selectedEdgeToRemove, showHistory,activeNodes, activeEdges,bomTree, lpgRecords, rdfTtl, formatProperties, queryCode,visContainer, mermaidContainer,startResizeH, startResizeV};},template: `<div class="control-deck"><!-- Tier 1: Architecture Settings --><div class="deck-row deck-row-top"><div class="section-label">1 unmodified line<span>{{ t.ontoTitle }}</span></div><div class="btn-group"><button :class="{ active: settings.ontology === 'BFO' }" @click="settings.ontology = 'BFO'">BFO (3D)</button><button :class="{ active: settings.ontology === 'ISO15926' }" @click="settings.ontology = 'ISO15926'">ISO 15926 (4D)</button></div><div class="divider"></div>3 unmodified lines<span>{{ t.graphTitle }}</span></div><div class="btn-group"><button :class="{ active: settings.storage === 'LPG' }" @click="settings.storage = 'LPG'">LPG</button><button :class="{ active: settings.storage === 'RDF' }" @click="settings.storage = 'RDF'">RDF (W3C)</button></div><div class="divider"></div><div class="section-label">🎨 <span>{{ t.engineTitle }}</span></div><div class="btn-group"><button :class="{ active: settings.engine === 'vis' }" @click="settings.engine = 'vis'">🌐 Vis.js</button><button :class="{ active: settings.engine === 'mermaid' }" @click="settings.engine = 'mermaid'">📊 Mermaid</button></div><div style="margin-left: auto;" class="btn-group flag-group"><button :class="{ active: settings.language === 'sv' }" @click="settings.language = 'sv'" title="Svenska">🇸🇪</button><button :class="{ active: settings.language === 'en' }" @click="settings.language = 'en'" title="British English">🇬🇧</button><button :class="{ active: settings.language === 'ru' }" @click="settings.language = 'ru'" title="Русский">🇷🇺</button></div></div><!-- Tier 2: Operations --><div class="deck-row"><span class="badge">T = {{ state.currentTime }}</span><button @click="advanceTime">{{ t.stepBtn }}</button><div class="divider"></div><span class="iec-badge" style="background: #f1f5f9; color: #475569; border-color: #cbd5e1;">IEC 63339 / SMRM: <span style="font-weight: normal; margin-left: 3px;">{{ t.smrmStatus }}</span><span class="iec-tooltip" v-html="t.tooltips.smrm"></span></span><div class="divider"></div><label style="font-size: 11px; font-weight: 600;">{{ t.parent }}</label><select v-model="selectedParent"><option v-for="node in activeNodes" :key="node" :value="node">{{ node }}</option></select><input type="text" v-model="partNameInput" :placeholder="t.partPlaceholder" style="width: 120px;"><button class="secondary" @click="handleAdd">{{ t.addBtn }}</button><div class="divider"></div><select v-model="selectedEdgeToRemove"><option v-for="edge in activeEdges" :key="edge.id" :value="edge.id">{{ edge.from }} → {{ edge.to }}</option></select><button class="danger" @click="handleRemove">{{ t.removeBtn }}</button><div class="divider"></div><label style="font-size: 11px; display: flex; align-items: center; gap: 4px;"><input type="checkbox" v-model="showHistory"> {{ t.history }}</label></div></div><div class="main-container"><div id="canvas-container" :style="{ flex: \`0 0 \${layout.leftWidth}%\` }"><div ref="visContainer" v-show="settings.engine === 'vis'" style="width: 100%; height: 100%; position: absolute;"></div><div ref="mermaidContainer" v-show="settings.engine === 'mermaid'" id="mermaid-container"></div></div><!-- Horizontal Resizer -->69 unmodified lines</div></div></div>`};5 unmodified lines678910111213141516171819202122232425262728293031323334353631 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401 unmodified line1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353362 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736832 unmodified lines40140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977040 unmodified lines8118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309311 unmodified line9339349359369379389399409419423 unmodified lines946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109669 unmodified lines11661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212535 unmodified lines* passes data between the Event Log, Domain Actions, Ontologies, and Renderers.*/import { createApp, computed, watch, onMounted, ref, reactive, nextTick } from 'vue';import { state, advanceTime, loadState } from './state.js';import { i18n } from './i18n.js';import {createRegisterPartEvent,createAssembleEvent,createReportDefectEvent,createDismantleEvent} from './smrm/actions.js';import { ENTITY_CLASSES, RELATION_TYPES } from './smrm/definitions.js';import * as bfoAdapter from './smim/bfo.js';import * as isoAdapter from './smim/iso15926.js';import * as naiveAdapter from './smim/naive.js';import { initVisNetwork, updateVisNetwork } from './renderers/vis-adapter.js';import { updateMermaidNetwork } from './renderers/mermaid-adapter.js';import { generateBomTree } from './urmsm/bom-view.js';import { reduceGraphForSMRM } from './urmsm/smrm-view.js';import { generateLpgStorage, generateLpgQuery } from './sms/lpg-generator.js';import { generateRdfStorage, generateRdfQuery } from './sms/rdf-generator.js';import { generatePhysicalGraph } from './sms/sms-graph-generator.js';import {vanishingCrackScenario,onTimeUpdate as dispatchScenarioTimeline,resetTimeline} from './scenarios/scenario-vanishing-crack.js';/*** RECURSIVE BOM TREE NODE COMPONENT31 unmodified lines// 1. Local UI Settings (Isolated from domain state)const settings = reactive({language: 'sv', // Available options: 'sv', 'en', 'ru'ontology: 'NAIVE_NODE', // SMIM Top-Level Ontology: 'BFO' | 'ISO15926' | 'NAIVE_NODE' | 'NAIVE_EDGE'storage: 'LPG', // SMS Storage Paradigm: 'LPG' or 'RDF'engine: 'vis', // Renderer: 'vis' (Vis.js) or 'mermaid'perspective: 'SMRM' // Perspective: 'SMRM' | 'SMIM' | 'SMS'});// User Role State ('UNI_ENGINEER')const userRole = ref('UNI_ENGINEER');watch(userRole, (newRole) => {state.userRole = newRole;});watch(() => state.userRole, (newRole) => {if (newRole && userRole.value !== newRole) {userRole.value = newRole;}});// Synchronise reactive ontology between settings and domain statewatch(() => state.ontology, (newOnto) => {if (newOnto === 'ISO_15926_4D' || newOnto === 'ISO15926') {settings.ontology = 'ISO15926';} else if (newOnto === 'NAIVE_NODE') {settings.ontology = 'NAIVE_NODE';} else if (newOnto === 'NAIVE_EDGE') {settings.ontology = 'NAIVE_EDGE';} else if (newOnto === 'NAIVE') {settings.ontology = 'NAIVE_NODE';} else if (newOnto === 'BFO') {settings.ontology = 'BFO';}}, { immediate: true });watch(() => settings.ontology, (newOnto) => {if (state.ontology !== newOnto) {state.ontology = newOnto;}});// Synchronise perspective between settings and domain statewatch(() => state.perspective, (newPersp) => {if (newPersp && settings.perspective !== newPersp) {settings.perspective = newPersp;}}, { immediate: true });watch(() => settings.perspective, (newPersp) => {if (state.perspective !== newPersp) {state.perspective = newPersp;}});// Synchronise engine between settings and domain statewatch(() => state.graphEngine, (newEngine) => {const lower = (newEngine || 'VIS').toLowerCase();if (settings.engine !== lower) {settings.engine = lower;}}, { immediate: true });watch(() => settings.engine, (newEngine) => {const upper = (newEngine || 'vis').toUpperCase();if (state.graphEngine !== upper) {state.graphEngine = upper;}});// DOM References for renderers & file operationsconst visContainer = ref(null);const mermaidContainer = ref(null);const fileInput = ref(null);// Form inputsconst partNameInput = ref('');1 unmodified lineconst selectedEdgeToRemove = ref('');const showHistory = ref(true);// New Sandbox & Domain Extension Form inputsconst selectedNodeClass = ref(ENTITY_CLASSES[0]);const newNodeIdInput = ref('');const selectedRelSource = ref('System_A');const selectedRelType = ref(RELATION_TYPES[0]);const selectedRelTarget = ref('');const propTargetType = ref('NODE');const propTargetId = ref('');const propKeyInput = ref('');const propValInput = ref('');// Universal Engineer Business UI inputsconst bizRegType = ref('Vehicle');const bizRegId = ref('');const bizInstSource = ref('');const bizInstTarget = ref('');const bizDefTarget = ref('');const bizDefType = ref('');const bizDefVal = ref('');const bizRevDefect = ref('');const bizDismPart = ref('');const bizStorePart = ref('');const bizStoreTarget = ref('');// Scenario Player Stateconst scenarioAudio = ref(null);const isPlaying = ref(false);const audioCurrentTime = ref(0);const audioDuration = ref(0);const showSubtitles = ref(true);const currentSubtitleText = ref('');const executedTimelineActions = ref(new Set());// Layout State (Flex percentages for resizers)const layout = reactive({ leftWidth: 66, bomHeight: 25, storageHeight: 40 });// Active dictionary based on local settingsconst t = computed(() => i18n[settings.language]);/*** Resolves the domain entity class of a node by inspecting ID conventions.** @param {string} nodeId - Identifier of the node.* @returns {string} Domain entity class ('Vehicle' | 'Slot' | 'Part' | 'Defect' | 'Warehouse').*/function getNodeEntityClass(nodeId) {if (!nodeId) return 'Part';if (/^veh/i.test(nodeId) || /^sys/i.test(nodeId)) return 'Vehicle';if (/^slot/i.test(nodeId)) return 'Slot';if (/^ware|^wh/i.test(nodeId)) return 'Warehouse';if (/^def/i.test(nodeId)) return 'Defect';return 'Part';}// Dynamic entity projection: Reconstruct base entities from pure business events in eventLogconst baseNodes = computed(() => {const nodeMap = new Map();state.eventLog.forEach(event => {if (event.valid_from !== undefined && event.valid_from > state.currentTime) return;if (event.type === 'REGISTER_PART' && event.partId) {nodeMap.set(event.partId, {id: event.partId,label: event.partId,type: getNodeEntityClass(event.partId),entityClass: getNodeEntityClass(event.partId)});} else if (event.type === 'ASSEMBLE') {if (event.parentId && !nodeMap.has(event.parentId)) {nodeMap.set(event.parentId, {id: event.parentId,label: event.parentId,type: getNodeEntityClass(event.parentId),entityClass: getNodeEntityClass(event.parentId)});}if (event.childId && !nodeMap.has(event.childId)) {nodeMap.set(event.childId, {id: event.childId,label: event.childId,type: getNodeEntityClass(event.childId),entityClass: getNodeEntityClass(event.childId)});}}});return Array.from(nodeMap.values());});const availableNodes = computed(() => {return baseNodes.value.map(n => n.id);});const activeNodes = computed(() => {return availableNodes.value;});const activeEdges = computed(() => {return naiveAdapter.generateSemanticGraph(state.eventLog,baseNodes.value,state.currentTime).edges.filter(e => e.properties?.isCurrent !== false);});const activeVehicles = computed(() => availableNodes.value.filter(id => getNodeEntityClass(id) === 'Vehicle'));const activeSlots = computed(() => availableNodes.value.filter(id => getNodeEntityClass(id) === 'Slot'));const activeParts = computed(() => availableNodes.value.filter(id => !id.startsWith('Slot_')));const activeWarehouses = computed(() => availableNodes.value.filter(id => getNodeEntityClass(id) === 'Warehouse'));const bizInstallSources = computed(() => {return availableNodes.value.filter(id => !id.startsWith('Slot_'));});const bizInstallTargets = computed(() => {return availableNodes.value.filter(id => !id.startsWith('Slot_'));});const installedComponents = computed(() => {const comps = new Set();activeEdges.value.forEach(e => {if (e.label === 'mounted_in' || e.label === 'stored_at') {comps.add(e.childId || e.from);}});return Array.from(comps).filter(id => !id.startsWith('Slot_'));});const activeDefectsList = computed(() => {return state.eventLog.map((e, index) => ({ event: e, logIndex: index })).filter(({ event: e }) => e.type === 'REPORT_DEFECT' && (e.valid_to === null || e.valid_to > state.currentTime) && (e.valid_from === undefined || e.valid_from <= state.currentTime)).map(({ event: e, logIndex }) => {const id = e.id || `def_${logIndex}_${e.targetId}_${e.defectName}`;return {id,logIndex,targetId: e.targetId,defectName: e.defectName,defectValue: e.defectValue,label: `${e.targetId} • ${e.defectName}=${e.defectValue}`};});});watch(bizInstallSources, (sources) => {if (!sources.includes(bizInstSource.value)) {bizInstSource.value = sources[0] || '';}}, { immediate: true });watch(bizInstallTargets, (targets) => {if (!targets.includes(bizInstTarget.value)) {bizInstTarget.value = targets[0] || '';}}, { immediate: true });watch(activeParts, (parts) => {if (!parts.includes(bizStorePart.value)) {bizStorePart.value = parts[0] || '';}}, { immediate: true });watch(activeWarehouses, (warehouses) => {if (!warehouses.includes(bizStoreTarget.value)) {bizStoreTarget.value = warehouses[0] || '';}}, { immediate: true });watch(installedComponents, (comps) => {if (!comps.includes(bizDismPart.value)) {bizDismPart.value = comps[0] || '';}}, { immediate: true });watch(activeDefectsList, (defects) => {if (!defects.some(d => d.id === bizRevDefect.value)) {bizRevDefect.value = defects[0]?.id || '';}}, { immediate: true });watch(availableNodes, (nodes) => {if (!nodes.includes(bizDefTarget.value)) {bizDefTarget.value = nodes[0] || '';}}, { immediate: true });/*** Central Event Dispatcher* ------------------------2 unmodified lines** @param {Object} event - The domain event object to dispatch.*//*** Central Event Dispatcher (Pure Event Sourcing)* ------------------------------------------------* Directly appends immutable business facts to the event log.** @param {Object} event - The domain event object to dispatch.*/function dispatch(event) {if (!event) return;state.eventLog.push(event);}// The core transformation pipeline: Event Log -> Ontology -> Semantic Graphconst semanticGraph = computed(() => {const eventsToProcess = state.eventLog;if (settings.ontology === 'BFO') {return bfoAdapter.generateSemanticGraph(eventsToProcess, baseNodes.value, state.currentTime);} else if (settings.ontology === 'ISO15926') {return isoAdapter.generateSemanticGraph(eventsToProcess, baseNodes.value, state.currentTime);} else {return naiveAdapter.generateSemanticGraph(eventsToProcess, baseNodes.value, state.currentTime, {ontology: settings.ontology});}});32 unmodified lines}});// Physical projection (SMS) vs Engineer View (SMRM) vs Canonical Logical (SMIM) graph routingconst activeGraph = computed(() => {if (settings.perspective === 'SMS') {return generatePhysicalGraph(semanticGraph.value, settings.storage);}if (settings.perspective === 'SMRM') {return reduceGraphForSMRM(semanticGraph.value);}return semanticGraph.value;});// Reactive Graph Captionconst graphCaption = computed(() => {let ontoText = 'BFO (3D)';if (settings.ontology === 'ISO15926') ontoText = 'ISO 15926 (4D)';if (settings.ontology === 'NAIVE_NODE') ontoText = t.value.ontoNaiveNode || 'Naive Graph (Node)';if (settings.ontology === 'NAIVE_EDGE') ontoText = t.value.ontoNaiveEdge || 'Naive Graph (Edge)';const storageText = settings.storage;let viewText = t.value.viewLogicalCaption;if (settings.perspective === 'SMRM') viewText = t.value.viewSmrmCaption;if (settings.perspective === 'SMS') viewText = t.value.viewPhysicalCaption;return `${ontoText} | ${storageText} | ${viewText}`;});// Contextual Dynamic Legendconst graphLegendItems = computed(() => {const nodes = [];const edges = [];const dict = t.value.legend;if (settings.ontology === 'NAIVE_NODE' || settings.ontology === 'NAIVE_EDGE' || settings.ontology === 'NAIVE') {nodes.push({ id: 'naiveVehicle', label: dict.naiveVehicle, swatch: 'swatch-box-vehicle' });nodes.push({ id: 'naiveSlot', label: dict.naiveSlot, swatch: 'swatch-box-slot' });nodes.push({ id: 'naivePart', label: dict.naivePart, swatch: 'swatch-box-part' });nodes.push({ id: 'naiveDefect', label: dict.naiveDefect, swatch: 'swatch-diamond-defect' });nodes.push({ id: 'naiveWarehouse', label: dict.naiveWarehouse, swatch: 'swatch-box-warehouse' });edges.push({ id: 'relHasSlot', label: dict.relHasSlot, swatch: 'swatch-line-slot' });edges.push({ id: 'relMountedIn', label: dict.relMountedIn, swatch: 'swatch-line-mount' });edges.push({ id: 'relStoredAt', label: dict.relStoredAt, swatch: 'swatch-line-store' });edges.push({ id: 'relHasDefect', label: dict.relHasDefect, swatch: 'swatch-line-defect' });} else if (settings.ontology === 'BFO') {nodes.push({ id: 'bfoSys', label: dict.bfoSys, swatch: 'swatch-box-sys' });nodes.push({ id: 'bfoElem', label: dict.bfoElem, swatch: 'swatch-box-elem' });nodes.push({ id: 'bfoQuality', label: dict.bfoQuality, swatch: 'swatch-diamond' });if (settings.perspective === 'SMS' && settings.storage === 'RDF') {nodes.push({ id: 'rdfStmt', label: dict.rdfStmt, swatch: 'swatch-diamond' });nodes.push({ id: 'rdfLit', label: dict.rdfLit, swatch: 'swatch-literal' });edges.push({ id: 'rdfPred', label: dict.rdfPred, swatch: 'swatch-line-past' });} else {edges.push({ id: 'bfoActive', label: dict.bfoActiveEdge, swatch: 'swatch-line-active' });edges.push({ id: 'bfoInheres', label: dict.bfoInheres, swatch: 'swatch-line-transition' });if (showHistory.value) {edges.push({ id: 'bfoPast', label: dict.bfoPastEdge, swatch: 'swatch-line-past' });}}} else {// ISO 15926 (4D)nodes.push({ id: 'iso4d', label: dict.iso4d, swatch: 'swatch-box-4d' });nodes.push({ id: 'isoState', label: dict.isoState, swatch: 'swatch-box-state' });nodes.push({ id: 'isoDefect', label: dict.isoDefect, swatch: 'swatch-diamond-defect' });edges.push({ id: 'isoPart', label: dict.isoPartRel, swatch: 'swatch-line-active' });edges.push({ id: 'isoSlice', label: dict.isoSliceRel, swatch: 'swatch-line-past' });edges.push({ id: 'isoDefectRel', label: dict.isoDefectRel, swatch: 'swatch-line-defect' });if (settings.perspective === 'SMS' && settings.storage === 'LPG') {edges.push({ id: 'isoTrans', label: dict.isoTransitionRel, swatch: 'swatch-line-transition' });}}return { nodes, edges };});// Watch for graph or engine changes to trigger re-renderswatch([activeGraph, () => settings.engine], () => {renderGraph();}, { deep: true });function renderGraph() {if (state.currentView === 'MENU') return;const graphToRender = activeGraph.value;if (settings.engine === 'vis') {const isComplex = settings.ontology === 'ISO15926' || settings.perspective === 'SMS';updateVisNetwork(graphToRender, isComplex);} else if (mermaidContainer.value) {updateMermaidNetwork(graphToRender, mermaidContainer.value);}}// Watch for view changes to initialise the canvas when entering the sandbox workspacewatch(() => state.currentView, async (newView) => {if (newView !== 'SCENARIO') {stopAudio();}if (newView === 'SCENARIO') {userRole.value = 'UNI_ENGINEER';state.eventLog.length = 0;resetTimeline(0);state.currentTime = 0;state.ontology = 'NAIVE_NODE';state.perspective = 'SMRM';state.graphEngine = 'MERMAID';}if (newView !== 'MENU') {await nextTick();if (visContainer.value) {initVisNetwork(visContainer.value);}renderGraph();}});// Lifecycle hooksonMounted(() => {// Inject initial seed data via pure factories and central dispatcherdispatch(createRegisterPartEvent('System_A', state.currentTime));dispatch(createRegisterPartEvent('SubAssembly_1', state.currentTime));dispatch(createAssembleEvent('System_A', 'SubAssembly_1', 'has_part', state.currentTime));dispatch(createRegisterPartEvent('Part_A', state.currentTime));dispatch(createAssembleEvent('System_A', 'Part_A', 'has_part', state.currentTime));dispatch(createRegisterPartEvent('Sensor_X', state.currentTime));dispatch(createAssembleEvent('SubAssembly_1', 'Sensor_X', 'has_part', state.currentTime));if (state.currentView !== 'MENU' && visContainer.value) {initVisNetwork(visContainer.value);renderGraph();}});// UI Event Handlers/*** Resets the application state, stops audio playback, and returns to the main menu.*/function goHome() {stopAudio();state.currentView = 'MENU';state.eventLog.splice(0, state.eventLog.length);state.currentTime = 0;state.edgeSequence = 1;}/*** Starts audio playback.*/function playAudio() {if (scenarioAudio.value) {scenarioAudio.value.play().catch(err => {console.warn('Audio playback was prevented or failed:', err);});}}/*** Pauses audio playback.*/function pauseAudio() {if (scenarioAudio.value) {scenarioAudio.value.pause();}}/*** Toggles audio playback between play and pause states.*/function togglePlayAudio() {if (isPlaying.value) {pauseAudio();} else {playAudio();}}/*** Stops audio playback, resets the timeline to zero, and clears the Event Sourcing log.*/function stopAudio() {if (scenarioAudio.value) {scenarioAudio.value.pause();scenarioAudio.value.currentTime = 0;}isPlaying.value = false;audioCurrentTime.value = 0;currentSubtitleText.value = '';// Reset Event Sourcing statestate.eventLog.length = 0;resetTimeline(0);state.ontology = 'NAIVE_NODE';state.perspective = 'SMRM';state.graphEngine = 'MERMAID';nextTick(() => {renderGraph();});}/*** Synchronises reactive audio time, subtitles, and timeline graph events with HTML5 audio playback.*/function onTimeUpdate() {if (scenarioAudio.value) {audioCurrentTime.value = scenarioAudio.value.currentTime;}const currentTime = audioCurrentTime.value;// Subtitle synchronisationconst activeSubtitle = vanishingCrackScenario.subtitles.find(sub => currentTime >= sub.start && currentTime <= sub.end);currentSubtitleText.value = activeSubtitle ? activeSubtitle.text : '';// Scenario timeline dispatcherdispatchScenarioTimeline(currentTime, state, renderGraph);}/*** Initialises audio duration when metadata is loaded.*/function onLoadedMetadata() {if (scenarioAudio.value) {audioDuration.value = scenarioAudio.value.duration || 0;}}/*** Handles completion of audio playback.* Crucial: On audio end, do NOT rewind or reset the state. Let the graph remain on screen!*/function onAudioEnded() {isPlaying.value = false;currentSubtitleText.value = '';}/*** Seeks to a specific position in the audio timeline based on range input,* resetting and re-evaluating the Event Sourcing state up to the new timestamp.** @param {Event} event - The range slider input event.*/function onSeek(event) {const targetTime = parseFloat(event.target.value);if (scenarioAudio.value) {scenarioAudio.value.currentTime = targetTime;}audioCurrentTime.value = targetTime;// Reset Event Sourcing state for replaystate.eventLog.length = 0;resetTimeline(0);state.ontology = 'NAIVE_NODE';state.perspective = 'SMRM';state.graphEngine = 'MERMAID';// Fast-forward timeline events and update subtitles to targetTimeonTimeUpdate();}/*** Formats seconds into a human-readable mm:ss format.** @param {number} seconds - Time duration in seconds.* @returns {string} Formatted time string.*/function formatTime(seconds) {if (!seconds || isNaN(seconds) || seconds < 0) return '00:00';const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;}/*** Universal Engineer Action 1: Register Asset*/function handleBizRegister() {if (!bizRegId.value) return;const event = createRegisterPartEvent(bizRegId.value,state.currentTime);if (event) {dispatch(event);bizRegId.value = '';}}/*** Universal Engineer Action 2: Install / Assemble*/function handleBizInstall() {if (!bizInstSource.value || !bizInstTarget.value) return;const childId = bizInstSource.value;const parentId = bizInstTarget.value;if (childId === parentId) return;const event = createAssembleEvent(parentId,childId,'mounted_in',state.currentTime);if (event) {dispatch(event);}}/*** Universal Engineer Action 3: Report Defect*/function handleBizReportDefect() {if (!bizDefTarget.value || !bizDefType.value) return;const event = createReportDefectEvent(bizDefTarget.value,bizDefType.value,bizDefVal.value || 'present',state.currentTime);if (event) {dispatch(event);bizDefType.value = '';bizDefVal.value = '';}}/*** Universal Engineer Action 4: Revoke Defect*/function handleBizRevokeDefect() {if (!bizRevDefect.value) return;const item = activeDefectsList.value.find(d => d.id === bizRevDefect.value);if (item && item.logIndex !== undefined) {state.eventLog.splice(item.logIndex, 1);bizRevDefect.value = '';}}/*** Universal Engineer Action 5: Dismantle*/function handleBizDismantle() {if (!bizDismPart.value) return;const event = createDismantleEvent(bizDismPart.value,state.currentTime);if (event) {dispatch(event);bizDismPart.value = '';}}/*** Universal Engineer Action 6: Move to Storage*/function handleBizStore() {if (!bizStorePart.value || !bizStoreTarget.value) return;const event = createAssembleEvent(bizStoreTarget.value,bizStorePart.value,'stored_at',state.currentTime);if (event) {dispatch(event);}}40 unmodified linesdocument.body.classList.add('no-select');}/*** Serialises and exports the current Event Sourcing state to a JSON file.*/function saveJson() {const exportData = {version: '1.0',savedAt: new Date().toISOString(),userRole: userRole.value,currentTime: state.currentTime,edgeSequence: state.edgeSequence,eventLog: JSON.parse(JSON.stringify(state.eventLog))};const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = `workbench-state-t${state.currentTime}.json`;document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);}/*** Opens the native file dialogue for loading a saved state JSON file.*/function triggerLoadJson() {if (fileInput.value) {fileInput.value.value = '';fileInput.value.click();}}/*** Reads, deserialises, and restores the application domain state from a JSON file.** @param {Event} e - HTML input change event.*/function onFileLoaded(e) {const file = e.target.files?.[0];if (!file) return;const reader = new FileReader();reader.onload = (event) => {try {const parsed = JSON.parse(event.target.result);if (Array.isArray(parsed)) {loadState({ eventLog: parsed });} else if (parsed && typeof parsed === 'object') {loadState(parsed);if (parsed.userRole && (parsed.userRole === 'DB_ADMIN' || parsed.userRole === 'UNI_ENGINEER')) {userRole.value = parsed.userRole;}}nextTick(() => {renderGraph();});} catch (err) {console.error('Failed to parse state JSON:', err);alert('Invalid JSON file format.');}};reader.readAsText(file);}return {state, settings, t, layout, advanceTime, dispatch,userRole, fileInput, saveJson, triggerLoadJson, onFileLoaded,entityClasses: ENTITY_CLASSES,relationTypes: RELATION_TYPES,availableNodes, goHome, showHistory,activeNodes, activeEdges,activeVehicles, activeSlots, activeParts, activeWarehouses,bizRegType, bizRegId, handleBizRegister,bizInstSource, bizInstTarget, handleBizInstall, bizInstallSources, bizInstallTargets,bizDefTarget, bizDefType, bizDefVal, handleBizReportDefect,bizRevDefect, handleBizRevokeDefect, activeDefectsList,bizDismPart, handleBizDismantle, installedComponents,bizStorePart, bizStoreTarget, handleBizStore,bomTree, lpgRecords, rdfTtl, formatProperties, queryCode,visContainer, mermaidContainer,graphCaption, graphLegendItems,startResizeH, startResizeV,scenarioAudio, isPlaying, audioCurrentTime, audioDuration,showSubtitles, currentSubtitleText, executedTimelineActions,playAudio, pauseAudio, togglePlayAudio, stopAudio,onTimeUpdate, onLoadedMetadata, onAudioEnded, onSeek, formatTime};},template: `<!-- Main Menu (Landing View) --><div v-if="state.currentView === 'MENU'" class="landing-view"><div class="menu-card"><div class="menu-badge">IEC 63339 Workbench</div><h1 class="menu-title">Knowledge Architecture Workbench</h1><p class="menu-subtitle">Top-Level Ontologies (SMIM), Storage Paradigms (SMS) & Event Sourcing</p><div class="menu-actions"><button class="menu-btn menu-btn-primary" @click="state.currentView = 'SANDBOX'"><span class="btn-main-text">Sandbox Mode</span><span class="btn-sub-text">Interactive exploration of 3D/4D ontologies & temporal graph models</span></button><button class="menu-btn menu-btn-scenario" @click="state.currentView = 'SCENARIO'"><span class="btn-main-text">Scenario: The Vanishing Crack</span><span class="btn-sub-text">Guided demonstration of temporal defect tracing across lifecycle states</span></button></div></div></div><!-- Main Sandbox Workspace --><div v-if="state.currentView !== 'MENU'" class="sandbox-workspace"><div class="control-deck"><!-- Tier 1: Architecture Settings --><div class="deck-row deck-row-top"><div class="section-label">1 unmodified line<span>{{ t.ontoTitle }}</span></div><div class="btn-group"><button id="ctrl-onto-bfo" :class="{ active: settings.ontology === 'BFO' }" @click="settings.ontology = 'BFO'">BFO (3D)</button><button id="ctrl-onto-iso" :class="{ active: settings.ontology === 'ISO15926' }" @click="settings.ontology = 'ISO15926'">ISO 15926 (4D)</button><button id="ctrl-onto-naive-node" :class="{ active: settings.ontology === 'NAIVE_NODE' }" @click="settings.ontology = 'NAIVE_NODE'">{{ t.ontoNaiveNode }}</button><button id="ctrl-onto-naive-edge" :class="{ active: settings.ontology === 'NAIVE_EDGE' }" @click="settings.ontology = 'NAIVE_EDGE'">{{ t.ontoNaiveEdge }}</button></div><div class="divider"></div>3 unmodified lines<span>{{ t.graphTitle }}</span></div><div class="btn-group"><button id="ctrl-storage-lpg" :class="{ active: settings.storage === 'LPG' }" @click="settings.storage = 'LPG'">LPG</button><button id="ctrl-storage-rdf" :class="{ active: settings.storage === 'RDF' }" @click="settings.storage = 'RDF'">RDF (W3C)</button></div><div class="divider"></div><div class="section-label">🎨 <span>{{ t.engineTitle }}</span></div><div class="btn-group"><button id="ctrl-engine-vis" :class="{ active: settings.engine === 'vis' }" @click="settings.engine = 'vis'">🌐 Vis.js</button><button id="ctrl-engine-mermaid" :class="{ active: settings.engine === 'mermaid' }" @click="settings.engine = 'mermaid'">📊 Mermaid</button></div><div class="divider"></div><div class="section-label">👁️ <span>{{ t.viewTitle }}</span></div><div class="btn-group"><button id="ctrl-view-smrm" :class="{ active: settings.perspective === 'SMRM' }" @click="settings.perspective = 'SMRM'">{{ t.viewSmrm }}</button><button id="ctrl-view-logical" :class="{ active: settings.perspective === 'SMIM' }" @click="settings.perspective = 'SMIM'">{{ t.viewLogical }}</button><button id="ctrl-view-physical" :class="{ active: settings.perspective === 'SMS' }" @click="settings.perspective = 'SMS'">{{ t.viewPhysical }}</button></div><div class="divider"></div><!-- JSON State Operations --><button id="ctrl-save-json" class="secondary" @click="saveJson" :title="t.saveBtn">{{ t.saveBtn }}</button><button id="ctrl-load-json" class="secondary" @click="triggerLoadJson" :title="t.loadBtn">{{ t.loadBtn }}</button><input ref="fileInput" type="file" accept=".json" style="display: none;" @change="onFileLoaded" /><div style="margin-left: auto;" class="btn-group flag-group"><button id="ctrl-lang-sv" :class="{ active: settings.language === 'sv' }" @click="settings.language = 'sv'" title="Svenska">🇸🇪</button><button id="ctrl-lang-en" :class="{ active: settings.language === 'en' }" @click="settings.language = 'en'" title="British English">🇬🇧</button><button id="ctrl-lang-ru" :class="{ active: settings.language === 'ru' }" @click="settings.language = 'ru'" title="Русский">🇷🇺</button></div></div><!-- Universal Engineer Workspace --><template v-if="userRole === 'UNI_ENGINEER'"><!-- Row 1: Time, Register, Install, Dismantle --><div class="deck-row"><span id="biz-time-badge" class="badge">T = {{ state.currentTime }}</span><button id="biz-step-btn" @click="advanceTime">{{ t.stepBtn }}</button><div class="divider"></div><!-- Action 1: Register Part --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">1. Register Part:</label><input id="biz-reg-id" type="text" v-model="bizRegId" placeholder="Part ID" style="width: 110px;"><button id="biz-reg-btn" class="secondary" @click="handleBizRegister">Register</button><div class="divider"></div><!-- Action 2: Install / Assemble --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">2. Install:</label><select id="biz-inst-source" v-model="bizInstSource"><option v-for="node in bizInstallSources" :key="'src_' + node" :value="node">{{ node }}</option></select><select id="biz-inst-target" v-model="bizInstTarget"><option v-for="node in bizInstallTargets" :key="'tgt_' + node" :value="node">{{ node }}</option></select><button id="biz-inst-btn" class="secondary" @click="handleBizInstall">Install</button><div class="divider"></div><!-- Action 5: Dismantle --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">5. Dismantle:</label><select id="biz-dism-part" v-model="bizDismPart"><option v-for="comp in installedComponents" :key="'comp_' + comp" :value="comp">{{ comp }}</option></select><button id="biz-dism-btn" class="danger" @click="handleBizDismantle">Dismantle</button></div><!-- Row 2: Defect, Revoke, Storage, History --><div class="deck-row" style="border-top: 1px solid #f1f5f9; background: #fafafa;"><!-- Action 3: Report Defect --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">3. Defect:</label><select id="biz-def-target" v-model="bizDefTarget"><option v-for="node in availableNodes" :key="'dn_' + node" :value="node">{{ node }}</option></select><input id="biz-def-type" type="text" v-model="bizDefType" placeholder="Type (e.g. crack)" style="width: 110px;"><input id="biz-def-val" type="text" v-model="bizDefVal" placeholder="Value (e.g. 2mm)" style="width: 80px;"><button id="biz-def-btn" class="secondary" @click="handleBizReportDefect">Report Defect</button><div class="divider"></div><!-- Action 4: Revoke Defect --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">4. Revoke:</label><select id="biz-rev-defect" v-model="bizRevDefect"><option v-for="d in activeDefectsList" :key="d.id" :value="d.id">{{ d.label }}</option></select><button id="biz-rev-btn" class="danger" @click="handleBizRevokeDefect">Revoke</button><div class="divider"></div><!-- Action 6: Move to Storage --><label style="font-size: 11px; font-weight: 700; color: #0284c7;">6. Storage:</label><select id="biz-store-part" v-model="bizStorePart"><option v-for="part in activeParts" :key="'sp_' + part" :value="part">{{ part }}</option></select><select id="biz-store-target" v-model="bizStoreTarget"><option v-for="wh in activeWarehouses" :key="'sw_' + wh" :value="wh">{{ wh }}</option></select><button id="biz-store-btn" class="secondary" @click="handleBizStore">Store</button><div class="divider"></div><!-- History Checkbox --><label style="font-size: 11px; display: flex; align-items: center; gap: 4px;"><input type="checkbox" v-model="showHistory"> {{ t.history }}</label></div></template></div><div class="main-container"><div id="canvas-container" :style="{ flex: \`0 0 \${layout.leftWidth}%\` }"><div ref="visContainer" v-show="settings.engine === 'vis'" style="width: 100%; height: 100%; position: absolute;"></div><div ref="mermaidContainer" v-show="settings.engine === 'mermaid'" id="mermaid-container"></div><!-- Dynamic Graph Caption Overlay --><div class="graph-caption"><span>📌</span><span>{{ graphCaption }}</span></div><!-- Contextual Dynamic Legend Overlay --><div class="graph-legend"><div class="legend-title"><span>{{ t.legend.title }}</span></div><div v-if="graphLegendItems.nodes.length > 0" class="legend-section"><div class="legend-section-title">{{ t.legend.nodes }}</div><div v-for="item in graphLegendItems.nodes" :key="item.id" class="legend-item"><div :class="item.swatch"></div><span>{{ item.label }}</span></div></div><div v-if="graphLegendItems.edges.length > 0" class="legend-section"><div class="legend-section-title">{{ t.legend.edges }}</div><div v-for="item in graphLegendItems.edges" :key="item.id" class="legend-item"><div :class="item.swatch"></div><span>{{ item.label }}</span></div></div></div></div><!-- Horizontal Resizer -->69 unmodified lines</div></div></div><!-- Hidden Scenario Audio Element --><audioref="scenarioAudio"src="./narratives/Ontologies_-_Disappearing_Crack.mp3"preload="metadata"@timeupdate="onTimeUpdate"@loadedmetadata="onLoadedMetadata"@play="isPlaying = true"@pause="isPlaying = false"@ended="onAudioEnded"></audio><!-- Subtitles Overlay (Scenario Mode) --><divv-if="state.currentView === 'SCENARIO' && showSubtitles"class="scenario-subtitles">{{ currentSubtitleText }}</div><!-- Floating Scenario Player Panel --><divv-if="state.currentView === 'SCENARIO'"class="scenario-player-panel"><buttonclass="player-btn"@click="togglePlayAudio":title="isPlaying ? 'Pause' : 'Play'":aria-label="isPlaying ? 'Pause' : 'Play'"><span v-if="isPlaying">⏸</span><span v-else>▶</span></button><buttonclass="player-btn"@click="stopAudio"title="Stop"aria-label="Stop"><span>⏹</span></button><inputtype="range"class="player-progress"min="0":max="audioDuration || 100"step="0.1":value="audioCurrentTime"@input="onSeek"aria-label="Audio Timeline"/><span class="player-time">{{ formatTime(audioCurrentTime) }} / {{ formatTime(audioDuration) }}</span><buttonclass="player-btn player-btn-cc":class="{ active: showSubtitles }"@click="showSubtitles = !showSubtitles"title="Toggle Subtitles"aria-label="Toggle Subtitles">CC</button></div><!-- Floating Home Button --><buttonv-if="state.currentView !== 'MENU'"class="floating-home-btn"@click="goHome"title="Return to Main Menu (Resets Sandbox)"aria-label="Return to Main Menu"><svg viewBox="0 0 24 24" width="22" height="22" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg></button>`};
8 unmodified lines9101112131412 unmodified lines2728293031328 unmodified lines414243444546474849505152535455565758596012 unmodified lines7374757677788 unmodified lines8788899091929394959697989910010110210310410510612 unmodified lines1191201211221231248 unmodified lines1331341351361371381391401411421431441451468 unmodified linesontoTitle: "Ontologi:",graphTitle: "Datamodell:",engineTitle: "Grafmotor:",stepBtn: "Lås steg (T+1)",parent: "Överordnad:",partPlaceholder: "Komponentnamn",12 unmodified linesloadBtn: "📂 Ladda JSON",queryTitle: "Databasfråga",queryDesc: "Visa aktuell struktur (T = T_nu)",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Definierar intressentens perspektiv (ISO 42010 Viewpoint). Användaren ser bara BOM-strukturen vid tidpunkten T, oavsett underliggande IT-lager.",smrm: "<b>SMRM (Concept Repository)</b><br/>Domänontologi och gemensam begreppsbank (System, Component, Physical/Functional Object). Här låst till standardiserad produktnedbrytning.",8 unmodified linesbfoElem: "Continuant / Komponent (:Element)",bfoActiveEdge: "Aktiv relation [giltig till nu]",bfoPastEdge: "Historisk relation (avslutad)",iso4d: "4D-individ (Spatio-Temporal Extent)",isoState: "Temporal del / Tillstånd (State)",isoPartRel: "Tidlös komposition (hasPart)",isoSliceRel: "temporalPartOf (del av 4D-individ)",isoTransitionRel: "TRANSITION_TO (tillståndskedja i LPG)",rdfStmt: "Reifiering (_:statement)",rdfLit: "Literal (tidsstämpel xsd:int)",rdfPred: "RDF-predikat"}},en: {ontoTitle: "Ontology:",graphTitle: "Data Model:",engineTitle: "Renderer:",stepBtn: "Commit step (T+1)",parent: "Parent:",partPlaceholder: "Component name",12 unmodified linesloadBtn: "📂 Load JSON",queryTitle: "Database Query",queryDesc: "Show current structure (T = T_now)",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Captures the stakeholder concern and viewpoint (ISO 42010). The engineer always sees a unified BOM snapshot at time T, decoupled from graph mechanics.",smrm: "<b>SMRM (Concept Repository)</b><br/>Domain Ontology: the shared engineering lexicon (System, System Element, Physical/Functional Object). Fixed here to physical decomposition.",8 unmodified linesbfoElem: "Continuant / Component (:Element)",bfoActiveEdge: "Active relation [valid to now]",bfoPastEdge: "Historical relation (closed)",iso4d: "4D Individual (Spatio-Temporal Extent)",isoState: "Temporal Part / State",isoPartRel: "Tenseless Composition (hasPart)",isoSliceRel: "temporalPartOf (Extent link)",isoTransitionRel: "TRANSITION_TO (State Chain in LPG)",rdfStmt: "Reification Node (_:statement)",rdfLit: "Literal (xsd:int timestamp)",rdfPred: "RDF Predicate"}},ru: {ontoTitle: "Онтология:",graphTitle: "Модель данных:",engineTitle: "Движок:",stepBtn: "Зафиксировать шаг (T+1)",parent: "Родитель:",partPlaceholder: "Имя компонента",12 unmodified linesloadBtn: "📂 Загрузить JSON",queryTitle: "Запрос к БД",queryDesc: "Показать текущую структуру (T = T_now)",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Уровень точки зрения пользователя (ISO 42010). Инженер всегда видит чистый срез BOM на момент времени T, абстрагированный от структуры базы данных.",smrm: "<b>SMRM (Concept Repository)</b><br/>Онтология предметной области (Domain Ontology). Общий словарь понятий проекта (System, Component, Physical Object). Зафиксирована на базовой декомпозиции.",8 unmodified linesbfoElem: "Континуант / Компонент (:Element)",bfoActiveEdge: "Активная связь [действует сейчас]",bfoPastEdge: "Архивная связь (закрыта)",iso4d: "4D-индивид (Пространственно-временной объем)",isoState: "Темпоральный срез / Состояние",isoPartRel: "Вневременной состав (hasPart)",isoSliceRel: "temporalPartOf (связь с 4D-целым)",isoTransitionRel: "TRANSITION_TO (цепочка состояний в LPG)",rdfStmt: "Узел реификации (_:statement)",rdfLit: "Литерал (метка времени xsd:int)",rdfPred: "RDF-предикат"}}};8 unmodified lines910111213141516171819202112 unmodified lines34353637383940414243444546474849505152538 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010112 unmodified lines1141151161171181191201211221231241251261271281291301311321338 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018112 unmodified lines1941951961971981992002012022032042052062072082092102112122138 unmodified lines2222232242252262272282292302312322332342352362372382392402412422432442452462472488 unmodified linesontoTitle: "Ontologi:",graphTitle: "Datamodell:",engineTitle: "Grafmotor:",viewTitle: "Perspektiv:",viewSmrm: "Ingenjör (SMRM)",viewLogical: "Logisk (SMIM)",viewPhysical: "Fysisk (SMS)",viewSmrmCaption: "Ingenjörsperspektiv (SMRM)",viewLogicalCaption: "Logiskt perspektiv (SMIM)",viewPhysicalCaption: "Fysiskt perspektiv (SMS)",stepBtn: "Lås steg (T+1)",parent: "Överordnad:",partPlaceholder: "Komponentnamn",12 unmodified linesloadBtn: "📂 Ladda JSON",queryTitle: "Databasfråga",queryDesc: "Visa aktuell struktur (T = T_nu)",ontoNaive: "Naiv Graf",ontoNaiveNode: "Naiv Graf (Node)",ontoNaiveEdge: "Naiv Graf (Edge)",nodeClass: "Klass:",nodeIdPlaceholder: "Nod-ID",addNodeBtn: "+ Nod",relTypeLabel: "Relation:",addRelBtn: "+ Relation",propTarget: "Mål:",propKeyPlaceholder: "Nyckel (t.ex. crack)",propValPlaceholder: "Värde (t.ex. 2mm)",addPropBtn: "+ Egenskap",targetNode: "Nod",targetEdge: "Relation",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Definierar intressentens perspektiv (ISO 42010 Viewpoint). Användaren ser bara BOM-strukturen vid tidpunkten T, oavsett underliggande IT-lager.",smrm: "<b>SMRM (Concept Repository)</b><br/>Domänontologi och gemensam begreppsbank (System, Component, Physical/Functional Object). Här låst till standardiserad produktnedbrytning.",8 unmodified linesbfoElem: "Continuant / Komponent (:Element)",bfoActiveEdge: "Aktiv relation [giltig till nu]",bfoPastEdge: "Historisk relation (avslutad)",bfoQuality: "Kvalitet / Egenskap (:Quality)",bfoInheres: "inheres_in (egenskap i bärare)",iso4d: "4D-individ (Spatio-Temporal Extent)",isoState: "Temporal del / Tillstånd (State)",isoPartRel: "Tidlös komposition (hasPart)",isoSliceRel: "temporalPartOf (del av 4D-individ)",isoTransitionRel: "TRANSITION_TO (tillståndskedja i LPG)",isoDefect: "Defekt (Tillståndsklassificering)",isoDefectRel: "has_defect (tillståndsklassificering)",rdfStmt: "Reifiering (_:statement)",rdfLit: "Literal (tidsstämpel xsd:int)",rdfPred: "RDF-predikat",naiveVehicle: "Fordon (:Vehicle)",naiveSlot: "Plats (:Slot)",naivePart: "Komponent (:Part)",naiveDefect: "Defekt (:Defect)",naiveWarehouse: "Lager (:Warehouse)",relHasSlot: "has_slot (fordonsslot)",relMountedIn: "mounted_in (monterad i)",relStoredAt: "stored_at (lagrad på)",relHasDefect: "has_defect (identifierad defekt)"}},en: {ontoTitle: "Ontology:",graphTitle: "Data Model:",engineTitle: "Renderer:",viewTitle: "Perspective:",viewSmrm: "Engineer (SMRM)",viewLogical: "Logical (SMIM)",viewPhysical: "Physical (SMS)",viewSmrmCaption: "Engineer Perspective (SMRM)",viewLogicalCaption: "Logical Perspective (SMIM)",viewPhysicalCaption: "Physical Perspective (SMS)",stepBtn: "Commit step (T+1)",parent: "Parent:",partPlaceholder: "Component name",12 unmodified linesloadBtn: "📂 Load JSON",queryTitle: "Database Query",queryDesc: "Show current structure (T = T_now)",ontoNaive: "Naive Graph",ontoNaiveNode: "Naive Graph (Node)",ontoNaiveEdge: "Naive Graph (Edge)",nodeClass: "Class:",nodeIdPlaceholder: "Node ID",addNodeBtn: "+ Node",relTypeLabel: "Relation:",addRelBtn: "+ Relation",propTarget: "Target:",propKeyPlaceholder: "Key (e.g. crack)",propValPlaceholder: "Value (e.g. 2mm)",addPropBtn: "+ Property",targetNode: "Node",targetEdge: "Relation",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Captures the stakeholder concern and viewpoint (ISO 42010). The engineer always sees a unified BOM snapshot at time T, decoupled from graph mechanics.",smrm: "<b>SMRM (Concept Repository)</b><br/>Domain Ontology: the shared engineering lexicon (System, System Element, Physical/Functional Object). Fixed here to physical decomposition.",8 unmodified linesbfoElem: "Continuant / Component (:Element)",bfoActiveEdge: "Active relation [valid to now]",bfoPastEdge: "Historical relation (closed)",bfoQuality: "Dependent Continuant (:Quality)",bfoInheres: "inheres_in (Quality inherence)",iso4d: "4D Individual (Spatio-Temporal Extent)",isoState: "Temporal Part / State",isoPartRel: "Tenseless Composition (hasPart)",isoSliceRel: "temporalPartOf (Extent link)",isoTransitionRel: "TRANSITION_TO (State Chain in LPG)",isoDefect: "Defect (State Classification)",isoDefectRel: "has_defect (State Classification)",rdfStmt: "Reification Node (_:statement)",rdfLit: "Literal (xsd:int timestamp)",rdfPred: "RDF Predicate",naiveVehicle: "Vehicle (:Vehicle)",naiveSlot: "Slot (:Slot)",naivePart: "Part (:Part)",naiveDefect: "Defect (:Defect)",naiveWarehouse: "Warehouse (:Warehouse)",relHasSlot: "has_slot (Vehicle Slot)",relMountedIn: "mounted_in (Installed in Slot)",relStoredAt: "stored_at (Stored in Warehouse)",relHasDefect: "has_defect (Identified Defect)"}},ru: {ontoTitle: "Онтология:",graphTitle: "Модель данных:",engineTitle: "Движок:",viewTitle: "Ракурс:",viewSmrm: "Инженер (SMRM)",viewLogical: "Логический (SMIM)",viewPhysical: "Физический (SMS)",viewSmrmCaption: "Инженерный ракурс (SMRM)",viewLogicalCaption: "Логический ракурс (SMIM)",viewPhysicalCaption: "Физический ракурс (SMS)",stepBtn: "Зафиксировать шаг (T+1)",parent: "Родитель:",partPlaceholder: "Имя компонента",12 unmodified linesloadBtn: "📂 Загрузить JSON",queryTitle: "Запрос к БД",queryDesc: "Показать текущую структуру (T = T_now)",ontoNaive: "Наивный граф",ontoNaiveNode: "Наивный граф (Узел)",ontoNaiveEdge: "Наивный граф (Ребро)",nodeClass: "Класс:",nodeIdPlaceholder: "ID узла",addNodeBtn: "+ Узел",relTypeLabel: "Связь:",addRelBtn: "+ Связь",propTarget: "Цель:",propKeyPlaceholder: "Ключ (напр. crack)",propValPlaceholder: "Значение (напр. 2mm)",addPropBtn: "+ Свойство",targetNode: "Узел",targetEdge: "Связь",tooltips: {urmsm: "<b>URMSM (Dimension & Aspect)</b><br/>Уровень точки зрения пользователя (ISO 42010). Инженер всегда видит чистый срез BOM на момент времени T, абстрагированный от структуры базы данных.",smrm: "<b>SMRM (Concept Repository)</b><br/>Онтология предметной области (Domain Ontology). Общий словарь понятий проекта (System, Component, Physical Object). Зафиксирована на базовой декомпозиции.",8 unmodified linesbfoElem: "Континуант / Компонент (:Element)",bfoActiveEdge: "Активная связь [действует сейчас]",bfoPastEdge: "Архивная связь (закрыта)",bfoQuality: "Зависимый континуант (:Quality)",bfoInheres: "inheres_in (присущ носителю)",iso4d: "4D-индивид (Пространственно-временной объем)",isoState: "Темпоральный срез / Состояние",isoPartRel: "Вневременной состав (hasPart)",isoSliceRel: "temporalPartOf (связь с 4D-целым)",isoTransitionRel: "TRANSITION_TO (цепочка состояний в LPG)",isoDefect: "Дефект (Классификация среза)",isoDefectRel: "has_defect (классификация среза)",rdfStmt: "Узел реификации (_:statement)",rdfLit: "Литерал (метка времени xsd:int)",rdfPred: "RDF-предикат",naiveVehicle: "Транспорт (:Vehicle)",naiveSlot: "Слот (:Slot)",naivePart: "Деталь (:Part)",naiveDefect: "Дефект (:Defect)",naiveWarehouse: "Склад (:Warehouse)",relHasSlot: "has_slot (слот транспорта)",relMountedIn: "mounted_in (установлен в)",relStoredAt: "stored_at (хранится на складе)",relHasDefect: "has_defect (выявлен дефект)"}}};
78 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712878 unmodified linesdef += ' classDef default fill:#f8fafc,stroke:#cbd5e1,color:#334155,stroke-width:1px\n';def += ' classDef bfoSys fill:#0284c7,stroke:#0369a1,color:#ffffff,stroke-width:2px\n';def += ' classDef bfoElem fill:#64748b,stroke:#475569,color:#ffffff,stroke-width:1px\n';def += ' classDef iso4d fill:#4f46e5,stroke:#3730a3,color:#ffffff,stroke-width:2px\n';def += ' classDef isoState fill:#0d9488,stroke:#0f766e,color:#ffffff,stroke-width:1px\n\n';// 2. Add NodessemanticGraph.nodes.forEach(node => {const safeId = sanitizeId(node.id);const styleClass = getNodeClass(node);const safeLabel = node.label.replace(/\n/g, '<br/>'); // Support multi-linedef += ` ${safeId}["<b>${safeLabel}</b><br/><i>${node.type}</i>"]:::${styleClass}\n`;});def += '\n';// 3. Add EdgessemanticGraph.edges.forEach(edge => {const safeFrom = sanitizeId(edge.from);const safeTo = sanitizeId(edge.to);const isCurrent = edge.properties?.isCurrent !== false;// Solid line for active composition, dashed line for closed or structural classification linksconst linkStyle = (!isCurrent || edge.type === 'classification') ? '-.->' : '-->';// Escape quotes in the labelconst safeEdgeLabel = (edge.label || '').replace(/"/g, "'");def += ` ${safeFrom} ${linkStyle}|"${safeEdgeLabel}"| ${safeTo}\n`;});return def;}/*** Maps ontological node types to Mermaid CSS classes.*/function getNodeClass(node) {switch (node.type) {case 'MaterialEntity':return node.properties?.entityType === 'system' ? 'bfoSys' : 'bfoElem';case 'ActualIndividual':return 'iso4d';case 'State':return 'isoState';default:return 'default';}}78 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226378 unmodified linesdef += ' classDef default fill:#f8fafc,stroke:#cbd5e1,color:#334155,stroke-width:1px\n';def += ' classDef bfoSys fill:#0284c7,stroke:#0369a1,color:#ffffff,stroke-width:2px\n';def += ' classDef bfoElem fill:#64748b,stroke:#475569,color:#ffffff,stroke-width:1px\n';def += ' classDef bfoQuality fill:#f59e0b,stroke:#d97706,color:#000000,stroke-width:2px\n';def += ' classDef rdfStmt fill:#f59e0b,stroke:#d97706,color:#000000,stroke-width:1px\n';def += ' classDef rdfLit fill:#f1f5f9,stroke:#cbd5e1,color:#334155,stroke-dasharray:3 3\n';def += ' classDef iso4d fill:#4f46e5,stroke:#3730a3,color:#ffffff,stroke-width:2px\n';def += ' classDef isoState fill:#0d9488,stroke:#0f766e,color:#ffffff,stroke-width:1px\n';def += ' classDef naiveVehicle fill:#0284c7,stroke:#0369a1,color:#ffffff,stroke-width:2px\n';def += ' classDef naiveSlot fill:#64748b,stroke:#475569,color:#ffffff,stroke-width:1px\n';def += ' classDef naivePart fill:#10b981,stroke:#059669,color:#ffffff,stroke-width:2px\n';def += ' classDef naiveDefect fill:#ef4444,stroke:#dc2626,color:#ffffff,stroke-width:2px\n';def += ' classDef naiveWarehouse fill:#f97316,stroke:#ea580c,color:#ffffff,stroke-width:2px\n\n';// 2. Add Nodes directly from the Semantic Graph (pure renderer)(semanticGraph.nodes || []).forEach(node => {const safeId = sanitizeId(node.id);const styleClass = getNodeClass(node);let labelText = node.label || '';if (node.properties) {const customProps = Object.entries(node.properties).filter(([k]) => !['isCurrent', 'originalId', 'entityType', 'validFrom', 'validTo', 'ownerId'].includes(k));if (customProps.length > 0) {const propStr = customProps.map(([k, v]) => `${k}: ${v}`).join(', ');labelText = `${labelText} {${propStr}}`;}}const safeLabel = labelText.replace(/\n/g, '<br/>').replace(/"/g, '"');let shapeOpen = '["';let shapeClose = '"]';const entityType = node.type || node.properties?.entityClass;if (entityType === 'TemporalPartMembership' || entityType === 'RelationalQuality' || entityType === 'Defect' || /^def/i.test(node.id)) {shapeOpen = '{{"'; // Rhombus / diamond shapeshapeClose = '"}}';} else if (entityType === 'Literal' || entityType === 'Quality' || entityType === 'DependentContinuant' || /^qual/i.test(node.id)) {shapeOpen = '(["'; // Oval / capsule shape for Quality and LiteralsshapeClose = '"])';}def += ` ${safeId}${shapeOpen}<b>${safeLabel}</b><br/><i>${entityType || 'Node'}</i>${shapeClose}:::${styleClass}\n`;});def += '\n';// 4. Add Edges and collect explicit linkStyle declarationsconst linkStyles = [];(semanticGraph.edges || []).forEach((edge, idx) => {const safeFrom = sanitizeId(edge.from);const safeTo = sanitizeId(edge.to);const isCurrent = edge.properties?.isCurrent !== false;let linkArrow = '-->';if (edge.type === 'transition') {linkArrow = '==>'; // Thick arrow for LPG state transitions} else if (!isCurrent || edge.type === 'classification' || edge.type === 'reification' || edge.type === 'predicate') {linkArrow = '-.->'; // Dashed line for inactive, classification, or reification links}// Format edge label and append custom properties (e.g. defect observations) if presentlet rawLabel = edge.label || '';if (edge.properties) {const customEdgeProps = Object.entries(edge.properties).filter(([k]) => !['isCurrent', 'validFrom', 'validTo', 'originalId', 'ownerId', 'entityType', 'childId', 'parentId'].includes(k));if (customEdgeProps.length > 0) {const propStr = customEdgeProps.map(([k, v]) => `${k}: ${v}`).join(', ');rawLabel = `${rawLabel}\\n{${propStr}}`;}}// Escape quotes in the labelconst safeEdgeLabel = rawLabel.replace(/"/g, "'");def += ` ${safeFrom} ${linkArrow}|"${safeEdgeLabel}"| ${safeTo}\n`;// Calculate edge colour and line styling to match the legendconst style = getMermaidEdgeStyle(edge);let styleDecl = `stroke:${style.stroke},stroke-width:${style.width}px`;if (style.dash) {styleDecl += `,stroke-dasharray:${style.dash}`;}linkStyles.push(` linkStyle ${idx} ${styleDecl};`);});if (linkStyles.length > 0) {def += '\n' + linkStyles.join('\n') + '\n';}return def;}/*** Determines the stroke colour, width, and dash style for a Mermaid edge.* Perfectly synchronises canvas edge rendering with the UI legend colours.** @param {Object} edge - Canonical semantic edge.* @returns {{ stroke: string, width: number, dash?: string }} Styling descriptor.*/function getMermaidEdgeStyle(edge) {const isCurrent = edge.properties?.isCurrent !== false;if (!isCurrent) {return { stroke: '#94a3b8', width: 1, dash: '4 4' };}const rel = (edge.type || '').toLowerCase();const label = (edge.label || '').toLowerCase();if (rel === 'has_defect' || label === 'has_defect' || label === 'defect') {return { stroke: '#ef4444', width: 2 }; // Red}if (rel === 'inherence' || label === 'inheres_in' || label === 'bearer_of') {return { stroke: '#f59e0b', width: 2 }; // Amber}if (rel === 'has_slot' || label === 'has_slot') {return { stroke: '#0284c7', width: 2 }; // Blue}if (rel === 'mounted_in' || label === 'mounted_in') {return { stroke: '#10b981', width: 2 }; // Green}if (rel === 'stored_at' || label === 'stored_at') {return { stroke: '#f97316', width: 2 }; // Orange}if (rel === 'composition' || rel === 'has_part' || label === 'has_part' || label === 'haspart' || label === 'partof') {return { stroke: '#10b981', width: 2 }; // Emerald green}if (rel === 'transition') {return { stroke: '#f59e0b', width: 2 }; // Amber}if (rel === 'classification' || rel === 'reification' || rel === 'predicate' || label === 'temporalpartof') {return { stroke: '#94a3b8', width: 1, dash: '3 3' };}return { stroke: '#94a3b8', width: 1 };}/*** Maps ontological node types to Mermaid CSS classes.*/function getNodeClass(node) {const entityType = node.type || node.properties?.entityClass || node.properties?.entityType;switch (entityType) {case 'Vehicle':return 'naiveVehicle';case 'Slot':return 'naiveSlot';case 'Part':return 'naivePart';case 'Defect':return 'naiveDefect';case 'Warehouse':return 'naiveWarehouse';case 'MaterialEntity':return node.properties?.entityType === 'system' ? 'bfoSys' : 'bfoElem';case 'Quality':case 'DependentContinuant':return 'bfoQuality';case 'RelationalQuality':case 'TemporalPartMembership':return 'rdfStmt';case 'Literal':return 'rdfLit';case 'ActualIndividual':return 'iso4d';case 'State':return 'isoState';default:if (/^def/i.test(node.id)) return 'naiveDefect';if (/^qual/i.test(node.id)) return 'bfoQuality';return 'default';}}
16 unmodified lines17181920212217 unmodified lines4041424344454647484950515253545556575818 unmodified lines777879808182838485868714 unmodified lines1021031041051061071084 unmodified lines1131141151161171189 unmodified lines1281291301311321331341357 unmodified lines14314414514614714814915015115215315415515615715816 unmodified lines* @param {HTMLElement} container - The DOM element to host the canvas.*/export function initVisNetwork(container) {const data = { nodes: visNodes, edges: visEdges };network = new vis.Network(container, data, getBaseOptions(false));}17 unmodified linesvisNodes.clear();visEdges.clear();// 1. Map and style Nodesconst styledNodes = semanticGraph.nodes.map(node => {const style = getNodeStyle(node);return {id: node.id,label: node.label,shape: style.shape,color: style.color,font: style.font,size: style.size,margin: 10,borderWidth: 1.5};});visNodes.add(styledNodes);18 unmodified linesconst style = getEdgeStyle(edge);styledEdges.push({id: edge.id,from: edge.from,to: edge.to,label: edge.label,color: style.color,dashes: style.dashes,width: style.width,14 unmodified lines* @returns {Object} Vis.js node styling object.*/function getNodeStyle(node) {switch (node.type) {// BFO 3D Continuantscase 'MaterialEntity': {const isSystem = node.properties?.entityType === 'system';4 unmodified lines};}// ISO 15926 4D Perdurantscase 'ActualIndividual':return {9 unmodified linesfont: { color: '#ffffff' }};default:return { shape: 'box', color: '#94a3b8', font: { color: '#ffffff' } };}}7 unmodified linesconst isCurrent = edge.properties?.isCurrent !== false;switch (edge.type) {case 'composition':return {color: isCurrent ? { color: '#10b981' } : { color: '#cbd5e1' }, // Emerald active, Slate pastdashes: !isCurrent,width: isCurrent ? 2 : 1};case 'classification':return {color: { color: '#94a3b8' }, // Subtle slate for structural 4D temporalPartOf linksdashes: !isCurrent,width: 1};16 unmodified lines1718192021222324252617 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818218 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212314 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821834 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202219 unmodified lines2312322332342352362372382392402412422432442457 unmodified lines25325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231316 unmodified lines* @param {HTMLElement} container - The DOM element to host the canvas.*/export function initVisNetwork(container) {if (network) {network.destroy();network = null;}const data = { nodes: visNodes, edges: visEdges };network = new vis.Network(container, data, getBaseOptions(false));}17 unmodified linesvisNodes.clear();visEdges.clear();// 1. Map and style Nodes directly from the Semantic Graph (pure renderer)const styledNodes = (semanticGraph.nodes || []).map(node => {const style = getNodeStyle(node);// Display custom properties directly on the node label if presentlet displayLabel = node.label || node.id;if (node.properties) {const customProps = Object.entries(node.properties).filter(([k]) => !['isCurrent', 'originalId', 'entityType', 'validFrom', 'validTo', 'ownerId'].includes(k));if (customProps.length > 0) {const propStr = customProps.map(([k, v]) => `${k}: ${v}`).join(', ');displayLabel = `${displayLabel}\n{${propStr}}`;}}const styledNode = {id: node.id,label: displayLabel,shape: style.shape,color: style.color,font: style.font,borderWidth: 1.5};if (style.size !== undefined) {styledNode.size = style.size;}if (style.shape === 'box' || style.shape === 'ellipse') {styledNode.margin = 10;}return styledNode;});visNodes.add(styledNodes);18 unmodified linesconst style = getEdgeStyle(edge);// Display custom properties directly on the edge label if presentlet displayEdgeLabel = edge.label;if (edge.properties) {const customEdgeProps = Object.entries(edge.properties).filter(([k]) => !['isCurrent', 'validFrom', 'validTo'].includes(k));if (customEdgeProps.length > 0) {const propStr = customEdgeProps.map(([k, v]) => `${k}: ${v}`).join(', ');displayEdgeLabel = `${displayEdgeLabel} {${propStr}}`;}}styledEdges.push({id: edge.id,from: edge.from,to: edge.to,label: displayEdgeLabel,color: style.color,dashes: style.dashes,width: style.width,14 unmodified lines* @returns {Object} Vis.js node styling object.*/function getNodeStyle(node) {const entityType = node.type || node.properties?.entityClass || node.properties?.entityType;switch (entityType) {// Specific Manufacturing Domain Classes (Naive Mode)case 'Vehicle':return {shape: 'box',color: '#0284c7', // Bluefont: { color: '#ffffff', bold: true }};case 'Slot':return {shape: 'box',color: '#64748b', // Greyfont: { color: '#ffffff' }};case 'Part':return {shape: 'box',color: '#10b981', // Greenfont: { color: '#ffffff', bold: true }};case 'Defect':return {shape: 'diamond',size: 25,color: '#ef4444', // Redfont: { color: '#ffffff', bold: true }};case 'Warehouse':return {shape: 'box',color: '#f97316', // Orangefont: { color: '#ffffff', bold: true }};// BFO 3D Continuantscase 'MaterialEntity': {const isSystem = node.properties?.entityType === 'system';4 unmodified lines};}case 'Quality':case 'DependentContinuant':return {shape: 'diamond',size: 25,color: '#f59e0b', // Amber / orange for Dependent Continuantfont: { color: '#000000', bold: true }};// W3C RDF Reification and Literals (SMS physical layer)case 'RelationalQuality':case 'TemporalPartMembership': {const isStmtActive = node.properties?.isCurrent !== false;return {shape: 'diamond',size: 15,color: isStmtActive ? '#f59e0b' : '#e2e8f0', // Amber if active, light grey if pastfont: { size: 10, color: isStmtActive ? '#000000' : '#64748b', bold: true }};}case 'Literal':return {shape: 'ellipse', // Oval shapecolor: '#f8fafc',font: { size: 8, color: '#334155' }};// ISO 15926 4D Perdurantscase 'ActualIndividual':return {9 unmodified linesfont: { color: '#ffffff' }};default: {if (/^def/i.test(node.id)) {return { shape: 'diamond', color: '#ef4444', font: { color: '#ffffff', bold: true } };}if (/^qual/i.test(node.id)) {return { shape: 'diamond', color: '#f59e0b', font: { color: '#000000', bold: true } };}return { shape: 'box', color: '#94a3b8', font: { color: '#ffffff' } };}}}7 unmodified linesconst isCurrent = edge.properties?.isCurrent !== false;switch (edge.type) {case 'has_slot':return {color: isCurrent ? { color: '#0284c7' } : { color: '#cbd5e1' }, // Bluedashes: !isCurrent,width: isCurrent ? 2 : 1};case 'mounted_in':return {color: isCurrent ? { color: '#10b981' } : { color: '#cbd5e1' }, // Greendashes: !isCurrent,width: isCurrent ? 2 : 1};case 'stored_at':return {color: isCurrent ? { color: '#f97316' } : { color: '#cbd5e1' }, // Orangedashes: !isCurrent,width: isCurrent ? 2 : 1};case 'has_defect':return {color: isCurrent ? { color: '#ef4444' } : { color: '#cbd5e1' }, // Reddashes: !isCurrent,width: 2};case 'inherence':return {color: isCurrent ? { color: '#f59e0b' } : { color: '#cbd5e1' }, // Amber for inheres_indashes: !isCurrent,width: 2};case 'composition':case 'has_part':return {color: isCurrent ? { color: '#10b981' } : { color: '#cbd5e1' }, // Emerald active, Slate pastdashes: !isCurrent,width: isCurrent ? 2 : 1};case 'transition':return {color: { color: '#f59e0b' }, // Amber for LPG state transitionsdashes: false,width: 2};case 'classification':case 'reification':case 'predicate':return {color: { color: '#94a3b8' }, // Subtle slate for structural 4D or RDF linksdashes: !isCurrent,width: 1};
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280/** * SCENARIO: THE VANISHING CRACK * ----------------------------- * Contains narrative subtitle data and the chronological action timeline * synchronised with audio playback. * * Timestamps are represented in seconds (float). */
import { createRegisterPartEvent, createAssembleEvent, createReportDefectEvent, createDismantleEvent} from '../smrm/actions.js';
/** * Highlights specified UI elements by IDs with a temporary glowing effect. * Simulates a Phantom User interacting with the workbench controls. * * @param {string[]} elementIds - Array of DOM element IDs to highlight. * @param {number} [duration=1200] - Duration of the highlight effect in milliseconds. */export function highlightUI(elementIds, duration = 1200) { if (typeof document === 'undefined' || !Array.isArray(elementIds)) return; elementIds.forEach(id => { const el = document.getElementById(id); if (el) { el.classList.add('scenario-highlight'); setTimeout(() => { el.classList.remove('scenario-highlight'); }, duration); } });}
const subtitles = [ { start: 0.14, end: 1.84, text: "Welcome to the Data Sandbox." }, { start: 2.46, end: 7.50, text: "Currently, the system is operating in naive graph mode. We have no strict" }, { start: 7.50, end: 10.62, text: "ontological rules, just nodes and relationships." }, { start: 11.26, end: 13.78, text: "Let's model a typical manufacturing scenario." }, { start: 15.50, end: 16.38, text: "We have a vehicle." }, { start: 17.02, end: 22.02, text: "Within it, there is a suspension slot where part M01 is installed." }, { start: 22.64, end: 23.84, text: "Everything is straightforward." }, { start: 24.44, end: 27.06, text: "But what happens when a real-world problem occurs?" }, { start: 28.62, end: 33.72, text: "During an inspection, a two-millimeter crack is discovered on part M01." }, { start: 34.64, end: 37.06, text: "How do we store this fact in a naive graph?" }, { start: 38.74, end: 40.44, text: "The developer faces a dilemma." }, { start: 41.12, end: 45.72, text: "If we add the property crack two millimeters directly to the part node," }, { start: 46.26, end: 50.32, text: "then when we try to query the car's condition a year ago, the system will" }, { start: 50.32, end: 55.68, text: "answer that the part was already broken because the node exists outside of time." }, { start: 55.68, end: 56.74, text: "It has been overwritten." }, { start: 58.58, end: 63.08, text: "The obvious workaround is to attach the defect information to the temporal edge," }, { start: 63.66, end: 64.40, text: "mounted_in." }, { start: 66.02, end: 71.26, text: "Excellent. The crack is anchored in time. The inspector is satisfied, and the" }, { start: 71.26, end: 73.08, text: "database has saved the information." }, { start: 74.74, end: 76.26, text: "But then comes the next day." }, { start: 77.00, end: 80.76, text: "The part is removed from the vehicle and sent to the warehouse for repair." }, { start: 82.46, end: 87.68, text: "The mounting edge is closed and archived. The part is now linked to the warehouse." }, { start: 88.46, end: 90.02, text: "Now, let's ask the system," }, { start: 90.76, end: 93.60, text: "how many defective parts are currently in the warehouse?" }, { start: 95.08, end: 96.14, text: "The system answers" }, { start: 96.78, end: 97.20, text: "zero." }, { start: 97.86, end: 102.02, text: "The crack has disappeared from the vehicle, but in the warehouse, the part is" }, { start: 102.02, end: 106.96, text: "registered as completely flawless. The defect attribute remains buried in the" }, { start: 106.96, end: 108.20, text: "archived mounting edge." }, { start: 108.84, end: 112.92, text: "Our naive approach has just destroyed critical data about a fault." }, { start: 114.50, end: 119.42, text: "This is exactly where the naive approach collapses and an industrial ontology is" }, { start: 119.42, end: 124.68, text: "required. We are now switching the system to ISO 15926 mode." }, { start: 126.06, end: 131.42, text: "Under this standard, a part is not a static node, but a four-dimensional object" }, { start: 131.42, end: 133.08, text: "with temporal life stages." }, { start: 133.76, end: 138.78, text: "A defect is an independent entity that classifies the condition of a specific" }, { start: 138.78, end: 140.30, text: "temporal stage of the part." }, { start: 141.06, end: 146.48, text: "Now, when moved to the warehouse, the part takes its state history with it. Data is" }, { start: 146.48, end: 147.42, text: "no longer lost." }];
export const vanishingCrackScenario = { subtitles, timeline: [ // 1. t = 1.0: Initialize Naive Node mode, SMRM perspective, and Mermaid engine { id: 'step_1_0_init_naive', time: 1.0, executed: false, action(state, renderGraph) { state.ontology = 'NAIVE_NODE'; state.perspective = 'SMRM'; state.graphEngine = 'MERMAID'; } },
// 2. t = 15.5: highlight UI. Action: createRegisterPartEvent('System_A', time) { id: 'step_15_5_reg_vehicle', time: 15.5, executed: false, action(state, renderGraph) { highlightUI(['biz-reg-id', 'biz-reg-btn']); state.currentTime = 15.5; const event = createRegisterPartEvent('System_A', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 3. t = 18.0: Audio mentions slot: Simply register Part_M01 and assemble System_A and Part_M01 // The smart adapters implicitly generate the contextual slot! { id: 'step_18_0_reg_part_install', time: 18.0, executed: false, action(state, renderGraph) { highlightUI(['biz-reg-id', 'biz-inst-btn']); state.currentTime = 18.0; const regEvent = createRegisterPartEvent('Part_M01', state.currentTime); if (regEvent) { state.eventLog.push(regEvent); } const asmEvent = createAssembleEvent('System_A', 'Part_M01', 'mounted_in', state.currentTime); if (asmEvent) { state.eventLog.push(asmEvent); } } },
// 4. t = 43.0: highlight UI. Action: createReportDefectEvent('Part_M01', 'crack', '2mm', time) -> Adapter will attach to NODE { id: 'step_43_0_attach_crack_node', time: 43.0, executed: false, action(state, renderGraph) { highlightUI(['biz-def-target', 'biz-def-btn']); state.currentTime = 43.0; const event = createReportDefectEvent('Part_M01', 'crack', '2mm', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 5. t = 56.5: Revoke the defect { id: 'step_56_5_revoke_crack_node', time: 56.5, executed: false, action(state, renderGraph) { highlightUI(['biz-rev-defect', 'biz-rev-btn']); state.currentTime = 56.5; const idx = state.eventLog.findIndex(e => e.type === 'REPORT_DEFECT' && e.targetId === 'Part_M01'); if (idx !== -1) { state.eventLog.splice(idx, 1); } } },
// 6. t = 58.5: Switch state.ontology = 'NAIVE_EDGE' and highlight top header button { id: 'step_58_5_switch_strategy_edge', time: 58.5, executed: false, action(state, renderGraph) { highlightUI(['ctrl-onto-naive-edge']); state.ontology = 'NAIVE_EDGE'; } },
// 7. t = 61.0: highlight UI. Action: createReportDefectEvent('Part_M01', 'crack', '2mm', time) -> Adapter attaches to EDGE { id: 'step_61_0_attach_crack_edge', time: 61.0, executed: false, action(state, renderGraph) { highlightUI(['biz-def-target', 'biz-def-btn']); state.currentTime = 61.0; const event = createReportDefectEvent('Part_M01', 'crack', '2mm', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 8. t = 78.0: highlight UI. Action: createDismantleEvent('Part_M01', time) { id: 'step_78_0_dismantle_part', time: 78.0, executed: false, action(state, renderGraph) { highlightUI(['biz-dism-part', 'biz-dism-btn']); state.currentTime = 78.0; const event = createDismantleEvent('Part_M01', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 9. t = 82.0: highlight UI. Action: createRegisterPartEvent('Warehouse_1', time) { id: 'step_82_0_reg_warehouse', time: 82.0, executed: false, action(state, renderGraph) { highlightUI(['biz-reg-id', 'biz-reg-btn']); state.currentTime = 82.0; const event = createRegisterPartEvent('Warehouse_1', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 10. t = 84.0: highlight UI. Action: createAssembleEvent('Warehouse_1', 'Part_M01', 'stored_at', time) { id: 'step_84_0_store_part', time: 84.0, executed: false, action(state, renderGraph) { highlightUI(['biz-store-part', 'biz-store-target', 'biz-store-btn']); state.currentTime = 84.0; const event = createAssembleEvent('Warehouse_1', 'Part_M01', 'stored_at', state.currentTime); if (event) { state.eventLog.push(event); } } },
// 11. t = 122.0: highlight UI (ontology switch). Action: state.ontology = 'ISO15926' { id: 'step_122_0_switch_iso', time: 122.0, executed: false, action(state, renderGraph) { highlightUI(['ctrl-onto-iso']); state.ontology = 'ISO15926'; } } ]};
/** * Dispatches pending timeline actions based on current playback time. * Resolves float chunking using `>= step.time && !step.executed`. * * @param {number} currentTime - Current audio playback time in seconds. * @param {Object} state - The reactive domain state. * @param {Function} [renderGraph] - Function to trigger canvas redraw. */export function onTimeUpdate(currentTime, state, renderGraph) { if (!Array.isArray(vanishingCrackScenario.timeline)) return;
vanishingCrackScenario.timeline.forEach(step => { if (currentTime >= step.time && !step.executed) { console.log('Executing step:', step.time); step.executed = true; const fn = step.action || step.execute; if (typeof fn === 'function') { fn(state, renderGraph); } if (typeof renderGraph === 'function') { renderGraph(); } } });}
/** * Resets execution flags on timeline steps when seeking, stopping, or rewinding. * * @param {number} [targetTime=0] - Audio target time. Steps with step.time >= targetTime are reset to unexecuted. */export function resetTimeline(targetTime = 0) { if (!Array.isArray(vanishingCrackScenario.timeline)) return; vanishingCrackScenario.timeline.forEach(step => { if (step.time >= targetTime) { step.executed = false; } });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/*** BFO ONTOLOGY ADAPTER (3D Continuant)* ------------------------------------* Maps the Event Log into a 3D Semantic Graph.* Entities are 'MaterialEntities' that endure through time.* Relations are Continuant compositions ('has_part') carrying temporal properties.** Completely decoupled from database storage (SMS) and UI concerns.** @param {Array} eventLog - The projection of temporal events.* @param {Array} baseNodes - The projection of base continuant entities.* @param {number|null} [currentTime=null] - Global time to evaluate current validity.* @returns {{ nodes: Array, edges: Array }} The canonical Semantic Graph.*/export function generateSemanticGraph(eventLog, baseNodes, currentTime = null) {const nodes = [];const edges = [];// 1. Create Base Continuant NodesbaseNodes.forEach(n => {nodes.push({id: n.id,label: n.label,type: 'MaterialEntity',properties: {originalId: n.id,entityType: n.type}});});// 2. Process the Event Log into canonical 3D relationshipseventLog.forEach(event => {// Check temporal validityif (currentTime !== null && currentTime !== undefined && event.valid_from > currentTime) {return;}const isCurrent = event.valid_to === null ||(currentTime !== null && currentTime !== undefined ? event.valid_to > currentTime : false);edges.push({id: event.id,from: event.from,to: event.to,label: 'has_part',type: 'composition',properties: {validFrom: event.valid_from,validTo: event.valid_to,isCurrent}});});return { nodes, edges };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227/*** BFO ONTOLOGY ADAPTER (3D Continuant)* ------------------------------------* Maps Domain Business Events into a canonical 3D BFO Semantic Graph.** Ontological Axioms:* - Entities (Vehicle, Part, Warehouse) are Independent Continuants ('MaterialEntity')* that endure wholly through time without temporal parts or states.* - Defect observations are Specifically Dependent Continuants ('Quality')* that exist only by inhering in an independent continuant via the 'inheres_in' relation.* - Relationships between continuants (mounted_in, stored_at, etc.) hold directly* between the continuants at a given time, carrying temporal validity intervals.* - Both the Quality node and the 'inheres_in' edge record validFrom: timestamp.* - NEVER generates 'State' or 'Temporal Part' nodes.** @param {Array} eventLog - The projection of temporal business events.* @param {Array} [baseNodes=[]] - The projection of base continuant entities.* @param {number|null} [currentTime=null] - Global time to evaluate current validity.* @returns {{ nodes: Array, edges: Array }} The canonical Semantic Graph.*/export function generateSemanticGraph(eventLog = [], baseNodes = [], currentTime = null) {const nodeMap = new Map();const edges = [];function ensureContinuantNode(partId, overrideClass = null) {if (!nodeMap.has(partId)) {nodeMap.set(partId, {id: partId,label: partId,type: 'MaterialEntity',properties: {originalId: partId,entityClass: overrideClass || inferContinuantClass(partId)}});}}// 1. Initialise base continuant entities (if provided)(baseNodes || []).forEach(bn => {ensureContinuantNode(bn.id);});// 2. Filter and sort business events by timestampconst eventsToProcess = (eventLog || []).filter(event => currentTime === null || currentTime === undefined || event.valid_from <= currentTime).slice().sort((a, b) => (a.valid_from || 0) - (b.valid_from || 0));// 3. Process business events in temporal ordereventsToProcess.forEach(event => {switch (event.type) {case 'REGISTER_PART': {ensureContinuantNode(event.partId);break;}case 'ASSEMBLE': {const { parentId, childId } = event;const relType = event.relationType || 'mounted_in';const timestamp = event.valid_from;ensureContinuantNode(parentId);ensureContinuantNode(childId);if (relType === 'stored_at') {const edgeId = event.id ? `edge_${event.id}` : `edge_${childId}_${parentId}_${timestamp}`;edges.push({id: edgeId,from: childId,to: parentId,label: 'stored_at',type: 'composition',childId,parentId,properties: {validFrom: timestamp,validTo: null,isCurrent: true}});break;}// Implicit contextual Slot generation: Slot_${parentId}_${childId}const slotId = `Slot_${parentId}_${childId}`;ensureContinuantNode(slotId, 'Slot');// Link 1: Parent -> Slot (has_slot)const slotEdgeId = `edge_slot_${parentId}_${slotId}_${timestamp}`;edges.push({id: slotEdgeId,from: parentId,to: slotId,label: 'has_slot',type: 'has_slot',childId: slotId,parentId: parentId,properties: {validFrom: timestamp,validTo: null,isCurrent: true}});// Link 2: Child -> Slot (mounted_in)const mountEdgeId = event.id ? `edge_${event.id}` : `edge_${childId}_${slotId}_${timestamp}`;edges.push({id: mountEdgeId,from: childId,to: slotId,label: 'mounted_in',type: 'composition',childId: childId,parentId: slotId,properties: {validFrom: timestamp,validTo: null,isCurrent: true}});break;}case 'DISMANTLE': {const { childId } = event;const dismantleTime = event.valid_from;// Locate active assembly relationship for the child componentconst activeEdge = edges.find(e => (e.childId === childId || e.from === childId) &&(e.label === 'mounted_in' || e.label === 'stored_at') &&e.properties.validTo === null);if (activeEdge) {activeEdge.properties.validTo = dismantleTime;activeEdge.properties.isCurrent = (currentTime !== null && currentTime !== undefined)? dismantleTime > currentTime: false;} else {console.warn(`[SMIM BFO] No active assembly relationship found to dismantle child part: ${childId}`);}break;}case 'REPORT_DEFECT': {const { targetId, defectName, defectValue } = event;const timestamp = event.valid_from;ensureContinuantNode(targetId);const qualityId = `qual_${targetId}_${defectName}`;const qualityLabel = `${capitalize(defectName)}: ${defectValue}`;// Specifically Dependent Continuant (Quality) node recording validFromnodeMap.set(qualityId, {id: qualityId,label: qualityLabel,type: 'Quality',properties: {originalId: qualityId,qualityType: defectName,value: defectValue,bearerId: targetId,entityClass: 'Quality',validFrom: timestamp}});// Canonical BFO relation: Quality inheres_in Independent Continuant (with validFrom)const edgeId = `inh_${targetId}_${defectName}_${timestamp}`;edges.push({id: edgeId,from: qualityId,to: targetId,label: 'inheres_in',type: 'inherence',properties: {validFrom: timestamp,validTo: null,isCurrent: true}});break;}default:break;}});// 4. Synchronise final temporal currentness flagsedges.forEach(edge => {edge.properties.isCurrent = edge.properties.validTo === null ||(currentTime !== null && currentTime !== undefined ? edge.properties.validTo > currentTime : false);});return {nodes: Array.from(nodeMap.values()),edges};}/*** Fallback helper to infer continuant entity class.** @param {string} id - Continuant identifier.* @returns {string} Inferred entity class name.*/function inferContinuantClass(id) {if (/^veh/i.test(id)) return 'Vehicle';if (/^slot/i.test(id)) return 'Slot';if (/^ware|^wh/i.test(id)) return 'Warehouse';return 'Part';}/*** Capitalises the first letter of a string.* @param {string} str* @returns {string}*/function capitalize(str) {if (!str) return '';return str.charAt(0).toUpperCase() + str.slice(1);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111/*** ISO 15926 ONTOLOGY ADAPTER (4D Perdurant)* -----------------------------------------* Maps the Event Log projection into a 4D Spatio-Temporal Semantic Graph.* Entities are treated as 'ActualIndividuals' (4D extents).* Relationships do not connect extents directly; instead, they connect* specific 'States' (temporal parts) of those entities via canonical 'hasPart'* composition, with states linked to their 4D extents via 'temporalPartOf'.** Completely decoupled from database storage (SMS) and UI concerns.** @param {Array} eventLog - The projection of temporal events.* @param {Array} baseNodes - The projection of base entities.* @param {number|null} [currentTime=null] - Global time to evaluate current validity.* @returns {{ nodes: Array, edges: Array }} The canonical Semantic Graph.*/export function generateSemanticGraph(eventLog, baseNodes, currentTime = null) {const nodes = [];const edges = [];// 1. Create Base 4D Extent Nodes (ActualIndividuals)baseNodes.forEach(n => {nodes.push({id: `4d_${n.id}`,label: `${n.label}_4D`,type: 'ActualIndividual',properties: {originalId: n.id,entityType: n.type}});});// 2. Process the Event Log to create Temporal Slices (States)eventLog.forEach(event => {if (currentTime !== null && currentTime !== undefined && event.valid_from > currentTime) {return;}const isCurrent = event.valid_to === null ||(currentTime !== null && currentTime !== undefined ? event.valid_to > currentTime : false);const parentStateId = `st_${event.from}_${event.id}`;const childStateId = `st_${event.to}_${event.id}`;// Add State nodes for both Parent and Child for this specific event durationnodes.push({id: parentStateId,label: `${event.from}_State`,type: 'State',properties: {ownerId: event.from,validFrom: event.valid_from,validTo: event.valid_to,isCurrent}});nodes.push({id: childStateId,label: `${event.to}_State`,type: 'State',properties: {ownerId: event.to,validFrom: event.valid_from,validTo: event.valid_to,isCurrent}});// Link States to their whole 4D Extentsedges.push({id: `tpo_p_${event.id}`,from: parentStateId,to: `4d_${event.from}`,label: 'temporalPartOf',type: 'classification',properties: {isCurrent}});edges.push({id: `tpo_c_${event.id}`,from: childStateId,to: `4d_${event.to}`,label: 'temporalPartOf',type: 'classification',properties: {isCurrent}});// Link Parent State to Child State (Tenseless composition between temporal parts)edges.push({id: event.id,from: parentStateId,to: childStateId,label: 'hasPart',type: 'composition',properties: {validFrom: event.valid_from,validTo: event.valid_to,isCurrent}});});return { nodes, edges };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393/*** ISO 15926 ONTOLOGY ADAPTER (4D Perdurant)* -----------------------------------------* Maps Domain Business Events into a canonical 4D ISO 15926 Semantic Graph.** Ontological Axioms:* - Physical entities (Vehicle, Part, Warehouse) are 4D individuals ('ActualIndividual')* with spatio-temporal extents across their entire lifetime.* - Relationships (mounted_in, stored_at, etc.) do not connect 4D extents directly;* they connect temporal slices ('State') of those entities during specific validity periods.* - Each 'State' is linked to its whole 4D extent via the 'temporalPartOf' relation.* - A 'Defect' is an independent condition/classification entity that classifies a specific* temporal part ('State') of an entity during a specific time slice, NOT the root 4D individual.** @param {Array} eventLog - The projection of temporal business events.* @param {Array} [baseNodes=[]] - The projection of base entities.* @param {number|null} [currentTime=null] - Global time to evaluate current validity.* @returns {{ nodes: Array, edges: Array }} The canonical Semantic Graph.*/export function generateSemanticGraph(eventLog = [], baseNodes = [], currentTime = null) {const nodeMap = new Map();const edges = [];const stateNodesByOwner = new Map();function registerStateNode(ownerId, stateNode) {if (!stateNodesByOwner.has(ownerId)) {stateNodesByOwner.set(ownerId, []);}stateNodesByOwner.get(ownerId).push(stateNode);}function ensureExtentNode(partId, overrideClass = null) {const extentId = `4d_${partId}`;if (!nodeMap.has(extentId)) {nodeMap.set(extentId, {id: extentId,label: `${partId}_4D`,type: 'ActualIndividual',properties: {originalId: partId,entityClass: overrideClass || inferEntityType(partId)}});}return extentId;}// 1. Initialise base 4D extent nodes (if provided)(baseNodes || []).forEach(bn => {ensureExtentNode(bn.id);});// 2. Filter and sort business events by timestampconst eventsToProcess = (eventLog || []).filter(event => currentTime === null || currentTime === undefined || event.valid_from <= currentTime).slice().sort((a, b) => (a.valid_from || 0) - (b.valid_from || 0));// 3. Process business events in temporal ordereventsToProcess.forEach(event => {switch (event.type) {case 'REGISTER_PART': {ensureExtentNode(event.partId);break;}case 'ASSEMBLE': {const { parentId, childId } = event;const relType = event.relationType || 'mounted_in';const timestamp = event.valid_from;const parentExtentId = ensureExtentNode(parentId);const childExtentId = ensureExtentNode(childId);if (relType === 'stored_at') {const parentStateId = `st_${parentId}_${event.id || `${childId}_${timestamp}`}`;const childStateId = `st_${childId}_${event.id || `${parentId}_${timestamp}`}`;const parentState = {id: parentStateId,label: `${parentId}_State`,type: 'State',properties: { ownerId: parentId, validFrom: timestamp, validTo: null, isCurrent: true }};nodeMap.set(parentStateId, parentState);registerStateNode(parentId, parentState);const childState = {id: childStateId,label: `${childId}_State`,type: 'State',properties: { ownerId: childId, validFrom: timestamp, validTo: null, isCurrent: true }};nodeMap.set(childStateId, childState);registerStateNode(childId, childState);edges.push({id: `tpo_${parentStateId}`,from: parentStateId,to: parentExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});edges.push({id: `tpo_${childStateId}`,from: childStateId,to: childExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});const storageEdgeId = event.id ? `rel_${event.id}` : `rel_${childId}_${parentId}_${timestamp}`;edges.push({id: storageEdgeId,from: childStateId,to: parentStateId,label: 'stored_at',type: 'composition',childId,parentId,properties: { validFrom: timestamp, validTo: null, isCurrent: true }});break;}// Implicit contextual Slot generation: Slot_${parentId}_${childId}const slotId = `Slot_${parentId}_${childId}`;const slotExtentId = ensureExtentNode(slotId, 'Slot');const parentStateId = `st_${parentId}_${event.id || `${slotId}_${timestamp}`}`;const slotStateId = `st_${slotId}_${event.id || `${childId}_${timestamp}`}`;const childStateId = `st_${childId}_${event.id || `${slotId}_${timestamp}`}`;const parentState = {id: parentStateId,label: `${parentId}_State`,type: 'State',properties: {ownerId: parentId,validFrom: timestamp,validTo: null,isCurrent: true}};nodeMap.set(parentStateId, parentState);registerStateNode(parentId, parentState);const slotState = {id: slotStateId,label: `${slotId}_State`,type: 'State',properties: {ownerId: slotId,validFrom: timestamp,validTo: null,isCurrent: true}};nodeMap.set(slotStateId, slotState);registerStateNode(slotId, slotState);const childState = {id: childStateId,label: `${childId}_State`,type: 'State',properties: {ownerId: childId,validFrom: timestamp,validTo: null,isCurrent: true}};nodeMap.set(childStateId, childState);registerStateNode(childId, childState);// Link temporal states to their 4D extentsedges.push({id: `tpo_${parentStateId}`,from: parentStateId,to: parentExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});edges.push({id: `tpo_${slotStateId}`,from: slotStateId,to: slotExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});edges.push({id: `tpo_${childStateId}`,from: childStateId,to: childExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});// Link 1: Parent State -> Slot State (has_slot)const slotEdgeId = `rel_slot_${parentId}_${slotId}_${timestamp}`;edges.push({id: slotEdgeId,from: parentStateId,to: slotStateId,label: 'has_slot',type: 'has_slot',childId: slotId,parentId: parentId,childStateId: slotStateId,parentStateId: parentStateId,properties: {validFrom: timestamp,validTo: null,isCurrent: true}});// Link 2: Child State -> Slot State (mounted_in)const assemblyEdgeId = event.id ? `rel_${event.id}` : `rel_${childId}_${slotId}_${timestamp}`;edges.push({id: assemblyEdgeId,from: childStateId,to: slotStateId,label: 'mounted_in',type: 'composition',childId,parentId: slotId,childStateId,parentStateId: slotStateId,properties: {validFrom: timestamp,validTo: null,isCurrent: true}});break;}case 'DISMANTLE': {const { childId } = event;const dismantleTime = event.valid_from;// Find active assembly or storage edge for this childconst activeAssembly = edges.find(e => (e.childId === childId || e.from.startsWith(`st_${childId}_`)) &&(e.label === 'mounted_in' || e.label === 'stored_at') &&e.properties.validTo === null);if (activeAssembly) {activeAssembly.properties.validTo = dismantleTime;activeAssembly.properties.isCurrent = (currentTime !== null && currentTime !== undefined)? dismantleTime > currentTime: false;// Close the child state sliceconst childState = nodeMap.get(activeAssembly.childStateId);if (childState) {childState.properties.validTo = dismantleTime;childState.properties.isCurrent = activeAssembly.properties.isCurrent;}// Close the child's temporalPartOf linkconst tpoChild = edges.find(e => e.id === `tpo_${activeAssembly.childStateId}`);if (tpoChild) {tpoChild.properties.validTo = dismantleTime;tpoChild.properties.isCurrent = activeAssembly.properties.isCurrent;}} else {console.warn(`[SMIM ISO15926] No active assembly found to dismantle child part: ${childId}`);}break;}case 'REPORT_DEFECT': {const { targetId, defectName, defectValue } = event;const timestamp = event.valid_from;const targetExtentId = ensureExtentNode(targetId);// Find current active State of the target partconst existingStates = stateNodesByOwner.get(targetId) || [];let targetState = existingStates.find(st => st.properties?.isCurrent && st.properties?.validTo === null) ||existingStates[existingStates.length - 1];if (!targetState) {const newStateId = `st_${targetId}_def_${event.id || `${defectName}_${timestamp}`}`;targetState = {id: newStateId,label: `${targetId}_State`,type: 'State',properties: {ownerId: targetId,validFrom: timestamp,validTo: null,isCurrent: true}};nodeMap.set(newStateId, targetState);registerStateNode(targetId, targetState);edges.push({id: `tpo_${newStateId}`,from: newStateId,to: targetExtentId,label: 'temporalPartOf',type: 'classification',properties: { validFrom: timestamp, validTo: null, isCurrent: true }});}const defectNodeId = `def_${targetId}_${defectName}`;const defectLabel = `Defect: ${capitalize(defectName)} (${defectValue})`;nodeMap.set(defectNodeId, {id: defectNodeId,label: defectLabel,type: 'Defect',properties: {originalId: defectNodeId,defectType: defectName,value: defectValue,targetId,entityClass: 'Defect',validFrom: timestamp}});const defectEdgeId = `def_class_${targetId}_${defectName}_${timestamp}`;edges.push({id: defectEdgeId,from: targetState.id,to: defectNodeId,label: 'has_defect',type: 'classification',properties: {validFrom: timestamp,validTo: null,isCurrent: targetState.properties.isCurrent}});break;}default:break;}});// 4. Synchronise final temporal currentness flagsedges.forEach(edge => {edge.properties.isCurrent = edge.properties.validTo === null ||(currentTime !== null && currentTime !== undefined ? edge.properties.validTo > currentTime : false);});return {nodes: Array.from(nodeMap.values()),edges};}/*** Fallback helper to infer entity type from common identifier naming conventions.** @param {string} id - Node identifier.* @returns {string} Inferred entity class name.*/function inferEntityType(id) {if (/^veh/i.test(id)) return 'Vehicle';if (/^slot/i.test(id)) return 'Slot';if (/^def/i.test(id)) return 'Defect';if (/^ware|^wh/i.test(id)) return 'Warehouse';return 'Part';}/*** Capitalises the first letter of a string.* @param {string} str* @returns {string}*/function capitalize(str) {if (!str) return '';return str.charAt(0).toUpperCase() + str.slice(1);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238/*** NAIVE GRAPH ADAPTER (Direct Property Graph)* --------------------------------------------* Maps Domain Business Events into a direct, unconstrained Property Graph without* enforcing 3D Continuant (BFO) or 4D Perdurant (ISO 15926) semantic rules.** In this mode:* - Entities (Vehicle, Part, Warehouse, etc.) are direct nodes.* - Assembly events create direct relationships (e.g. 'mounted_in', 'stored_at')* directed from child component to parent entity.* - Dismantling events locate the active assembly relationship and close its temporal validity.* - Defect reports are attached directly to Node properties (if naiveDefectTarget === 'NODE')* or to the active assembly Edge properties (if naiveDefectTarget === 'EDGE').** Decoupled from database storage (SMS) and UI concerns, strictly adhering* to the SemanticGraph data contract ({ nodes: [], edges: [] }).** @param {Array} eventLog - The projection of temporal business events.* @param {Array} [baseNodes=[]] - The projection of base entities.* @param {number|null} [currentTime=null] - Global time to evaluate current validity.* @param {Object} [options={}] - Optional configuration overrides.* @returns {{ nodes: Array, edges: Array }} The canonical Semantic Graph.*/import { state } from '../state.js';export function generateSemanticGraph(eventLog = [], baseNodes = [], currentTime = null, options = {}) {const nodeMap = new Map();const edges = [];const ontologyMode = options.ontology || state?.ontology || 'NAIVE_NODE';const defectTargetMode = ontologyMode === 'NAIVE_EDGE' ? 'EDGE' : (options.naiveDefectTarget || state?.naiveDefectTarget || 'NODE');// 1. Initialise base nodes from projection (if provided)(baseNodes || []).forEach(bn => {nodeMap.set(bn.id, {id: bn.id,label: bn.label || bn.id,type: bn.entityClass || bn.type || inferEntityType(bn.id),properties: { ...(bn.properties || {}) }});});// 2. Filter and sort business events by timestampconst eventsToProcess = (eventLog || []).filter(event => currentTime === null || currentTime === undefined || event.valid_from <= currentTime).slice().sort((a, b) => (a.valid_from || 0) - (b.valid_from || 0));// 3. Process business events in temporal ordereventsToProcess.forEach(event => {switch (event.type) {case 'REGISTER_PART': {const partId = event.partId;if (!nodeMap.has(partId)) {nodeMap.set(partId, {id: partId,label: partId,type: inferEntityType(partId),properties: {}});}break;}case 'ASSEMBLE': {const { parentId, childId } = event;const relType = event.relationType || 'mounted_in';// Ensure both parent and child nodes exist in the node mapif (!nodeMap.has(parentId)) {nodeMap.set(parentId, {id: parentId,label: parentId,type: inferEntityType(parentId),properties: {}});}if (!nodeMap.has(childId)) {nodeMap.set(childId, {id: childId,label: childId,type: inferEntityType(childId),properties: {}});}// Warehouse storage links child directly to warehouseif (relType === 'stored_at') {const edgeId = event.id ? `edge_${event.id}` : `edge_${childId}_${parentId}_${event.valid_from}`;edges.push({id: edgeId,from: childId,to: parentId,label: 'stored_at',type: 'stored_at',childId,parentId,properties: {validFrom: event.valid_from,validTo: null,isCurrent: true}});break;}// Implicit contextual Slot generation: Slot_${parentId}_${childId}const slotId = `Slot_${parentId}_${childId}`;if (!nodeMap.has(slotId)) {nodeMap.set(slotId, {id: slotId,label: slotId,type: 'Slot',properties: { entityClass: 'Slot' }});}// Link 1: Parent -> Slot (has_slot)const slotEdgeId = `edge_slot_${parentId}_${slotId}_${event.valid_from}`;edges.push({id: slotEdgeId,from: parentId,to: slotId,label: 'has_slot',type: 'has_slot',childId: slotId,parentId: parentId,properties: {validFrom: event.valid_from,validTo: null,isCurrent: true}});// Link 2: Child -> Slot (mounted_in)const mountEdgeId = event.id ? `edge_${event.id}` : `edge_${childId}_${slotId}_${event.valid_from}`;edges.push({id: mountEdgeId,from: childId,to: slotId,label: 'mounted_in',type: 'mounted_in',childId,parentId: slotId,properties: {validFrom: event.valid_from,validTo: null,isCurrent: true}});break;}case 'DISMANTLE': {const { childId } = event;const dismantleTime = event.valid_from;// Locate active assembly/storage edge for the child componentconst activeEdge = edges.find(e => (e.childId === childId || e.from === childId) &&(e.label === 'mounted_in' || e.label === 'stored_at') &&e.properties.validTo === null);if (activeEdge) {activeEdge.properties.validTo = dismantleTime;activeEdge.properties.isCurrent = (currentTime !== null && currentTime !== undefined)? dismantleTime > currentTime: false;} else {console.warn(`[SMIM Naive] No active assembly edge found to dismantle child part: ${childId}`);}break;}case 'REPORT_DEFECT': {const { targetId, defectName, defectValue } = event;if (defectTargetMode === 'NODE') {let targetNode = nodeMap.get(targetId);if (!targetNode) {targetNode = {id: targetId,label: targetId,type: inferEntityType(targetId),properties: {}};nodeMap.set(targetId, targetNode);}targetNode.properties[defectName] = defectValue;} else if (defectTargetMode === 'EDGE') {// Find the active assembly edge where targetId is the mounted componentconst activeEdge = edges.find(e => (e.childId === targetId || e.from === targetId) &&(e.label === 'mounted_in' || e.type === 'mounted_in') &&(e.properties.validTo === null || e.properties.validTo >= event.valid_from));if (activeEdge) {activeEdge.properties[defectName] = defectValue;} else {console.warn(`[SMIM Naive] No active edge found for defect report on part: ${targetId}`);}}break;}default:break;}});// 4. Synchronise final temporal currentness flagsedges.forEach(edge => {edge.properties.isCurrent = edge.properties.validTo === null ||(currentTime !== null && currentTime !== undefined ? edge.properties.validTo > currentTime : false);});return {nodes: Array.from(nodeMap.values()),edges};}/*** Fallback helper to infer entity type from common identifier naming conventions.** @param {string} id - Node identifier.* @returns {string} Inferred entity class name.*/function inferEntityType(id) {if (/^veh/i.test(id)) return 'Vehicle';if (/^slot/i.test(id)) return 'Slot';if (/^def/i.test(id)) return 'Defect';if (/^ware|^wh/i.test(id)) return 'Warehouse';return 'Part';}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798/*** DOMAIN ACTION FACTORIES (SMRM Layer)* ------------------------------------* This module contains pure factory functions responsible for validating* business rules and creating immutable Event objects.** Strict Architectural Rule:* Functions here MUST NOT import the singleton state or directly mutate data.* All functions are pure factories returning event descriptors to be dispatched.*//*** Creates an event representing the addition of a new part to a parent component.* Pure factory function - does not mutate any external state.** @param {string} parentId - The unique identifier of the parent node.* @param {string} partName - The raw string name/identifier of the new part.* @param {number} [currentTime=0] - The current system timestamp.* @param {number|string|null} [edgeSequence=null] - Optional sequence number or ID for the relationship.* @param {Array} [existingEvents=[]] - Optional list of existing events to validate uniqueness.* @returns {Object|null} The created relationship event object, or null if validation fails.*/export function createAddPartEvent(parentId, partName, currentTime = 0, edgeSequence = null, existingEvents = []) {if (!parentId || !partName) return null;const trimmedParent = String(parentId).trim();const trimmedPart = String(partName).trim();// Rule 1: A node cannot be a parent to itselfif (!trimmedParent || !trimmedPart || trimmedParent === trimmedPart) {return null;}// Rule 2: Prevent duplicating an active edge between the same parent and childif (Array.isArray(existingEvents) && existingEvents.length > 0) {const edgeExists = existingEvents.some(e =>e.from === trimmedParent &&e.to === trimmedPart &&e.valid_to === null);if (edgeExists) {console.warn(`[SMRM] Active edge already exists between ${trimmedParent} and ${trimmedPart}`);return null;}}const eventId = edgeSequence != null? (typeof edgeSequence === 'number' ? `e${edgeSequence}` : String(edgeSequence)): null;return {id: eventId,from: trimmedParent,to: trimmedPart,valid_from: currentTime,valid_to: null // null indicates the relationship is active indefinitely};}/*** Creates an event representing the severing (closing) of an active relationship.* Pure factory function - does not mutate any external state.** @param {string} edgeId - The unique identifier of the edge/relationship to sever.* @param {number} [currentTime=0] - The timestamp at which the relationship is severed.* @param {Array} [existingEvents=[]] - Optional list of existing events to validate against.* @returns {Object|null} The relationship closure descriptor, or null if validation fails.*/export function createRemoveEdgeEvent(edgeId, currentTime = 0, existingEvents = []) {if (!edgeId) return null;const strEdgeId = String(edgeId);// Rule: Validate that the edge exists and is currently activeif (Array.isArray(existingEvents) && existingEvents.length > 0) {const edge = existingEvents.find(e => e.id === strEdgeId);if (!edge) {console.error(`[SMRM] Cannot sever relation. Edge ${strEdgeId} not found.`);return null;}if (edge.valid_to !== null) {console.warn(`[SMRM] Relation ${strEdgeId} is already closed.`);return null;}}return {type: 'EDGE_REMOVED',edgeId: strEdgeId,valid_to: currentTime};}// Aliases for terminology consistency and backwards compatibilityexport const createCloseEdgeEvent = createRemoveEdgeEvent;export const addPart = createAddPartEvent;export const removeEdge = createRemoveEdgeEvent;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128/*** DOMAIN ACTION FACTORIES (SMRM Layer)* ------------------------------------* This module contains pure factory functions responsible for creating* immutable business Domain Events for the Event Sourcing architecture.** In accordance with Domain-Driven Event Sourcing:* - Events represent pure business facts, NOT low-level graph mutations.* - No graph concepts (e.g. 'NODE', 'EDGE') exist at this layer.** Strict Architectural Rule:* Functions here MUST NOT import the singleton state or directly mutate data.* All functions are pure factories returning event descriptors to be dispatched.*/import { RELATION_TYPES } from './definitions.js';/*** Creates a business event representing the registration/creation of a domain part.* Pure factory function - does not mutate any external state.** @param {string} partId - The unique business identifier of the part or component.* @param {number} [timestamp=0] - The discrete system timestamp of the registration.* @returns {Object|null} The created registration business event, or null if validation fails.*/export function createRegisterPartEvent(partId, timestamp = 0) {if (!partId) return null;const trimmedId = String(partId).trim();if (!trimmedId) return null;return {id: `evt_reg_${trimmedId}`,type: 'REGISTER_PART',partId: trimmedId,valid_from: timestamp,valid_to: null};}/*** Creates a business event representing the assembly or containment of a child part into a parent entity.* Pure factory function - does not mutate any external state.** @param {string} parentId - The unique business identifier of the parent entity/container.* @param {string} childId - The unique business identifier of the assembled child component.* @param {string} [relationType='mounted_in'] - The relationship category (e.g. 'mounted_in', 'stored_at').* @param {number} [timestamp=0] - The discrete system timestamp of the assembly.* @returns {Object|null} The created assembly business event, or null if validation fails.*/export function createAssembleEvent(parentId, childId, relationType = 'mounted_in', timestamp = 0) {if (!parentId || !childId) return null;const trimmedParent = String(parentId).trim();const trimmedChild = String(childId).trim();// Rule 1: An entity cannot be assembled into itselfif (!trimmedParent || !trimmedChild || trimmedParent === trimmedChild) {return null;}const validRelation = relationType && RELATION_TYPES.includes(relationType)? relationType: (relationType ? String(relationType).trim() : 'mounted_in');return {id: `evt_asm_${trimmedChild}_${timestamp}`,type: 'ASSEMBLE',parentId: trimmedParent,childId: trimmedChild,relationType: validRelation,valid_from: timestamp,valid_to: null};}/*** Creates a business event reporting a physical defect or quality observation on an entity.* Pure factory function - targetId is ALWAYS the Part/Vehicle ID, never a relationship/edge ID.** @param {string} targetId - The unique identifier of the part or vehicle bearing the defect.* @param {string} defectName - The characteristic or defect category (e.g. 'crack', 'dent', 'wear').* @param {string|number} defectValue - The recorded measurement or severity value (e.g. '2mm', 'high').* @param {number} [timestamp=0] - The discrete system timestamp of the defect observation.* @returns {Object|null} The created defect report business event, or null if validation fails.*/export function createReportDefectEvent(targetId, defectName, defectValue, timestamp = 0) {if (!targetId || !defectName) return null;const trimmedTarget = String(targetId).trim();const trimmedDefect = String(defectName).trim();if (!trimmedTarget || !trimmedDefect) {return null;}return {id: `evt_def_${trimmedTarget}_${trimmedDefect}_${timestamp}`,type: 'REPORT_DEFECT',targetId: trimmedTarget,defectName: trimmedDefect,defectValue: defectValue,valid_from: timestamp,valid_to: null};}/*** Creates a business event representing the dismantling or removal of a component.* Pure factory function - does not mutate any external state.** @param {string} childId - The unique business identifier of the dismantled component.* @param {number} [timestamp=0] - The discrete system timestamp when dismantling occurred.* @returns {Object|null} The created dismantling business event, or null if validation fails.*/export function createDismantleEvent(childId, timestamp = 0) {if (!childId) return null;const trimmedChild = String(childId).trim();if (!trimmedChild) return null;return {id: `evt_dsm_${trimmedChild}_${timestamp}`,type: 'DISMANTLE',childId: trimmedChild,valid_from: timestamp};}
123456789101112131415161718192021222324252627282930/*** SMRM DEFINITIONS & DOMAIN VOCABULARY* ------------------------------------* Standard domain vocabulary and reference model definitions for the* IEC 63339 Knowledge Architecture Workbench.*//*** Standard manufacturing domain entity classes.* @type {ReadonlyArray<string>}*/export const ENTITY_CLASSES = Object.freeze(['Vehicle','Slot','Part','Defect','Warehouse']);/*** Standard manufacturing domain relationship types.* @type {ReadonlyArray<string>}*/export const RELATION_TYPES = Object.freeze(['has_slot','mounted_in','stored_at','has_defect']);
41 unmodified lines42434445464748495051525354555657585960616241 unmodified lines* @returns {string} Cypher query string.*/export function generateLpgQuery(semanticGraph, currentTime) {const is4D = semanticGraph?.nodes?.some(n => n.type === 'State');if (is4D) {return `// Cypher (Neo4j) - 4D PerdurantMATCH (p_state:State)-[:hasPart]->(c_state:State)WHERE p_state.validFrom <= ${currentTime}AND (p_state.validTo IS NULL OR p_state.validTo > ${currentTime})MATCH (p_state)-[:temporalPartOf]->(p_4d:ActualIndividual)MATCH (c_state)-[:temporalPartOf]->(c_4d:ActualIndividual)RETURN p_4d.id AS Parent4D, c_4d.id AS Child4D`;}return `// Cypher (Neo4j) - 3D ContinuantMATCH (p)-[r:has_part]->(c)WHERE r.validFrom <= ${currentTime}AND (r.validTo IS NULL OR r.validTo > ${currentTime})RETURN p.id AS Parent, c.id AS Child`;}41 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767741 unmodified lines* @returns {string} Cypher query string.*/export function generateLpgQuery(semanticGraph, currentTime) {if (!semanticGraph) return '';const nodes = semanticGraph.nodes || [];const is4D = nodes.some(n => n.type === 'State');if (is4D) {return `// Cypher (Neo4j) - 4D Perdurant Full Graph TopologyMATCH (n)-[r]->(m)RETURN n, r, m`;}// Check for BFO Quality (Dependent Continuant)const hasQuality = nodes.some(n => n.type === 'Quality');if (hasQuality) {return `// Cypher (Neo4j) - 3D BFO Full Graph Topology & InherenceMATCH (n)-[r]->(m)RETURN n, r, m`;}// Check if we are in domain / naive modeconst domainClasses = ['Vehicle', 'Slot', 'Part', 'Defect', 'Warehouse'];const hasDomainNodes = nodes.some(n => domainClasses.includes(n.type));if (hasDomainNodes) {return `// Cypher (Neo4j) - Domain Graph Full Topology & PropertiesMATCH (n)-[r]->(m)RETURN n, r, m`;}return `// Cypher (Neo4j) - Full Structural Topology & Edge PropertiesMATCH (n)-[r]->(m)RETURN n, r, m`;}
32 unmodified lines333435363738394041424344455 unmodified lines515253545556575859604 unmodified lines65666768697071727374757677787980818283848586878889909192939495969710 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014132 unmodified linesttl += `:${ind.id} a iso:ActualIndividual .\n`;});const states = (semanticGraph.nodes || []).filter(n => n.type === 'State');states.forEach(st => {const tpoEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'temporalPartOf' || e.type === 'classification'));const hasPartEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'hasPart' || e.type === 'composition'));const vFrom = st.properties?.validFrom;5 unmodified linesttl += ` ;\n iso:temporalPartOf :${e.to}`;});hasPartEdges.forEach(e => {ttl += ` ;\n iso:hasPart :${e.to}`;});if (vFrom !== undefined && vFrom !== null) {ttl += ` ;\n iso:validFrom "${vFrom}"^^xsd:integer`;}4 unmodified linesttl += ` .\n`;});} else {ttl += `@prefix : <http://example.org/> .\n`;ttl += `@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n`;ttl += `# 3D Continuant Graph persisted via W3C Reification\n`;// 1. Base continuant entities(semanticGraph.nodes || []).forEach(n => {ttl += `:${n.id} a :${n.type || 'MaterialEntity'} .\n`;});// 2. Synthesise reified statements autonomously for temporal relations(semanticGraph.edges || []).forEach(edge => {const vFrom = edge.properties?.validFrom;const vTo = edge.properties?.validTo;ttl += `\n_:${edge.id} a :TemporalPartMembership ;\n`;ttl += ` :hasParent :${edge.from} ;\n`;ttl += ` :hasChild :${edge.to}`;if (vFrom !== undefined && vFrom !== null) {ttl += ` ;\n :validFrom "${vFrom}"^^xsd:integer`;}if (vTo !== undefined && vTo !== null) {ttl += ` ;\n :validTo "${vTo}"^^xsd:integer`;}ttl += ` .\n`;});}return ttl;10 unmodified linesconst is4D = semanticGraph?.nodes?.some(n => n.type === 'State');if (is4D) {return `# SPARQL - 4D Perdurant StoragePREFIX iso: <http://example.org/iso15926/>SELECT ?parent4D ?child4DWHERE {?pState a iso:State ;iso:temporalPartOf ?parent4D ;iso:hasPart ?cState ;iso:validFrom ?from .?cState a iso:State ;iso:temporalPartOf ?child4D .OPTIONAL { ?pState iso:validTo ?to }FILTER (?from <= ${currentTime} &&(!bound(?to) || ?to > ${currentTime}))}`;}return `# SPARQL - 3D Reified StoragePREFIX : <http://example.org/>SELECT ?parent ?childWHERE {?stmt a :TemporalPartMembership ;:hasParent ?parent ;:hasChild ?child ;:validFrom ?from .OPTIONAL { ?stmt :validTo ?to }FILTER (?from <= ${currentTime} &&(!bound(?to) || ?to > ${currentTime}))}`;}32 unmodified lines3334353637383940414243444546474849505152535455565758596061625 unmodified lines68697071727374757677787980818283848586878889909192934 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517610 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923032 unmodified linesttl += `:${ind.id} a iso:ActualIndividual .\n`;});const defectNodes = (semanticGraph.nodes || []).filter(n => n.type === 'Defect');defectNodes.forEach(d => {ttl += `:${d.id} a iso:DefectClass .\n`;});const states = (semanticGraph.nodes || []).filter(n => n.type === 'State');states.forEach(st => {const tpoEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'temporalPartOf' || e.type === 'classification') && !e.to.startsWith('def'));const partOfEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'mounted_in' || e.type === 'mounted_in' || e.label === 'partOf'));const hasPartEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'hasPart' || (e.type === 'composition' && e.label !== 'mounted_in' && e.type !== 'mounted_in')));const hasSlotEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'has_slot' || e.type === 'has_slot'));const storedAtEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'stored_at' || e.type === 'stored_at'));const hasDefectEdges = (semanticGraph.edges || []).filter(e => e.from === st.id && (e.label === 'has_defect' || e.to.startsWith('def')));const vFrom = st.properties?.validFrom;5 unmodified linesttl += ` ;\n iso:temporalPartOf :${e.to}`;});partOfEdges.forEach(e => {ttl += ` ;\n iso:partOf :${e.to}`;});hasPartEdges.forEach(e => {ttl += ` ;\n iso:hasPart :${e.to}`;});hasSlotEdges.forEach(e => {ttl += ` ;\n iso:hasSlot :${e.to}`;});storedAtEdges.forEach(e => {ttl += ` ;\n iso:storedAt :${e.to}`;});hasDefectEdges.forEach(e => {ttl += ` ;\n iso:hasDefect :${e.to}`;});if (vFrom !== undefined && vFrom !== null) {ttl += ` ;\n iso:validFrom "${vFrom}"^^xsd:integer`;}4 unmodified linesttl += ` .\n`;});} else {const domainClasses = ['Vehicle', 'Slot', 'Part', 'Defect', 'Warehouse'];const hasDomainNodes = (semanticGraph.nodes || []).some(n => domainClasses.includes(n.type));ttl += `@prefix : <http://example.org/> .\n`;ttl += `@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n`;if (hasDomainNodes) {ttl += `# Naive Domain Graph persisted as Direct Triples & Properties\n`;// 1. Domain entities and inline properties(semanticGraph.nodes || []).forEach(n => {ttl += `:${n.id} a :${n.type || 'Part'}`;if (n.properties) {const customProps = Object.entries(n.properties).filter(([k]) => !['isCurrent', 'originalId', 'entityType', 'validFrom', 'validTo', 'ownerId'].includes(k));customProps.forEach(([k, v]) => {ttl += ` ;\n :${k} "${v}"`;});}ttl += ` .\n`;});// 2. Direct relationships(semanticGraph.edges || []).forEach(edge => {const edgeRel = edge.label || 'has_part';ttl += `:${edge.from} :${edgeRel} :${edge.to} .\n`;});} else {ttl += `# 3D Continuant Graph persisted via W3C Reification & Quality Inherence\n`;// 1. Base continuant entities(semanticGraph.nodes || []).filter(n => n.type === 'MaterialEntity').forEach(n => {ttl += `:${n.id} a :MaterialEntity .\n`;});// 1b. Dependent Continuants (Quality)(semanticGraph.nodes || []).filter(n => n.type === 'Quality').forEach(q => {ttl += `:${q.id} a :Quality`;const inh = (semanticGraph.edges || []).find(e => e.from === q.id && e.label === 'inheres_in');if (inh) {ttl += ` ;\n :inheres_in :${inh.to}`;}ttl += ` .\n`;});// 2. Synthesise reified statements autonomously for temporal relations(semanticGraph.edges || []).filter(e => e.type !== 'inherence').forEach(edge => {const vFrom = edge.properties?.validFrom;const vTo = edge.properties?.validTo;const rel = edge.label || edge.relationType || edge.type;// Respect semantic directionality of predicates:// - mounted_in: Part (from) is mounted in Slot/Vehicle (to) => parent is edge.to, child is edge.from// - has_slot / has_part / composition: parent is edge.from, child is edge.toconst isMountedIn = rel === 'mounted_in';const parentId = isMountedIn ? edge.to : edge.from;const childId = isMountedIn ? edge.from : edge.to;ttl += `\n_:${edge.id} a :RelationalQuality ;\n`;ttl += ` :hasParent :${parentId} ;\n`;ttl += ` :hasChild :${childId}`;if (vFrom !== undefined && vFrom !== null) {ttl += ` ;\n :validFrom "${vFrom}"^^xsd:integer`;}if (vTo !== undefined && vTo !== null) {ttl += ` ;\n :validTo "${vTo}"^^xsd:integer`;}ttl += ` .\n`;});}}return ttl;10 unmodified linesconst is4D = semanticGraph?.nodes?.some(n => n.type === 'State');if (is4D) {return `# SPARQL (W3C RDF) - 4D Perdurant Full Graph TopologyPREFIX iso: <http://example.org/iso15926/>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>SELECT ?subject ?predicate ?objectWHERE {?subject ?predicate ?object .}`;}const hasQuality = semanticGraph?.nodes?.some(n => n.type === 'Quality');if (hasQuality) {return `# SPARQL (W3C RDF) - 3D BFO Full Graph Topology & InherencePREFIX : <http://example.org/>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>SELECT ?subject ?predicate ?objectWHERE {?subject ?predicate ?object .}`;}const domainClasses = ['Vehicle', 'Slot', 'Part', 'Defect', 'Warehouse'];const hasDomainNodes = (semanticGraph?.nodes || []).some(n => domainClasses.includes(n.type));if (hasDomainNodes) {return `# SPARQL (W3C RDF) - Domain Graph Full Topology & PropertiesPREFIX : <http://example.org/>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>SELECT ?subject ?predicate ?objectWHERE {?subject ?predicate ?object .}`;}return `# SPARQL (W3C RDF) - Full Graph TopologyPREFIX : <http://example.org/>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>SELECT ?subject ?predicate ?objectWHERE {?subject ?predicate ?object .}`;}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172/** * SMS LAYER: PHYSICAL GRAPH GENERATOR * ----------------------------------- * Transforms a canonical Semantic Graph (SMIM) into physical storage (SMS) per IEC 63339. * RDF: Reifies 3D composition relations carrying temporal properties into W3C statement nodes. * LPG: Links sequential 4D states of the same entity via TRANSITION_TO edges. */
/** * Generates a physical graph projection from a canonical semantic graph. * * @param {Object} semanticGraph - Standardised Semantic Graph ({ nodes: Array, edges: Array }). * @param {string} storageMode - Physical storage paradigm ('LPG' or 'RDF'). * @returns {{ nodes: Array, edges: Array }} Transformed physical graph. */export function generatePhysicalGraph(semanticGraph, storageMode) { if (!semanticGraph || !Array.isArray(semanticGraph.nodes) || !Array.isArray(semanticGraph.edges)) { return { nodes: [], edges: [] }; }
// Deep clone nodes and edges to maintain immutability const physicalNodes = semanticGraph.nodes.map(node => ({ ...node, properties: node.properties ? { ...node.properties } : {} }));
const physicalEdges = semanticGraph.edges.map(edge => ({ ...edge, properties: edge.properties ? { ...edge.properties } : {} }));
const is4D = physicalNodes.some(n => n.type === 'State');
// Case 1: W3C RDF Mode if (storageMode === 'RDF') { if (!is4D) { const finalEdges = [];
physicalEdges.forEach(edge => { const hasTemporalProps = edge.properties && ( edge.properties.validFrom !== undefined || edge.properties.validTo !== undefined );
if (edge.type === 'composition' && hasTemporalProps) { const stmtId = `stmt_${edge.id}`; const isCurrent = edge.properties.isCurrent !== false;
physicalNodes.push({ id: stmtId, label: `_:${edge.id}`, type: 'RelationalQuality', properties: { isCurrent, originalEdgeId: edge.id } });
finalEdges.push({ id: `rel_p_${edge.id}`, from: stmtId, to: edge.from, label: ':hasParent', type: 'reification', properties: { isCurrent } });
finalEdges.push({ id: `rel_c_${edge.id}`, from: stmtId, to: edge.to, label: ':hasChild', type: 'reification', properties: { isCurrent } });
if (edge.properties.validFrom !== undefined && edge.properties.validFrom !== null) { const litFromId = `lit_vf_${edge.id}`; physicalNodes.push({ id: litFromId, label: `"${edge.properties.validFrom}"^^xsd:integer`, type: 'Literal', properties: { value: edge.properties.validFrom } });
finalEdges.push({ id: `rel_vf_${edge.id}`, from: stmtId, to: litFromId, label: ':validFrom', type: 'reification', properties: { isCurrent } }); }
if (edge.properties.validTo !== undefined && edge.properties.validTo !== null) { const litToId = `lit_vt_${edge.id}`; physicalNodes.push({ id: litToId, label: `"${edge.properties.validTo}"^^xsd:integer`, type: 'Literal', properties: { value: edge.properties.validTo } });
finalEdges.push({ id: `rel_vt_${edge.id}`, from: stmtId, to: litToId, label: ':validTo', type: 'reification', properties: { isCurrent: false } }); } } else { finalEdges.push(edge); } });
return { nodes: physicalNodes, edges: finalEdges }; }
return { nodes: physicalNodes, edges: physicalEdges }; }
// Case 2: Labeled Property Graph (LPG) Mode if (storageMode === 'LPG' && is4D) { const stateNodes = physicalNodes.filter(n => n.type === 'State'); const entityStates = new Map();
stateNodes.forEach(stateNode => { let ownerId = stateNode.properties?.ownerId; if (!ownerId) { const tpoEdge = physicalEdges.find(e => e.from === stateNode.id && e.label === 'temporalPartOf'); if (tpoEdge) ownerId = tpoEdge.to.replace(/^4d_/, ''); }
if (ownerId) { if (!entityStates.has(ownerId)) entityStates.set(ownerId, []); entityStates.get(ownerId).push(stateNode); } });
entityStates.forEach((states, ownerId) => { states.sort((a, b) => { const fromA = a.properties?.validFrom ?? 0; const fromB = b.properties?.validFrom ?? 0; return fromA !== fromB ? fromA - fromB : a.id.localeCompare(b.id); });
for (let i = 0; i < states.length - 1; i++) { const currState = states[i]; const nextState = states[i + 1]; const transitionEdgeId = `trans_${ownerId}_${i}`;
if (!physicalEdges.some(e => e.id === transitionEdgeId)) { physicalEdges.push({ id: transitionEdgeId, from: currState.id, to: nextState.id, label: 'TRANSITION_TO', type: 'transition', properties: { atTime: nextState.properties?.validFrom, isCurrent: nextState.properties?.isCurrent ?? true } }); } } });
return { nodes: physicalNodes, edges: physicalEdges }; }
return { nodes: physicalNodes, edges: physicalEdges };}12344 unmodified lines9101112131415161718192021222324252627286 unmodified lines35363738394041424344455 unmodified lines51525354import { reactive } from 'vue';/*** SINGLE SOURCE OF TRUTH (Event Sourcing)4 unmodified lines** We only store the absolute domain truth:* - Current Time dimension* - Event Log (temporal relationships over time)* - Edge sequence counter*/export const state = reactive({// 1. Global Time DimensioncurrentTime: 0,// 2. The Event Log (The core of our Event Sourcing)// Format: { id: 'e1', from: 'Parent', to: 'Child', valid_from: 0, valid_to: null }// A 'null' valid_to indicates the relationship is currently active.eventLog: [],// 3. Counter to ensure unique IDs for our events/edgesedgeSequence: 1});/**6 unmodified lines/*** Completely replaces the current domain state.* Useful for loading a saved JSON file or injecting a predefined Scenario.** @param {Object} newState - The data object containing the state to inject.*/export function loadState(newState) {if (newState.currentTime !== undefined) {state.currentTime = newState.currentTime;}5 unmodified linesif (newState.edgeSequence !== undefined) {state.edgeSequence = newState.edgeSequence;}}123454 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243446 unmodified lines51525354555657585960616263646566676869707172735 unmodified lines79808182838485868788899091import { reactive } from 'vue';export { ENTITY_CLASSES, RELATION_TYPES } from './smrm/definitions.js';/*** SINGLE SOURCE OF TRUTH (Event Sourcing)4 unmodified lines** We only store the absolute domain truth:* - Current Time dimension* - Event Log (domain business events over time)* - Edge/Event sequence counter* - Domain settings (e.g. Naive defect target variant)*/export const state = reactive({// 1. Navigation View ('MENU' | 'SANDBOX' | 'SCENARIO')currentView: 'MENU',// 2. User Role ('UNI_ENGINEER')userRole: 'UNI_ENGINEER',// 3. Global Time DimensioncurrentTime: 0,// 4. Current Domain Ontology ('NAIVE_NODE' | 'NAIVE_EDGE' | 'BFO' | 'ISO15926')ontology: 'NAIVE_NODE',// 5. The Event Log (The core of our Domain-Driven Event Sourcing)// Format: Pure business events (e.g. REGISTER_PART, ASSEMBLE, REPORT_DEFECT, DISMANTLE)eventLog: [],// 6. Counter to ensure unique identifiers for eventsedgeSequence: 1,// 7. Perspective View ('SMRM' | 'SMIM' | 'SMS')perspective: 'SMRM',// 8. Visual Graph Engine ('VIS' | 'MERMAID')graphEngine: 'VIS'});/**6 unmodified lines/*** Completely replaces the current domain state.* Useful for loading a saved JSON file or injecting a predefined scenario.** @param {Object} newState - The data object containing the state to inject.*/export function loadState(newState) {if (newState.currentView !== undefined) {state.currentView = newState.currentView;}if (newState.userRole !== undefined) {state.userRole = newState.userRole;}if (newState.ontology !== undefined) {state.ontology = newState.ontology;}if (newState.currentTime !== undefined) {state.currentTime = newState.currentTime;}5 unmodified linesif (newState.edgeSequence !== undefined) {state.edgeSequence = newState.edgeSequence;}if (newState.perspective !== undefined) {state.perspective = newState.perspective;}if (newState.graphEngine !== undefined) {state.graphEngine = newState.graphEngine;}}
21 unmodified lines2223242526278 unmodified lines3637383940414243444521 unmodified lines/*** Helper function to recursively populate tree nodes while guarding against circular references.** @param {string} nodeId - Current node identifier.* @param {Array<Object>} activeEdges - Array of active relationship edges.8 unmodified linesconst nextVisited = new Set(visited);nextVisited.add(nodeId);// Find all child IDs where this node acts as the parentconst children = activeEdges.filter(e => e.from === nodeId).map(e => buildTreeRecursive(e.to, activeEdges, nextVisited));return {id: nodeId,21 unmodified lines22232425262728293031328 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848521 unmodified lines/*** Helper function to recursively populate tree nodes while guarding against circular references.* Strictly traverses the ontological hierarchy: Parent -> Slot -> Child.** - When at a Parent (non-Slot): traverses outgoing has_slot or has_part edges to find contextual Slots or sub-components.* - When at a Slot: traverses incoming mounted_in edges to locate the mounted Child component.* - Under no circumstances does a Slot traverse backwards to its Parent, or a Child backwards to its Slot.** @param {string} nodeId - Current node identifier.* @param {Array<Object>} activeEdges - Array of active relationship edges.8 unmodified linesconst nextVisited = new Set(visited);nextVisited.add(nodeId);const childIds = new Set();const edges = activeEdges || [];// Determine if the current node is a contextual Slotconst isSlotNode = nodeId.startsWith('Slot_') ||nodeId.startsWith('st_Slot_') ||edges.some(e => e.to === nodeId && (e.label === 'has_slot' || e.type === 'has_slot'));if (isSlotNode) {// A Slot ONLY contains components mounted into it (Child -[mounted_in]-> Slot)edges.forEach(e => {const rel = e.label || e.relationType || e.type;if (e.to === nodeId && (rel === 'mounted_in' || e.label === 'mounted_in')) {if (!nextVisited.has(e.from)) {childIds.add(e.from);}}});} else {// A non-Slot component/system traverses forward:// 1. Outgoing slots: Parent -[has_slot]-> Slot// 2. Direct sub-components: Parent -[has_part]-> Childedges.forEach(e => {const rel = e.label || e.relationType || e.type;if (e.from === nodeId) {if (rel === 'has_slot' || e.label === 'has_slot') {if (!nextVisited.has(e.to)) {childIds.add(e.to);}} else if (rel === 'has_part' || e.label === 'has_part') {if (!nextVisited.has(e.to)) {childIds.add(e.to);}}}});}const children = Array.from(childIds).map(childId => buildTreeRecursive(childId, edges, nextVisited));return {id: nodeId,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106/** * URMSM LAYER: SMRM GRAPH REDUCTION VIEWPOINT (ISO 42010) * ------------------------------------------------------- * Transforms a canonical SMIM Semantic Graph into the engineer's SMRM perspective. * Visually collapses intermediate contextual Slot nodes and renders direct * transitive relationships between parent and child components. * * Crucially preserves and transfers properties (such as defects like { crack: '2mm' }) * from the original mounting relationship onto the direct transitive relationship. * * Adheres strictly to the Rule of Isolation: * Pure graph-to-graph reduction middleware without DOM or Vue coupling. * * @param {Object} semanticGraph - Canonical Semantic Graph ({ nodes: Array, edges: Array }). * @returns {Object} Reduced Semantic Graph ({ nodes: Array, edges: Array }) for SMRM rendering. */
export function reduceGraphForSMRM(semanticGraph) { if (!semanticGraph || !Array.isArray(semanticGraph.nodes) || !Array.isArray(semanticGraph.edges)) { return { nodes: [], edges: [] }; }
// 1. Identify all Slot nodes in the semantic graph const slotNodeIds = new Set(); semanticGraph.nodes.forEach(node => { const isSlot = node.type === 'Slot' || node.properties?.entityClass === 'Slot' || node.id.startsWith('Slot_') || node.id.startsWith('4d_Slot_') || node.id.startsWith('st_Slot_'); if (isSlot) { slotNodeIds.add(node.id); } });
if (slotNodeIds.size === 0) { return { nodes: semanticGraph.nodes.map(n => ({ ...n, properties: { ...(n.properties || {}) } })), edges: semanticGraph.edges.map(e => ({ ...e, properties: { ...(e.properties || {}) } })) }; }
const nodesToRemove = new Set(slotNodeIds); const edgesToRemove = new Set(); const directTransitiveEdges = [];
// 2. Locate and collapse [Parent] -[has_slot]-> [Slot] <-[mounted_in]- [Child] slotNodeIds.forEach(slotId => { // Find has_slot edges from Parent to Slot const hasSlotEdges = semanticGraph.edges.filter( e => e.to === slotId && (e.label === 'has_slot' || e.type === 'has_slot') );
// Find mounted_in edges from Child to Slot const mountedInEdges = semanticGraph.edges.filter( e => e.to === slotId && (e.label === 'mounted_in' || e.type === 'mounted_in' || e.type === 'composition') );
hasSlotEdges.forEach(hasSlotEdge => { edgesToRemove.add(hasSlotEdge.id); const parentNodeId = hasSlotEdge.from;
mountedInEdges.forEach(mountedInEdge => { edgesToRemove.add(mountedInEdge.id); const childNodeId = mountedInEdge.from;
// Formulate direct transitive edge: Parent -> Child const directEdgeId = `smrm_${parentNodeId}_${childNodeId}_${mountedInEdge.properties?.validFrom ?? 0}`;
directTransitiveEdges.push({ id: directEdgeId, from: parentNodeId, to: childNodeId, label: 'has_part', type: 'composition', childId: childNodeId, parentId: parentNodeId, properties: { ...(mountedInEdge.properties || {}) } }); }); });
// Also remove temporalPartOf edges linking slot state slices to 4D extents semanticGraph.edges.forEach(e => { if ((e.from === slotId || e.to === slotId) && e.label === 'temporalPartOf') { edgesToRemove.add(e.id); } }); });
const remainingNodes = semanticGraph.nodes .filter(n => !nodesToRemove.has(n.id)) .map(n => ({ ...n, properties: { ...(n.properties || {}) } }));
const remainingEdges = semanticGraph.edges .filter(e => !edgesToRemove.has(e.id)) .map(e => ({ ...e, properties: { ...(e.properties || {}) } })) .concat(directTransitiveEdges);
return { nodes: remainingNodes, edges: remainingEdges };}123version https://git-lfs.github.com/spec/v1oid sha256:70128830a78572eef8c50af4700df8285068911e4b27fba0d8b4d6d02f8dca40size 3548006123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149100:00:00,000 --> 00:00:05,701Welcome to the data sandbox. Currently,the system is operating in 'Naive Graph'
200:00:05,701 --> 00:00:11,186mode. We have no strict ontologicalrules—just nodes and relationships. Let’s
300:00:11,186 --> 00:00:14,000model a typical manufacturing scenario.
400:00:14,029 --> 00:00:19,652We have a vehicle. Within it, there is asuspension slot, where part "M zero one"
500:00:19,652 --> 00:00:24,361is installed. Everything isstraightforward. But what happens when a
600:00:24,361 --> 00:00:26,189real-world problem occurs?
700:00:26,230 --> 00:00:32,184During an inspection, a two-millimetrecrack is discovered on part "M zero one".
800:00:32,184 --> 00:00:35,350How do we store this fact in a naivegraph?
900:00:35,322 --> 00:00:40,485The developer faces a dilemma. If we addthe property "crack: two millimetres"
1000:00:40,485 --> 00:00:45,715directly to the part node, then when wetry to query the car's condition a year
1100:00:45,715 --> 00:00:50,878ago, the system will answer that the partwas already broken. Because the node
1200:00:50,878 --> 00:00:53,962exists outside of time—it has beenoverwritten.
1300:00:53,923 --> 00:00:59,807The obvious workaround is to attach thedefect information to the temporal edge:
1400:00:59,807 --> 00:01:05,095"MOUNTED_IN". Excellent. The crack isanchored in time. The inspector is
1500:01:05,095 --> 00:01:09,043satisfied, and the database has saved theinformation.
1600:01:08,997 --> 00:01:14,256But then comes the next day. The part isremoved from the vehicle and sent to the
1700:01:14,256 --> 00:01:15,637warehouse for repair.
1800:01:15,607 --> 00:01:21,341The mounting edge is closed and archived.The part is now linked to the warehouse.
1900:01:21,341 --> 00:01:26,438Now, let’s ask the system: "How manydefective parts are currently in the
2000:01:26,438 --> 00:01:27,287warehouse?".
2100:01:27,259 --> 00:01:32,747The system answers: Zero. The crack hasdisappeared from the vehicle, but in the
2200:01:32,747 --> 00:01:38,097warehouse, the part is registered ascompletely flawless! The defect attribute
2300:01:38,097 --> 00:01:43,099remains buried in the archived mountingedge. Our naive approach has just
2400:01:43,099 --> 00:01:45,739destroyed critical data about a fault.
2500:01:45,703 --> 00:01:51,206This is exactly where the naive approachcollapses, and an industrial ontology is
2600:01:51,206 --> 00:01:56,503required. We are now switching the systemto ISO fifteen nine twenty-six mode.
2700:01:56,467 --> 00:02:01,568Under this standard, a part is not astatic node, but a four-dimensional
2800:02:01,568 --> 00:02:06,669object with temporal life stages. Adefect is an independent entity that
2900:02:06,669 --> 00:02:12,057classifies the condition of a specifictemporal stage of the part. Now, when
3000:02:12,057 --> 00:02:17,445moved to the warehouse, the part takesits state history with it. Data is no
3100:02:17,445 --> 00:02:18,307longer lost.
123version https://git-lfs.github.com/spec/v1oid sha256:95afd85539738fa5ebe772911ba403dce82b90c14c8cb4a13325a86fc239c7a2size 338250012324 unmodified lines2829303132333411 unmodified lines4647484950519 unmodified lines61626364656616 unmodified lines83848586* { box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }body { margin: 0; padding: 12px; background: #f8fafc; color: #0f172a; display: flex; flex-direction: column; height: 100vh; }24 unmodified lines.btn-group button { border-radius: 0; background: #ffffff; color: #475569; padding: 4px 10px; border-right: 1px solid #cbd5e1; font-size: 12px; font-weight: 600; line-height: 1.2; }.btn-group button:last-child { border-right: none; }.btn-group button.active { background: #0284c7; color: #ffffff; }.btn-group.flag-group button { font-size: 15px; padding: 3px 8px; }input, select { padding: 5px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 12px; }.divider { height: 18px; width: 1px; background: #cbd5e1; margin: 0 4px; }11 unmodified lines.resizer-h:hover, .resizer-h.dragging { background-color: #cbd5e1; border-color: #94a3b8; }body.no-select { user-select: none; }.graph-legend { position: absolute; bottom: 12px; left: 12px; background: rgba(255, 255, 255, 0.96); backdrop-filter: blur(4px); border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px 14px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); font-size: 11px; color: #334155; z-index: 20; max-width: 330px; }.legend-title { font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #475569; margin-bottom: 6px; display: flex; justify-content: space-between; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; }.legend-section { margin-top: 5px; }9 unmodified lines.swatch-line-active { width: 16px; height: 2px; background: #10b981; margin-right: 8px; flex-shrink: 0; }.swatch-line-past { width: 16px; height: 0; border-top: 2px dashed #94a3b8; margin-right: 8px; flex-shrink: 0; }.swatch-line-transition { width: 16px; height: 2px; background: #f59e0b; margin-right: 8px; flex-shrink: 0; }.sidebar { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 350px; }.card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; overflow-y: auto; display: flex; flex-direction: column; }16 unmodified linesflex: 1;height: 100%;min-height: 0;}1234567891024 unmodified lines353637383940414243444511 unmodified lines575859606162639 unmodified lines7374757677787980818283848586878816 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420@font-face {font-family: 'Twemoji';src: url('./Twemoji-16.0.1.ttf') format('truetype');font-weight: normal;font-style: normal;}* { box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }body { margin: 0; padding: 12px; background: #f8fafc; color: #0f172a; display: flex; flex-direction: column; height: 100vh; }24 unmodified lines.btn-group button { border-radius: 0; background: #ffffff; color: #475569; padding: 4px 10px; border-right: 1px solid #cbd5e1; font-size: 12px; font-weight: 600; line-height: 1.2; }.btn-group button:last-child { border-right: none; }.btn-group button.active { background: #0284c7; color: #ffffff; }.btn-group.flag-group button {font-family: 'Twemoji', system-ui, sans-serif;font-size: 15px;padding: 3px 8px;}input, select { padding: 5px 8px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 12px; }.divider { height: 18px; width: 1px; background: #cbd5e1; margin: 0 4px; }11 unmodified lines.resizer-h:hover, .resizer-h.dragging { background-color: #cbd5e1; border-color: #94a3b8; }body.no-select { user-select: none; }.graph-caption { position: absolute; top: 12px; left: 12px; background: rgba(255, 255, 255, 0.94); backdrop-filter: blur(4px); border: 1px solid #cbd5e1; border-radius: 6px; padding: 6px 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); font-size: 11px; font-weight: 700; color: #1e293b; z-index: 20; display: flex; align-items: center; gap: 6px; letter-spacing: 0.02em; pointer-events: none; }.graph-legend { position: absolute; bottom: 12px; left: 12px; background: rgba(255, 255, 255, 0.96); backdrop-filter: blur(4px); border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px 14px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); font-size: 11px; color: #334155; z-index: 20; max-width: 330px; }.legend-title { font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: #475569; margin-bottom: 6px; display: flex; justify-content: space-between; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; }.legend-section { margin-top: 5px; }9 unmodified lines.swatch-line-active { width: 16px; height: 2px; background: #10b981; margin-right: 8px; flex-shrink: 0; }.swatch-line-past { width: 16px; height: 0; border-top: 2px dashed #94a3b8; margin-right: 8px; flex-shrink: 0; }.swatch-line-transition { width: 16px; height: 2px; background: #f59e0b; margin-right: 8px; flex-shrink: 0; }.swatch-box-vehicle { width: 13px; height: 11px; background: #0284c7; border: 1px solid #0369a1; border-radius: 2px; margin-right: 8px; flex-shrink: 0; }.swatch-box-slot { width: 13px; height: 11px; background: #64748b; border: 1px solid #475569; border-radius: 2px; margin-right: 8px; flex-shrink: 0; }.swatch-box-part { width: 13px; height: 11px; background: #10b981; border: 1px solid #059669; border-radius: 2px; margin-right: 8px; flex-shrink: 0; }.swatch-diamond-defect { width: 9px; height: 9px; background: #ef4444; border: 1px solid #dc2626; transform: rotate(45deg); margin: 0 10px 0 2px; flex-shrink: 0; }.swatch-box-warehouse { width: 13px; height: 11px; background: #f97316; border: 1px solid #ea580c; border-radius: 2px; margin-right: 8px; flex-shrink: 0; }.swatch-line-slot { width: 16px; height: 2px; background: #0284c7; margin-right: 8px; flex-shrink: 0; }.swatch-line-mount { width: 16px; height: 2px; background: #10b981; margin-right: 8px; flex-shrink: 0; }.swatch-line-store { width: 16px; height: 2px; background: #f97316; margin-right: 8px; flex-shrink: 0; }.swatch-line-defect { width: 16px; height: 2px; background: #ef4444; margin-right: 8px; flex-shrink: 0; }.sidebar { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 350px; }.card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; overflow-y: auto; display: flex; flex-direction: column; }16 unmodified linesflex: 1;height: 100%;min-height: 0;}/* Sandbox Workspace Wrapper */.sandbox-workspace {display: flex;flex-direction: column;flex: 1;min-height: 0;}/* Main Menu / Landing View */.landing-view {display: flex;flex: 1;align-items: center;justify-content: center;min-height: 100%;padding: 24px;}.menu-card {max-width: 540px;width: 100%;background: #ffffff;border: 1px solid #cbd5e1;border-radius: 12px;padding: 36px 32px;box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.08), 0 8px 10px -6px rgba(15, 23, 42, 0.04);text-align: center;display: flex;flex-direction: column;align-items: center;}.menu-badge {display: inline-block;background: #e0f2fe;color: #0369a1;border: 1px solid #7dd3fc;padding: 4px 12px;border-radius: 9999px;font-size: 11px;font-weight: 700;letter-spacing: 0.05em;text-transform: uppercase;margin-bottom: 16px;}.menu-title {font-size: 22px;font-weight: 800;color: #0f172a;margin: 0 0 8px 0;letter-spacing: -0.02em;}.menu-subtitle {font-size: 13px;color: #64748b;margin: 0 0 28px 0;line-height: 1.5;}.menu-actions {display: flex;flex-direction: column;gap: 14px;width: 100%;}.menu-btn {display: flex;flex-direction: column;align-items: flex-start;text-align: left;padding: 16px 20px;border-radius: 8px;border: 1px solid transparent;cursor: pointer;transition: all 0.2s ease-in-out;width: 100%;}.menu-btn .btn-main-text {font-size: 15px;font-weight: 700;margin-bottom: 4px;}.menu-btn .btn-sub-text {font-size: 12px;font-weight: 400;opacity: 0.85;line-height: 1.35;}.menu-btn-primary {background: #0284c7;color: #ffffff;border-color: #0369a1;}.menu-btn-primary:hover {background: #0369a1;box-shadow: 0 4px 12px rgba(2, 132, 199, 0.3);transform: translateY(-1px);}.menu-btn-scenario {background: #ffffff;color: #0f172a;border-color: #cbd5e1;}.menu-btn-scenario:hover {background: #f8fafc;border-color: #94a3b8;box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);transform: translateY(-1px);}/* Floating Home Button */.floating-home-btn {position: fixed;bottom: 20px;right: 20px;z-index: 9999;width: 48px;height: 48px;border-radius: 50%;background: #0f172a;color: #ffffff;border: 1px solid #334155;box-shadow: 0 4px 14px rgba(15, 23, 42, 0.25);display: flex;align-items: center;justify-content: center;padding: 0;cursor: pointer;transition: all 0.2s ease-in-out;}.floating-home-btn:hover {background: #1e293b;transform: translateY(-2px);box-shadow: 0 6px 18px rgba(15, 23, 42, 0.35);}.floating-home-btn:active {transform: translateY(0);}/* Floating Player Panel & Subtitles Overlay (Scenario Mode) */.scenario-subtitles {position: fixed;bottom: 82px;left: 50%;transform: translateX(-50%);z-index: 9999;background: rgba(15, 23, 42, 0.88);backdrop-filter: blur(6px);-webkit-backdrop-filter: blur(6px);color: #ffffff;padding: 12px 24px;border-radius: 8px;font-size: 15px;font-weight: 500;line-height: 1.45;text-align: center;max-width: 680px;min-width: 320px;box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);border: 1px solid rgba(255, 255, 255, 0.12);pointer-events: none;transition: opacity 0.2s ease-in-out;}.scenario-player-panel {position: fixed;bottom: 20px;left: 50%;transform: translateX(-50%);z-index: 9999;display: flex;align-items: center;gap: 12px;background: #0f172a;color: #f8fafc;padding: 8px 18px;border-radius: 40px;box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);border: 1px solid #334155;user-select: none;}.player-btn {display: inline-flex;align-items: center;justify-content: center;width: 34px;height: 34px;border-radius: 50%;background: #1e293b;color: #ffffff;border: 1px solid #475569;cursor: pointer;padding: 0;font-size: 13px;transition: background-color 0.15s ease, transform 0.1s ease, border-color 0.15s ease;}.player-btn:hover {background: #334155;border-color: #64748b;transform: scale(1.05);}.player-btn:active {transform: scale(0.95);}.player-btn.active {background: #0284c7;border-color: #38bdf8;color: #ffffff;}.player-btn-cc {font-size: 11px;font-weight: 700;letter-spacing: 0.05em;border-radius: 6px;width: 34px;height: 30px;}.player-progress {width: 240px;height: 6px;-webkit-appearance: none;appearance: none;background: #334155;border-radius: 3px;outline: none;cursor: pointer;}.player-progress::-webkit-slider-thumb {-webkit-appearance: none;appearance: none;width: 14px;height: 14px;border-radius: 50%;background: #38bdf8;cursor: pointer;box-shadow: 0 0 6px rgba(0, 0, 0, 0.4);transition: transform 0.1s ease, background-color 0.15s ease;}.player-progress::-webkit-slider-thumb:hover {transform: scale(1.2);background: #7dd3fc;}.player-progress::-moz-range-thumb {width: 14px;height: 14px;border-radius: 50%;background: #38bdf8;border: none;cursor: pointer;}/* Role Switcher Styling */.btn-group.role-group button {font-weight: 600;display: inline-flex;align-items: center;gap: 5px;}.btn-group.role-group button.active {background: #4f46e5;color: #ffffff;}/* Universal Engineer Workspace Placeholder */.uni-engineer-placeholder {min-height: 52px;background: #f8fafc;border-top: 1px solid #e2e8f0;border-bottom-left-radius: 7px;border-bottom-right-radius: 7px;display: flex;align-items: center;padding: 12px 16px;}.player-time {font-size: 12px;font-variant-numeric: tabular-nums;color: #94a3b8;min-width: 80px;text-align: center;user-select: none;}/* Phantom User UI Highlight (Scenario Mode) */.scenario-highlight {box-shadow: 0 0 10px 3px rgba(255, 215, 0, 0.8) !important;background-color: rgba(255, 255, 200, 0.3) !important;transition: all 0.3s ease;}
.gitattributes+2
ARCHITECTURE.md+14-3
js/app.js+918-144
js/i18n.js+105-3
js/renderers/mermaid-adapter.js+147-12
js/renderers/vis-adapter.js+165-10
js/scenarios/scenario-vanishing-crack.jsAdded+280
js/smim/bfo.js+209-40
js/smim/iso15926.js+372-90
js/smim/naive.js+238
js/smrm/actions.js+96-66
js/smrm/definitions.js+30
js/sms/lpg-generator.js+28-13
js/sms/rdf-generator.js+133-44
js/sms/sms-graph-generator.jsAdded+172
js/state.js+46-9
js/urmsm/bom-view.js+44-4
js/urmsm/smrm-view.jsAdded+106
narratives/Ontologies_-_Disappearing_Crack.mp3Added+3
narratives/Ontologies_-_Disappearing_Crack.srtAdded+149
styles/Twemoji-16.0.1.ttfAdded+3
styles/main.css+336-2