The Interface Codex

The Controls That Inspect and Query: Exhaustive Reference for All 33 System Interfaces

33 Documented Operations Vanilla ES2020+ Architecture 9 Functional Categories Air-Gapped Local LLM
The Three Standard Questions

Every control, interface boundary, and utility in this codex answers three architectural questions: What it does (user actions, triggers, and UI changes), How it works (internal execution trace across DOM elements, state transitions, and asynchronous promises), and Why it works (software invariants, security rationale, and failure resilience).


📂 File Loading & Ingestion (4 Controls)

Foundational controls for ingesting individual Markdown documents or whole folder hierarchies into workspace memory.

Control / Action Synopsis / Target Summary
ADD FILES #fileInputLabel / #mdFileInput Opens native file selection dialog to ingest one or more .md documents.
Scan Folder #scanFolderBtn Recursively scans a chosen directory tree for Markdown files via the File System Access API.
FILES Readout #fileCountDisplay Displays real-time count of total Markdown documents currently loaded in memory.
File Ingestion Filter addFilesAndDisplay() Filters incoming files, rejects non-markdown files, skips duplicate file contents.

ADD FILES : Native File Picker

📂 File Loading & Ingestion Async Event DOM: #mdFileInput, #fileInputLabel
INTERACTION: Click #fileInputLabel -> Trigger change event on #mdFileInput -> Process FileList
What It Does

Opens the operating system's native multi-file selection picker filtered to .md documents, reads selected files asynchronously, and populates the workspace buffer.

How It Works
  1. Clicking #fileInputLabel triggers the hidden <input type="file" multiple accept=".md"> element.
  2. On change, files are mapped to an array of Promises reading text via file.text().
  3. addFilesAndDisplay() receives {name, content} objects, rejects duplicates already existing in state.loadedFiles, and selects an initial document to render.
  4. Clears the input's value so selecting the same file again triggers a fresh change event.
Why It Works

Standard HTML5 file inputs provide universal cross-browser compatibility across all desktop and mobile platforms without requiring experimental browser permissions.

Scan Folder : Recursive Directory Scanner

📂 File Loading & Ingestion Async Coroutine DOM: #scanFolderBtn
INTERACTION: Click #scanFolderBtn -> window.showDirectoryPicker() -> Recursive scan() traversal
What It Does

Prompts the user to select an entire directory tree, traverses all nested subdirectories, and loads every .md document found.

How It Works
  1. Feature-detects window.showDirectoryPicker; if unsupported, alerts the user to use the file picker or switch to Chromium.
  2. Calls window.showDirectoryPicker(), obtaining a root FileSystemDirectoryHandle.
  3. An asynchronous recursive generator scan(dirHandle) traverses directory entries using for await (const entry of dirHandle.values()).
  4. For each file ending in .md, reads content via await entry.getFile().text() and streams the file into addFilesAndDisplay().
Why It Works

Allows instant exploration of large Obsidian vaults, documentation repositories, and note collections with a single click, skipping non-markdown assets automatically.

FILES Readout : Workspace Document Counter

📂 File Loading & Ingestion Reactive Update DOM: #fileCountDisplay
INTERACTION: Triggered automatically by updateUI() -> Reflects state.loadedFiles.length
What It Does

Renders the total count of loaded Markdown documents in the retro status footer (e.g. FILES: 42).

How It Works

Whenever files are added, restored, or restarted, updateUI() executes elements.fileCountDisplay.textContent = `FILES: ${state.loadedFiles.length}`.

Why It Works

Provides immediate peripheral feedback to the user on the scale of their active workspace corpus.

File Ingestion Filter : Duplicate & Type Guard

📂 File Loading & Ingestion Pure Logic State: state.loadedFiles
INTERACTION: Invoked by addFilesAndDisplay(newFiles) -> Content deduplication & verification
What It Does

Prevents duplicate documents from cluttering the workspace and ensures only valid markdown files enter the buffer.

How It Works
  1. Filters incoming file objects by comparing filename and text content against existing entries in state.loadedFiles.
  2. If a file matches both name and content, it is skipped.
  3. Updates the status log with counts of added files and skipped duplicates (e.g. "Loaded 5 files (2 duplicates skipped).").
