### Event Listeners Setup Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Sets up various event listeners for user interactions including clicks, input changes, focus out, keydown events, and window resize. Also initializes the application. ```javascript document.addEventListener("click", handleClicks); document.addEventListener("toggle", handleDetailsToggle, true); document.addEventListener("input", handleInputs); document.addEventListener("focusout", handleFocusOut, true); document.addEventListener("keydown", handleKeydown); document.addEventListener("fullscreenchange", updateFullscreenButton); byId("snapshotInput").addEventListener("change", handleSnapshotInput); window.addEventListener("resize", renderCollapsiblePanels); initialMount(); })(); ``` -------------------------------- ### Initialize Application State and Render Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Performs initial setup by loading storage, initializing file structures if empty, running checks, and rendering all application components. It ensures the application is ready for user interaction. ```javascript function initialMount(){ storageLoad(); if(!Object.keys(app.files).length) app.files = initEmptyFiles(); for(const surface of SURFACES){ if(!app.files[surface.id]){ app.files[surface.id] = parseSurfaceContent(surface, surface.files[0], "", null); } } runChecks(); app.overlayOpen = app.checks.some(c => c.level === "bad"); updateFullscreenButton(); renderAll(); } ``` -------------------------------- ### Initialize Workstation State and Events Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Initializes the workstation's state and event handling by setting up storage keys and defining main and dashboard tab configurations. This code runs at the start of the workstation application. ```javascript (() => { "use strict"; const STORAGE_KEY = "sr_workstation_final_state"; const EVENTS_KEY = "sr_workstation_final_events"; const MAIN_TABS = [ { id: "read", label: "READ" }, { id: "write", label: "WRITE" }, { id: "system", label: "SYSTEM" }, { id: "dashboard", label: "DASHBOARD" } ]; const DASHBOARD_TABS = [ { id: "overview", label: "Overview" }, { id: "radar", label: "Radar" }, { id: "timeline", label: "Timeline" } ]; const SURFACES = [ { id: "readme", files: ["README.txt"], label: "README", group: "reference", writable: false, sensitive: false, live: false, purpose: "High-level guide to the instance.", notFor: "Live project truth and operational capture.", }, { id: "entry", files: ["00_runtime_entry.txt"], label: "Entry", group: "reference", writable: false, sensitive: true, live: false, purpose: "Valid entry into the system and minimum reading boundaries.", notFor: "Project identity, current work, and decisions." }, { id: "orientation", files: ["01_orientation.txt"], label: "Project Identity", group: "core", writable: true, sensitive: true, live: false, purpose: "What the project is, where it begins and ends, and how to read it.", notFor: "Minute-by-minute work state and temporary session notes." }, { id: "freeze", files: ["02_protocol_freeze.txt"], label: "Core Constants", group: "core", writable: true, sensitive: true, live: false, purpose: "Identity-level constants that should be hard to reopen.", notFor: "Preferences, temporary ideas, or live blockers." }, { id: "working", files: ["03_master_working.txt"], label: "Project Now", group: "core", writable: true, sensitive: false, live: true, purpose: "Current live state: what is active, blocked, and next.", notFor: "Identity, archive, or long-term parking." }, { id: "decisions", files: ["04_decision_log.txt"], label: "Won Decisions", group: "core", writable: true, sensitive: true, live: false, purpose: "Already-won choices that beat real alternatives and are in effect.", notFor: "Loose preferences or unresolved ideas." }, { id: "latent", files: ["05_latent_ideas.txt"], label: "Ideas in Transit", group: "core", writable: true, sensitive: false, live: true, purpose: "Unresolved but meaningful material that should stay alive.", notFor: "Archive or final decisions by default." }, { id: "kernel", files: ["06_ai_to_ai.txt"], label: "Kernel", group: "reference", writable: false, sensitive: true, live: false, purpose: "Shared horizontal behavior for the agent inside Signal Rail.", notFor: "Project truth, host identity, or live project state." }, { id: "guided", files: ["07_guided_prompts_test.txt"], label: "Guided Prompts", group: "reference", writable: false, sensitive: false, live: false, purpose: "Safer opening flows and guided prompt patterns.", notFor: "Current project truth or operational records." }, { id: "technical", files: ["08_surface_map.txt"], label: "Technical Map", group: "core", writable: true, sensitive: true, live: false, purpose: "Where the project lives technically, what is sensitive, and how to enter safely.", notFor: "Identity or general live work notes." }, { id: "handoff", files: ["09_handoff_reentry.txt"], label: "Session Handoff", group: "support", writable: true, sensitive: false, live: false, purpose: "Short continuity between sessions and re-entry points.", notFor: "Canonical project truth." }, { id: "findings", files: ["97_field_findings.txt"], label: "Findings", group: "support", writable: true, sensitive: false, live: false, purpose: "Signals, seeds, bugs, and refinements observed during work.", notFor: "Stable project truth or final decisions." }, { id: "parking", files: ["98_parking.txt"], label: "Parked", group: "support", writable: true, sensitive: false, live: false, purpose: "Material that may matter later but should not weigh on the present.", notFor: "Current live work." }, { id: "archive", files: ["99_archive.txt"], label: "Archive", group: "support", writable: true, sensitive: false, live: false, purpose: "Closed, historical, or no-longer-live material.", notFor: "Current action or active unresolved ideas." }, { id: "marker", files: ["AI_TO_AI__DEPLOYED_INSTANCE_SIGNAL_RAIL.txt"], label: "Instance Marker", group: "reference", writable: false, sensitive: false, live: false } ]; })(); ``` -------------------------------- ### Get Current Surface Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Retrieves the data for the currently selected surface from the application's file store. Returns null if the surface ID is not found. ```javascript function currentSurface(){ return app.files[app.selectedSurfaceId] || null; } ``` -------------------------------- ### Get Surface Display Mode Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Retrieves the display mode for a given surface ID from a predefined contract. Defaults to 'raw_only' if the surface ID is not found. ```javascript function getSurfaceDisplayMode(surfaceId){ return SURFACE_DISPLAY_CONTRACT[surfaceId] || "raw_only"; } ``` -------------------------------- ### Get Global Search Results Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Retrieves and ranks global search results based on a user query. It limits the number of results returned to a predefined maximum. ```javascript function getGlobalSearchResults(query){ const normalized = normalizeSearchText(query); if(!normalized) return []; const tokens = normalized.split(" ").filter(Boolean); const scored = buildGlobalSearchIndex().map(entry => ({ entry, score: scoreGlobalSearchEntry(entry, normalized, tokens) })).filter(item => item.score >= 0); scored.sort((a, b) => b.score - a.score || a.entry.label.localeCompare(b.entry.label)); return scored.slice(0, GLOBAL_SEARCH_MAX_RESULTS).map(item => item.entry); } ``` -------------------------------- ### Get Current Write Action Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Returns the currently active write action based on the application's state. Defaults to the first action if the current one is not found. ```javascript function currentAction(){ return WRITE_ACTIONS.find(a => a.id === app.currentWriteActionId) || WRITE_ACTIONS[0]; } ``` -------------------------------- ### Build Project Suggestions Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Constructs a list of actionable suggestions based on various project metrics and states. It prioritizes suggestions like setting an objective or reviewing dense 'Transit' items. ```javascript function buildSuggestions(metrics = []){ const suggestions = []; const seen = new Set(); const working = app.files.working; const latent = app.files.latent; const decisions = app.files.decisions; const technical = app.files.technical; const handoff = app.files.handoff; const findings = app.files.findings; const parking = app.files.parking; const archive = app.files.archive; const transitCount = Number(latent?.blockCount || 0); const decisionsCount = Number(decisions?.blockCount || 0); const handoffCount = Number(handoff?.blockCount || 0); const findingsCount = Number(findings?.blockCount || 0); const parkingCount = Number(parking?.blockCount || 0); const archiveCount = Number(archive?.blockCount || 0); const hasObjective = !!normalizeSingleLine(working?.latestNow?.objective || ""); const pushSuggestion = (kindClass, kindLabel, title, body, target) => { const key = normalizeSearchText(title); if(!title || !body || !target || seen.has(key)) return; seen.add(key); suggestions.push({ kindClass, kindLabel, title, body, target }); }; if(!hasObjective){ pushSuggestion( "bad", "urgent", "Project Now needs a clear objective", "The live working surface is missing a strong objective line. Add one to stabilize direction.", "working" ); } if(transitCount >= 6){ pushSuggestion( "warn", "density review", "Transit is dense and needs sorting", `Ideas in Transit contains ${transitCount} active items. Review and promote or trim the oldest unresolved blocks.`, "latent" ); } else if(transitCount >= 3){ pushSuggestion( "core", "review candidate", "Transit likely contains promotion candidates", "Transit has enough active material to review for promotion into Won Decisions or Project Now.", "latent" ); } if(decisionsCount === 0 && transitCount > 0){ pushSuggestion( "sensitive", "decision check", "Check if a real decision already exists", "Transit has active material but no visible won decision blocks. Verify whether an alternative has already been beaten.", "decisions" ); } if(technical && technical.status !== "active"){ pushSuggestion( "warn", "technical attention", "Technical map may need strengthening", "The technical map looks thin relative to curr" ); } // ... more logic for other suggestions return suggestions; } ``` -------------------------------- ### Import Workstation Snapshot Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Handles the import of a workstation snapshot file. It reads the file content, parses it as JSON, and updates the application state. Includes error handling for invalid files. ```javascript function importSnapshot(file){ try{ const reader = new FileReader(); reader.onload = function(e){ const data = JSON.parse(e.target.result); if(data.sessionName) app.sessionName = data.sessionName; logEvent("snapshot", "Snapshot imported", "Workspace snapshot imported.", [], "imported"); runChecks(); storageSave(); renderAll(); }catch{ app.overlayOpen = true; runChecks([{ level: "bad", title: "Snapshot import failed", body: "The selected file is not a valid workstation snapshot." }]); renderAll(); } }; reader.readAsText(file); } ``` -------------------------------- ### Get Current HTML Folder Windows Path Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Determines the current HTML folder path on Windows when running from a local file. Returns an empty string if not applicable. ```javascript function currentHtmlFolderWindowsPath(){ if(typeof window === "undefined" || !window.location) return ""; if(String(window.location.protocol || "").toLowerCase() !== "file:") return ""; try{ let rawPath = decodeURIComponent(String(window.location.pathname || "")); if(!rawPath) return ""; rawPath = rawPath.replace(/\//g, "\\\\"); rawPath = rawPath.replace(/^\\([A-Za-z]:\\)/, "$1"); rawPath = rawPath.replace(/\\+/g, "\\\\"); rawPath = raw ``` -------------------------------- ### Focus View Start Element Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Sets focus to a specific element within a view based on the view ID. It temporarily sets tabindex to -1 for focusability and then removes it. ```javascript function focusViewStart(viewId){ const targets = { read: "readHeroTitle", write: "writeFormTitle", system: "healthGrid", dashboard: "overviewGrid" }; const node = byId(targets[viewId] || ""); if(!node) return; node.setAttribute("tabindex", "-1"); node.focus(); setTimeout(() => node.removeAttribute("tabindex"), 0); } ``` -------------------------------- ### Render Project Overview UI Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Renders the main overview section of the workstation, including the 'Do This Now' card, metric cards, and suggestions. It dynamically updates the HTML content based on calculated metrics and suggestions. ```javascript function renderOverview(){ const metrics = overviewMetrics(); const suggestions = buildSuggestions(metrics); const doNow = buildOverviewAction(metrics, suggestions); byId("overviewDoNow").innerHTML = ` `; byId("overviewGrid").innerHTML = metrics.map(metric => ` `).join(""); byId("dashboardSuggestions").innerHTML = suggestions.map(s => ` `).join("") || `
No suggestions available yet.
`; } ``` -------------------------------- ### Initialize Empty Files Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Creates an initial empty file structure for all defined surfaces. Used when no files are present. ```javascript function initEmptyFiles(){ const empty = {}; for(const surface of SURFACES){ empty[surface.id] = parseSurfaceContent(surface, surface.files[0], "", null); } return empty; } ``` -------------------------------- ### Build Overview Action Button Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Constructs the HTML for an action button within the project overview, based on calculated metrics and suggestions. It orders metrics and determines the primary focus for user action. ```javascript function buildOverviewAction(metrics, suggestions){ const ordered = ["Now", "Technical", "Transit", "Continuity"] .map(name => metrics.find(m => m.title === name)) .filter(Boolean); const focus = ordered.find(m => m.level === ``` -------------------------------- ### Signal Rail Initialization Prompt Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/README.md This is a prompt used to ask an AI agent to read the runtime entry file for Signal Rail. ```text 00_runtime_entry.txt ``` -------------------------------- ### Append-Driven File Entries Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/README.md New live entries in append-driven canonicals must be placed between the 'ENTRIES START' and 'ENTRIES END' markers. The marker contract must be strictly followed to ensure valid operation. ```text --- ENTRIES START --- ... --- ENTRIES END --- ``` -------------------------------- ### Build Working Write Plan Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Initiates the process of building a working write plan based on an action, draft data, and existing text. It prepares the next state of the text, including ISO date formatting. ```javascript function buildWorkingWritePlan(action, draft, text){ let next = String(text || ""); const dateValue = new Date().toISOString().slice( ``` -------------------------------- ### Apply Live Directory Changes Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Updates the application state with content from a live directory. Handles mounting and refreshing operations, logging events, and triggering UI updates. ```javascript async function applyLiveDirectory(dir, mode = "mount"){ const { loaded, handles, readmeMd } = await readSurfacesFromDirectory(dir); app.dirHandle = dir; app.fileHandles = handles; app.files = loaded; app.readmeMd = readmeMd; app.sourceMode = "live"; app.folderName = dir.name || "mounted folder"; app.folderPath = resolveFolderPathFromHandle(dir); if(mode === "mount"){ if(!app.workspaceName || app.workspaceName === "Signal Rail Workspace"){ app.workspaceName = dir.name || "Signal Rail Workspace"; } logEvent("source", "Folder opened", "Live folder mounted successfully.", [], "observed"); } else { logEvent("source", "Folder refreshed", "Live folder content reloaded from disk.", [], "manual"); } runChecks(); storageSave(); renderAll(); } ``` -------------------------------- ### Extract Local IDs from Raw Text Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Extracts local identifiers (e.g., F-XX, D-XX) from raw text content, typically from surface files. It uses a regular expression to find lines starting with '- id:' followed by the ID pattern. ```javascript function extractLocalIds(raw){ return Array.from( String(raw || "").matchAll(/^\s*-\s*id:\s*((?:F|D|L|P|A)-\d{2})\b/gim), m => m[1] ); } ``` -------------------------------- ### Build Global Search Index Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Constructs a comprehensive search index for surfaces, write actions, and system references. Each entry includes metadata and a 'run' function to execute the associated action. ```javascript function buildGlobalSearchIndex(){ const entries = []; for(const surface of SURFACES){ const loaded = app.files[surface.id]; const shortCode = parseSurfaceShortCode(surface); const fileName = loaded?.actualFileName || surface.files[0]; entries.push({ key: `surface:${surface.id}`, kind: "surface", label: `${shortCode} · ${surface.label}`, subtitle: `READ · ${fileName}`, searchText: normalizeSearchText([ shortCode, surface.id, surface.label, fileName, surface.group, surface.purpose ].join(" ")), run: () => openSurface(surface.id, "read") }); } for(const action of WRITE_ACTIONS){ const surface = findSurface(action.surfaceId); const shortCode = parseSurfaceShortCode(surface); entries.push({ key: `write:${action.id}`, kind: "write", label: `${shortCode} · ${action.title}`, subtitle: `WRITE · ${surface?.label || action.surfaceId}`, searchText: normalizeSearchText([ shortCode, action.id, action.title, action.desc, "write", surface?.label || "", surface?.id || "" ].join(" ")), run: () => { app.currentWriteActionId = action.id; app.currentView = "write"; app.overlayOpen = false; app.referenceOverlayOpen = false; app.attentionOverlayOpen = false; app.dashboardActionOverlayOpen = false; storageSave(); renderAll(); focusViewStart("write"); } }); } for(const ref of SURFACES.filter(s => s.group === "reference")){ const shortCode = parseSurfaceShortCode(ref); const loaded = app.files[ref.id]; entries.push({ key: `reference:${ref.id}`, kind: "reference", label: `${shortCode} · ${ref.label}`, subtitle: "SYSTEM · Reference mini-layer", searchText: normalizeSearchText([ shortCode, ref.id, ref.label, loaded?.actualFileName || ref.files[0], "reference", "system" ].join(" ")), run: () => { app.currentView = "system"; app.systemRefLayerId = ref.id; storageSave(); openReferenceOverlay(ref.id); } }); } for(const action of GLOBAL_SYSTEM_ACTIONS){ entries.push({ key: `system:${action.id}` }); } } ``` -------------------------------- ### Build Freeze Write Plan Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Initiates the write plan for freezing a project, with support for 'edit' mode. ```javascript function buildFreezeWritePlan(action, draft, text){ const mode = String(draft._mode || "add").trim().toLowerCase(); let result; if(mode === "edit"){ const targetId = normalizeSingleLine(draft._targetId); ``` -------------------------------- ### Save Write Operation Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Initiates the save write operation. Checks for live source mode and then builds and executes the write plan. Displays an error if live save is unavailable. ```javascript async function saveWrite(){ const action = currentAction(); const surfaceMeta = findSurface(action.surfaceId); const draft = ensureDraftForAction(action.id); if(app.sourceMode !== "live"){ app.overlayOpen = true; runChecks([ { level: "bad", title: "Live save unavailable", body: "Direct save to TXT requires a live mounted folder. Open a folder in Chrome or another Chromium browser." } ]); renderAll(); return; } try{ const plan = buildWritePlan(action, draft, app.files[action.surfaceId]); // ... rest of the save logic ``` -------------------------------- ### Render Project References Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Dynamically generates HTML for displaying project references based on available data. It maps reference data to button elements, including status pills and file details. Used to populate the reference library view. ```javascript byId("referenceLibrary").innerHTML = refs.length ? refs.map(ref => { const surface = app.files[ref.id]; const pills = [ ref.group, ref.writable ? "writable" : "read-only", ref.sensitive ? "sensitive" : "", ref.live ? "live" : "" ].filter(Boolean); return `; }).join("") : bind
No reference guides are available.
ind; ``` -------------------------------- ### Open System Overlay Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Opens the main system overlay, ensuring other specific overlays (reference, attention, dashboard action) are closed. It synchronizes state aliases and triggers a full render. ```javascript function openSystemOverlay(){ app.overlayOpen = true; app.referenceOverlayOpen = false; app.attentionOverlayOpen = false; app.dashboardActionOverlayOpen = false; syncStateAliases(); renderAll(); } ``` -------------------------------- ### Open Folder Dialog Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Initiates the process to open a local directory using the browser's directory picker API. Handles potential errors and updates the UI. ```javascript async function openFolder(){ if(typeof window.showDirectoryPicker !== "function"){ app.overlayOpen = true; runChecks(); renderAll(); return; } try{ const dir = await window.showDirectoryPicker(); await applyLiveDirectory(dir, "mount"); } catch (error) { if(error && error.name === "AbortError") return; app.overlayOpen = true; runChecks(); renderAll(); } } ``` -------------------------------- ### Navigate to Write Mode for Surface Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Transitions the application to the 'write' view for a given surface. It selects the appropriate write action and updates the application state. ```javascript function goToWriteForSurface(surfaceId){ const action = WRITE_ACTIONS.find(a => a.surfaceId === surfaceId) || WRITE_ACTIONS[0]; app.currentWriteActionId = action.id; app.currentView = "write"; app.overlayOpen = false; app.referenceOverlayOpen = false; app.attentionOverlayOpen = false; app.dashboardActionOverlayOpen = false; storageSave(); renderAll(); } ``` -------------------------------- ### Build Parking Write Plan Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Handles the creation or modification of parking entries. It includes validation for target entry format (P-xx) and checks if any editable fields are present. ```javascript function buildParkingWritePlan(action, draft, text) { const source = String(text || ""); const mode = String(draft._mode || "add").trim().toLowerCase(); if (mode === "edit") { const targetId = normalizeSingleLine(draft._targetId).toUpperCase(); if (!/^P-\d{2}$/.test(targetId)) { throw new Error("Parking edit requires selecting a valid target entry (P-xx)."); } const hasAny = [ draft.title, draft.body, draft.why, draft.return ].some(value => normalizeSingleLine(value)); if (!hasAny) { throw new Error("Parking edit requires at le ``` -------------------------------- ### Render System README Content Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Renders the README.md content for the system, separating it into general and technical sections. Displays a 'not found' message if the README is absent. ```javascript function renderSystemReadme(){ const rootGeneral = byId("systemReadmeGeneral"); const rootTechnical = byId("systemReadmeTechnical"); if(!rootGeneral || !rootTechnical) return; const readme = app.readmeMd || { raw: "", present: false }; if(!readme.present){ rootGeneral.innerHTML = \`
README.md not found in the mounted folder.
ylic`; rootTechnical.innerHTML = \`
README.md not found in the mounted folder.
ylic`; return; } const sections = parseReadmeMdSections(readme.raw || ""); rootGeneral.innerHTML = sections.general ? renderReadmeMarkdown(sections.general) : \`
General section not found in README.md.
ylic`; rootTechnical.innerHTML = sections.technical ? renderReadmeMarkdown(sections.technical) : \`
Technical section not found in README.md.
ylic`; } ``` -------------------------------- ### Windows Bootstrap Script Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/README.md Run this batch script on Windows to create a new Signal Rail instance structure in your project. ```batch init_signal_rail.bat ``` -------------------------------- ### Execute System Search Action Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Handles the execution of specific system-level actions triggered from search results. This includes actions like opening folders or importing/exporting snapshots. ```javascript function executeSystemSearchAction(actionId){ if(actionId === "open-folder"){ openFolder(); return; } if(actionId === "import-snapshot"){ byId("snapshotInput").click(); return; } if(actionId === "export-snapshot"){ exportSnapshot(); return; } if(actionId === "refresh-source"){ refreshLiveFolder(); return; } if(actionId === "system-checks"){ openSystemOverlay(); } } ``` -------------------------------- ### Import Workspace Snapshot Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Imports a workspace state from a JSON snapshot file. Updates the application's files, events, and metadata based on the imported data. ```javascript function importSnapshot(file){ const reader = new FileReader(); reader.onload = () => { try{ const data = JSON.parse(String(reader.result || "{}")); if(!data.files || typeof data.files !== "object"){ throw new Error("Invalid snapshot"); } const imported = {}; for(const surface of SURFACES){ const entry = data.files[surface.id]; imported[surface.id] = entry ? parseSurfaceContent(surface, entry.actualFileName || surface.files[0], entry.raw || "", entry.modifiedAt || null) : parseSurfaceContent(surface, surface.files[0], "", null); } app.files = imported; app.events = Array.isArray(data.events) ? data.events : []; app.sourceMode = "snapshot"; app.folderName = data.folderName || "snapshot"; app.folderPath = data.folderPath || data.folderName || "snapshot"; app.dirHandle = null; app.fileHandles = {}; app.readmeMd = data.readmeMd && typeof data.readmeMd === "object" ? { raw: String(data.readmeMd.raw || ""), modifiedAt: data.readmeMd.modifiedAt || null, present: !!data.readmeMd.present } : { raw: "", modifiedAt: null, present: false }; if(data.workspaceName) app.workspaceName = data.workspace ``` -------------------------------- ### Render System Source Actions Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Generates buttons for system source actions like Open Folder, Import Snapshot, Export Snapshot, and Refresh. Each button includes system status pills indicating mode and availability. ```javascript const runtimePillClass = app.sourceMode === "live" ? "live" : "warn"; const runtimePillLabel = app.sourceMode === "live" ? "live" : app.sourceMode || "offline"; const actions = [ { id: "sysOpenFolderBtn", title: "Open Folder", copy: "Mount a live folder to enable direct TXT save and real-time refresh.", mode: "mount" }, { id: "sysImportBtn", title: "Import Snapshot", copy: "Load a JSON snapshot to inspect an instance without live folder access.", mode: "snapshot" }, { id: "sysExportBtn", title: "Export Snapshot", copy: "Save workstation state and content into a portable JSON file.", mode: "snapshot" }, { id: "sysRefreshBtn", title: "Refresh", copy: "Reload files from mounted live folder and rerun runtime checks.", mode: "manual" } ]; byId("systemSourceActions").innerHTML = actions.map(action => ` `).join(""); ``` -------------------------------- ### Write File to Handle Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Saves the current plan's text to a file handle. It handles creating the file if it doesn't exist and updates the application's file state. This function should be used when saving changes to a surface. ```javascript async function writeSurface(action) { try { const plan = app.plans.get(action.id); const surfaceMeta = findSurface(action.surfaceId); const fileHandle = app.fileHandles[action.surfaceId]?.raw || (app.files[action.surfaceId]?.handle?.raw || ""); if(plan.blocked){ throw new Error(plan.preview || "Write is blocked because canonical routing is not clear."); } let handle = app.fileHandles[action.surfaceId]; let actualName = app.files[action.surfaceId]?.actualFileName || surfaceMeta.files[0]; if(!handle){ if(!app.dirHandle){ throw new Error("No mounted folder handle is available for writing."); } handle = await app.dirHandle.getFileHandle(actualName, { create: true }); app.fileHandles[action.surfaceId] = handle; } const writable = await handle.createWritable(); await writable.write(plan.nextText); await writable.close(); app.files[action.surfaceId] = parseSurfaceContent(surfaceMeta, actualName, plan.nextText, Date.now()); logEvent("write", action.title + " saved", "A new write entry was saved to " + actualName + ".", [action.surfaceId], "manual"); app.writeDraft[action.id] = {}; runChecks(); storageSave(); renderAll(); } catch (error) { app.overlayOpen = true; runChecks([ { level: "bad", title: "Save failed", body: String(error && error.message ? error.message : error) } ]); renderAll(); } } ``` -------------------------------- ### Build Generic Write Plan Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Determines the appropriate write plan strategy based on the action's surface ID. Handles various surfaces like 'working', 'orientation', 'parking', and 'archive', with fallback for undefined surfaces. ```javascript function buildWritePlan(action, draft, currentText){ const text = String(currentText || ""); const surfaceMeta = findSurface(action.surfaceId); if(!hasMeaningfulDraft(action, draft)){ return { strategy: "waiting-input", preview: "Fill at least one field to generate a canonical write preview.", nextText: ensureFinalNewline(text), blocked: true }; } if(app.sourceMode === "unmounted"){ return { strategy: "blocked-source", preview: "No source is mounted. Open a Signal Rail folder or import a snapshot before generating canonical write output.", nextText: ensureFinalNewline(text), blocked: true }; } if(APPEND_DRIVEN_SURFACE_IDS.includes(action.surfaceId)){ if(!text.trim()){ return { strategy: "blocked-surface", preview: `${surfaceMeta?.files?.[0] || action.surfaceId}: target surface is empty or missing. Load a valid instance before writing append-driven entries.`, nextText: ensureFinalNewline(text), blocked: true }; } const marker = analyzeEntriesMarkerContract(text); if(!marker.ok){ return { strategy: "blocked-marker-contract", preview: `${surfaceMeta?.files?.[0] || action.surfaceId}: marker contract violation (${marker.reason})`, nextText: ensureFinalNewline(text), blocked: true }; } } let plan = null; switch(action.surfaceId){ case "working": plan = buildWorkingWritePlan(action, draft, text); break; case "orientation": plan = buildOrientationWritePlan(action, draft, text); break; case "freeze": plan = buildFreezeWritePlan(action, draft, text); break; case "decisions": plan = buildDecisionsWritePlan(action, draft, text); break; case "latent": plan = buildLatentWritePlan(action, draft, text); break; case "technical": plan = buildTechnicalWritePlan(action, draft, text); break; case "handoff": plan = buildHandoffWritePlan(action, draft, text); break; case "findings": plan = buildFindingsWritePlan(action, draft, text); break; case "parking": plan = buildParkingWritePlan(action, draft, text); break; case "archive": plan = buildArchiveWritePlan(action, draft, text); break; default: plan = { strategy: "blocked", preview: `No canonical writer rule is defined for surface '${action.surfaceId}'.`, nextText: ensureFinalNewline(text), blocked: true }; } assertNoLegacyWorkstationMarkers(plan.preview); assertNoLegacyWorkstationMarkers(plan.nextText); return plan; } ``` -------------------------------- ### Build Session Handoff Write Plan Source: https://github.com/xxyoudeadpunkxx/signal-rail/blob/main/signal_rail_workstation_final.html Generates a plan for updating or inserting session handoff entries. It validates required fields like 'done', 'open', and 'next move' for new entries. ```javascript function buildHandoffWritePlan(action, draft, text) { const source = String(text || ""); const mode = String(draft._mode || "add").trim().toLowerCase(); if (mode === "edit") { const targetKey = normalizeSingleLine(draft._targetKey).toLowerCase(); if (!/^idx:\d+$/.test(targetKey)) { throw new Error("Session Handoff edit requires selecting a target entry."); } const nextText = updateHandoffEntryByIndex(source, targetKey, draft); const preview = [ "HANDOFF ENTRY UPDATE", `- target: ${targetKey}`, `- what was done: ${normalizeSingleLine(draft.delta || draft.title)}`, `- what remains open: ${normalizeSingleLine(draft.stopped || draft.risk)}`, `- next move: ${normalizeSingleLine(draft.next)}`, `- active risk: ${normalizeSingleLine(draft.risk)}` ].join("\n"); return { strategy: "canonical-entry-update", preview, nextText }; } const done = normalizeSingleLine(draft.delta || draft.title); const open = normalizeSingleLine(draft.stopped || draft.risk); const nextMove = normalizeSingleLine(draft.next); if (!done || !open || !nextMove) { throw new Error("Session Handoff requires what was done, what remains open, and next move."); } const block = [ `- date: ${new Date().toISOString().slice(0, 10)}`, `- what was done: ${done}`, `- what remains open: ${open}`, `- next move: ${nextMove}`, `- active risk: ${normalizeSingleLine(draft.risk)}` ].join("\n"); return { strategy: "canonical-entry-insert", preview: block, nextText: insertBlockInsideEntriesZone(source, block, "09_handoff_reentry.txt") }; } ```