Why It Works

Prevents memory waste and duplicate search results when users scan overlapping folders or re-select files.


🧭 Navigation & History Stack (4 Controls)

Controls driving linear and random traversal through the document buffer.

Control / Action Synopsis / Target Summary
PREV Button #prevBtn Navigates backward in the document viewing history stack.
NEXT Button #nextBtn Navigates forward in the document viewing history stack.
Random Document Selector pickAndDisplayRandomFile() Selects an initial random file upon fresh folder ingestion.
Markdown Viewport #markdownDisplay Primary content container rendering the sanitized HTML representation of the document.

PREV Button : Historical Backtrack Navigation

🧭 Navigation & History Stack Sync Event DOM: #prevBtn
INTERACTION: Click #prevBtn -> state.historyIndex-- -> displayFile(state.history[state.historyIndex])
What It Does

Displays the previous document visited in the navigation history stack. Automatically disabled when at the beginning of the history.

How It Works

Decrements state.historyIndex, retrieves the file index from state.history, and invokes displayFile(fileIndex). updateUI() sets #prevBtn.disabled = (state.historyIndex <= 0).

Why It Works

Maintains intuitive browser-like back navigation without altering the underlying document array order.

NEXT Button : Forward Navigation & Random Step

🧭 Navigation & History Stack Sync Event DOM: #nextBtn
INTERACTION: Click #nextBtn -> Advance historyIndex or push newly discovered file
What It Does

Navigates forward through viewed documents. If already at the tip of history, randomly picks a new unread file from the loaded collection.

How It Works

If state.historyIndex < state.history.length - 1, increments historyIndex. Otherwise, randomly picks an index from state.loadedFiles, appends it to state.history, and renders the document.

Why It Works

Combines predictable forward history navigation with serendipitous serendipity-driven reading exploration.

Random Document Selector : Serendipitous Initializer

🧭 Navigation & History Stack Pure Logic State: state.history
INTERACTION: pickAndDisplayRandomFile() -> Math.floor(Math.random() * loadedFiles.length)
What It Does

Selects a random document from the workspace to initiate the reading experience when files are freshly imported.

How It Works

Generates a random integer index between 0 and state.loadedFiles.length - 1, seeds the history stack with that index, and displays the document.

Why It Works

Avoids the monotony of always opening the first alphabetical document (often an index or license file) when ingesting large vaults.

Markdown Viewport : Sanitized Display Frame

🧭 Navigation & History Stack DOM Frame DOM: #markdownDisplay
INTERACTION: Updated via displayFile() and appendAiOutput() -> Render target
What It Does

The central terminal reading viewport where rendered Markdown documents and subsequent AI dialogue responses appear.

How It Works

Constructed as an accessible <main> element styled with custom monospace typography. On file change, its inner HTML is replaced with the newly sanitized document content, followed by initial chat history seeding.

Why It Works

Provides a clean, scrollable, high-contrast reading environment that isolates document presentation from application controls.


🧠 Document Intelligence & Single-File AI (6 Controls)

Intelligence operations performed strictly against the currently active Markdown document.

Control / Action Synopsis / Target Summary
Summarize #summarizeBtn Requests a concise, structured executive summary of the current document.
Suggest #suggestQuestionsBtn Generates 3 to 5 insightful follow-up questions rendered as clickable buttons.
Ask Form #askForm Form container managing keyboard submission and event handling for inquiries.
Ask Input Field #askInput Text input field where users enter free-form follow-up questions about the active file.
Ask Submit Button #askBtn Submits the question entered in the Ask Input field to the local model.
Question Buttons .suggested-question-btn Clickable buttons representing suggested questions that trigger instant queries.

Summarize : Executive Synthesis

🧠 Document Intelligence Async API DOM: #summarizeBtn
INTERACTION: Click #summarizeBtn -> callModel() -> Append sanitized summary to #markdownDisplay
What It Does

Prompts the local model to distill the current document into a high-level summary highlighting key themes and arguments.

How It Works
  1. Locks UI controls and activates the header loader spinner.
  2. Dispatches the file text paired with the prompt: "Provide a concise summary of the following document. Highlight key points and main ideas."
  3. Captures the model response, verifies view invariance (isStale()), parses Markdown via DOMPurify, and appends the result to the display viewport.
Why It Works

Allows rapid comprehension of long technical articles, transcripts, or notes without leaving the document context.

Suggest : Interactive Inquiry Generation

🧠 Document Intelligence Async API DOM: #suggestQuestionsBtn
INTERACTION: Click #suggestQuestionsBtn -> callModel() -> Render .suggested-question-btn items
What It Does

Generates 3 to 5 probing questions regarding the document's content and formats each question as an interactive button.

How It Works

Asks the model to suggest questions a curious reader might ask. Parses lines beginning with numbers (e.g. 1. Why...) into interactive <button class="suggested-question-btn"> elements with bound click listeners.

Why It Works

Promotes deeper engagement with texts by highlighting nuances or unexplored ramifications of the author's arguments.

Ask Form : Inquiry Submission Controller

🧠 Document Intelligence Form Lifecycle DOM: #askForm
INTERACTION: Submit event -> e.preventDefault() -> askAboutCurrentFile(askInput.value)
What It Does

Captures Enter keypresses or button clicks to trigger follow-up questions without reloading the page.

How It Works

Binds a submit listener that prevents default navigation, checks if an answer is already in flight (state.isAsking), extracts trimmed text, and initiates the query.

Why It Works

Semantic form markup provides native keyboard submission handling (Enter to submit) while preserving single-page execution.

Ask Input Field : Free-Text Query Field

🧠 Document Intelligence Input Control DOM: #askInput
INTERACTION: User types question -> Managed enabled/disabled state via updateUI()
What It Does

Receives arbitrary user questions concerning the currently displayed file.

How It Works

Disabled when no files are loaded or while an inference request is in progress. Clears value on submit and automatically re-focuses when the model response completes.

Why It Works

Enables natural language follow-up conversations directly within the console without requiring modal dialogs.

Ask Submit Button : Query Dispatch Button

🧠 Document Intelligence Button Action DOM: #askBtn
INTERACTION: Click #askBtn -> Triggers #askForm submission
What It Does

Visual button to submit the question typed into the Ask Input field.

How It Works

Configured with type="submit" inside #askForm. Synchronously disabled whenever #askInput is disabled.

Why It Works

Provides an explicit touch- and mouse-accessible target alongside keyboard Enter submission.

Question Buttons : Clickable Suggestion Triggers

🧠 Document Intelligence Dynamic Elements DOM: .suggested-question-btn
INTERACTION: Click button -> askAboutCurrentFile(button.textContent)
What It Does

Clicking any generated suggestion immediately dispatches that exact question to the model.

How It Works

Constructed dynamically by suggestQuestionsBtn. Each button has a click listener invoking askAboutCurrentFile(questionText), adding the query to the conversation stack.

Why It Works

Eliminates the friction of manually copying and pasting suggested questions into the input bar.


📚 Corpus Synthesis & Multi-Document Analysis (2 Controls)

Intelligence operations performed across all documents currently loaded in the workspace.

Control / Action Synopsis / Target Summary
Ask All Files #askAllFilesBtn Queries every loaded Markdown document to synthesize cross-file answers.
Corpus Input Modal #inputModal Asynchronous modal dialog prompting the user for their cross-document inquiry.

Ask All Files : Global Corpus Synthesis

📚 Corpus Synthesis Async API DOM: #askAllFilesBtn
INTERACTION: Click #askAllFilesBtn -> showInputModal() -> Concatenate files -> callModel()
What It Does

Synthesizes an answer to a single question across all loaded documents simultaneously, citing sources across files.

How It Works
  1. Calls showInputModal() to capture the query text.
  2. Concatenates all documents in state.loadedFiles with clear delimiters (File: <name>).
  3. Dispatches the prompt to the local model, captures the response, verifies that the view hasn't been reset (isStale()), and displays the answer under an "Ask All Files" heading.
Why It Works

Acts as an ambient knowledge synthesis engine across disparate personal notes without requiring an external vector database.

Corpus Input Modal : Asynchronous Query Dialog

📚 Corpus Synthesis Promise Modal DOM: #inputModal, #inputModalField
INTERACTION: showInputModal({title, prompt}) -> Resolves with string or null
What It Does

Displays an overlay dialog requesting string input from the user with full keyboard navigation (Enter/Escape).

How It Works

Returns a Promise that unhides #inputModal, sets labels, focuses the input field, and resolves with the entered string on Confirm/Enter or null on Cancel/Escape.

Why It Works

Replaces blocking browser prompt() dialogs with a styled, non-blocking asynchronous interaction that matches the console aesthetic.


⚙️ Model Configuration & Local AI Engine (7 Controls)

Controls governing model server endpoints, discovery, and parameters.

Control / Action Synopsis / Target Summary
Model Settings Button #modelSettingsBtn Opens the Local Model Configuration dialog modal.
Server Type Selector #modelApiStyle Selects between Ollama native REST and OpenAI-compatible API endpoints.
Server URL Input #modelBaseUrl Input for configuring the local server loopback address.
Model Dropdown Selector #modelName Populated dropdown of available chat models fetched from the server.
Refresh List Button #fetchModelsBtn Actively queries the local server to refresh the model dropdown list.
Save Model Settings #saveModelSettingsBtn Validates loopback constraints and saves settings to state and storage.
Cancel Model Settings #cancelModelSettingsBtn Dismisses the model settings dialog without applying changes.

Model Settings Button : Server Configuration Opener

⚙️ Model Configuration Modal Trigger DOM: #modelSettingsBtn
INTERACTION: Click #modelSettingsBtn -> showModelSettings() -> Unhide #modelSettingsModal
What It Does

Opens the Model Settings modal dialog, pre-populating existing settings and querying available models.

How It Works

Initializes form fields from state.modelSettings (or defaults), clears error messages, unhides #modelSettingsModal, and invokes fetchAndFillModels().

Why It Works

Gives users immediate visual access to local server configuration without editing text configuration files.

Server Type Selector : Protocol Adapter Dropdown

⚙️ Model Configuration Input Control DOM: #modelApiStyle
INTERACTION: Change selection -> Adjust default URL placeholder & endpoint routing
What It Does

Switches between Ollama's native protocol and the OpenAI-compatible completions format.

How It Works

Changing selection updates the URL placeholder to the protocol's default (http://localhost:11434 for Ollama, http://localhost:8080/v1 for OpenAI) and refreshes model capability queries.

Why It Works

Provides transparent protocol switching across popular local inference runtimes without manual header configuration.

Server URL Input : Loopback Address Target

⚙️ Model Configuration Input Control DOM: #modelBaseUrl
INTERACTION: Input URL -> Validated against isLocalUrl() on change / save
What It Does

Specifies the network address of the local model daemon.

How It Works

Accepts loopback URLs. Validated by isLocalUrl() to ensure requests never leave the machine.

Why It Works

Allows users to bind custom ports (e.g. LM Studio on 1234, vLLM on 8000) while strictly maintaining the Zero-Key localhost perimeter.

Model Dropdown Selector : Capability-Filtered Picker

⚙️ Model Configuration Dynamic Select DOM: #modelName
INTERACTION: User selects model -> Captured into state.modelSettings.model
What It Does

Lists available models with disabled states for non-chat embedding models (Roadmap P2-04).

How It Works

Populated by fillModelSelect(). Capable models are listed first; embedding-only models are disabled and appended at the bottom with visual notices.

Why It Works

Prevents model selection errors and avoids failures caused by calling embedding models for text generation.

Refresh List Button : Live Endpoint Prober

⚙️ Model Configuration Async Query DOM: #fetchModelsBtn
INTERACTION: Click #fetchModelsBtn -> Query /api/tags or /models -> Re-populate #modelName
What It Does

Actively queries the configured server URL to fetch newly pulled or loaded models.

How It Works

Validates the URL with isLocalUrl(), fetches model listings, executes capability probing, and updates the select options.

Why It Works

Users can pull new models in another terminal (e.g. ollama pull phi4) and refresh the list without reloading the web page.

Save Model Settings : Configuration Committer

⚙️ Model Configuration Validation & Commit DOM: #saveModelSettingsBtn
INTERACTION: Click #saveModelSettingsBtn -> Validate -> state.modelSettings -> saveSession()
What It Does

Validates inputs, commits configuration to application state, persists settings to localStorage, and closes the modal.

How It Works
  1. Enforces non-empty URL and selected model.
  2. Verifies isLocalUrl(baseUrl); displays an inline error if external.
  3. Assigns state.modelSettings = {apiStyle, baseUrl, model}, calls saveSession(), and hides the modal.
Why It Works

Atomic validation ensures that invalid or unsafe configurations can never be committed to runtime state.

Cancel Model Settings : Dialog Dismissal

⚙️ Model Configuration Dismissal DOM: #cancelModelSettingsBtn
INTERACTION: Click #cancelModelSettingsBtn -> Hide #modelSettingsModal without mutation
What It Does

Closes the Model Settings modal without modifying existing configuration.

How It Works

Adds the hidden class to #modelSettingsModal, discarding uncommitted form adjustments.

Why It Works

Provides a safe escape route from configuration dialogs without side effects.


💾 Session Persistence & Storage Management (5 Controls)

Controls managing persistent state snapshots, hydration, and quota limits.

Control / Action Synopsis / Target Summary
Save Session #saveSessionBtn Persists the current workspace state to browser localStorage.
Restart Session #restartSessionBtn Wipes active session state and purges stored session data.
Restore Confirm #confirmRestoreBtn Confirms rehydration of a saved session discovered on page boot.
Restore Deny #denyRestoreBtn Declines session restoration to start with a fresh workspace.
Quota Circuit Breaker saveSession() try/catch Traps quota errors when session size exceeds browser limits (P2-02).

Save Session : Snapshot Serializer

💾 Session Persistence Sync Storage DOM: #saveSessionBtn
INTERACTION: Click #saveSessionBtn -> saveSession() -> localStorage.setItem('chidiMdSession', json)
What It Does

Serializes all loaded files, navigation history, active conversations, and model configurations into localStorage.

How It Works

Packages {loadedFiles, history, historyIndex, chatHistory, modelSettings} into a JSON string and writes to chidiMdSession. Updates the status log with "Session saved."

Why It Works

Users can close their browser or shut down their workstation and return directly to their exact reading and conversation state.

Restart Session : Complete State Wipe

💾 Session Persistence State Reset DOM: #restartSessionBtn
INTERACTION: Click #restartSessionBtn -> restartSession() -> Reset state & localStorage
What It Does

Wipes all in-memory files, conversations, and history, removes the saved session from localStorage, and resets the console.

How It Works

Removes chidiMdSession from localStorage, resets state.loadedFiles = [], state.history = [], state.chatHistory = [], increments state.viewId to invalidate pending requests, and resets the UI.

Why It Works

Provides a clean slate for starting a new document reading session without lingering state from previous vaults.

Restore Confirm : Session Hydration

💾 Session Persistence Hydration Action DOM: #confirmRestoreBtn
INTERACTION: Click #confirmRestoreBtn -> restoreSession() -> Hide #restoreSessionModal
What It Does

Restores previously saved workspace files and conversation threads on application startup.

How It Works

Parses the stored JSON payload, re-populates state arrays, restores the last viewed file, purges any legacy secrets, and updates the status log.

Why It Works

Gives the user explicit control over whether to resume prior work or begin fresh.

Restore Deny : Discard Saved Workspace

💾 Session Persistence Clean Start DOM: #denyRestoreBtn
INTERACTION: Click #denyRestoreBtn -> localStorage.removeItem('chidiMdSession') -> Hide modal
What It Does

Rejects restoring the saved session, clears the stored record, and presents a clean start.

How It Works

Removes chidiMdSession from localStorage, hides the modal, and leaves the console in its default ready state.

Why It Works

Allows users to cleanly discard stale sessions without manually navigating browser developer tools.

Quota Circuit Breaker : Storage Exhaustion Protector

💾 Session Persistence Exception Trap Roadmap: P2-02
INTERACTION: Catch QuotaExceededError in saveSession() -> Alert user with session MB calculation
What It Does

Traps browser storage quota exceptions when saving sessions that exceed ~5 MB and alerts the user while leaving prior saves intact.

How It Works

Wraps localStorage.setItem in a try/catch block. On exception, calculates payload megabytes and logs: "Error: Session is ~X MB; browser storage is full. Your previous save is still kept."

Why It Works

Prevents unhandled crashes and data loss when loading large corpora, preserving previous saves safely.


🛡️ Security Boundaries & Sanitization (4 Controls)

Architectural filters enforcing input validation, sanitization, and network isolation.

Control / Action Synopsis / Target Summary
DOMPurify Sanitizer convertMarkdownToHtml() Strips XSS vectors and script tags from all rendered Markdown output.
Localhost URL Enforcer isLocalUrl() Restricts network communication strictly to local loopback hosts.
Stale Response Quarantine isStale() / state.viewId Quarantines late AI responses to prevent cross-document contamination.
Legacy Credential Scrubber restoreSession() cleanup Automatically scrubs legacy API keys from older saved sessions.

DOMPurify Sanitizer : Render Security Boundary

🛡️ Security Boundaries Pure Sanitizer Decisions: D-006, P1-01
INTERACTION: DOMPurify.sanitize(marked.parse(content)) -> Verified safe HTML string
What It Does

Sanitizes all HTML generated from Markdown files and model responses before it touches the DOM.

How It Works

Filters AST HTML output via pinned DOMPurify 3.4.16, stripping inline event handlers (onerror), script elements, and javascript: URI schemes.

Why It Works

Guarantees that untrusted or hostile Markdown documents cannot execute arbitrary code in the user's browser.

Localhost URL Enforcer : Network Perimeter Guard

🛡️ Security Boundaries URL Validator Decision: D-007
INTERACTION: isLocalUrl(url) -> Strict loopback verification before fetch()
What It Does

Ensures that outbound model requests are only sent to the user's local machine.

How It Works

Parses the hostname via the standard URL constructor and validates that it matches localhost, 127.0.0.1, [::1], or ends with .localhost.

Why It Works

Prevents data exfiltration and accidental requests to third-party cloud APIs.

Stale Response Quarantine : View Invariance Guard

🛡️ Security Boundaries Concurrency Control Roadmap: P2-05
INTERACTION: Capture state.viewId at request start -> Check isStale() at resolution
What It Does

Drops responses that arrive after the user has navigated to another document or restarted the session.

How It Works

Increments state.viewId on document change. When a response resolves, verifies that the active view ID matches the captured view ID. If mismatched, drops output and logs a notice.

Why It Works

Protects conversation integrity from race conditions caused by slow model generation.

Legacy Credential Scrubber : Storage Sanitizer

🛡️ Security Boundaries Migration Routine Decision: D-007
INTERACTION: restoreSession() -> delete parsedData.apiKey -> saveSession()
What It Does

Detects and scrubs legacy cloud API keys from sessions created by older versions of the app.

How It Works

During session restoration, checks for apiKey or geminiChatHistory properties, removes them from state, and re-saves the clean session.

Why It Works

Ensures user secrets are completely evicted from persistent storage in compliance with the Zero-Key Mandate.


🖥️ Operational Feedback & Console Telemetry (3 Controls)

UI indicators providing operational status and activity telemetry.

Control / Action Synopsis / Target Summary
SYSTEM LOG Readout #messageBox Status bar rendering system events, operational state, and error alerts.
Activity Loader #loader Animated console spinner indicating background model inference.
Console Title Header #mainTitle Top console header displaying product title and active document filename.

SYSTEM LOG Readout : Console Message Bar

🖥️ Operational Feedback Telemetry Bar DOM: #messageBox
INTERACTION: Updated via elements.messageBox.textContent = `SYSTEM LOG: ${msg}`
What It Does

Renders real-time feedback on user actions, model generation progress, and system alerts.

How It Works

Displays standardized status messages (e.g. "SYSTEM LOG: Standby.", "SYSTEM LOG: Answering question...", "SYSTEM LOG: Error: ...").

Why It Works

Provides a consistent, non-intrusive status readout that avoids distracting popup notifications.

Activity Loader : Inference Activity Spinner

🖥️ Operational Feedback Visual Feedback DOM: #loader
INTERACTION: Toggled via #loader.classList.remove('hidden') / add('hidden')
What It Does

Displays an animated spinner in the console header during active model inference or file loading.

How It Works

Controlled by setLoading(true/false). Unhides the CSS animation when an operation begins and hides it upon completion.

Why It Works

Informs users that the system is processing their request, especially during longer model generations.

Console Title Header : Header & Breadcrumb Display

🖥️ Operational Feedback Header Bar DOM: #mainTitle
INTERACTION: Reflects active file name: 'chidi.md // '
What It Does

Displays the application title and active document filename in retro terminal styling.

How It Works

Updates on document navigation to display chidi.md // <filename>, resetting to default when no file is active.

Why It Works

Gives users clear, persistent context on which document they are currently viewing.


🛠️ Developer & Verification Tooling (4 Controls)

Command-line utilities and test harnesses ensuring code quality and safety.

Control / Action Synopsis / Target Summary
serve.py python3 tools/serve.py Local development server with no-cache headers and browser auto-launch.
check_docs.py python3 tools/check_docs.py Automated documentation auditor verifying links, roadmap items, and decisions.
check_structure.py python3 tests/check_structure.py Fast linting script verifying DOM ID wiring and sanitization rules.
Playwright Smoke Suite cd tests/e2e && npm test 34-test dual-browser end-to-end verification suite in Chromium and Firefox.

serve.py : Development Server & Cache Buster

🛠️ Developer Tooling CLI Utility File: tools/serve.py
SYNOPSIS: python3 tools/serve.py [--port 8000] [--no-browser]
What It Does

Serves the application locally with strict Cache-Control: no-cache headers and opens the page in Google Chrome.

How It Works

Extends Python's http.server.SimpleHTTPRequestHandler to send no-cache headers on all responses, preventing stale browser caching during local development.

Why It Works

Ensures developers always test the latest code modifications without aggressive browser caching issues.

check_docs.py : Documentation Truth Auditor

🛠️ Developer Tooling CLI Auditor File: tools/check_docs.py
SYNOPSIS: python3 tools/check_docs.py [--template]
What It Does

Scans documentation for broken links, duplicate decisions, invalid roadmap checkboxes, and unfulfilled placeholders.

How It Works

Uses regular expressions to validate relative paths, decision references (D-NNN), roadmap IDs (P#-##), and handoff session logs across all documentation files.

Why It Works

Maintains absolute consistency between codebase changes and documentation records across development sessions.

check_structure.py : Wiring & Lint Auditor

🛠️ Developer Tooling CLI Linter File: tests/check_structure.py
SYNOPSIS: python3 tests/check_structure.py
What It Does

Audits index.html and main.js to confirm that all DOM element references match and sanitization rules are respected.

How It Works

Extracts all IDs from index.html and verifies that every document.getElementById() call targets a valid, uniquely defined ID. Rejects un-sanitized innerHTML assignments and unpinned CDN scripts.

Why It Works

Catches missing elements, typos, and security regressions before code reaches staging or production.

Playwright Smoke Suite : Dual-Browser E2E Harness

🛠️ Developer Tooling Test Harness File: tests/e2e/smoke.spec.js
SYNOPSIS: cd tests/e2e && npm test
What It Does

Runs 34 automated smoke tests in headless Chromium and Firefox, validating all key user flows offline.

How It Works

Uses Playwright to boot the app with local SRI-pinned libraries, mock model servers, test XSS sanitization, verify storage quota handling, and exercise concurrent request guards.

Why It Works

Provides conclusive, observed proof of feature correctness and security enforcement across multiple browser engines.