diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0f99b09 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: HumOS CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + tests: + name: Tests (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.8", "3.11", "3.13"] + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Compile Python sources + run: python -m compileall -q src tests + + - name: Run regression tests + env: + PYTHONPATH: src + run: python -m unittest discover -s tests -v + + package: + name: Build Python package + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install build frontend + run: python -m pip install --upgrade build + + - name: Build wheel and source distribution + run: python -m build src diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fd8ce6b..d1f9afb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,25 +8,25 @@ ## 1. Code of Technical Conduct & Architectural Philosophy -The HumOS project enforces strict deterministic engineering standards. Unlike conventional conversational agent frameworks, HumOS and its Domain-Specific Language (LINGHOS) operate as an intermediate deterministic representation (IR) between biological cognitive volatility and downstream Large Language Model (LLM) execution kernels. +HumOS aims for predictable, testable behavior in its implemented compiler and state model. LINGHOS can serve as a compact intermediate representation for downstream Large Language Model (LLM) applications, but the current repository does not enforce deterministic LLM inference. Every contribution—whether a parser patch, visual cockpit enhancement, or documentation revision—must strictly preserve: -1. **Zero Hallucination Tolerance:** The compiler and runtime must never output non-deterministic or speculative state parameters. -2. **Strict Context Budgeting:** Token overhead must be minimized at all serialization boundaries. -3. **Formal Invariant Guarantees:** Core Self isolation (`CS_SECURE`), spatial proximity mathematics, and thermodynamic accounting (`RAM`, `BPM`) cannot be bypassed or weakened. +1. **Deterministic compiler behavior:** For a fixed source and runtime state, supported parsing and serialization paths must be repeatable and covered by tests. +2. **Measured context budgeting:** Token-efficiency claims must identify the tokenizer, corpus, and measurement method; do not publish unverified reduction percentages. +3. **Explicit simulation boundaries:** State that VM, RAM, BPM, and defense values are application-level models unless real host-level enforcement or sensor integration exists. --- ## 2. Primitive Proposal Protocol (PPP) -Any addition to the LINGHOS standard library, language grammar, or execution primitives must follow the **Primitive Proposal Protocol**. Unchecked keyword proliferation bloats the AST, consumes token budget, and introduces downstream reasoning ambiguities. +Any addition to the LINGHOS language, documented primitives, or execution behavior must follow the **Primitive Proposal Protocol**. Keep proposed syntax clearly distinguished from runtime-supported commands; the current parser is line-oriented and does not construct a formal AST. ### 2.1 Criteria for Primitive Acceptance Before submitting a proposal for a new primitive (e.g., `MEMORY.*`, `THREAD.*`, `SHIELD.*`), the author must demonstrate that: 1. **Non-Redundancy:** The capability cannot be synthesized using an existing primitive sequence (e.g., `RAM.alloc()` + `THREAD.spawn()`). -2. **Context Window Efficiency:** The serialized token footprint of the primitive must not exceed **24 tokens** under standard UTF-8 Byte-Pair Encoding (BPE). +2. **Context Window Efficiency:** Report the token footprint using a named tokenizer and version. Apply a 24-token target only when the tokenizer and measurement corpus are specified; UTF-8 encoding is not itself a BPE tokenizer. 3. **Deterministic State Transition:** The primitive must yield a mathematically provable state change in the runtime memory model (e.g., deallocating RAM, clamping BPM, or altering threat radius). -4. **Backward Parser Compatibility:** The addition must not introduce Lookahead conflicts ($LR(1)$ shift-reduce or reduce-reduce ambiguities) in `linghos/parser.py`. +4. **Backward Parser Compatibility:** Add regression tests for supported parser behavior and malformed input. The current parser is hand-written and is not an LR(1) parser. ### 2.2 Formal RFC Template for Primitive Proposals Every primitive proposal must be submitted as an issue or pull request referencing `docs/SPEC.md` using the following technical schema: @@ -49,10 +49,10 @@ Every Pull Request (PR) must satisfy an automated and manual verification checkl ```mermaid flowchart TD - PR[Pull Request Submitted] --> CHECK_SYNTAX[1. Strict Grammar & AST Parser Audit] - CHECK_SYNTAX --> CHECK_LEAK[2. Context Isolation & Leak Proof] - CHECK_LEAK --> CHECK_TOKEN[3. Token Overhead & Footprint Benchmark] - CHECK_TOKEN --> CHECK_INVARIANT[4. Thermodynamic Invariant Unit Tests] + PR[Pull Request Submitted] --> CHECK_SYNTAX[1. Supported Grammar & Parser Regression Tests] + CHECK_SYNTAX --> CHECK_LEAK[2. State Boundary Model Tests] + CHECK_LEAK --> CHECK_TOKEN[3. Reproducible Token Measurement] + CHECK_TOKEN --> CHECK_INVARIANT[4. Runtime State Model Tests] CHECK_INVARIANT --> PASS[All Invariants Verified -> Approved for Merge] CHECK_SYNTAX -- Failure --> REJECT[PR Rejected: Syntax Invariant Violation] @@ -64,20 +64,20 @@ flowchart TD ### 3.1 Step-by-Step Verification Checklist - [ ] **1. Strict Grammar & Lexer Compliance** - - All `.lghos` and `.lgh` examples compile cleanly through `linghos/compiler.py` without syntax warnings. + - Changed and referenced examples are checked against the currently supported parser/compiler subset. - Semicolons, block closures (`Main() { ... }`), directives (`/SET_Lockdown_Mode`), and macro headers (`#include`) strictly follow the grammar defined in `docs/SPEC.md`. - No trailing whitespace or broken delimiters. - [ ] **2. Context Leak Verification (Zero Prompt Bleeding)** - - Variables declared in local sandboxes (`PRS_VM`, `LP_Ambient_VM`) must not leak into primary memory buffers or adjacent threads. - - Injected LLM system payloads must strictly contain isolated target profiles without unescaped cross-talk. + - Tests must verify the modeled target/VM associations and ensure no accidental cross-state mutation. Do not describe application VM objects as OS-level isolation. + - Prompt payload construction must escape and delimit untrusted source content; downstream LLM policy remains outside this runtime's enforcement boundary. - [ ] **3. Token Footprint Benchmark** - - The compiled state vector generated by the runtime must demonstrate at least an **85% reduction** in token count relative to the raw input stream. - - Serialization overhead must be verified via character and token profiling (`len(json.dumps(state_vector)) <= 512 bytes` for nominal workloads). + - Token claims must include a reproducible raw-input corpus, tokenizer name/version, serialization rules, repeated measurements, and raw results. Do not impose an 85% reduction target until a baseline benchmark has been published. + - Track byte size and token count as separate measurements; bytes are not tokens. - [ ] **4. Thermodynamic Invariant Unit Tests** - - Memory bounds test: Verify that `RAM.purge()` resets utilization to $\le 20\%$. + - Model test: Verify that `Call >> Drop_All_Background_Threads;` produces the documented modeled telemetry in the current implementation. Treat `RAM.purge()` as specification-only until implemented. - Spatial radius test: Verify that threat proximity radius satisfies $r = \max(50.0, 175.0 - (W \cdot 6.5 + C \cdot 5.5))$. - Defensive clamp test: Verify that `Ice_shield` prevents thermal throttling when RAM exceeds $85\%$. @@ -100,10 +100,10 @@ Commit messages must strictly follow the **Conventional Commits 1.0.0** specific | Scope | Description | Permitted Types | Example | | :--- | :--- | :--- | :--- | -| `lghos` | Core LINGHOS language grammar, lexical scanner, AST additions | `feat`, `fix`, `refactor` | `feat(lghos): add THREAD.suspend opcode support` | -| `parser` | AST compilation, parsing engine, statement normalization | `fix`, `perf`, `test` | `fix(parser): resolve lookahead stall on nested IF blocks` | +| `linghos` | LINGHOS language syntax, lexical scanner, compiler and parser behavior | `feat`, `fix`, `refactor` | `fix(linghos): add regression coverage for supported syntax` | +| `parser` | Parsing engine, block scanning, statement normalization | `fix`, `perf`, `test` | `fix(parser): handle malformed nested IF blocks safely` | | `cockpit` | Web UI, interactive SVG radar canvas, HTML/JS console | `feat`, `fix`, `style` | `feat(cockpit): render active defense labels on SVG perimeter` | -| `gap` | G.A.P. security module, recursion interrupts, kill-switch | `sec`, `fix`, `feat` | `sec(gap): enforce mandatory timeout on unclassified inputs` | +| `gap` | G.A.P. protocol specification and supported defensive state transitions | `sec`, `fix`, `feat` | `docs(gap): clarify protocol runtime implementation boundary` | | `spec` | Formal documentation, language contracts, developer guides | `docs` | `docs(spec): document RAM.alloc memory invariants` | | `storage` | Local scenario persistence, JSON serializations, sessions | `feat`, `fix`, `test` | `feat(storage): support custom symbol de-registration` | @@ -111,9 +111,9 @@ Commit messages must strictly follow the **Conventional Commits 1.0.0** specific #### ✅ Valid Commit Messages ```bash -feat(lghos): implement RAM.alloc buffer reservation syntax +feat(linghos): implement the supported LINGHOS syntax fix(parser): prevent variable leakage across multi-VM declarations -sec(gap): force TRIGGER.kill_switch execution on heart rate breach +fix(gap): clarify protocol runtime enforcement boundary docs(spec): update Section 3 primitive matrix with arity contracts ``` @@ -136,7 +136,7 @@ To test contributions locally: git clone https://github.com/SystemAdmin01/HumOS.git cd HumOS -# 2. Validate compiler and storage engine +# 2. Validate compiler and storage engine (implemented subset) python3 -c " from src.linghos.compiler import LINGHOSCompiler from src.linghos.storage import GLOBAL_STORAGE @@ -146,7 +146,10 @@ assert res['telemetry']['ice_shield'] is True print('Compiler verification passed.') " -# 3. Launch test cockpit instance +# 3. Run the regression tests +PYTHONPATH=src python3 -m unittest discover -s tests -v + +# 4. Launch the local Cockpit python3 src/app.py ``` diff --git a/README.md b/README.md index b918066..7ace8f8 100644 --- a/README.md +++ b/README.md @@ -1,199 +1,206 @@ -
- # 🧠 HumOS — Human Operating System -### *Your brain runs on an OS. HumOS gives you root access.* +### Your mind is not broken. It deserves an explicit operating system. -**An engineering-based cognitive framework for ADHD, neurodivergence, and overthinkers.** -*Transform mental friction into structured cybernetic clarity — using computer architecture logic.* +**HumOS is an opinionated, low-overhead cognitive state-vector framework for ADHD, neurodivergent workflows, and people who overthink.** It is designed to turn unstructured inputs—including emotional vents, competing priorities, and noisy context—into compact, inspectable state through explicit LINGHOS authoring and serialization. The current Python runtime compiles a supported LINGHOS subset; automatic natural-language demodulation is an architectural goal, not a shipped feature. ---- +[![Architecture Spec: 2.1.0-REV4](https://img.shields.io/badge/Architecture%20Spec-2.1.0--REV4-7857C5)](#architecture) +[![Python Package: 1.0.0](https://img.shields.io/badge/Python%20Package-1.0.0-3776AB)](#quick-start) +[![Security: G.A.P. protocol](https://img.shields.io/badge/Security-G.A.P.--001-2E8B57)](#gap-security-layer) +[![GUI: Cockpit Ready](https://img.shields.io/badge/GUI-Cockpit%20Ready-1677B8)](#humos-cockpit) +[![Languages: EN | IT](https://img.shields.io/badge/Languages-EN%20%7C%20IT-555555)](#documentation) +[![License: CC BY-NC 4.0](https://img.shields.io/badge/License-CC%20BY--NC%204.0-blue.svg)](LICENSE.txt) -[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.txt) -[![Language: LINGHOS | Python](https://img.shields.io/badge/Language-LINGHOS%20%7C%20Python%203.11+-cyan.svg)]() -[![Architecture: Cognitive OS](https://img.shields.io/badge/Architecture-Cognitive%20OS%20v2.1-purple.svg)]() -[![Status: Production Ready](https://img.shields.io/badge/Status-Active%20Development-success.svg)]() -[![Platform: macOS & Windows](https://img.shields.io/badge/Platform-macOS%20%7C%20Windows%20%7C%20Linux-lightgrey.svg)]() +[English documentation](docs/GUIDE.md) · [Documentazione italiana](docs/GUIDE_IT.md) · [HumOS Cockpit](src/linghos/cockpit.html) · [Examples](examples/) --- -[🇮🇹 Documentazione Italiana](./docs/it/README.md) • [🇬🇧 English Documentation](./docs/en/README.md) • [🛡️ Cockpit Web UI](#-interactive-cockpit--visual-compiler) • [🩹 Protocols](./protocols/en/) +![HumOS Cockpit preview](assets/humos_cockpit_preview.png) -
+## What HumOS does ---- +HumOS applies operating-system concepts to cognitive self-management. It treats attention, working memory, recurring thought loops, perceived threats, and personal boundaries as explicit state that can be named, inspected, and handled through a small domain-specific language. -

- HumOS Cockpit Preview -

+| Cognitive signal | HumOS model | Intended role | +| :--- | :--- | :--- | +| Working-memory overload | RAM pool and memory buffers | Make cognitive load visible and support explicit cleanup | +| Rumination and repetitive thought | CPU / associative loop | Detect repeated cycles and provide interruption paths | +| External stressors | Threat targets with weight and criticality | Represent perceived impact and proximity | +| Self-regulation strategies | Defense shields | Model boundaries and protective responses | +| Personal and external context | Isolated virtual-machine concepts | Keep distinct contexts from being conflated | +| Core identity and boundaries | Core Self (CS) state | Make the protected state explicit | -
+HumOS is a cognitive organization and reflection framework, not a medical device or a substitute for professional care. -> *"Your mind is not broken. It just lacks an explicit operating system."* +## Architecture -
+The execution path is designed to move from noisy human input to a compact, inspectable representation before downstream semantic processing. ---- +```mermaid +flowchart TD + INPUT["Raw Cognitive Input / Emotional Vent"] + FILTER["HumOS Signal-to-Noise Filter"] + COMPILER["LINGHOS Primitive Compiler"] + GAP["G.A.P. Threat Sandbox & Kill-Switch Policy"] + LLM["LLM Semantic Processor & Cockpit GUI"] -## 🖥️ What is HumOS? + INPUT --> FILTER --> COMPILER --> GAP --> LLM +``` -**HumOS** bridges cognitive psychology, ADHD management, and operating system principles. Instead of ambiguous emotional journaling, HumOS maps neurodivergent cognitive states directly to computer architecture: +> **Implementation boundary:** This diagram describes the intended end-to-end architecture. In the current package, users author LINGHOS scripts which are parsed/compiled by the Python runtime and visualized in the Cockpit. There is no shipped natural-language/emotional-vent classifier, operating-system-level VM sandbox, enforced G.A.P. watchdog or `TRIGGER.kill_switch()` primitive, and no built-in external LLM client. See the [implementation-status matrix](docs/SPEC.md#13-implementation-status-and-conformance-boundary). -| Human Cognitive State | HumOS Cybernetic Mapping | Engine Role | -| :--- | :--- | :--- | -| **Working Memory** | **RAM Memory Pool** | Monitored to avoid cognitive leaks and thrashing | -| **Anxiety / Rumination** | **CPU-Loop / Infinite Execution** | High-cycle drain stopped via interrupt triggers | -| **Interpersonal Threats** | **Threat Targets with Weight & Criticality** | Positioned dynamically in visual proximity arena | -| **Self-Regulation Skills** | **Defense Shields (Ice Shield, Double-Bottom)** | Firewalls separating raw data from emotional charge | -| **Emotional Boundaries** | **Sandbox Virtual Machines (PRS_VM, EXT_VM)** | Isolates volatile variables from the core identity | -| **Core Vulnerability** | **CS (Core Self) State [SECURE, EXPOSED, UNLOCKED]** | Protected kernel status regulating defensive posture | -| **Sensory / Panic Overwhelm** | **Thermal Throttling & Biofeedback Clamps** | Heart-rate dampening and physiological resets | +### The core layers ---- +1. **Input conditioning (architectural goal)** — the intended design separates useful signal from repetition, ambiguity, and irrelevant context; an automatic natural-language filter is not shipped yet. +2. **LINGHOS DSL and compiler** — lets users express cognitive state through the implemented subset of explicit primitives and a constrained, line-oriented parser; the design specification describes a broader future language. +3. **G.A.P. security layer** — GAP-001 (**Active Paranoia Management**): defines sandbox boundaries, loop-interruption policies, threat handling, and proposed hard-stop behavior; only part of the model is currently represented in the runtime. +4. **Downstream LLM integration and HumOS Cockpit** — the compiler output can be consumed by an external LLM integration; the repository itself does not call an LLM. The Cockpit makes modeled state, telemetry, and defensive actions inspectable. -## ⚡ LINGHOS — The Cybernetic Language of the Mind -**LINGHOS** is the domain-specific language (DSL) powering HumOS. Write readable architectural code to diagnose, isolate, and defend your mental state: +## LINGHOS — the cognitive DSL -```linghos -// INCIDENT: Toxic variable attempting emotional drain -#include +LINGHOS (**Language for Interfacing Neurodivergent Gestalt Human Operating Systems**) is the low-level language of HumOS. It provides a compact, readable way to declare targets, assign state, invoke protections, and describe bounded actions. -Get: HostileTarget(htg)[8], ChaoticEvent(evt)[6]; -Set_CriticVal >> htg = [9] +```linghos +// Example: isolate a high-priority stressor +Get: HostileTarget(target)[8]; +Set_CriticVal >> target = [9]; Main() { - // 1. Isolate threats into high-priority sandboxes @Start>(HP_EXT_Defense_VM) { - ON> htg, evt; + ON> target; } - // 2. Intercept loop & engage cryogenic shields if core exposed IF(CS_EXPOSED) { Call >> Ice_shield; Call >> Double_Bottom_Shield; - OVR >> (DDS, ADS); - } - - // 3. Complete emotional lockdown: sever bridges & fidelity - /SET_Lockdown_Mode { - Take_DOWN(all) > (htg)'s_Core - Close(all) > (htg)'s_bridges } <<@end } ``` -The HumOS compiler parses the code, evaluates thermodynamic telemetry, calculates threat orbits, and outputs immediate, structured mitigation steps. +The grammar, primitives, and language contract are documented in the [LINGHOS specification](docs/SPEC.md). Runnable scenarios are available in [examples/](examples/). ---- +## G.A.P. security layer -## 🛡️ Interactive Cockpit & Visual Compiler +**G.A.P. — Active Paranoia Management (GAP-001)** is HumOS's cognitive-security and containment protocol. It defines a vocabulary and policy model for untrusted input, modeled target isolation, loop-interruption responses, and a proposed hard-stop path. The current runtime does not enforce a G.A.P. watchdog or hard kill-switch. -The **HumOS Cockpit** (`src/linghos/cockpit.html`) is a standalone cybernetic console running locally in your browser: +Key concepts include: -* 🎯 **Dynamic Threat Proximity Radar**: Renders real-time orbits where threat distance is directly determined by emotional weight $[1..10]$ and criticality $[1..10]$. -* 🛡️ **Active Defense Shields**: Visual representation of deployed shields (`Ice Shield`, `Double-Bottom`, `Lockdown`) buffering the Core. -* 🖱️ **Drag-and-Drop Defense Palette**: Drag shields directly onto the arena to synthesize LINGHOS code automatically. -* 📡 **Live Thermodynamic Telemetry**: Real-time meters for **RAM %**, **BPM Heart Rate**, **Core Self (CS) State**, and **Thermal Throttling Alert**. -* 🤖 **Autonomous Symbol Registry**: Dynamically discovers and learns custom skills and macro definitions on the fly. -* 📖 **Built-in Interactive Command Manual**: Full clickable reference for all language constructs. +- **Guard:** define boundaries around protected state and isolate untrusted or high-criticality inputs. +- **Analyze:** inspect state, threat criticality, loop behavior, and context-boundary violations. +- **Patch:** apply a mitigation, clear or quarantine state where supported, and stop execution when a configured threshold is crossed. ---- +G.A.P. is a framework-level protection model. Its guarantees depend on the runtime primitives and enforcement paths actually enabled; the protocol documentation is not an independent security certification. + +See the [Security Policy](SECURITY.md), [Italian Security Policy](docs/SECURITY_IT.md), and [G.A.P. protocol materials](protocols/). + +## HumOS Cockpit -## 🚀 Quick Start (Instant Launch) +The **HumOS Cockpit GUI** is a local, browser-based visual console. It keeps the human-facing experience central rather than reducing HumOS to a DSL or command-line tool. -### 🍎 Option 1 — macOS One-Click App (Recommended) -1. Download [**HumOS.app.zip**](https://github.com/SystemAdmin01/HumOS/releases) from Releases. -2. Unzip and double-click **`HumOS.app`**. -3. Your browser automatically opens at `http://127.0.0.1:8080`. +![Cockpit source preview](assets/humos_cockpit_preview.png) -*(First-time macOS notice: Right-click `HumOS.app` → **Open**).* +The Cockpit is designed to provide: + +- **Threat Proximity Radar** — visualizes threat targets using their configured weight and criticality. +- **Defense Shield Controls** — represents protections such as Ice Shield, Double-Bottom, and Lockdown. +- **Drag-and-Drop Defense Palette** — lets users compose defensive actions visually and generate corresponding LINGHOS structures. +- **Live Telemetry** — surfaces RAM usage, BPM, Core Self state, and thermal-throttling indicators where available. +- **Symbol Registry** — exposes custom symbols and reusable command definitions. +- **Interactive Command Manual** — makes language constructs discoverable from the interface. + +The frontend is located at [`src/linghos/cockpit.html`](src/linghos/cockpit.html); the local application entry point is [`src/app.py`](src/app.py). + +## Benchmarks: determinism and token efficiency + +The following matrix captures **unverified planning estimates and design targets** for a comparable input—not measurements produced by this repository. Treat the token ranges as hypotheses until benchmark data is published. + +| Performance Metric | Natural Language Prompting | LINGHOS Serialized Vector | System Advantage | +| :--- | :--- | :--- | :--- | +| **Context Window Footprint** | ~650–1,200 tokens | ~90–180 tokens | **~80%–85% fewer tokens*** | +| **Parsing & Execution Latency** | Variable; interpretation can drift | Rule-based, line-oriented parser | **Repeatable rules; latency measurement pending** | +| **State Vector Integrity** | Implicit state; omissions and drift are possible | Explicit target/state fields with subset diagnostics | **Inspectable structure; full schema validation is pending** | +| **Memory Protection** | Context can accumulate across turns | Modeled RAM accounting; `RAM.purge()` remains specification-only | **Inspectable resource model; no hard memory reset yet** | +| **Loop & Overthink Control** | Retry and loop behavior often sits outside the prompt | G.A.P. interruption policy (watchdog pending) | **Explicit policy path; hard termination is not yet implemented** | + +\* Token figures are estimates and depend on the input, tokenizer, and serialization format. The reduction assumes like-for-like inputs; reproduce measurements with the same tokenizer and a published benchmark corpus before treating them as performance claims. Deterministic serialization does **not** make downstream LLM inference deterministic. + +## Quick start + +### Run from source + +Requirements: Python 3.8+ (as declared by the package metadata). -### 💻 Option 2 — Run from Source (Universal) ```bash -# Clone the repository git clone https://github.com/SystemAdmin01/HumOS.git cd HumOS/src - -# Launch the visual cockpit python3 app.py ``` -*Zero external dependencies required. Pure Python 3 standard library + vanilla web standards.* - ---- -## 📁 Repository Architecture +The local server starts the Cockpit; open the local address printed by the application in your browser. The project is designed to use Python's standard library and browser-native HTML, CSS, and JavaScript. -The codebase follows enterprise repository standards: - -```text -HumOS/ -├── assets/ # Media, high-resolution screenshots & UI previews -│ └── humos_cockpit_preview.png -│ -├── docs/ # Comprehensive documentation -│ ├── it/ # 🇮🇹 Italian manual & full LINGHOS reference -│ └── en/ # 🇬🇧 English manual & complete framework guide -│ -├── examples/ # Executable LINGHOS scripts & scenarios -│ ├── adhd_ram_flush.lgh # Instant cognitive memory purger -│ ├── incident_01.lgh # Complete perimeter defense sample -│ ├── GAP-001_paranoia.lgh # Chaotic loop interrupt implementation -│ └── demo_pythonic.py # Python SDK integration demonstration -│ -├── protocols/ # Tactical cognitive intervention protocols -│ ├── it/ # Italian protocol specifications (G.A.P., Safe Mode) -│ └── en/ # English protocol specifications -│ -├── src/ # Core Python Engine & Interactive Cockpit -│ ├── app.py # Server entrypoint -│ ├── HumOS_Cockpit.command # Native macOS executable launcher script -│ ├── pyproject.toml # Modern packaging configuration -│ └── linghos/ # Core language compiler package -│ ├── compiler.py # Lexer, AST evaluator & symbol learner -│ ├── kernel.py # Cognitive OS runtime state manager -│ ├── models.py # Domain dataclasses & telemetry structures -│ ├── parser.py # LINGHOS grammar engine -│ ├── web.py # Low-latency local HTTP & REST API server -│ └── cockpit.html # Interactive visual frontend application -│ -├── updates/ # Version changelogs and system patches -│ ├── Patch00-ITA.md -│ └── Patch00-ENG.md -│ -├── LICENSE.txt # MIT Open Source License -└── README.md # Repository landing page -``` +### macOS application ---- +Prebuilt macOS packages, when published, are available from [GitHub Releases](https://github.com/SystemAdmin01/HumOS/releases). Follow the release-specific instructions included with the package. -## 🩹 Standard Protocols Catalog +## Documentation -| Protocol ID | Classification | Objective | Implementation | +| Documentation | English Version | Versione Italiana | Scope | | :--- | :--- | :--- | :--- | -| **`PATCH-00`** | System Lockdown | Safe Mode Offline: complete isolation & external input disconnect | [`updates/Patch00-ENG.md`](./updates/Patch00-ENG.md) | -| **`GAP-001`** | Loop Interrupt | G.A.P. Protocol: Active paranoia management & unclassified loop brake | [`protocols/en/GAP-001-protocol.md`](./protocols/en/GAP-001-protocol.md) | +| **Language Spec** | [`docs/SPEC.md`](docs/SPEC.md) | [`docs/SPEC_IT.md`](docs/SPEC_IT.md) | Formal syntax, primitives, and implementation boundaries | +| **Developer Guide** | [`docs/GUIDE.md`](docs/GUIDE.md) | [`docs/GUIDE_IT.md`](docs/GUIDE_IT.md) | Pipeline walkthrough, runtime concepts, and prompt-injection considerations | +| **Code Examples** | [`examples/`](examples/) | [`examples/`](examples/) | LINGHOS scripts and Python integration examples | +| **Contribution** | [`CONTRIBUTING.md`](CONTRIBUTING.md) | [`docs/CONTRIBUTING_IT.md`](docs/CONTRIBUTING_IT.md) | Pull-request verification and contribution conventions | +| **Security Protocol** | [`SECURITY.md`](SECURITY.md) | [`docs/SECURITY_IT.md`](docs/SECURITY_IT.md) | Vulnerability disclosure, threat model, and G.A.P. limits | ---- +### Example scenarios -## 🌐 Language Areas / Aree Linguistiche +- [Loop isolation](examples/01_loop_isolation.lghos) +- [RAM dump](examples/02_ram_dump.lghos) +- [G.A.P. loop interruption](examples/GAP-001_paranoia_break.lgh) +- [Working-memory flush](examples/adhd_ram_flush.lgh) +- [Incident response](examples/incident_01.lgh) +- [Python integration](examples/demo_pythonic.py) -* 🇮🇹 **[Documentazione Ufficiale in Italiano](./docs/it/README.md)** — Leggi la guida approfondita, il manifesto di ingegneria cognitiva e la sintassi completa di LINGHOS. -* 🇬🇧 **[English Official Documentation](./docs/en/README.md)** — Read the core framework architecture, ADHD operating models, and LINGHOS manual. +## Repository layout ---- +```text +HumOS/ +├── assets/ # Cockpit screenshots and visual assets +├── docs/ # English and Italian specifications and guides +├── examples/ # LINGHOS scripts and Python examples +├── protocols/ # G.A.P. and cognitive safety protocols (EN / IT) +├── src/ +│ ├── README.md # Python package installation and usage +│ ├── pyproject.toml # Package metadata (linghos 1.0.0) +│ ├── app.py # Local application entry point +│ ├── HumOS_Cockpit.command +│ └── linghos/ +│ ├── compiler.py # LINGHOS compiler +│ ├── parser.py # Supported syntax interpreter +│ ├── syntax.py # Shared normalization and block scanning +│ ├── kernel.py # Cognitive runtime state model +│ └── cockpit.html # HumOS Cockpit GUI +├── tests/ # Parser/compiler and example smoke tests +├── .github/workflows/ci.yml # Python matrix tests and package build +├── updates/ # Release notes and patches +├── CONTRIBUTING.md +├── LICENSE.txt +├── README.md +└── SECURITY.md +``` -## 📄 License +## Contributing -Distributed under the **MIT License**. See [`LICENSE.txt`](LICENSE.txt) for more details. +Contributions to the DSL, kernel, security protocols, and Cockpit are welcome. Please read the [English contribution guide](CONTRIBUTING.md) or [guida italiana](docs/CONTRIBUTING_IT.md) before opening a pull request. ---- +## License -
+HumOS is distributed under the [Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0)](LICENSE.txt). Commercial use is not permitted under the repository license. -**HumOS Project** • Designed with precision by [SystemAdmin01](https://github.com/SystemAdmin01) -*Cognitive Engineering for the Neurodivergent Mind.* +--- -
+**HumOS** · Cognitive engineering for the neurodivergent mind. +Designed and maintained by [SystemAdmin01](https://github.com/SystemAdmin01). diff --git a/SECURITY.md b/SECURITY.md index 44963b4..cf3af52 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,8 +1,8 @@ # HumOS & LINGHOS Cognitive Security Policy **Document Identifier:** `SEC-POLICY-20261108-EN` -**Standard Status:** `Production Security Standard & Vulnerability Disclosure Protocol` +**Standard Status:** `Project Security Policy & Vulnerability Disclosure Guide` **Classification:** `Runtime Safety Architecture & Threat Model` -**Security Lead:** `SystemAdmin01` (`security@humos.local`) +**Security Contact:** [SystemAdmin01 on GitHub](https://github.com/SystemAdmin01) --- @@ -51,36 +51,38 @@ flowchart TD --- -## 3. Sandbox Isolation Invariants (`G.A.P.` Architecture) +## 3. Sandbox Isolation Invariants — G.A.P. Design Targets -The **G.A.P.** (**Guard, Analyze, Patch**) subsystem provides non-bypassable runtime isolation guarantees. +> **Implementation boundary (package 1.0.0):** This policy describes intended controls and the threat model; it is not a security certification. The current runtime models target/VM state but does not provide operating-system VM isolation, a G.A.P. loop watchdog, or the documented `TRIGGER.kill_switch()` primitive. The Cockpit server binds to loopback, rejects cross-origin browser POST requests, and caps JSON request bodies at 1 MiB. It does not authenticate local users or processes. Do not expose it through a public interface, reverse proxy, or tunnel. -### 3.1 Hard Memory Boundary Enforcement -1. **Zero Unshielded Exposure:** When `CS_EXPOSED` is evaluated, the Core Vault immediately engages `Ice_shield` (thermal decoupling) and `Double_Bottom_Shield` (semantic firewall). No raw data can reach the Core without passing through the semantic filter. +The **G.A.P.** protocol (GAP-001, **Active Paranoia Management**) defines the project's intended containment and response model. Runtime enforcement is partial; see the implementation boundary below. + +### 3.1 Intended Containment Targets (Not Runtime Guarantees) +1. **Protected-State Boundary:** The design target is to engage `Ice_shield` and `Double_Bottom_Shield` when `CS_EXPOSED` is detected. The current runtime models selected shield states; it does not enforce a non-bypassable semantic firewall. 2. **Strict VM Quarantine:** Any target declared with threat score $\ge 7.0$ is forced into `HP_EXT_Defense_VM`. It cannot access shared working memory segments or ambient threads. -3. **Loop Interrupt Guarantee:** If an associative cycle exceeds the declared tick limit (`TIMEOUT = [30]`), `G.A.P.` executes a hard `BREAK_LOOP(X)` and forces `SET_VALUE(X, UNDEFINED)`. Speculative processing is permanently prohibited. +3. **Loop Interruption:** The protocol specifies a proposed timeout and `BREAK_LOOP(X)` response. The current runtime does not ship a G.A.P. watchdog, `BREAK_LOOP()`, or `SET_VALUE()` primitive. -### 3.2 Mandatory Execution Abort via `TRIGGER.kill_switch()` -The runtime mandates an immediate, non-catchable abort (`TRIGGER.kill_switch()`) under any of the following critical security conditions: -- **Corrupted State Vector:** The AST contains syntactically invalid nodes or contradictory invariants (e.g., `CS_SECURE` asserted while `core_connected == True` on a lockdown target). +### 3.2 Proposed Hard-Stop Behavior — `TRIGGER.kill_switch()` +The architectural target is to request an immediate abort (`TRIGGER.kill_switch()`) under the following critical conditions. This primitive is not implemented by the current runtime: +- **Corrupted State Vector:** A future parser/validation layer detects malformed source or contradictory modeled state (e.g., `CS_SECURE` asserted while `core_connected == True` on a lockdown target). - **Injection Signature Detected:** An input variable contains active exploit syntax targeting downstream LLM tokenizers. - **Biometric Saturation Threshold:** Autonomic heart rate breaches $130\text{ BPM}$ or working memory load reaches $95\%$. -#### Invariant Abort Guarantees: -When `TRIGGER.kill_switch()` fires: -1. All communication bridges are severed: `Close(all) > bridges`. -2. Target fidelity is zeroed: `Fidelity = 0%`. -3. Emotional detachment is absolute: `Take_DOWN(all) > Core`. -4. Overrides are enforced: `OVR >> (DDS, ADS)`. -5. The host enters zero-fidelity cold standby until manual operator authentication. +#### Proposed response sequence if implemented: +If a future runtime implements and activates `TRIGGER.kill_switch()`, the intended sequence is: +1. The runtime would close the modeled communication bridges: `Close(all) > bridges`. +2. The modeled target fidelity would be set to zero: `Fidelity = 0%`. +3. The modeled core connection would be cleared: `Take_DOWN(all) > Core`. +4. The modeled defense overrides would be applied: `OVR >> (DDS, ADS)`. +5. The modeled host state enters zero-fidelity cold standby until manual operator authentication. --- -## 4. Threat Severity Matrix & SLA Resolution Timelines +## 4. Threat Severity Matrix & Target Resolution Windows Vulnerabilities reported to the HumOS Security Team are classified according to the **Cognitive Security Vulnerability Scoring (CSVS)** model: -| Severity Level | Threat Definition | Operational Impact | SLA Resolution | +| Severity Level | Threat Definition | Operational Impact | Target Resolution Window* | | :--- | :--- | :--- | :--- | | **CRITICAL** | Direct breach of Core Vault (`CS_UNLOCKED`); uncatchable recursive loop causing total cognitive freeze; prompt injection leading to unauthorized external tool execution. | Complete loss of cognitive boundary; severe emotional dysregulation; arbitrary LLM dispatch. | **Patch within 24 Hours** | | **HIGH** | Failure of `G.A.P.` sandbox to isolate a high-threat target ($C \ge 8$); memory leak in `RAM.alloc()` causing gradual resource starvation; failure of `Ice_shield` to damp thermal throttling. | Working memory saturation ($>85\%$); acute anxiety trigger leakage; loss of task focus. | **Patch within 72 Hours** | @@ -91,20 +93,22 @@ Vulnerabilities reported to the HumOS Security Team are classified according to ## 5. Vulnerability Disclosure & Reporting Protocol -We practice structured, responsible disclosure. Do **not** disclose cognitive vulnerabilities publicly on issue trackers or social platforms before a patch is published. +We practice structured, responsible disclosure. Do **not** disclose vulnerabilities publicly before coordinating with the maintainer. Response times are not currently guaranteed by a formal SLA. ### 5.1 Disclosure Steps -1. **Report Submission:** Encrypt your vulnerability report and dispatch it to `security@humos.local` (or via GitHub Private Vulnerability Reporting at `https://github.com/SystemAdmin01/HumOS/security/advisories`). +1. **Report Submission:** Use [GitHub Private Vulnerability Reporting](https://github.com/SystemAdmin01/HumOS/security/advisories) if it is enabled for the repository. Otherwise, contact the maintainer through the [GitHub profile](https://github.com/SystemAdmin01). Do not send reports to the placeholder address `security@humos.local`. 2. **Payload Submission Format:** - Detailed description of the cognitive vulnerability vector. - Minimal Reproducible Example (MRE) written in `.lghos` syntax demonstrating the exploit. - Raw input stream that bypasses demodulation or triggers runaway recursion. - Observed telemetry state vs expected invariant behavior. -3. **Triaging & Confirmation:** The security team confirms receipt within **12 hours** and provides an initial severity assessment within **24 hours**. -4. **Embargo Period:** A standard **30-day embargo** applies from the date of confirmed triage while the patch is developed and verified across unit suites. +3. **Triaging & Confirmation:** The maintainer will acknowledge and assess reports as availability permits; no acknowledgement or remediation time is guaranteed. +4. **Embargo Period:** Coordinate any disclosure timeline with the maintainer; do not assume a fixed embargo period. 5. **Public Advisory & Credit:** Upon release of the patch release, a formal security advisory (`SEC-ADV-YYYYMMDD-XX`) is published, crediting the security researcher. --- -*Authored and verified under the HumOS Specification Group.* +**Resolution windows above are planning targets, not contractual SLAs or guaranteed response times.* + +*Maintained by SystemAdmin01.* *Official Repository:* [https://github.com/SystemAdmin01/HumOS](https://github.com/SystemAdmin01/HumOS) diff --git a/docs/CONTRIBUTING_IT.md b/docs/CONTRIBUTING_IT.md index 78fd6b0..d8595fd 100644 --- a/docs/CONTRIBUTING_IT.md +++ b/docs/CONTRIBUTING_IT.md @@ -8,25 +8,25 @@ ## 1. Codice di Condotta Tecnica & Filosofia Architetturale -Il progetto HumOS impone standard ingegneristici deterministici rigorosi. A differenza dei framework tradizionali per agenti conversazionali, HumOS e il suo Domain-Specific Language (LINGHOS) operano come una rappresentazione intermedia deterministica (IR) tra la volatilità cognitiva biologica e i kernel di esecuzione a valle basati su Large Language Model (LLM). +HumOS mira a un comportamento prevedibile e verificabile nel compilatore e nel modello di stato implementati. LINGHOS può fungere da rappresentazione intermedia compatta per applicazioni a valle basate su Large Language Model (LLM), ma il repository attuale non garantisce inferenze LLM deterministiche. Ogni contributo — che si tratti di una patch al parser, di un potenziamento al cockpit visuale o di una revisione documentale — deve preservare tassativamente: -1. **Tolleranza Zero alle Allucinazioni:** Il compilatore e il runtime non devono mai generare parametri di stato speculativi o non deterministici. -2. **Budget Rigoroso del Contesto:** L'overhead di token deve essere ridotto al minimo su tutti i confini di serializzazione. -3. **Garanzie Formali degli Invarianti:** L'isolamento del Core Self (`CS_SECURE`), la matematica della prossimità spaziale e il bilancio termodinamico (`RAM`, `BPM`) non possono essere aggirati né indeboliti. +1. **Comportamento deterministico del compilatore:** A parità di sorgente e stato runtime, i percorsi di parsing e serializzazione supportati devono essere ripetibili e coperti da test. +2. **Budget del contesto misurato:** Ogni affermazione sull'efficienza in token deve indicare tokenizer, corpus e metodo di misura; non pubblicare percentuali non verificate. +3. **Limiti espliciti della simulazione:** RAM, BPM, VM e difese sono modelli applicativi finché non esistono controlli reali sull'host o integrazioni con sensori. --- ## 2. Protocollo di Proposta Primitivi (PPP) -Qualsiasi estensione alla libreria standard di LINGHOS, alla grammatica del linguaggio o ai primitivi di esecuzione deve rispettare il **Protocollo di Proposta Primitivi**. La proliferazione incontrollata di parole chiave appesantisce l'AST, consuma budget di token e introduce ambiguità nel ragionamento a valle. +Qualsiasi estensione al linguaggio LINGHOS, ai primitivi documentati o al comportamento d'esecuzione deve rispettare il **Protocollo di Proposta Primitivi**. La sintassi proposta deve essere distinta chiaramente dai comandi supportati dal runtime; il parser attuale è line-oriented e non costruisce un AST formale. ### 2.1 Criteri di Accettazione dei Primitivi Prima di inviare una proposta per un nuovo primitivo (es. `MEMORY.*`, `THREAD.*`, `SHIELD.*`), l'autore deve dimostrare che: 1. **Non Ridondanza:** La funzionalità non può essere ottenuta componendo una sequenza di primitivi già esistenti (es. `RAM.alloc()` + `THREAD.spawn()`). -2. **Efficienza nel Context Window:** L'impronta di token serializzata del primitivo non deve superare **24 token** con codifica standard Byte-Pair Encoding (BPE) UTF-8. +2. **Efficienza nel Context Window:** Riporta l'impronta di token indicando nome e versione del tokenizer. Applica l'obiettivo di 24 token solo quando tokenizer e corpus di misura sono specificati; UTF-8 non è di per sé un tokenizer BPE. 3. **Transizione di Stato Deterministica:** Il primitivo deve produrre una modifica di stato matematicamente dimostrabile nel modello di memoria runtime (es. deallocare RAM, limitare i BPM o modificare il raggio di minaccia). -4. **Compatibilità Retroattiva del Parser:** L'aggiunta non deve introdurre conflitti di lookahead (ambiguità shift-reduce o reduce-reduce $LR(1)$) in `linghos/parser.py`. +4. **Compatibilità Retroattiva del Parser:** Aggiungi test di regressione per il comportamento supportato e per gli input malformati. Il parser attuale è scritto manualmente e non implementa LR(1). ### 2.2 Schema Formale RFC per Proposta Primitivi Ogni proposta deve essere presentata tramite issue o pull request con riferimento a `docs/SPEC.md` utilizzando il seguente schema tecnico: @@ -49,10 +49,10 @@ Ogni Pull Request (PR) deve superare una checklist di verifica manuale e automat ```mermaid flowchart TD - PR[Pull Request Inviata] --> CHECK_SYNTAX[1. Audit Rigoroso di Grammatica & Parser AST] - CHECK_SYNTAX --> CHECK_LEAK[2. Prova di Isolamento del Contesto & Anti-Fuga] - CHECK_LEAK --> CHECK_TOKEN[3. Benchmark dell'Overhead & Budget Token] - CHECK_TOKEN --> CHECK_INVARIANT[4. Test Unitari degli Invarianti Termodinamici] + PR[Pull Request Inviata] --> CHECK_SYNTAX[1. Test di Regressione di Grammatica & Parser] + CHECK_SYNTAX --> CHECK_LEAK[2. Test dei Confini del Modello di Stato] + CHECK_LEAK --> CHECK_TOKEN[3. Misurazione Token Riproducibile] + CHECK_TOKEN --> CHECK_INVARIANT[4. Test del Modello di Stato Runtime] CHECK_INVARIANT --> PASS[Tutti gli Invarianti Verificati -> Approvata per Merge] CHECK_SYNTAX -- Fallimento --> REJECT[PR Respinta: Violazione Invariante Sintattico] @@ -64,20 +64,20 @@ flowchart TD ### 3.1 Checklist di Verifica Passo-Passo - [ ] **1. Conformità Rigorosa a Grammatica & Lexer** - - Tutti gli esempi `.lghos` e `.lgh` compilano correttamente tramite `linghos/compiler.py` senza alcun avviso sintattico. + - Gli esempi modificati o citati vengono verificati rispetto al sottoinsieme attualmente supportato da parser e compilatore. - I punti e virgola, le chiusure dei blocchi (`Main() { ... }`), le direttive (`/SET_Lockdown_Mode`) e gli header macro (`#include`) seguono rigorosamente la grammatica definita in `docs/SPEC.md`. - Nessuno spazio bianco superfluo a fine riga o delimitatori spezzati. - [ ] **2. Verifica Isolamento Contesto (Zero Fuga di Prompt)** - - Le variabili dichiarate nelle sandbox locali (`PRS_VM`, `LP_Ambient_VM`) non devono riversarsi nei buffer di memoria primaria o nei thread adiacenti. - - I payload iniettati nel system prompt dell'LLM devono contenere unicamente profili target isolati senza contaminazioni incrociate. + - I test devono verificare le associazioni target/VM modellate e prevenire mutazioni accidentali tra stati. Gli oggetti VM applicativi non devono essere descritti come isolamento a livello di sistema operativo. + - La costruzione dei payload prompt deve delimitare i contenuti sorgente non fidati; la policy LLM a valle resta fuori dal perimetro di enforcement del runtime. - [ ] **3. Benchmark dell'Impronta di Token** - - Il vettore di stato compilato dal runtime deve dimostrare una **riduzione minima dell'85%** nel conteggio dei token rispetto al flusso di input grezzo. - - L'overhead di serializzazione deve essere verificato tramite profilazione di caratteri e token (`len(json.dumps(state_vector)) <= 512 bytes` per carichi di lavoro nominali). + - Le affermazioni sui token devono includere corpus grezzo riproducibile, nome/versione del tokenizer, regole di serializzazione, misurazioni ripetute e risultati grezzi. Non imporre una riduzione dell'85% finché non è stato pubblicato un benchmark di riferimento. + - Misura separatamente dimensione in byte e conteggio token: i byte non sono token. - [ ] **4. Test Unitari degli Invarianti Termodinamici** - - Test dei limiti di memoria: Verificare che `RAM.purge()` ripristini l'utilizzo a $\le 20\%$. + - Test del modello: verificare che `Call >> Drop_All_Background_Threads;` produca la telemetria modellata documentata nell'implementazione corrente. Considerare `RAM.purge()` come parte della specifica finché non viene implementato. - Test del raggio spaziale: Verificare che il raggio di prossimità rispetti l'equazione $r = \max(50.0, 175.0 - (W \cdot 6.5 + C \cdot 5.5))$. - Test di clamp difensivo: Verificare che `Ice_shield` prevenga il thermal throttling quando la RAM supera l'$85\%$. @@ -100,7 +100,7 @@ I messaggi di commit devono aderire tassativamente alla specifica **Conventional | Ambito | Descrizione | Tipi Consentiti | Esempio | | :--- | :--- | :--- | :--- | -| `lghos` | Grammatica core LINGHOS, scanner lessicale, aggiunte AST | `feat`, `fix`, `refactor` | `feat(lghos): add THREAD.suspend opcode support` | +| `linghos` | Sintassi LINGHOS, scanner lessicale, comportamento di compilatore e parser | `feat`, `fix`, `refactor` | `feat(lghos): add THREAD.suspend opcode support` | | `parser` | Compilazione AST, motore di parsing, normalizzazione istruzioni | `fix`, `perf`, `test` | `fix(parser): resolve lookahead stall on nested IF blocks` | | `cockpit` | Interfaccia Web, canvas radar SVG interattivo, console HTML/JS | `feat`, `fix`, `style` | `feat(cockpit): render active defense labels on SVG perimeter` | | `gap` | Modulo di sicurezza G.A.P., interrupt ricorsivi, kill-switch | `sec`, `fix`, `feat` | `sec(gap): enforce mandatory timeout on unclassified inputs` | @@ -146,7 +146,10 @@ assert res['telemetry']['ice_shield'] is True print('Verifica del compilatore superata con successo.') " -# 3. Avvia l'istanza locale del Cockpit +# 3. Esegui i test di regressione +PYTHONPATH=src python3 -m unittest discover -s tests -v + +# 4. Avvia l'istanza locale del Cockpit python3 src/app.py ``` diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 3aa38cc..d8bd519 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1,353 +1,153 @@ -# HumOS & LINGHOS Developer Implementation Guide -**Document Identifier:** `DOC-GUIDE-20261108-EN` -**Revision:** `2.1.0-STAGING` -**Classification:** `Technical Implementation Standard & Reference Integration Manual` -**Maintainer:** `SystemAdmin01` +# HumOS & LINGHOS Developer Guide ---- +**Package:** `linghos 1.0.0` · **Architecture specification:** `2.1.0-REV4` · **Minimum Python:** `3.8` -> [!IMPORTANT] -> **ACTIVE STAGING SPECIFICATION NOTICE** -> LINGHOS (**Language for Interfacing Neurodivergent Gestalt Human Operating Systems**) is an evolving, active specification. This implementation guide operates as a **live staging environment** where experimental directives, lexical expansions, dynamic AST abstractions, and compiler pipeline optimizations are developed, validated, and documented prior to formal core freezing. Implementers must adhere to the data-contract invariants defined herein to guarantee backward and forward execution compatibility. +## 1. Purpose and scope ---- +HumOS applies operating-system concepts to cognitive self-management. The repository ships a Python package, the LINGHOS compiler and line-oriented interpreter, an in-memory state model, local JSON persistence, a command-line interface, and the browser-based **HumOS Cockpit GUI**. -## 1. Architectural Philosophy & Developer Primitives +This guide describes the software that is present in the repository. The wider architecture in the specification and protocol documents includes design goals that are not runtime features yet. -Modern computational cognitive interfaces face a critical bottleneck: **the high-entropy nature of raw human affective streams**. When an individual experiences ADHD overwhelm, sensory hyper-arousal, or recursive cognitive looping, the resulting text stream exhibits high token redundancy, conversational fluff, and ambiguous entity relationships. +> **Implementation boundary:** The shipped package does not automatically classify raw natural-language or emotional input, construct a formal AST, isolate operating-system processes or virtual machines, acquire biometric signals, enforce a G.A.P. loop watchdog, implement `RAM.purge()` or `TRIGGER.kill_switch()`, or call an external LLM. Runtime VM, RAM, BPM, and defense values are application-level models. -Feeding raw affective prose directly into downstream reasoning systems (such as Large Language Model agents) introduces three catastrophic failure modes: -1. **Context Window Satiation:** Multi-paragraph emotional vents consume thousands of tokens on circular restatements, exhausting working context. -2. **Stochastic Drift & Hallucination:** Ambiguous emotional expressions cause the model's probabilistic attention mechanisms to latch onto hyper-dramatic metaphors rather than actionable state variables. -3. **Absence of Verifiable Invariants:** Natural language prompts cannot guarantee that boundaries (e.g., disconnecting from a toxic variable or enforcing physiological clamps) are deterministically executed. +See the [implementation-status section in the specification](SPEC.md#13-implementation-status-and-conformance-boundary). -LINGHOS resolves these vulnerabilities by acting as an **intermediate deterministic representation (IR)**. It compiles human cognitive states into a formal grammar that guarantees strict encapsulation, spatial boundary math, and explicit thermodynamic metrics. +## 2. What runs today ---- - -## 2. Ingestion Pipeline Walkthrough: From Raw Vent to LINGHOS State Vector - -Converting an unformatted human thought stream into a verified LINGHOS state vector proceeds across four deterministic steps. +The current local execution path is: ```mermaid -sequenceDiagram - autonumber - participant Host as Human Operator (Host) - participant Demod as Signal Demodulator - participant Compiler as LINGHOS Compiler (AST Engine) - participant State as Runtime Invariant Matrix - participant LLM as Downstream LLM Backend - - Host->>Demod: Raw Unstructured Cognitive Stream - Note over Demod: Regex filtering, entity extraction,
weight/criticality classification - Demod->>Compiler: Structured Intermediary Telemetry - Note over Compiler: Lexical scan, AST construction,
proximity radius math: r = max(50, 175 - threat_factor) - Compiler->>State: Evaluate Invariants (RAM, BPM, CS State) - State-->>Compiler: Invariants Verified (No overflow/panics) - Compiler->>LLM: Deterministic State Vector & LINGHOS Payload - Note over LLM: Zero-hallucination semantic parsing,
targeted action dispatch +flowchart TD + SOURCE["User-authored LINGHOS source"] + NORMALIZE["Quote-aware normalization and comment handling"] + ENGINE["Line-oriented parser / compiler"] + KERNEL["HumOSKernel state model"] + OUTPUT["Diagnostics, logs, targets, VMs, modeled telemetry"] + COCKPIT["HumOS Cockpit GUI / CLI output"] + EXTERNAL["Optional external application or LLM integration"] + + SOURCE --> NORMALIZE --> ENGINE --> KERNEL --> OUTPUT --> COCKPIT + OUTPUT -. "consumer-controlled handoff" .-> EXTERNAL ``` -### Step 1: Raw Capture (Ingestion) -The operator inputs an unedited, high-entropy mental vent through a terminal, audio-transcription buffer, or input card. +The compiler returns a structured result containing `compiler_meta`, `diagnostics`, modeled `telemetry`, target and VM records, solution steps, logs, and the symbol registry. The local Cockpit presents this result and provides visual editing and scenario workflows. -```text -"Everything is blowing up right now. Mark keeps pinging me about the Q3 infrastructure review, Sarah is complaining that the database migration failed, and I can hear my pulse in my ears. I feel like if I don't reply in five seconds my career is over. I cannot think straight and I have twelve tasks open at once." -``` +The compiler and CLI interpreter are separate line-oriented execution paths. They share lexical normalization and block scanning, but they are not a formal AST implementation and are not guaranteed to have identical behavior for every design-language construct. -### Step 2: Signal Demodulation & Entity Extraction -The demodulator passes the raw stream through a regular-expression filter and syntactic entity classifier: -1. **Identify Human Targets:** - - `Mark` $\rightarrow$ Alias: `mrk`, Type: Interpersonal Task Source. - - `Sarah` $\rightarrow$ Alias: `srh`, Type: Critical Incident Source. -2. **Assign Weight & Criticality:** - - `Mark`: Emotional Weight = `7/10`, Criticality = `6/10`. - - `Sarah`: Emotional Weight = `8/10`, Criticality = `9/10`. -3. **Extract Physiological & RAM Markers:** - - "Hear pulse in ears" $\rightarrow$ `BPM >= 120`. - - "Twelve tasks open at once" $\rightarrow$ `RAM_LOAD >= 90%`. - -### Step 3: Formal LINGHOS Script Synthesis -The extracted parameters are formatted into a deterministic `.lghos` architectural script: +## 3. Supported language subset -```linghos -// ============================================================================== -// COMPILED INGESTION VIRTUAL SCRIPT -// ============================================================================== -#include -#include -#include -#include +The following constructs have implementation paths in the current compiler and/or interpreter. Their exact behavior is defined by the code and regression tests, not by the broader design specification. -Get: Mark(mrk)[7], Sarah(srh)[8]; -Set_CriticVal >> mrk = [6] -Set_CriticVal >> srh = [9] +| Construct | Current role | +| :--- | :--- | +| `#include` | Register a named module with the kernel / symbol registry | +| `Get:` | Register targets, aliases, and weight values | +| `Set_CriticVal` | Set a target's criticality in the compiler path | +| `@Start>(...)` / `ON>` | Associate targets with an in-memory VM model | +| `Call >>` | Invoke a supported kernel skill/state action | +| `/SET_Lockdown_Mode` | Apply modeled lockdown state | +| `/SET_Attack_Mode` | Set the modeled attack mode | +| `Take_DOWN` / `Close` | Update modeled target connection and bridge state | +| `OVR >>` | Set modeled defense overrides | +| `BE>` | Set a modeled behavior label | +| `IF(...)` | Evaluate a supported kernel condition and process its block | +| `Echo(...)` | Write a message to the runtime log | +| `<<@end` | Record the script termination marker | -LP = low priority -HP = High priority +`Main()` acts as a source wrapper; it is not a function body compiled into an AST. Dotted design primitives such as `RAM.alloc()`, `THREAD.spawn()`, and `TRIGGER.kill_switch()` are not implemented as native runtime commands. -Main() { - // Stage 1: Purge saturated volatile RAM - Call >> RAM.purge(); - Call >> Drop_All_Background_Threads; +### Minimal example - // Stage 2: Sandboxing high-threat variables +```linghos +Get: Review(review)[6]; +Set_CriticVal >> review = [7]; + +Main() { @Start>(HP_EXT_Defense_VM) { - priority = HP; - ON> mrk, srh; + ON> review; } - // Stage 3: Perimeter defenses IF(CS_EXPOSED) { Call >> Ice_shield; Call >> Double_Bottom_Shield; - OVR >> (DDS, ADS); } - // Stage 4: Hardware clamp - Execute >> Physiological_Sigh(Rapporto_4_7_8); - - // Stage 5: Focus pinning - Call >> RAM.alloc(DB_MIGRATION_FOCUS, 256MB); - Call >> THREAD.spawn(TH_DB_TRIAGE, srh, HP); - + Echo("Review isolated in the modeled defense VM"); <<@end } ``` -### Step 4: Verification of State Invariants -Before routing to downstream execution, the runtime evaluates spatial and thermodynamic equations: -- **Spatial Threat Proximity:** - $$\text{threat\_factor}(srh) = (8 \cdot 6.5) + (9 \cdot 5.5) = 52.0 + 49.5 = 101.5$$ - $$\text{radius}(srh) = \max(50.0, 175.0 - 101.5) = 73.5\text{ px}$$ -- **Thermodynamic Invariants:** - - `RAM %` before purge: `92%` $\rightarrow$ After `RAM.purge()`: `22%`. - - `BPM`: `124` $\rightarrow$ With `Ice_shield` active: clamped to nominal descent ($\approx 75$). - - `CS_STATE`: Verified as `SECURE` (Core Vault isolated by `Double_Bottom_Shield`). - ---- - -## 3. LLM Context Injection Pattern - -To eliminate stochastic drift and context window bloat, the compiled LINGHOS state vector is injected into the LLM system prompt via a structured schema. The model is instructed to behave strictly as an execution runtime kernel, rather than a conversational therapist. - -### 3.1 Token Optimization Metrics - -| Metric | Raw Natural Language Vent | Compiled LINGHOS State Vector | Improvement | -| :--- | :--- | :--- | :--- | -| **Input Token Count** | 1,480 tokens | 114 tokens | **92.3% Reduction** | -| **Semantic Drift / Hallucination Rate** | 18.4% variance across runs | 0.0% (deterministic output schema) | **100% Elimination** | -| **Context Window Consumption** | High (circular conversational memory) | Negligible (compact JSON state vector) | **Maximum Efficiency** | -| **Execution Latency** | 2,850 ms (reasoning on ambiguous fluff) | 410 ms (direct function dispatch) | **85.6% Speedup** | - -### 3.2 Production Python Injection Harness - -The following complete, dependency-free Python implementation loads raw inputs, synthesizes LINGHOS vectors, and constructs an optimal LLM payload: - -```python -""" -HumOS Engine: LINGHOS Context Injection Harness. -Author: SystemAdmin01 -Target: Production LLM Runtime Integration -""" - -import json -import re -from typing import Dict, Any, List - - -class CognitiveDemodulator: - """Demodulates unstructured natural language into structured signal parameters.""" - - @staticmethod - def extract_state(raw_text: str) -> Dict[str, Any]: - targets: List[Dict[str, Any]] = [] - - # Detect high-arousal names or entities with heuristic urgency - words = re.findall(r'\b[A-Z][a-z]+\b', raw_text) - known_entities = [w for w in words if w not in {"I", "The", "Everything", "My", "When"}] - - for idx, ent in enumerate(known_entities[:3]): - targets.append({ - "name": ent, - "alias": ent[:3].lower(), - "weight": 7 + (idx % 3), - "criticality": 6 + (idx % 4) - }) - - # Detect physiological markers - has_pulse = bool(re.search(r'\b(pulse|heart|bpm|pounding|chest)\b', raw_text, re.I)) - has_multitask = bool(re.search(r'\b(twelve|tasks|tabs|everything|swamped)\b', raw_text, re.I)) - - return { - "targets": targets, - "estimated_bpm": 128 if has_pulse else 72, - "estimated_ram": 94 if has_multitask else 35, - "cs_exposed": has_pulse or has_multitask - } - - -class LinghosCompilerBridge: - """Translates demodulated signal state into a concrete LINGHOS state vector.""" - - @staticmethod - def compile_payload(state: Dict[str, Any]) -> Dict[str, Any]: - targets = state.get("targets", []) - - target_lines = [f"{t['name']}({t['alias']})[{t['weight']}]" for t in targets] - target_decl = f"Get: {', '.join(target_lines)};" if target_lines else "// No external targets declared." - - critic_lines = [f"Set_CriticVal >> {t['alias']} = [{t['criticality']}]" for t in targets] - critic_decl = "\n".join(critic_lines) - - # Calculate spatial proximity for each target - proximity_vectors = {} - for t in targets: - threat_factor = (t['weight'] * 6.5) + (t['criticality'] * 5.5) - radius = max(50.0, 175.0 - threat_factor) - proximity_vectors[t['alias']] = { - "name": t['name'], - "radius_px": round(radius, 1), - "threat_score": round((t['weight'] * 0.4) + (t['criticality'] * 0.6), 2) - } - - linghos_script = f"""#include -#include -#include -#include - -{target_decl} -{critic_decl} - -LP = low priority -HP = High priority - -Main() {{ - Call >> RAM.purge(); - Call >> Drop_All_Background_Threads; - @Start>(HP_EXT_Defense_VM) {{ - priority = HP; - ON> {', '.join(t['alias'] for t in targets)}; - }} - IF(CS_EXPOSED) {{ - Call >> Ice_shield; - Call >> Double_Bottom_Shield; - OVR >> (DDS, ADS); - }} - Execute >> Physiological_Sigh(Rapporto_4_7_8); - <<@end -}}""" - - return { - "linghos_code": linghos_script, - "proximity_vectors": proximity_vectors, - "telemetry": { - "ram_usage_pct": 20, # post-purge nominal invariant - "heart_rate_bpm": 74, # clamped nominal invariant - "cs_state": "SECURE", - "active_shields": ["Ice_shield", "Double_Bottom_Shield", "DDS_ADS_Override"] - } - } - - -class LLMPromptInjector: - """Builds hardened, zero-drift system prompts from compiled LINGHOS vectors.""" - - SYSTEM_TEMPLATE = """You are the HumOS Autonomous Execution Kernel. -You do not engage in therapeutic, conversational, or emotional discourse. -You consume compiled LINGHOS state vectors and execute deterministic, structured actions. - -[MANDATORY OPERATIONAL INVARIANTS] -1. Core Self status is {cs_state}. You must maintain strict boundary isolation. -2. Mental RAM is clamped to {ram_pct}%. Prohibit opening multi-task threads. -3. Active shields engaged: {active_shields}. -4. Target Proximity Matrix: -{target_matrix} - -[INCOMING LINGHOS STATE VECTOR] -```linghos -{linghos_script} +The numeric values and VM assignment above are inputs to HumOS's state model. They do not create an operating-system virtual machine or measure a person's physiological state. + +## 4. Run the Cockpit + +From the repository root: + +```bash +python3 src/app.py +``` + +The application binds to loopback and prints the local URL, normally `http://127.0.0.1:8080`. Use the URL printed by the process if the default port is busy. + +The browser GUI is implemented in [`src/linghos/cockpit.html`](../src/linghos/cockpit.html). It includes a LINGHOS editor, visual target/defense controls, modeled telemetry, symbol management, and scenario persistence. + +The local HTTP service accepts JSON requests up to 1 MiB and checks browser request origin on POST. It does not authenticate local users or processes. Keep it on loopback; do not expose it through a public network interface, reverse proxy, or tunnel. + +## 5. Use the command-line interface + +From the package directory: + +```bash +cd src +python3 -m linghos --help +python3 -m linghos run ../examples/adhd_ram_flush.lgh +python3 -m linghos repl +python3 -m linghos gui ``` -[OUTPUT CONTRACT] -You must respond exclusively with a valid JSON object matching this schema: -{{ - "action_status": "LOCKED | EXECUTING | CLAMPED", - "isolated_targets": ["target_alias_list"], - "atomic_immediate_task": "Concise non-divisible directive", - "boundary_statement": "Firm, cold message to deliver externally if contact required", - "system_telemetry_post_eval": {{ - "ram_pct": {ram_pct}, - "cs_state": "{cs_state}" - }} -}}""" - - @classmethod - def generate_messages(cls, compiled_data: Dict[str, Any]) -> List[Dict[str, str]]: - telemetry = compiled_data["telemetry"] - prox = json.dumps(compiled_data["proximity_vectors"], indent=2) - - system_content = cls.SYSTEM_TEMPLATE.format( - cs_state=telemetry["cs_state"], - ram_pct=telemetry["ram_usage_pct"], - active_shields=", ".join(telemetry["active_shields"]), - target_matrix=prox, - linghos_script=compiled_data["linghos_code"] - ) - - return [ - {"role": "system", "content": system_content}, - {"role": "user", "content": "EXECUTE LINGHOS DISPATCH."} - ] - - -# ============================================================================== -# EXECUTION VERIFICATION SUITE -# ============================================================================== -if __name__ == "__main__": - sample_raw_input = ( - "Mark is spamming me about deadlines, Sarah said the migration is broken, " - "and my pulse is pounding. I have twelve open problems in my head right now." - ) - - # 1. Demodulate - raw_state = CognitiveDemodulator.extract_state(sample_raw_input) - - # 2. Compile to LINGHOS - compiled = LinghosCompilerBridge.compile_payload(raw_state) - - # 3. Generate LLM Payload - messages = LLMPromptInjector.generate_messages(compiled) - - print("=== INJECTED LLM SYSTEM PROMPT ===") - print(messages[0]["content"]) - print("\n=== PAYLOAD VALIDATION SUCCESSFUL ===") +The package can also be installed locally: + +```bash +cd src +python3 -m pip install . ``` ---- - -## 4. Reference Implementation Directory Structure - -When authoring or integrating `.lghos` scripts into your codebase, follow this verified repository hierarchy: - -```text -HumOS/ -├── docs/ -│ ├── SPEC.md # Core Architectural Formal Specification (EN) -│ ├── SPEC_IT.md # Core Architectural Formal Specification (IT) -│ ├── GUIDE.md # Developer Implementation & Injection Guide (EN) -│ └── GUIDE_IT.md # Developer Implementation & Injection Guide (IT) -├── examples/ -│ ├── 01_loop_isolation.lghos # Reference script: G.A.P. Sandbox & Paranoia Breaker -│ ├── 02_ram_dump.lghos # Reference script: RAM.purge() & Focus Pinning -│ ├── adhd_ram_flush.lgh # Standalone quick-flush utility -│ └── incident_01.lgh # Multi-vector defense simulation -└── src/ - ├── app.py # Execution entrypoint - └── linghos/ # Compiler, Kernel, Web & Storage Modules +See [`src/README.md`](../src/README.md) for package-specific usage. + +## 6. G.A.P. protocol and security boundaries + +The English protocol identifies GAP-001 as **Active Paranoia Management**; the Italian protocol title is **Gestione Attiva delle Paranoie**. G.A.P. describes a cognitive containment and response model. The current runtime provides modeled target/VM states and selected defense actions, but it does not implement the documented watchdog, operating-system sandbox enforcement, or hard kill-switch. + +Read the [Security Policy](../SECURITY.md), [Italian Security Policy](SECURITY_IT.md), and [G.A.P.-001 protocol](../protocols/en/GAP-001-protocol.md) before making security claims about the project. + +## 7. LLM integration and benchmarks + +The repository does not ship an LLM client or a complete raw-input-to-LLM pipeline. An external application may consume compiler output and choose to forward a serialized state to a model, with its own consent, privacy, validation, and safety controls. + +There are no reproducible token-reduction, hallucination-rate, or end-to-end latency benchmarks in this repository. Any numeric figures should be treated as unverified estimates until a public corpus, tokenizer/model versions, measurement scripts, run counts, and raw results are available. Deterministic parsing does not make downstream LLM inference deterministic. + +## 8. Test and build + +From the repository root: + +```bash +PYTHONPATH=src python3 -m unittest discover -s tests -v +python3 -m compileall -q src tests ``` ---- +Build the Python package: + +```bash +cd src +python3 -m pip wheel . --no-deps +``` + +GitHub Actions runs the regression suite across the declared Python support matrix and builds the package. The local commands above are the same basic checks used for contributions. + +## 9. Related documentation -*Authored under the HumOS Specification Group.* -*Official Repository:* [https://github.com/SystemAdmin01/HumOS](https://github.com/SystemAdmin01/HumOS) +- [Root README](../README.md) — overview and quick start. +- [LINGHOS specification](SPEC.md) · [Specifiche LINGHOS in italiano](SPEC_IT.md). +- [Italian developer guide](GUIDE_IT.md). +- [English LINGHOS language notes](en/LINGHOS.md) · [Italian LINGHOS language notes](it/LINGHOS.md). +- [Contribution guidelines](../CONTRIBUTING.md) · [Linee guida italiane](CONTRIBUTING_IT.md). diff --git a/docs/GUIDE_IT.md b/docs/GUIDE_IT.md index 31d36ae..d55fd9a 100644 --- a/docs/GUIDE_IT.md +++ b/docs/GUIDE_IT.md @@ -1,353 +1,153 @@ -# Guida all'Implementazione per Sviluppatori HumOS & LINGHOS -**Identificatore Documento:** `DOC-GUIDE-20261108-IT` -**Revisione:** `2.1.0-STAGING` -**Classificazione:** `Standard Tecnico d'Implementazione & Manuale di Integrazione di Riferimento` -**Maintainer:** `SystemAdmin01` +# Guida Sviluppatori HumOS & LINGHOS ---- +**Package:** `linghos 1.0.0` · **Specifica architetturale:** `2.1.0-REV4` · **Python minimo:** `3.8` -> [!IMPORTANT] -> **AVVISO DI SPECIFICA IN STAGING ATTIVO** -> LINGHOS (**Language for Interfacing Neurodivergent Gestalt Human Operating Systems**) è una specifica attiva in costante evoluzione. Questa guida per sviluppatori opera come un **ambiente di staging permanente** in cui direttive sperimentali, espansioni lessicali, astrazioni AST dinamiche e ottimizzazioni della pipeline del compilatore vengono sviluppate, validate e documentate prima del congelamento formale del core. Gli sviluppatori sono tenuti a rispettare gli invarianti contrattuali qui definiti per garantire la piena compatibilità di esecuzione presente e futura. +## 1. Scopo e ambito ---- +HumOS applica concetti dei sistemi operativi alla gestione cognitiva. Il repository distribuisce un package Python, il compilatore e l'interprete line-oriented LINGHOS, un modello di stato in memoria, persistenza JSON locale, un'interfaccia CLI e la GUI browser-based **HumOS Cockpit**. -## 1. Filosofia Architetturale & Primitivi di Sviluppo +Questa guida descrive il software effettivamente presente nel repository. L'architettura più ampia descritta nelle specifiche e nei protocolli comprende obiettivi di progetto che non sono ancora funzionalità runtime. -Le moderne interfacce computazionali cognitive affrontano un collo di bottiglia critico: **l'elevata entropia dei flussi emotivi umani grezzi**. Quando un individuo attraversa sovraccarico da ADHD, iper-eccitazione sensoriale o loop cognitivi ricorsivi, il flusso di testo risultante manifesta un'altissima ridondanza di token, divagazioni conversazionali e relazioni ambigue tra le entità. +> **Limiti dell'implementazione:** Il package distribuito non classifica automaticamente input in linguaggio naturale o sfoghi emotivi, non costruisce un AST formale, non isola processi o macchine virtuali del sistema operativo, non acquisisce segnali biometrici, non applica un watchdog G.A.P. per i loop, non implementa `RAM.purge()` o `TRIGGER.kill_switch()` e non chiama un LLM esterno. I valori runtime di VM, RAM, BPM e difese sono modelli applicativi. -Inviare direttamente prosa emotiva non strutturata ai sistemi di ragionamento a valle (come gli agenti basati su Large Language Model) introduce tre modalità di fallimento catastrofiche: -1. **Saturazione del Context Window:** Sfoghi emotivi su più paragrafi consumano migliaia di token in riformulazioni circolari, esaurendo la memoria di lavoro utile del modello. -2. **Deriva Stocastica & Allucinazione:** Espressioni emotive ambigue inducono i meccanismi di attenzione probabilistica del modello a focalizzarsi su metafore drammatiche anziché su variabili di stato azionabili. -3. **Assenza di Invarianti Verificabili:** I prompt in linguaggio naturale non possono garantire che i confini (es. disconnettersi da una variabile tossica o applicare clamp fisiologici) vengano eseguiti in modo deterministico. +Consulta la [sezione sullo stato d'implementazione nella specifica](SPEC_IT.md#13-stato-dellimplementazione-e-limiti-di-conformita). -LINGHOS risolve queste criticità operando come una **rappresentazione deterministica intermedia (IR)**. Compila gli stati cognitivi umani in una grammatica formale che assicura un incapsulamento rigoroso, il calcolo matematico della prossimità spaziale e metriche termodinamiche esplicite. +## 2. Cosa viene eseguito oggi ---- - -## 2. Guida della Pipeline di Ingestione: Dallo Sfogo Grezzo al Vettore di Stato LINGHOS - -La conversione di un flusso di pensieri umani non formattato in un vettore di stato verificato LINGHOS si articola in quattro passaggi deterministici. +Il percorso di esecuzione locale attuale è: ```mermaid -sequenceDiagram - autonumber - participant Host as Operatore Umano (Host) - participant Demod as Demodulatore di Segnale - participant Compiler as Compilatore LINGHOS (Motore AST) - participant State as Matrice Invarianti Runtime - participant LLM as Backend LLM a Valle - - Host->>Demod: Flusso Cognitivo Grezzo Non Strutturato - Note over Demod: Filtro regex, estrazione entità,
classificazione peso/criticità - Demod->>Compiler: Telemetria Intermedia Strutturata - Note over Compiler: Scansione lessicale, costruzione AST,
calcolo raggio prossimità: r = max(50, 175 - threat_factor) - Compiler->>State: Valutazione Invarianti (RAM, BPM, Stato CS) - State-->>Compiler: Invarianti Verificati (Nessun overflow/panico) - Compiler->>LLM: Vettore di Stato Deterministico & Payload LINGHOS - Note over LLM: Parsing semantico a zero allucinazioni,
dispatch azioni mirate +flowchart TD + SOURCE["Sorgente LINGHOS scritto dall'utente"] + NORMALIZE["Normalizzazione quote-aware e gestione commenti"] + ENGINE["Parser / compilatore line-oriented"] + KERNEL["Modello di stato HumOSKernel"] + OUTPUT["Diagnostica, log, target, VM, telemetria modellata"] + COCKPIT["GUI HumOS Cockpit / output CLI"] + EXTERNAL["Applicazione o integrazione LLM esterna opzionale"] + + SOURCE --> NORMALIZE --> ENGINE --> KERNEL --> OUTPUT --> COCKPIT + OUTPUT -. "passaggio controllato dall'applicazione consumer" .-> EXTERNAL ``` -### Passo 1: Ingestione Grezza -L'operatore inserisce uno sfogo mentale grezzo e ad alta entropia tramite terminale, buffer di trascrizione vocale o scheda di input. +Il compilatore restituisce un risultato strutturato contenente `compiler_meta`, `diagnostics`, `telemetry` modellata, record di target e VM, passaggi di soluzione, log e registro dei simboli. Il Cockpit locale visualizza il risultato e offre editing visuale e gestione degli scenari. -```text -"Sta crollando tutto adesso. Marco continua a scrivermi su Slack per la revisione dell'infrastruttura Q3, Sara si lamenta che la migrazione del database è fallita e sento il battito nelle orecchie. Mi sembra che se non rispondo entro cinque secondi la mia carriera sia finita. Non riesco a pensare lucidamente e ho dodici task aperti contemporaneamente." -``` +Il compilatore e l'interprete CLI sono due percorsi line-oriented distinti. Condividono la normalizzazione lessicale e la scansione dei blocchi, ma non costituiscono un'implementazione AST formale e non garantiscono comportamento identico per ogni costrutto del linguaggio descritto nella specifica. -### Passo 2: Demodulazione Segnale-Rumore & Estrazione Entità -Il demodulatore fa passare il testo grezzo attraverso un filtro basato su espressioni regolari e un classificatore sintattico di entità: -1. **Identificazione Target Umani:** - - `Marco` $\rightarrow$ Alias: `mrk`, Tipo: Sorgente Task Interpersonale. - - `Sara` $\rightarrow$ Alias: `srh`, Tipo: Sorgente Incidente Critico. -2. **Assegnazione Peso Emotivo & Criticità:** - - `Marco`: Peso Emotivo = `7/10`, Criticità = `6/10`. - - `Sara`: Peso Emotivo = `8/10`, Criticità = `9/10`. -3. **Rilevamento Marcatori Fisiologici & RAM:** - - "Sento battito nelle orecchie" $\rightarrow$ `BPM >= 120`. - - "Dodici task aperti contemporaneamente" $\rightarrow$ `RAM_LOAD >= 90%`. - -### Passo 3: Sintesi Formale dello Script LINGHOS -I parametri estratti vengono impaginati in uno script architetturale deterministico `.lghos`: +## 3. Sottoinsieme del linguaggio supportato -```linghos -// ============================================================================== -// SCRIPT VIRTUALE COMPILATO DA INGESTIONE -// ============================================================================== -#include -#include -#include -#include +I costrutti seguenti hanno percorsi implementati nel compilatore e/o nell'interprete attuali. Il loro comportamento esatto è definito dal codice e dai test di regressione, non dalla specifica di progetto più ampia. -Get: Marco(mrk)[7], Sara(srh)[8]; -Set_CriticVal >> mrk = [6] -Set_CriticVal >> srh = [9] +| Costrutto | Ruolo attuale | +| :--- | :--- | +| `#include` | Registra un modulo nominato nel kernel / registro simboli | +| `Get:` | Registra target, alias e valori di peso | +| `Set_CriticVal` | Imposta la criticità di un target nel percorso del compilatore | +| `@Start>(...)` / `ON>` | Associa target a un modello VM in memoria | +| `Call >>` | Invoca una skill/azione di stato supportata dal kernel | +| `/SET_Lockdown_Mode` | Applica uno stato di lockdown modellato | +| `/SET_Attack_Mode` | Imposta la modalità attack modellata | +| `Take_DOWN` / `Close` | Aggiorna lo stato modellato delle connessioni e dei ponti | +| `OVR >>` | Imposta override difensivi modellati | +| `BE>` | Imposta un'etichetta di comportamento modellata | +| `IF(...)` | Valuta una condizione supportata dal kernel e processa il relativo blocco | +| `Echo(...)` | Registra un messaggio nel log runtime | +| `<<@end` | Registra il marcatore di terminazione dello script | -LP = low priority -HP = High priority +`Main()` funge da wrapper sorgente; non è una funzione compilata in un AST. I primitivi di progetto con notazione puntata come `RAM.alloc()`, `THREAD.spawn()` e `TRIGGER.kill_switch()` non sono implementati come comandi nativi del runtime. -Main() { - // Stadio 1: Purga della RAM volatile satura - Call >> RAM.purge(); - Call >> Drop_All_Background_Threads; +### Esempio minimo - // Stadio 2: Sandboxing delle variabili ad alta minaccia +```linghos +Get: Review(review)[6]; +Set_CriticVal >> review = [7]; + +Main() { @Start>(HP_EXT_Defense_VM) { - priority = HP; - ON> mrk, srh; + ON> review; } - // Stadio 3: Difese perimetrali IF(CS_EXPOSED) { Call >> Ice_shield; Call >> Double_Bottom_Shield; - OVR >> (DDS, ADS); } - // Stadio 4: Clamp fisiologico - Execute >> Physiological_Sigh(Rapporto_4_7_8); - - // Stadio 5: Blocco del focus atomico - Call >> RAM.alloc(DB_MIGRATION_FOCUS, 256MB); - Call >> THREAD.spawn(TH_DB_TRIAGE, srh, HP); - + Echo("Review isolata nella VM difensiva modellata"); <<@end } ``` -### Passo 4: Verifica degli Invarianti di Stato -Prima di inviare il payload all'esecuzione a valle, il runtime valuta le equazioni spaziali e termodinamiche: -- **Prossimità Spaziale della Minaccia:** - $$\text{threat\_factor}(srh) = (8 \cdot 6.5) + (9 \cdot 5.5) = 52.0 + 49.5 = 101.5$$ - $$\text{radius}(srh) = \max(50.0, 175.0 - 101.5) = 73.5\text{ px}$$ -- **Invarianti Termodinamici:** - - `RAM %` pre-purge: `92%` $\rightarrow$ Post `RAM.purge()`: `22%`. - - `BPM`: `124` $\rightarrow$ Con `Ice_shield` attivo: stabilizzato verso discesa nominale ($\approx 75$). - - `CS_STATE`: Verificato come `SECURE` (Core Vault isolato da `Double_Bottom_Shield`). - ---- - -## 3. Pattern di Iniezione del Contesto negli LLM - -Per azzerare la deriva stocastica e l'inflazione del context window, il vettore di stato LINGHOS compilato viene iniettato nel system prompt dell'LLM tramite uno schema rigido. Il modello viene istruito per agire strettamente come un kernel di esecuzione operativo, eliminando qualsiasi deviazione conversazionale o terapeutica. - -### 3.1 Metriche di Ottimizzazione dei Token - -| Metrica | Sfogo Grezzo in Linguaggio Naturale | Vettore di Stato Compilato LINGHOS | Miglioramento | -| :--- | :--- | :--- | :--- | -| **Conteggio Token di Input** | 1.480 token | 114 token | **Riduzione del 92,3%** | -| **Deriva Semantica / Tasso di Allucinazione** | Varianza del 18,4% tra esecuzioni | 0,0% (schema di output deterministico) | **Eliminazione al 100%** | -| **Consumo del Context Window** | Elevato (memoria conversazionale circolare) | Trascurabile (vettore JSON compatto) | **Massima Efficienza** | -| **Latenza di Esecuzione** | 2.850 ms (ragionamento su rumore ambiguo) | 410 ms (dispatch diretto delle azioni) | **Accelerazione dell'85,6%** | - -### 3.2 Harness di Iniezione Python per Ambienti di Produzione - -La seguente implementazione Python completa e autonoma carica gli input grezzi, sintetizza i vettori LINGHOS e costruisce il payload ottimizzato per il modello linguistico: - -```python -""" -HumOS Engine: Harness di Iniezione del Contesto LINGHOS. -Autore: SystemAdmin01 -Target: Integrazione Runtime LLM di Produzione -""" - -import json -import re -from typing import Dict, Any, List - - -class CognitiveDemodulator: - """Demodula il linguaggio naturale non strutturato in parametri di segnale precisi.""" - - @staticmethod - def extract_state(raw_text: str) -> Dict[str, Any]: - targets: List[Dict[str, Any]] = [] - - # Individua entità o nomi ad alta attivazione tramite euristica - words = re.findall(r'\b[A-Z][a-z]+\b', raw_text) - known_entities = [w for w in words if w not in {"Io", "Il", "La", "Tutto", "Mio", "Quando"}] - - for idx, ent in enumerate(known_entities[:3]): - targets.append({ - "name": ent, - "alias": ent[:3].lower(), - "weight": 7 + (idx % 3), - "criticality": 6 + (idx % 4) - }) - - # Rileva marcatori fisiologici - has_pulse = bool(re.search(r'\b(battito|cuore|bpm|palpitazioni|petto)\b', raw_text, re.I)) - has_multitask = bool(re.search(r'\b(dodici|task|schede|aperti|sommerso|tutto)\b', raw_text, re.I)) - - return { - "targets": targets, - "estimated_bpm": 128 if has_pulse else 72, - "estimated_ram": 94 if has_multitask else 35, - "cs_exposed": has_pulse or has_multitask - } - - -class LinghosCompilerBridge: - """Traduce lo stato del segnale demodulato in un vettore di stato LINGHOS concreto.""" - - @staticmethod - def compile_payload(state: Dict[str, Any]) -> Dict[str, Any]: - targets = state.get("targets", []) - - target_lines = [f"{t['name']}({t['alias']})[{t['weight']}]" for t in targets] - target_decl = f"Get: {', '.join(target_lines)};" if target_lines else "// Nessun target esterno dichiarato." - - critic_lines = [f"Set_CriticVal >> {t['alias']} = [{t['criticality']}]" for t in targets] - critic_decl = "\n".join(critic_lines) - - # Calcola la prossimità spaziale per ogni target - proximity_vectors = {} - for t in targets: - threat_factor = (t['weight'] * 6.5) + (t['criticality'] * 5.5) - radius = max(50.0, 175.0 - threat_factor) - proximity_vectors[t['alias']] = { - "name": t['name'], - "radius_px": round(radius, 1), - "threat_score": round((t['weight'] * 0.4) + (t['criticality'] * 0.6), 2) - } - - linghos_script = f"""#include -#include -#include -#include - -{target_decl} -{critic_decl} - -LP = low priority -HP = High priority - -Main() {{ - Call >> RAM.purge(); - Call >> Drop_All_Background_Threads; - @Start>(HP_EXT_Defense_VM) {{ - priority = HP; - ON> {', '.join(t['alias'] for t in targets)}; - }} - IF(CS_EXPOSED) {{ - Call >> Ice_shield; - Call >> Double_Bottom_Shield; - OVR >> (DDS, ADS); - }} - Execute >> Physiological_Sigh(Rapporto_4_7_8); - <<@end -}}""" - - return { - "linghos_code": linghos_script, - "proximity_vectors": proximity_vectors, - "telemetry": { - "ram_usage_pct": 20, # invariante nominale post-purge - "heart_rate_bpm": 74, # invariante nominale clampato - "cs_state": "SECURE", - "active_shields": ["Ice_shield", "Double_Bottom_Shield", "DDS_ADS_Override"] - } - } - - -class LLMPromptInjector: - """Costruisce system prompt corazzati e privi di allucinazioni a partire dai vettori LINGHOS.""" - - SYSTEM_TEMPLATE = """Sei il Kernel di Esecuzione Autonoma di HumOS. -Non impegnarti in dialoghi terapeutici, conversazionali o emotivi. -Consumi vettori di stato compilati in LINGHOS ed esegui azioni deterministiche e strutturate. - -[INVARIANTI OPERATIVI OBBLIGATORI] -1. Lo stato del Core Self è {cs_state}. Devi mantenere un isolamento perimetrale rigoroso. -2. La RAM mentale è vincolata al {ram_pct}%. È vietato aprire thread multi-task. -3. Barriere difensive attive: {active_shields}. -4. Matrice di Prossimità dei Target: -{target_matrix} - -[VETTORE DI STATO LINGHOS IN ENTRATA] -```linghos -{linghos_script} +I valori numerici e l'assegnazione VM in questo esempio sono input del modello di stato HumOS. Non creano una macchina virtuale del sistema operativo e non misurano lo stato fisiologico di una persona. + +## 4. Avviare il Cockpit + +Dalla root del repository: + +```bash +python3 src/app.py +``` + +L'applicazione si lega al loopback e stampa l'URL locale, normalmente `http://127.0.0.1:8080`. Se la porta predefinita è occupata, usa l'indirizzo stampato dal processo. + +La GUI browser è implementata in [`src/linghos/cockpit.html`](../src/linghos/cockpit.html). Include editor LINGHOS, controlli visuali per target/difese, telemetria modellata, gestione simboli e persistenza scenari. + +Il servizio HTTP locale accetta richieste JSON fino a 1 MiB e verifica l'origine delle richieste POST del browser. Non autentica utenti o processi locali. Mantienilo sul loopback; non esporlo tramite interfacce di rete pubbliche, reverse proxy o tunnel. + +## 5. Usare l'interfaccia a riga di comando + +Dalla directory del package: + +```bash +cd src +python3 -m linghos --help +python3 -m linghos run ../examples/adhd_ram_flush.lgh +python3 -m linghos repl +python3 -m linghos gui ``` -[CONTRATTO DI OUTPUT] -Devi rispondere esclusivamente con un oggetto JSON valido conforme a questo schema: -{{ - "action_status": "LOCKED | EXECUTING | CLAMPED", - "isolated_targets": ["lista_alias_target"], - "atomic_immediate_task": "Direttiva atomica concisa non divisibile", - "boundary_statement": "Dichiarazione ferma e distaccata da trasmettere esternamente in caso di contatto", - "system_telemetry_post_eval": {{ - "ram_pct": {ram_pct}, - "cs_state": "{cs_state}" - }} -}}""" - - @classmethod - def generate_messages(cls, compiled_data: Dict[str, Any]) -> List[Dict[str, str]]: - telemetry = compiled_data["telemetry"] - prox = json.dumps(compiled_data["proximity_vectors"], indent=2, ensure_ascii=False) - - system_content = cls.SYSTEM_TEMPLATE.format( - cs_state=telemetry["cs_state"], - ram_pct=telemetry["ram_usage_pct"], - active_shields=", ".join(telemetry["active_shields"]), - target_matrix=prox, - linghos_script=compiled_data["linghos_code"] - ) - - return [ - {"role": "system", "content": system_content}, - {"role": "user", "content": "ESEGUI DISPATCH LINGHOS."} - ] - - -# ============================================================================== -# SUITE DI VERIFICA DELL'ESECUZIONE -# ============================================================================== -if __name__ == "__main__": - sample_raw_input = ( - "Marco mi sta tempestando per le scadenze, Sara dice che la migrazione è bloccata, " - "e sento il cuore battere forte. Ho dodici problemi aperti in testa in questo momento." - ) - - # 1. Demodulazione - raw_state = CognitiveDemodulator.extract_state(sample_raw_input) - - # 2. Compilazione in LINGHOS - compiled = LinghosCompilerBridge.compile_payload(raw_state) - - # 3. Generazione Payload LLM - messages = LLMPromptInjector.generate_messages(compiled) - - print("=== SYSTEM PROMPT LLM INIETTATO ===") - print(messages[0]["content"]) - print("\n=== VALIDAZIONE PAYLOAD COMPLETATA CON SUCCESSO ===") +È anche possibile installare il package in locale: + +```bash +cd src +python3 -m pip install . ``` ---- - -## 4. Struttura delle Directory di Riferimento - -Nell'integrare gli script `.lghos` nel tuo progetto, mantieni la seguente struttura gerarchica verificata: - -```text -HumOS/ -├── docs/ -│ ├── SPEC.md # Specifica Architetturale Formale Core (EN) -│ ├── SPEC_IT.md # Specifica Architetturale Formale Core (IT) -│ ├── GUIDE.md # Guida Sviluppatori & Pattern Iniezione (EN) -│ └── GUIDE_IT.md # Guida Sviluppatori & Pattern Iniezione (IT) -├── examples/ -│ ├── 01_loop_isolation.lghos # Script di riferimento: G.A.P. Sandbox & Loop Break -│ ├── 02_ram_dump.lghos # Script di riferimento: RAM.purge() & Focus Atomico -│ ├── adhd_ram_flush.lgh # Script autonomo di flush rapido -│ └── incident_01.lgh # Simulazione difensiva multi-vettore -└── src/ - ├── app.py # Entrypoint di esecuzione - └── linghos/ # Moduli Compilatore, Kernel, Web & Storage +Consulta [`src/README.md`](../src/README.md) per le istruzioni specifiche del package. + +## 6. Protocollo G.A.P. e limiti di sicurezza + +Il protocollo inglese identifica GAP-001 come **Active Paranoia Management**; il titolo del protocollo italiano è **Gestione Attiva delle Paranoie**. G.A.P. descrive un modello cognitivo di contenimento e risposta. Il runtime attuale fornisce stati modellati per target/VM e alcune azioni difensive, ma non implementa il watchdog descritto, l'isolamento sandbox a livello di sistema operativo o il kill-switch forzato. + +Leggi la [Politica di Sicurezza](../SECURITY.md), la [Politica di Sicurezza italiana](SECURITY_IT.md) e il [Protocollo G.A.P.-001](../protocols/it/GAP-001-protocol.md) prima di formulare affermazioni di sicurezza sul progetto. + +## 7. Integrazione LLM e benchmark + +Il repository non distribuisce un client LLM né una pipeline completa da input grezzo a LLM. Un'applicazione esterna può consumare l'output del compilatore e scegliere di inoltrare uno stato serializzato a un modello, applicando i propri controlli di consenso, privacy, validazione e sicurezza. + +In questo repository non sono presenti benchmark riproducibili di riduzione token, tasso di allucinazione o latenza end-to-end. I valori numerici vanno considerati stime non verificate fino alla pubblicazione di un corpus, versioni di tokenizer/modello, script di misura, numero di esecuzioni e risultati grezzi. Un parsing deterministico non rende deterministica l'inferenza LLM a valle. + +## 8. Test e build + +Dalla root del repository: + +```bash +PYTHONPATH=src python3 -m unittest discover -s tests -v +python3 -m compileall -q src tests ``` ---- +Per creare il package Python: + +```bash +cd src +python3 -m pip wheel . --no-deps +``` + +GitHub Actions esegue la suite di regressione sulla matrice di versioni Python dichiarata e costruisce il package. I comandi locali sopra riportati sono i controlli di base usati per i contributi. + +## 9. Documentazione correlata -*Redatto sotto il Gruppo di Specifica HumOS.* -*Repository Ufficiale:* [https://github.com/SystemAdmin01/HumOS](https://github.com/SystemAdmin01/HumOS) +- [README principale](../README.md) — panoramica e avvio rapido. +- [Specifica LINGHOS](SPEC_IT.md) · [LINGHOS specification in English](SPEC.md). +- [Guida sviluppatori inglese](GUIDE.md). +- [Note linguistiche LINGHOS in inglese](en/LINGHOS.md) · [note LINGHOS italiane](it/LINGHOS.md). +- [Linee guida per i contributi](CONTRIBUTING_IT.md) · [Contribution guidelines](../CONTRIBUTING.md). diff --git a/docs/SECURITY_IT.md b/docs/SECURITY_IT.md index 4ada7c3..e1efb7f 100644 --- a/docs/SECURITY_IT.md +++ b/docs/SECURITY_IT.md @@ -1,8 +1,8 @@ # Politica di Sicurezza Cognitiva per HumOS & LINGHOS **Identificatore Documento:** `SEC-POLICY-20261108-IT` -**Stato dello Standard:** `Standard di Sicurezza in Produzione & Protocollo di Divulgazione delle Vulnerabilità` +**Stato dello Standard:** `Politica di Sicurezza del Progetto & Guida alla Divulgazione delle Vulnerabilità` **Classificazione:** `Architettura di Sicurezza Runtime & Modello delle Minacce` -**Responsabile Sicurezza:** `SystemAdmin01` (`security@humos.local`) +**Contatto Sicurezza:** [SystemAdmin01 su GitHub](https://github.com/SystemAdmin01) --- @@ -51,36 +51,38 @@ flowchart TD --- -## 3. Invarianti di Isolamento delle Sandbox (Architettura G.A.P.) +## 3. Invarianti di Isolamento delle Sandbox — Obiettivi di Progetto G.A.P. -Il sottosistema **G.A.P.** (**Guard, Analyze, Patch**) fornisce garanzie d'isolamento a runtime non aggirabili. +> **Limiti dell'implementazione (package 1.0.0):** Questa politica descrive i controlli previsti e il modello delle minacce; non costituisce una certificazione di sicurezza. Il runtime attuale modella lo stato di target e VM, ma non fornisce isolamento VM a livello di sistema operativo, un watchdog G.A.P. per i loop o il primitivo documentato `TRIGGER.kill_switch()`. Il server Cockpit si lega al loopback, rifiuta le richieste POST browser cross-origin e limita i body JSON a 1 MiB. Non autentica utenti o processi locali. Non esporlo tramite interfacce pubbliche, reverse proxy o tunnel. -### 3.1 Applicazione Rigorosa dei Confini di Memoria -1. **Esposizione Zero Senza Scudo:** Quando viene rilevata la condizione `CS_EXPOSED`, il Core Vault attiva immediatamente `Ice_shield` (disaccoppiamento termico) e `Double_Bottom_Shield` (firewall semantico). Nessun dato grezzo può raggiungere il Core senza transitare attraverso il filtro semantico. +Il protocollo **G.A.P.** (GAP-001, **Gestione Attiva delle Paranoie**) definisce il modello di contenimento e risposta previsto dal progetto. L'applicazione nel runtime è parziale; consulta i limiti d'implementazione qui sotto. + +### 3.1 Obiettivi di Contenimento (Non Garanzie del Runtime) +1. **Confine dello Stato Protetto:** L'obiettivo progettuale è attivare `Ice_shield` e `Double_Bottom_Shield` quando viene rilevato `CS_EXPOSED`. Il runtime attuale modella alcuni stati degli scudi, ma non applica un firewall semantico non aggirabile. 2. **Quarantena Rigida in VM:** Qualsiasi target dichiarato con punteggio di minaccia $\ge 7.0$ viene forzato all'interno di `HP_EXT_Defense_VM`. Gli è precluso qualsiasi accesso a segmenti di memoria di lavoro condivisa o thread ambientali. -3. **Garanzia di Interruzione del Loop:** Se un ciclo associativo supera il limite di tick dichiarato (`TIMEOUT = [30]`), `G.A.P.` esegue un hard `BREAK_LOOP(X)` forzando lo stato `SET_VALUE(X, UNDEFINED)`. Qualsiasi elaborazione speculativa viene interrotta definitivamente. +3. **Interruzione dei Loop:** Il protocollo specifica un timeout proposto e la risposta `BREAK_LOOP(X)`. Il runtime attuale non distribuisce un watchdog G.A.P. né i primitivi `BREAK_LOOP()` e `SET_VALUE()`. -### 3.2 Aborto Obbligatorio dell'Esecuzione tramite `TRIGGER.kill_switch()` -Il runtime impone un'interruzione immediata e non intercettabile (`TRIGGER.kill_switch()`) al verificarsi di una qualsiasi delle seguenti condizioni critiche di sicurezza: -- **Vettore di Stato Corrotto:** L'AST contiene nodi sintatticamente non validi o invarianti contraddittori (es. asserzione di `CS_SECURE` mentre `core_connected == True` su un target in lockdown). +### 3.2 Comportamento di Hard-Stop Proposto — `TRIGGER.kill_switch()` +L'obiettivo architetturale è richiedere un'interruzione immediata (`TRIGGER.kill_switch()`) al verificarsi delle seguenti condizioni critiche. Questo primitivo non è implementato dal runtime attuale: +- **Vettore di Stato Corrotto:** Un futuro livello di parsing/validazione rileva sorgente malformata o stato modellato contraddittorio (es. asserzione di `CS_SECURE` mentre `core_connected == True` su un target in lockdown). - **Firma di Iniezione Rilevata:** Una variabile di input contiene sintassi di exploit attiva mirata ai tokenizer degli LLM a valle. - **Soglia di Saturazione Biometrica:** Il battito cardiaco autonomo supera $130\text{ BPM}$ o il carico della memoria di lavoro tocca il $95\%$. -#### Garanzie dell'Aborto Invariante: -All'attivazione di `TRIGGER.kill_switch()`: -1. Tutti i canali di comunicazione vengono troncati: `Close(all) > bridges`. -2. La fedeltà verso i target viene azzerata: `Fidelity = 0%`. -3. Il distacco emotivo è assoluto: `Take_DOWN(all) > Core`. -4. Gli override vengono imposti: `OVR >> (DDS, ADS)`. -5. L'host entra in cold standby a fedeltà zero fino all'autenticazione manuale dell'operatore. +#### Sequenza di risposta proposta, se implementata: +Se un futuro runtime implementerà e attiverà `TRIGGER.kill_switch()`, la sequenza prevista sarà: +1. I ponti di comunicazione modellati verrebbero chiusi: `Close(all) > bridges`. +2. La fedeltà modellata del target verrebbe impostata a zero: `Fidelity = 0%`. +3. La connessione modellata al Core verrebbe rimossa: `Take_DOWN(all) > Core`. +4. Gli override difensivi modellati verrebbero applicati: `OVR >> (DDS, ADS)`. +5. Lo stato modellato dell'host entra in cold standby a fedeltà zero fino all'autenticazione manuale dell'operatore. --- -## 4. Matrice di Gravità delle Minacce & Tempi di Risoluzione SLA +## 4. Matrice di Gravità delle Minacce & Finestre Obiettivo di Risoluzione Le vulnerabilità segnalate al Security Team di HumOS vengono classificate secondo il modello **Cognitive Security Vulnerability Scoring (CSVS)**: -| Livello di Gravità | Definizione della Minaccia | Impatto Operativo | SLA di Risoluzione | +| Livello di Gravità | Definizione della Minaccia | Impatto Operativo | Finestra Obiettivo di Risoluzione* | | :--- | :--- | :--- | :--- | | **CRITICA** | Violazione diretta del Core Vault (`CS_UNLOCKED`); loop ricorsivo inarrestabile con blocco cognitivo totale; prompt injection che causa esecuzione di tool esterni non autorizzati. | Perdita totale dei confini cognitivi; grave disregolazione emotiva; dispatch arbitrario dell'LLM. | **Risoluzione entro 24 Ore** | | **ALTA** | Mancato isolamento di un target ad alta minaccia ($C \ge 8$) nella sandbox `G.A.P.`; perdita di memoria in `RAM.alloc()` con progressivo esaurimento delle risorse; mancato contenimento del thermal throttling da parte di `Ice_shield`. | Saturazione della memoria di lavoro ($>85\%$); fuoriuscita di stimoli ansiogeni acuti; perdita del focus operativo. | **Risoluzione entro 72 Ore** | @@ -91,20 +93,22 @@ Le vulnerabilità segnalate al Security Team di HumOS vengono classificate secon ## 5. Protocollo di Divulgazione & Segnalazione Responsabile -Adottiamo una procedura di divulgazione strutturata e responsabile. **Non** divulgare vulnerabilità cognitive pubblicamente sui tracker di issue o sui social network prima della pubblicazione della relativa patch. +Adottiamo una procedura di divulgazione strutturata e responsabile. **Non** divulgare vulnerabilità pubblicamente prima di aver coordinato la segnalazione con il maintainer. I tempi di risposta non sono attualmente garantiti da uno SLA formale. ### 5.1 Fasi di Segnalazione -1. **Invio della Segnalazione:** Cripta il report di vulnerabilità e invialo a `security@humos.local` (oppure tramite la funzione GitHub Private Vulnerability Reporting su `https://github.com/SystemAdmin01/HumOS/security/advisories`). +1. **Invio della Segnalazione:** Utilizza [GitHub Private Vulnerability Reporting](https://github.com/SystemAdmin01/HumOS/security/advisories) se è abilitato per il repository. In caso contrario, contatta il maintainer tramite il [profilo GitHub](https://github.com/SystemAdmin01). Non inviare report all'indirizzo segnaposto `security@humos.local`. 2. **Formato del Payload Richiesto:** - Descrizione dettagliata del vettore di vulnerabilità cognitiva. - Minimal Reproducible Example (MRE) scritto in sintassi `.lghos` che dimostri l'exploit. - Flusso di input grezzo che bypassa la demodulazione o innesca la ricorsione incontrollata. - Stato telemetrico osservato rispetto al comportamento invariante atteso. -3. **Presa in Carico & Conferma:** Il team di sicurezza conferma la ricezione entro **12 ore** e fornisce una valutazione iniziale di gravità entro **24 ore**. -4. **Periodo di Embargo:** Si applica un embargo standard di **30 giorni** dalla data di conferma della presa in carico, durante il quale la patch viene sviluppata e verificata tramite suite di test unitari. +3. **Presa in Carico & Conferma:** Il maintainer prenderà in carico e valuterà le segnalazioni in base alla propria disponibilità; non sono garantiti tempi di conferma o risoluzione. +4. **Periodo di Embargo:** Concorda le tempistiche di divulgazione con il maintainer; non presumere l'esistenza di un periodo fisso di embargo. 5. **Bollettino Pubblico & Riconoscimenti:** Al rilascio della patch, viene pubblicato un bollettino ufficiale di sicurezza (`SEC-ADV-YYYYMMDD-XX`), con attribuzione del merito al ricercatore. --- -*Redatto e verificato sotto il Gruppo di Specifica HumOS.* +**Le finestre indicate sono obiettivi di pianificazione, non SLA contrattuali né tempi di risposta garantiti.* + +*Gestito da SystemAdmin01.* *Repository Ufficiale:* [https://github.com/SystemAdmin01/HumOS](https://github.com/SystemAdmin01/HumOS) diff --git a/docs/SPEC.md b/docs/SPEC.md index d7a17a6..eca1a6b 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -12,18 +12,28 @@ LINGHOS (**Language for Interfacing Neurodivergent Gestalt Human Operating Systems**) is an **Opinionated Personal Cognitive Syntax**. It is a deterministic, high-throughput Domain-Specific Language (DSL) architected specifically to map volatile, unstructured, neurodivergent internal states (ADHD hyper-arousal, cognitive overload, emotional dysregulation, and associative loop cascades) into discrete, verifiable state vectors. ### 1.2 Core Mission & Operational Mechanics -Traditional emotional expression and subjective journaling generate severe signal loss when interfaced with computational systems and Large Language Models (LLMs): -- **Token Inflation:** Unstructured emotional venting consumes excessive context window capacity with repetitive, circular tokens. -- **Semantic Ambiguity:** Subjective prose induces stochastic drift and hallucinations in downstream LLM reasoning engines. -- **Latency & Thermal Throttling:** Unstructured mental feedback loops consume cognitive working memory without convergence. -LINGHOS functions as an abstraction barrier between biological neuro-chemistry and deterministic cognitive execution. By enforcing strict lexical tokens, boundary declarations (`Sandboxes`), and thermodynamic resource accounting (`RAM`, `BPM`, `CS State`), LINGHOS strips conversational and emotional noise down to raw semantic payloads. The resulting state vectors enable zero-hallucination semantic parsing, verifiable state-transition tracking, and deterministic instruction execution. +Unstructured cognitive input can be difficult to inspect and reuse in computational workflows. Repetition, missing context, and ambiguous references may increase prompt size or make downstream interpretation less predictable. These are design motivations for HumOS, not measured claims about all natural-language prompts or all LLMs. + +LINGHOS is designed to provide an explicit representation layer: users can name targets, assign modeled attributes, and describe supported actions with a compact DSL. This can make the resulting state easier to inspect and pass to another application. The current package does not automatically extract that state from free text, and structured input does not guarantee zero hallucinations or deterministic behavior from an external LLM. + +--- + +### 1.3 Implementation Status and Conformance Boundary + +This document is the **architectural target specification**, not a claim that every primitive below is implemented by the current Python runtime. The package version (`1.0.0`) and this specification revision (`2.1.0-REV4`) are independent version lines. + +**Implemented in the current repository:** line-oriented parsing/compilation for the supported subset (`#include`, `Get:`, `Set_CriticVal`, `@Start>`, `Call >>`, lockdown/attack directives, `Take_DOWN`, `Close`, `OVR`, `BE`, `IF`, `Echo`, and `<<@end`); in-memory target and VM *models*; a subset of skill state transitions; compiler diagnostics and modeled telemetry; CLI and local Cockpit. + +**Design-level / not yet enforced as runtime primitives:** `RAM.alloc()`, `RAM.free()`, `RAM.purge()`, `THREAD.*`, `BREAK_LOOP()`, `SET_VALUE()`, `TRIGGER.kill_switch()`, a G.A.P. watchdog with a real timeout, operating-system VM/process isolation, hardware biometric acquisition, and automatic raw-language-to-state demodulation. The VM objects are application data models, not operating-system virtual machines. The package does not itself call an external LLM; integration snippets that construct prompts are examples for downstream applications. + +For identical source and identical initial runtime/registry state, the supported grammar decisions and non-time-dependent state updates are rule-based. Timestamped logs and persisted registry contents can vary between runs. This does **not** guarantee deterministic or hallucination-free behavior from an external LLM. Treat all unimplemented primitives in the following reference as proposed semantics until their runtime implementation and tests are added. --- ## 2. Processing Pipeline Mechanics -The HumOS runtime processes cognitive inputs across a deterministic 4-stage pipeline. Every transformation step adheres to an explicit structural contract. +The diagram below describes the intended reference architecture, not the execution path shipped in the current package. See section 1.3 for the implemented components. ```mermaid flowchart TD @@ -37,19 +47,19 @@ flowchart TD end subgraph Stage3["Stage 3: Compilation & State Synthesis"] - COMP["LINGHOS AST Compiler & Lexer
(Symbol Validation, Proximity Matrix)"] + COMP["LINGHOS Compiler / State Serialization
(Reference Design)"] STATE_CHECK{"Loop / Panic
Detected?"} AST_GEN["Target Vector Matrix
+ Thermodynamic Telemetry Engine"] end subgraph Stage4["Stage 4: Execution Engine"] - LLM["Deterministic Execution Backend
(LLM Semantic Interpreter / Action Dispatch)"] + LLM["Optional External LLM Consumer
(Probabilistic Inference / Application Actions)"] end subgraph TrapRouting["Exception & Interrupt Subsystems"] - GAP["G.A.P. Sandbox Subsystem
(Guard, Analyze, Patch)"] - KILL["Emergency Abort Subsystem
(TRIGGER.kill_switch - Hardware Clamp)"] - CS_LOCK["Core Vault Zero-Fidelity Clamp
[CS_SECURE Enforced]"] + GAP["G.A.P.-001 Protocol
(Active Paranoia Management)"] + KILL["Proposed Hard-Stop Path
(Not Implemented in Current Runtime)"] + CS_LOCK["Proposed Core-State Response
[Design Target]"] end RAW --> FILT @@ -303,14 +313,12 @@ flowchart TD ### 3.3 Security & Interception Layer -#### 3.3.1 `G.A.P.` (Guard, Analyze, Patch) +#### 3.3.1 `G.A.P.-001` (Active Paranoia Management) - **Syntax Spec:** ```linghos Call >> G.A.P.protocol; - // Formal expansion: - // Guard(X) -> Intercept volatile variable X - // Analyze(X) -> Detect Assoc_Engine loop condition - // Patch(X) -> BREAK_LOOP(X) + SET_VALUE(X, UNDEFINED) + Sandboxing + // Protocol identity: Active Paranoia Management. + // The operations below are proposed semantics, not implemented runtime primitives. ``` - **Arguments/Parameters:** - Implicit context or explicit target: `X` (`Variable / Threat Payload`). diff --git a/docs/SPEC_IT.md b/docs/SPEC_IT.md index 1cce84f..5f71d1b 100644 --- a/docs/SPEC_IT.md +++ b/docs/SPEC_IT.md @@ -12,18 +12,28 @@ LINGHOS (**Language for Interfacing Neurodivergent Gestalt Human Operating Systems**) è una **Sintassi Cognitiva Personale Rigorosa**. Si tratta di un Domain-Specific Language (DSL) deterministico ad alta efficienza, progettato specificamente dall'autore per mappare stati interni neurodivergenti e instabili (iper-attivazione da ADHD, sovraccarico cognitivo, disregolazione emotiva e cascate di loop associativi) in vettori di stato discreti e verificabili. ### 1.2 Obiettivo Primario & Meccanica Operativa -L'espressione emotiva non strutturata e il journaling soggettivo tradizionale generano una perdita di segnale critica quando interfacciati con sistemi computazionali e Large Language Model (LLM): -- **Inflazione dei Token:** Lo sfogo emotivo non strutturato satura il context window con token ridondanti e ciclici. -- **Ambiguità Semantica:** La prosa soggettiva introduce deviazioni stocastiche e allucinazioni nei motori di inferenza LLM a valle. -- **Latenza & Thermal Throttling:** I loop di feedback mentali non strutturati consumano la memoria di lavoro (RAM cognitiva) senza mai convergere verso una soluzione. -LINGHOS agisce come una barriera di astrazione tra la neurochimica biologica e l'esecuzione cognitiva deterministica. Imponendo token lessicali rigorosi, dichiarazioni di confine perimetrale (`Sandbox`), e un bilancio termodinamico delle risorse (`RAM`, `BPM`, `Stato CS`), LINGHOS estrae il segnale utile eliminando il rumore emotivo. I vettori di stato risultanti consentono un parsing semantico privo di allucinazioni, un tracciamento verificabile delle transizioni di stato e l'esecuzione deterministica delle istruzioni. +Gli input cognitivi non strutturati possono essere difficili da ispezionare e riutilizzare nei workflow computazionali. Ripetizioni, contesto mancante e riferimenti ambigui possono aumentare la dimensione dei prompt o rendere meno prevedibile l'interpretazione a valle. Sono motivazioni progettuali di HumOS, non affermazioni misurate su tutti i prompt in linguaggio naturale o su tutti gli LLM. + +LINGHOS è progettato per fornire un livello di rappresentazione esplicito: l'utente può nominare target, assegnare attributi modellati e descrivere azioni supportate tramite un DSL compatto. Questo può rendere lo stato risultante più facile da ispezionare e trasferire a un'altra applicazione. Il package attuale non estrae automaticamente tale stato dal testo libero e un input strutturato non garantisce l'assenza di allucinazioni o un comportamento deterministico da parte di un LLM esterno. + +--- + +### 1.3 Stato dell'Implementazione e Limiti di Conformità + +Questo documento è una **specifica architetturale di riferimento**, non la dichiarazione che ogni primitivo descritto sia già implementato nel runtime Python. La versione del package (`1.0.0`) e la revisione della specifica (`2.1.0-REV4`) appartengono a due linee di versione distinte. + +**Implementato nel repository attuale:** parsing/compilazione lineare del sottoinsieme supportato (`#include`, `Get:`, `Set_CriticVal`, `@Start>`, `Call >>`, direttive lockdown/attack, `Take_DOWN`, `Close`, `OVR`, `BE`, `IF`, `Echo` e `<<@end`); *modelli in memoria* per target e VM; un sottoinsieme di transizioni di stato delle skill; diagnostica del compilatore e telemetria modellata; CLI e Cockpit locale. + +**A livello di specifica / non ancora applicato come primitivo runtime:** `RAM.alloc()`, `RAM.free()`, `RAM.purge()`, `THREAD.*`, `BREAK_LOOP()`, `SET_VALUE()`, `TRIGGER.kill_switch()`, un watchdog G.A.P. con timeout effettivo, isolamento di processi/VM a livello di sistema operativo, acquisizione biometrica hardware e demodulazione automatica da linguaggio naturale a vettore di stato. Gli oggetti VM sono modelli applicativi, non macchine virtuali del sistema operativo. Il package non invoca direttamente un LLM esterno; gli esempi di generazione dei prompt sono integrazioni illustrative per applicazioni a valle. + +A parità di sorgente e stato iniziale identico del runtime/registro, le decisioni grammaticali supportate e gli aggiornamenti di stato non dipendenti dal tempo seguono regole esplicite. I log con timestamp e il contenuto persistito del registro possono variare tra esecuzioni. Questo **non** garantisce risposte deterministiche o prive di allucinazioni da parte di un LLM esterno. I primitivi non implementati descritti nelle sezioni successive vanno considerati semantica proposta fino all'aggiunta del runtime e dei relativi test. --- ## 2. Meccanica della Pipeline di Elaborazione -Il runtime di HumOS elabora gli input cognitivi attraverso una pipeline deterministica a 4 stadi. Ogni passaggio di trasformazione rispetta un contratto strutturale esplicito. +Il diagramma seguente rappresenta l'architettura di riferimento prevista, non il percorso implementato nel package attuale. Per i componenti disponibili consulta la sezione 1.3. ```mermaid flowchart TD @@ -37,19 +47,19 @@ flowchart TD end subgraph Stadio3["Stadio 3: Compilazione & Sintesi di Stato"] - COMP["Compilatore AST & Lexer LINGHOS
(Validazione Simboli, Matrice Prossimità)"] + COMP["Compilatore LINGHOS / Serializzazione dello Stato
(Architettura di Riferimento)"] STATE_CHECK{"Loop / Panico
Rilevato?"} AST_GEN["Matrice Vettori Target
+ Motore Telemetria Termodinamica"] end subgraph Stadio4["Stadio 4: Motore di Esecuzione"] - LLM["Backend di Esecuzione Deterministica
(Interprete Semantico LLM / Dispatch Azioni)"] + LLM["Consumer LLM Esterno Opzionale
(Inferenza Probabilistica / Azioni Applicative)"] end subgraph TrapRouting["Sottosistemi di Eccezione & Interrupt"] - GAP["Sottosistema Sandbox G.A.P.
(Guard, Analyze, Patch)"] - KILL["Sottosistema di Aborto d'Emergenza
(TRIGGER.kill_switch - Clamp Hardware)"] - CS_LOCK["Sigillo Core Vault a Fedeltà Zero
[Forzatura CS_SECURE]"] + GAP["Protocollo G.A.P.-001
(Gestione Attiva delle Paranoie)"] + KILL["Percorso Hard-Stop Proposto
(Non Implementato nel Runtime Attuale)"] + CS_LOCK["Risposta Proposta dello Stato Core
[Obiettivo Architetturale]"] end RAW --> FILT @@ -303,14 +313,12 @@ flowchart TD ### 3.3 Livello Sicurezza & Intercettazione (Security & Interception Layer) -#### 3.3.1 `G.A.P.` (Guard, Analyze, Patch) +#### 3.3.1 `G.A.P.-001` (Active Paranoia Management / Gestione Attiva delle Paranoie) - **Specifica Sintattica:** ```linghos Call >> G.A.P.protocol; - // Espansione formale: - // Guard(X) -> Intercetta la variabile caotica X - // Analyze(X) -> Rileva lo stato di loop in Assoc_Engine - // Patch(X) -> BREAK_LOOP(X) + SET_VALUE(X, UNDEFINED) + Sandboxing + // Identità del protocollo: Active Paranoia Management / Gestione Attiva delle Paranoie. + // Le operazioni seguenti sono semantiche proposte, non primitive runtime implementate. ``` - **Argomenti / Parametri:** - Contesto implicito o target esplicito: `X` (`Variabile Caotica / Payload di Minaccia`). diff --git a/docs/en/LINGHOS.md b/docs/en/LINGHOS.md index 6319a46..b99b242 100644 --- a/docs/en/LINGHOS.md +++ b/docs/en/LINGHOS.md @@ -1,4 +1,4 @@ -# LINGHOS (LINGuistic Human Operating System) +# LINGHOS — Language for Interfacing Neurodivergent Gestalt Human Operating Systems ### Official Specification of the Cognitive Command Language for Neurodivergent and Hyper-Logical Minds > *"You can write four pages like an emotional diary without ever understanding what makes you feel bad. LINGHOS describes in four lines dynamics that are hard to explain in words, showing you the exact steps to the solution."* — **OD, System Architect** @@ -351,8 +351,7 @@ LINGHOS is an actively evolving language. The following modules are currently in * `Route >> Sector_Beta` (Social Firewall and Mimicry) * `Route >> Sector_Gamma` (Cold Archive / De-emotionalised Trauma Logs) * `Route >> Sector_Delta` (Biological Hardware Maintenance) -* 🔄 **LINGHOS Parser & CLI (Open Source Tooling):** - Development of a software interpreter (terminal CLI) that allows users to type their LINGHOS scripts on a computer and obtain a tree-view visualisation of their active defences and variables. +* ✅ **Existing Python tooling:** The repository includes a line-oriented parser/interpreter, compiler, and CLI commands (`run`, `repl`, `gui`, and `web`). The currently supported syntax is a subset of this language reference; it does not construct a formal AST or enforce every primitive described in the design documents. See [the implementation-status notes](../SPEC.md#13-implementation-status-and-conformance-boundary). --- @@ -373,7 +372,7 @@ There is nowhere written that you must passively wait and hope to feel better. The **LINGHOS** language, the cognitive command syntax, and the **HumOS (Human Operating System)** framework are works of intellect created and released for the self-determination, personal sovereignty, and psychological freedom of neurodivergent and hyper-logical minds. The entire technical documentation is distributed under the licence: -**Creative Commons Attribution – NonCommercial – NoDerivatives 4.0 International (CC BY-NC-ND 4.0)**. +**Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)**. See the repository [LICENSE](../../LICENSE.txt) for the governing terms. ### Terms of Use: * 👤 **Mandatory Attribution (BY):** There is an absolute obligation to **acknowledge and cite the intellectual authorship of the original author of LINGHOS and HumOS** in every use, citation, transcription, or public fork of the code and syntax. diff --git a/docs/en/README.md b/docs/en/README.md index 1d55ee9..0fe3a4b 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -1,116 +1,42 @@ -# HumOS -HumOS — The Cognitive Management Framework for ADHD. +# HumOS — English documentation hub -# ⚡ HumOS: Human Operating System +HumOS (Human Operating System) is a cognitive-management framework that applies operating-system concepts to working memory, attention, recurring thought loops, boundaries, and self-regulation. Its implementation combines the **LINGHOS** domain-specific language, a Python runtime, the **G.A.P.** protocol model, and the browser-based **HumOS Cockpit GUI**. -> **The brain is the medium. HumOS is the runtime.** +This repository contains both implemented software and evolving architectural documentation. Read the implementation-status notes in the specifications before treating a documented primitive or security property as a runtime guarantee. -Tired of classical psychology? Do others consistently misread your language? -**Why keep adapting yourself to the wrong parameters?** +## Start here -HumOS is a cognitive engineering and tactical defence framework with a Zero-Trust architecture, designed for analytical, neurodivergent minds and extreme-pressure environments. +- [Root project README](../../README.md) — overview, architecture, quick start, and examples. +- [LINGHOS specification](../SPEC.md) — syntax and architectural reference. +- [Developer guide](../GUIDE.md) — implementation walkthrough and integration examples. +- [LINGHOS language notes](LINGHOS.md) — language concepts and design history. +- [HumOS framework document](HumOS-Framework.md) — broader conceptual framework. +- [HumOS Cockpit GUI](../../src/linghos/cockpit.html) — visual editor and runtime console. +- [Runnable examples](../../examples/) — scripts and Python integration sample. -HumOS is not a theory for changing yourself or others. -It is an emergency toolkit for when the external environment becomes unbearable chaos and you need to keep functioning. +## Governance and security +- [Contribution guidelines](../../CONTRIBUTING.md) +- [Security policy](../../SECURITY.md) +- [G.A.P.-001 protocol](../../protocols/en/GAP-001-protocol.md) +- [License](../../LICENSE.txt) — Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0). +## Runtime commands - ---- - - - - -You know that feeling of having 47 tabs open in your brain, music blasting in the background, and finding yourself paralysed in front of a two-minute task? -You have always been told you are lazy, disorganised, or broken. - -**That is a lie.** -You have a Formula 1 engine mounted on a bicycle frame: you accelerate to the max but swerve everywhere because **nobody ever gave you the instruction manual.** - -HumOS is not traditional psychology, not mindfulness, and not motivational quotes on sunset photos. -It is a **cybernetic self-determination framework**: it teaches you to treat your mind not as an emotional prison, but as a biological machine to be administered with surgical coldness. - ---- - -## 🛠️ How It Works (in 30 seconds) - -Stop saying: *"I am anxious"* (if you *are* the anxiety, you cannot defeat it without destroying yourself). -Start saying: **"My system is processing an anomalous anxiety load."** - -The moment you transform the emotion from "your identity" to **"an external object"**, you stop being its victim and become the **SysAdmin** (System Administrator): - -* 🔴 **Hardware (The Body):** Battery, sleep, hormones. Stop looking for philosophical answers to a crisis caused by 4 hours of sleep and dehydration. -* 🟡 **Software (The Programs):** Social anxiety, guilt, traumas. They are just *bloatware*: broken apps running in the background clogging the RAM. -* 🟢 **The Nucleus (You):** The user in command. The untouchable consciousness seated in the control room. - -### The two fundamental weapons: -1. **The Cybernetic Placebo:** Rename your blocks using engineering vocabulary. A server that overloads is not "bad" and has not "sinned": it simply needs repairing (*troubleshooting*). Remove the blame, and the paralysis disappears. -2. **Mental AIkido:** Pain, anger, and frustration are pure kinetic energy at extremely high voltage. Do not suppress them: forcibly route them into study, code, work, or weights at the gym. **With HumOS you gain even when you suffer.** - ---- - -## 🗂️ System Map (File Index) - -This repository contains the entire operational architecture: - -* 📖 **[Chapter 1: The Paradigm Shift](docs/01_THE_PARADIGM_SHIFT.md)** — From victim to SysAdmin, the 4-lane RAM motorway, and the Cybernetic Placebo. -* 🛡️ **[Chapter 2: The Source Code (SC)](docs/02_THE_SOURCE_CODE.md)** — The inner vault, the Vulnerability Charter, the Kernel Panic, and Safe Mode (apathy as a life-saving measure). -* ⚔️ **[Chapter 3: Defence & AIkido](docs/03_DEFENCE_AND_AIKIDO.md)** — The Double-Bottom Shield, disposable social Virtual Machines (VMs), and energy conversion. -* 🚨 **[Chapter 4: The DCICE Protocol](docs/04_DCICE_PROTOCOL.md)** — The operational cycle against threats (*Detect, Classify, Isolate, Counter, Escalate*) with LINGHOS implementation. -* 💻 **[Chapter 5: LINGHOS](docs/05_LINGHOS_SYNTAX.md)** — The command-line syntax for isolating mental bugs and forcing *Force Quit*. -* 📑 **[Complete Unified Document](docs/HUMOS_OFFICIAL_DOCUMENTATION.md)** — The full exportable text, ready for continuous reading or Notion. - -## ⚡ Manifesto & Architectural Philosophy - -Traditional psychology and conventional models have always repeated the same dogma: *"You must adapt. You must modify your syntax to conform to environments designed for other architectures."* - -**HumOS rejects this approach.** - -Attempting to run a high-cognitive-load and analytical brain on parameters designed for low-performance systems causes only three things: *latency*, forced *masking*, and *system crash* (burnout). - -### Kernel Principles: - -1. **No Legacy Adaptation:** We do not modify our code to conform to inefficient or manipulative social protocols. -2. **Standard Definition:** HumOS does not seek empathy or approval; it provides the interface, the Firewall, and the execution runtime so that the outside world must interface with our logical syntax. -3. **Cognitive Sovereignty (Zero-Trust):** The Kernel belongs to the SysAdmin. Every external input (provocation, gaslighting, sensory/emotional overload) is treated as an unverified data packet until it passes the Sandbox filter. - -> *"Do not adapt your code to an inadequate environment. Build the framework that forces the environment to respect your architecture."* - - -> 👉 To consult the full technical architecture, layers, and LINGHOS commands, read the **[Official Manual](Main.md)**. - ---- --- - -## ⚡ System Support & Protocol Indexing - -If you are using **HumOS**, have integrated it into your local prompts/LLMs, or are running it directly from the terminal, consider **leaving a Star (⭐)** on the repository. - -GitHub indexing helps the system remain visible, open, and independent from proprietary infrastructure. - -### 🌟 Support the project via GitHub CLI - -If you are in the terminal and want to star it instantly without going through the browser, you can run this command directly (requires `gh` CLI installed): +From the repository root: ```bash -gh repo star SystemAdmin01/HumOS +python3 src/app.py ``` +For the package CLI, from `src/` after installing the package: -## 📜 License and Copyright - -HumOS is a **public and open** project, created to restore clarity and sovereignty to those with minds out of scale. You may read it, study it, and apply it to yourself in complete freedom. - - **There are however two absolute legal constraints:** +```bash +python3 -m linghos --help +``` -1. 👤 **Mandatory Attribution:** In any use, citation, sharing, or public reworking, the **authorship of the original author of HumOS must ALWAYS be explicitly cited and acknowledged**. -2. 🚫 **Absolute Commercial Prohibition (Non-Commercial):** Any use of the work for profit purposes — paid courses, consulting, direct monetisation, or inclusion in commercial products — is **strictly forbidden** without the author's explicit written consent. +The package metadata declares Python 3.8 or newer. See the root README and package metadata for the current setup details. -*(Reference licence: Creative Commons CC BY-NC 4.0)* - MIT Copyright (c) 2026 Diego /SystemAdmin01 --- -## 🚀 Take the Controls - -> Stop enduring background processes you never chose. -> Sit down at the console. -> **Log in as Root.** +[Italian documentation hub](../it/README.md) · [Repository on GitHub](https://github.com/SystemAdmin01/HumOS) diff --git a/docs/it/LINGHOS.md b/docs/it/LINGHOS.md index 16ed290..f184ba5 100644 --- a/docs/it/LINGHOS.md +++ b/docs/it/LINGHOS.md @@ -1,4 +1,4 @@ -# LINGHOS (LINGuistic Human Operating System) +# LINGHOS — Language for Interfacing Neurodivergent Gestalt Human Operating Systems ### Specifica Ufficiale del Linguaggio di Comando Cognitivo per Menti Neurodivergenti e Iper-Logiche > *"Puoi scrivere quattro pagine come un diario di lacrime senza mai capire cosa ti faccia stare male. LINGHOS in quattro righe descrive dinamiche che a parole si fatica a spiegare, mostrandoti i passi esatti per la soluzione."* — **OD, Architetto del Sistema** @@ -341,8 +341,7 @@ LINGHOS è un linguaggio in evoluzione attiva. I seguenti moduli sono attualment * `Route >> Sector_Beta` (Firewall Sociale e Mimetismo) * `Route >> Sector_Gamma` (Archivio Freddo / Log di Traumi De-emozionalizzati) * `Route >> Sector_Delta` (Manutenzione Hardware Biologico) -* 🔄 **LINGHOS Parser & CLI (Tooling Open Source):** - Sviluppo di un interprete software (CLI per terminale) che consenta agli utenti di digitare i propri script LINGHOS su computer e ottenere una visualizzazione ad albero delle proprie difese e variabili attive. +* ✅ **Tooling Python disponibile:** Il repository include un parser/interprete line-oriented, un compilatore e i comandi CLI (`run`, `repl`, `gui` e `web`). La sintassi attualmente supportata è un sottoinsieme di questo riferimento linguistico; non costruisce un AST formale né applica tutti i primitivi descritti nei documenti di progetto. Consulta le [note sullo stato dell'implementazione](../SPEC_IT.md#13-stato-dellimplementazione-e-limiti-di-conformita). --- @@ -363,7 +362,7 @@ Non c'è scritto da nessuna parte che devi aspettare e sperare passivamente di s Il linguaggio **LINGHOS**, la sintassi di comando cognitivo e il framework **HumOS (Human Operating System)** sono opere dell'ingegno create e rilasciate per l'autodeterminazione, la sovranità personale e la libertà psicologica delle menti neurodivergenti e iper-logiche. L'intera documentazione tecnica è distribuita con licenza: -**Creative Commons Attribuzione - Non Commerciale - Non Opere Derivate 4.0 Internazionale (CC BY-NC-ND 4.0)**. +**Creative Commons Attribuzione - Non Commerciale 4.0 Internazionale (CC BY-NC 4.0)**. Consulta la [LICENZA](../../LICENSE.txt) del repository per i termini applicabili. ### Termini di Utilizzo: * 👤 **Paternità Obbligatoria (BY):** È fatto obbligo assoluto di **riconoscere e citare la paternità intellettuale dell'autore originale di LINGHOS e HumOS** in ogni utilizzo, citazione, trascrizione o fork pubblico del codice e della sintassi. diff --git a/docs/it/README.md b/docs/it/README.md index 34d36b4..da8c83e 100644 --- a/docs/it/README.md +++ b/docs/it/README.md @@ -1,116 +1,42 @@ -# HumOS -HumOS — The Cognitive Management Framework for ADHD. +# HumOS — Hub della documentazione italiana -# ⚡ HumOS: Human Operating System +HumOS (Human Operating System) è un framework di gestione cognitiva che applica concetti dei sistemi operativi alla memoria di lavoro, all'attenzione, ai loop ricorrenti, ai confini personali e all'autoregolazione. L'implementazione combina il linguaggio **LINGHOS**, un runtime Python, il modello di protocollo **G.A.P.** e la GUI browser-based **HumOS Cockpit**. -> **Il cervello è il mezzo. HumOS è il binario.** +Il repository contiene sia software implementato sia documentazione architetturale in evoluzione. Prima di considerare un primitivo documentato o una proprietà di sicurezza come una garanzia del runtime, consulta le note sullo stato d'implementazione nelle specifiche. -Stanco della psicologia classica? Gli altri decodificano male il tuo linguaggio? -**Perché continuare ad adattarti a parametri errati?** +## Per iniziare -HumOS è un framework di ingegneria cognitiva e difesa tattica ad architettura Zero-Trust, progettato per menti analitiche, neurodivergenti e contesti ad altissima pressione. +- [README principale del progetto](../../README.md) — panoramica, architettura, avvio rapido ed esempi. +- [Specifica LINGHOS](../SPEC_IT.md) — sintassi e riferimento architetturale. +- [Guida sviluppatori](../GUIDE_IT.md) — walkthrough dell'implementazione ed esempi d'integrazione. +- [Note sul linguaggio LINGHOS](LINGHOS.md) — concetti e storia del linguaggio. +- [Documento Framework HumOS](HumOS-Framework.md) — framework concettuale completo. +- [GUI HumOS Cockpit](../../src/linghos/cockpit.html) — editor visuale e console runtime. +- [Esempi eseguibili](../../examples/) — script e dimostrazione d'integrazione Python. -HumOS non è una teoria per cambiare te stesso o gli altri. -È una cassetta degli attrezzi di emergenza per quando l'ambiente esterno diventa un casino insopportabile e tu devi continuare a funzionare. +## Governance e sicurezza +- [Linee guida per i contributi](../CONTRIBUTING_IT.md) +- [Politica di sicurezza](../SECURITY_IT.md) +- [Protocollo G.A.P.-001](../../protocols/it/GAP-001-protocol.md) +- [Licenza](../../LICENSE.txt) — Creative Commons Attribuzione - Non Commerciale 4.0 Internazionale (CC BY-NC 4.0). +## Comandi runtime - ---- - - - - -Hai presente quando hai 47 schede aperte nel cervello, musica a palla in sottofondo e ti ritrovi paralizzato davanti a un compito da due minuti? -Ti hanno sempre convinto di essere pigro, disorganizzato o sbagliato. - -**È una menzogna.** -Hai un motore da Formula 1 montato sul telaio di una bicicletta: acceleri al massimo ma sbandi ovunque perché **nessuno ti ha mai dato il manuale di istruzioni.** - -HumOS non è psicologia tradizionale, non è mindfulness e non sono frasi motivazionali su foto di tramonti. -È un **framework cibernetico di autodeterminazione**: ti insegna a trattare la tua mente non come una prigione emotiva, ma come una macchina biologica da amministrare con freddezza chirurgica. - ---- - -## 🛠️ Come Funziona (in 30 secondi) - -Smetti di dire: *"Io sono ansioso"* (se tu *sei* l'ansia, non puoi sconfiggerla senza distruggere te stesso). -Inizia a dire: **"Il mio sistema sta processando un carico anomalo di ansia."** - -Nel momento in cui trasformi l'emozione da "tua identità" a **"oggetto esterno"**, smetti di esserne la vittima e diventi il **SysAdmin** (Amministratore di Sistema): - -* 🔴 **L'Hardware (Il Corpo):** Batteria, sonno, ormoni. Smetti di cercare risposte filosofiche a una crisi causata da 4 ore di sonno e disidratazione. -* 🟡 **Il Software (I Programmi):** Ansia sociale, sensi di colpa, traumi. Sono solo *bloatware*: app difettose aperte in background che intasano la RAM. -* 🟢 **Il Nucleo (Tu):** L'utente al comando. La coscienza intoccabile seduta nella cabina di regia. - -### Le due armi fondamentali: -1. **Il Placebo Cibernetico:** Rinomina i tuoi blocchi con un vocabolario ingegneristico. Un server che va in sovraccarico non è "cattivo" e non ha "peccato": va solo riparato (*troubleshooting*). Rimuovi la colpa, e la paralisi sparisce. -2. **AIkido Mentale:** Il dolore, la rabbia e la frustrazione sono pura energia cinetica ad altissimo voltaggio. Non reprimerli: instradali forzatamente su studio, codice, lavoro o ghisa in palestra. **Con HumOS guadagni anche quando soffri.** - ---- - -## 🗂️ Mappa del Sistema (Indice dei File) - -Questo repository contiene l'intera architettura operativa: - -* 📖 **[Capitolo 1: Il Cambio di Paradigma](docs/01_IL_CAMBIO_DI_PARADIGMA.md)** — Dalla vittima al SysAdmin, l'autostrada a 4 corsie della RAM e il Placebo Cibernetico. -* 🛡️ **[Capitolo 2: Il Codice Sorgente (CS)](docs/02_IL_CODICE_SORGENTE.md)** — Il caveau interiore, la Carta delle Vulnerabilità, il Kernel Panic e la Safe Mode (apatia come salvavita). -* ⚔️ **[Capitolo 3: Difesa & AIkido](docs/03_DIFESA_E_AIKIDO.md)** — Scudo a Doppio Fondo, Macchine Virtuali (VM) sociali sacrificabili e conversione dell'energia. -* 🚨 **[Capitolo 4: Il Protocollo DCICE](docs/04_PROTOCOLLO_DCICE.md)** — Il ciclo operativo contro le minacce (*Detect, Classify, Isolate, Counter, Escalate*) con implementazione LINGHOS. -* 💻 **[Capitolo 5: LINGHOS](docs/05_LINGHOS_SINTASSI.md)** — La sintassi a riga di comando per isolare i bug mentali e forzare il *Force Quit*. -* 📑 **[Documento Unico Completo](docs/HUMOS_DOCUMENTAZIONE_UFFICIALE.md)** — Il testo integrale esportabile pronto per la lettura continuativa o Notion. - -## ⚡ Manifesto & Filosofia Architetturale - -La psicologia tradizionale e i modelli convenzionali ripetono da sempre lo stesso dogma: *"Devi adattarti. Devi modificare la tua sintassi per conformarti ad ambienti pensati per altre architetture."* - -**HumOS rifiuta questo approccio.** - -Tentare di far girare un cervello ad alto carico cognitivo e analitico su parametri pensati per sistemi a basso rendimento causa unicamente tre cose: *latency*, *masking* forzato e *system crash* (burnout). - -### I Principi del Kernel: - -1. **Nessun Adattamento Legacy:** Non modifichiamo il nostro codice per adeguarci a protocolli sociali inefficienti o manipolatori. -2. **Definizione dello Standard:** HumOS non cerca empatia o approvazione; fornisce l'interfaccia, il Firewall e i binari d'esecuzione affinché l'esterno debba interfacciarsi con la nostra sintassi logica. -3. **Sovranità Cognitiva (Zero-Trust):** Il Kernel appartiene al SysAdmin. Ogni input esterno (provocazione, gaslighting, sovraccarico sensoriale/emotivo) è trattato come un pacchetto dati non verificato finché non supera il filtro di Sandbox. - -> *"Non adattare il tuo codice a un ambiente inadeguato. Costruisci il framework che costringe l'ambiente a rispettare la tua architettura."* - - -> 👉 Per consultare l'architettura tecnica completa, i livelli e i comandi LINGHOS, leggi il **[Manuale Ufficiale](Main.md)**. - ---- --- - -## ⚡ System Support & Protocol Indexing - -Se stai utilizzando **HumOS**, lo hai integrato nei tuoi prompt/LLM locali o lo stai eseguendo direttamente da terminale, considera di **lasciare una Stella (⭐)** al repository. - -L'indicizzazione su GitHub aiuta il sistema a rimanere visibile, aperto e indipendente da infrastrutture proprietarie. - -### 🌟 Supporta il progetto via GitHub CLI - -Se sei nel terminale e vuoi stellarlo al volo senza passare dal browser, puoi eseguire direttamente questo comando (richiede `gh` CLI installata): +Dalla root del repository: ```bash -gh repo star SystemAdmin01/HumOS +python3 src/app.py ``` +Per la CLI del package, dalla cartella `src/` dopo l'installazione: -## 📜 Licenza e Diritti d'Autore - -HumOS è un progetto **pubblico e aperto**, creato per restituire lucidità e sovranità a chi ha una mente fuori scala. Puoi leggerlo, studiarlo e applicarlo su te stesso in totale libertà. - - **Vi sono tuttavia due vincoli legali assoluti:** +```bash +python3 -m linghos --help +``` -1. 👤 **Paternità Obbligatoria (Attribution):** In qualsiasi utilizzo, citazione, condivisione o rielaborazione pubblica deve **SEMPRE essere esplicitamente citata e riconosciuta la paternità dell'autore originale di HumOS**. -2. 🚫 **Divieto Commerciale Assoluto (Non-Commercial):** È **severamente vietato** qualsiasi utilizzo dell'opera a fini di lucro: corsi a pagamento, consulenze, monetizzazione diretta o inclusione in prodotti commerciali senza esplicito consenso scritto dell'autore. +I metadati del pacchetto dichiarano Python 3.8 o superiore. Consulta il README principale e i metadati del package per i dettagli aggiornati. -*(Licenza di riferimento: Creative Commons CC BY-NC 4.0)* - MIT Copyright (c) 2026 Diego /SystemAdmin01 --- -## 🚀 Prendi i Comandi - -> Smetti di subire i processi in background che non hai scelto. -> Siediti alla console. -> **Accedi come Root.** +[English documentation hub](../en/README.md) · [Repository su GitHub](https://github.com/SystemAdmin01/HumOS) diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..b06c443 --- /dev/null +++ b/src/README.md @@ -0,0 +1,40 @@ +# LINGHOS Python package + +The `linghos` package contains the Python-side LINGHOS compiler, interpreter, state models, storage manager, command-line interface, and local HumOS Cockpit web server. + +- Package name: `linghos` +- Package version: `1.0.0` +- Minimum Python version: `3.8` +- Main GUI entry point: `python app.py` (run from this directory) +- CLI entry point: `python -m linghos` or the installed `linghos` command + +## Install from source + +From the repository root: + +```bash +cd src +python -m pip install . +``` + +## Run + +Launch the browser-based Cockpit: + +```bash +python app.py +``` + +Use the command-line interface: + +```bash +python -m linghos --help +python -m linghos run ../examples/adhd_ram_flush.lgh +python -m linghos repl +``` + +The runtime currently implements a subset of the evolving LINGHOS design specification. Consult the root README and `../docs/SPEC.md` for the implementation-status matrix and known boundaries. + +## License + +This package is distributed under the repository's [CC BY-NC 4.0 license](../LICENSE.txt). It is not MIT-licensed; commercial use is not permitted under that license. diff --git a/src/linghos/compiler.py b/src/linghos/compiler.py index ac7451d..d7e5344 100644 --- a/src/linghos/compiler.py +++ b/src/linghos/compiler.py @@ -1,7 +1,7 @@ """ LINGHOS Compiler & Bidirectional Code Generator. -Performs lexical analysis, AST generation, semantic validation, symbol learning, -dynamic telemetry synthesis, and inverse code generation from visual state. +Performs quote-aware normalization, line-oriented statement analysis, semantic diagnostics, +symbol learning, modeled telemetry synthesis, and inverse code generation from visual state. """ import re import time @@ -12,6 +12,7 @@ ) from .kernel import HumOSKernel from .storage import GLOBAL_STORAGE +from .syntax import find_block_end, normalize_script, strip_inline_comment class SymbolRegistry: """Dynamic symbol table that learns new symbols, skills, and macros from input.""" @@ -99,8 +100,8 @@ def list_all(self) -> List[Dict[str, Any]]: class LINGHOSCompiler: """ - Compiler that analyzes LINGHOS scripts, dynamically learns new symbols, - computes thermodynamic telemetry, and generates operational reports. + Line-oriented compiler that analyzes the supported LINGHOS subset, dynamically learns symbols, + computes modeled telemetry, and generates diagnostic reports. """ def __init__(self, registry: Optional[SymbolRegistry] = None): self.registry = registry or GLOBAL_REGISTRY @@ -117,11 +118,9 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over diagnostics: List[Dict[str, str]] = [] newly_learned: List[str] = [] - # Normalization - clean_code = code.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"') - clean_code = clean_code.replace("{", "{\n").replace("}", "\n}\n") - clean_code = re.sub(r';\s*(?=[A-Za-z#/@<])', ';\n', clean_code) - lines = clean_code.split("\n") + # Quote-aware normalization: structural characters inside strings/comments + # must not be interpreted as grammar delimiters. + lines = normalize_script(code).split("\n") # Parsing State double_bottom_shield = False @@ -135,7 +134,7 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over while i < total_lines: raw_line = lines[i] line_no = i + 1 - line = raw_line.split("//")[0].strip() + line = strip_inline_comment(raw_line).strip() if not line: i += 1 @@ -199,22 +198,27 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over if line.startswith("@Start>"): m = re.search(r'@Start>\s*\(\s*([A-Za-z0-9_]+)\s*\)', line) vm_name = m.group(1) if m else "General_VM" + block_end = find_block_end(lines, i) + if block_end is None: + diagnostics.append({"line": line_no, "level": "ERROR", "msg": "Blocco @Start non chiuso; compilazione interrotta."}) + i = total_lines + break + if vm_name.lower() not in self.registry.symbols: sym = self.registry.learn(vm_name, SymbolType.VM, f"Template VM custom '{vm_name}'", f"@Start>({vm_name}){{ ON>targets; }}") newly_learned.append(sym.name) targets = [] - while i < total_lines and "}" not in lines[i]: - i += 1 - sub_line = lines[i].split("//")[0].strip() + for sub_line in lines[i + 1:block_end]: + sub_line = strip_inline_comment(sub_line).strip() if "ON>" in sub_line: - on_targets = sub_line.split("ON>")[1].rstrip(";").strip() + on_targets = sub_line.split("ON>", 1)[1].rstrip(";").strip() targets = [t.strip() for t in on_targets.split(",") if t.strip()] kernel.start_vm(vm_name, targets) for t in targets: target_vms[t] = vm_name - i += 1 + i = block_end + 1 continue # 5. Call >> Skill(args) @@ -235,9 +239,14 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over # 6. /SET_Lockdown_Mode if "/SET_Lockdown_Mode" in line or "/SET_LOCKDOWN_MODE" in line: target_to_lockdown = "ALL" - while i < total_lines and "}" not in lines[i]: - i += 1 - sub_line = lines[i].split("//")[0].strip() + block_end = find_block_end(lines, i) + if block_end is None: + diagnostics.append({"line": line_no, "level": "ERROR", "msg": "Blocco /SET_Lockdown_Mode non chiuso; compilazione interrotta."}) + i = total_lines + break + + for sub_line in lines[i + 1:block_end]: + sub_line = strip_inline_comment(sub_line).strip() if "Take_DOWN" in sub_line: m_target = re.search(r'>\s*\(?([A-Za-z0-9_]+)\)?', sub_line) if m_target: @@ -252,7 +261,7 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over systems = [s.strip() for s in ovr_match.group(1).split(",")] kernel.override_defenses(systems) kernel.set_lockdown_mode(target_to_lockdown) - i += 1 + i = block_end + 1 continue # 7. /SET_Attack_Mode @@ -307,15 +316,12 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over # Check condition logic is_true = kernel.evaluate_condition(cond) - nested_lines = [] - open_braces = line.count("{") - line.count("}") - while i + 1 < total_lines: - i += 1 - sub = lines[i].split("//")[0].strip() - open_braces += sub.count("{") - sub.count("}") - nested_lines.append(lines[i]) - if open_braces <= 0: - break + block_end = find_block_end(lines, i) + if block_end is None: + diagnostics.append({"line": line_no, "level": "ERROR", "msg": f"Blocco IF({cond}) non chiuso; compilazione interrotta."}) + i = total_lines + break + nested_lines = lines[i + 1:block_end] if is_true: kernel.log("BRANCH", "IF_TRUE", f"Condizione '{cond}' VERIFICATA -> Esecuzione blocco interno.") @@ -330,7 +336,7 @@ def compile(self, code: str, cs_exposed_override: bool = False, cs_unlocked_over kernel.call_skill("Poison_skills") else: kernel.log("BRANCH", "IF_STANDBY", f"Clausola condizionale '{cond}' armata in standby (Core sicuro).") - i += 1 + i = block_end + 1 continue # 12. Echo diff --git a/src/linghos/parser.py b/src/linghos/parser.py index 20c1bf7..ad12a4c 100644 --- a/src/linghos/parser.py +++ b/src/linghos/parser.py @@ -5,6 +5,7 @@ import re from typing import Optional from .kernel import HumOSKernel +from .syntax import find_block_end, normalize_script, strip_inline_comment class LINGHOSParser: def __init__(self, kernel: Optional[HumOSKernel] = None): @@ -14,11 +15,7 @@ def execute_script(self, code: str): """ Executes a complete LINGHOS script line-by-line / block-by-block. """ - # Normalize typographic quotes and characters - normalized = code.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"') - normalized = normalized.replace("{", "{\n").replace("}", "\n}\n") - normalized = re.sub(r';\s*(?=[A-Za-z#/@<])', ';\n', normalized) - lines = normalized.split("\n") + lines = normalize_script(code).split("\n") i = 0 total_lines = len(lines) @@ -26,7 +23,7 @@ def execute_script(self, code: str): while i < total_lines: raw_line = lines[i] # Strip comments that start at the beginning of the line - line = raw_line.split("//")[0].strip() + line = strip_inline_comment(raw_line).strip() if not line: i += 1 @@ -81,17 +78,21 @@ def execute_script(self, code: str): m = re.search(r'@Start>\s*\(\s*([A-Za-z0-9_]+)\s*\)', line) vm_name = m.group(1) if m else "General_VM" - # Look ahead for ON>targets block + # Locate the complete VM block before scanning its contents. + block_end = find_block_end(lines, i) + if block_end is None: + self.kernel.log("ERROR", "PARSER", "Unclosed @Start block; script execution stopped.", level="ERROR") + return self.kernel + targets = [] - while i < total_lines and "}" not in lines[i]: - i += 1 - sub_line = lines[i].split("//")[0].strip() + for sub_line in lines[i + 1:block_end]: + sub_line = strip_inline_comment(sub_line).strip() if "ON>" in sub_line: - on_targets = sub_line.split("ON>")[1].rstrip(";").strip() + on_targets = sub_line.split("ON>", 1)[1].rstrip(";").strip() targets = [t.strip() for t in on_targets.split(",") if t.strip()] - + self.kernel.start_vm(vm_name, targets) - i += 1 + i = block_end + 1 continue # 5. Direct Skill Invocation: Call >> skill(args) @@ -106,11 +107,15 @@ def execute_script(self, code: str): # 6. Mode Selection: /SET_Lockdown_Mode or /SET_Attack_Mode if "/SET_Lockdown_Mode" in line or "/SET_LOCKDOWN_MODE" in line: - # Find targets or take-down references inside the block + # Locate the complete lockdown block before scanning its contents. target_to_lockdown = "ALL" - while i < total_lines and "}" not in lines[i]: - i += 1 - sub_line = lines[i].split("//")[0].strip() + block_end = find_block_end(lines, i) + if block_end is None: + self.kernel.log("ERROR", "PARSER", "Unclosed /SET_Lockdown_Mode block; script execution stopped.", level="ERROR") + return self.kernel + + for sub_line in lines[i + 1:block_end]: + sub_line = strip_inline_comment(sub_line).strip() if "Take_DOWN" in sub_line: m_target = re.search(r'>\s*\(?([A-Za-z0-9_]+)\)?', sub_line) if m_target: @@ -121,7 +126,7 @@ def execute_script(self, code: str): systems = [s.strip() for s in ovr_match.group(1).split(",")] self.kernel.override_defenses(systems) self.kernel.set_lockdown_mode(target_to_lockdown) - i += 1 + i = block_end + 1 continue if "/SET_Attack_Mode" in line: @@ -175,30 +180,18 @@ def execute_script(self, code: str): # or execute if the kernel is set to evaluate or force it is_true = self.kernel.evaluate_condition(condition) - # Check what is inside this IF block - nested_lines = [] - open_braces = 0 - if "{" in line: - open_braces += 1 - - while i + 1 < total_lines: - i += 1 - sub = lines[i].split("//")[0].strip() - if "{" in sub: - open_braces += sub.count("{") - if "}" in sub: - open_braces -= sub.count("}") - if open_braces <= 0: - break - nested_lines.append(lines[i]) - - # If condition evaluates to True (or in emergency simulation mode) + block_end = find_block_end(lines, i) + if block_end is None: + self.kernel.log("ERROR", "PARSER", f"Unclosed IF({condition}) block; script execution stopped.", level="ERROR") + return self.kernel + nested_lines = lines[i + 1:block_end] + if is_true: self.kernel.log("BRANCH", "IF_TRUE", f"Condition '{condition}' is TRUE -> Executing branch.") self.execute_script("\n".join(nested_lines)) else: self.kernel.log("BRANCH", "IF_STANDBY", f"Conditional trigger '{condition}' armed in standby (Core vault is secure).") - i += 1 + i = block_end + 1 continue # 11. Custom instructions: Echo("...") diff --git a/src/linghos/syntax.py b/src/linghos/syntax.py new file mode 100644 index 0000000..f18c787 --- /dev/null +++ b/src/linghos/syntax.py @@ -0,0 +1,115 @@ +"""Lexical helpers shared by the LINGHOS compiler and interpreter.""" + +from typing import List, Optional + + +def strip_inline_comment(line: str) -> str: + """Strip // comments without treating quoted URL-like text as a comment.""" + quote = None + escaped = False + index = 0 + while index < len(line): + char = line[index] + if quote: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + elif char in ("'", '"'): + quote = char + elif char == "/" and index + 1 < len(line) and line[index + 1] == "/": + return line[:index] + index += 1 + return line + + +def normalize_script(source: str) -> str: + """Normalize quotes and put structural delimiters on separate lines. + + Braces and semicolons inside quoted strings or comments are preserved. + """ + source = (source.replace("’", "'").replace("‘", "'") + .replace("“", '"').replace("”", '"')) + output = [] + quote = None + escaped = False + in_comment = False + index = 0 + + while index < len(source): + char = source[index] + next_char = source[index + 1] if index + 1 < len(source) else "" + + if in_comment: + output.append(char) + if char == "\n": + in_comment = False + elif quote: + output.append(char) + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + elif char in ("'", '"'): + quote = char + output.append(char) + elif char == "/" and next_char == "/": + in_comment = True + output.append("//") + index += 1 + elif char in ("{", "}"): + if output and not output[-1].endswith("\n"): + output.append("\n") + output.extend((char, "\n")) + elif char == ";": + output.extend((char, "\n")) + else: + output.append(char) + index += 1 + + return "".join(output) + + +def _mask_quoted_text(line: str) -> str: + """Replace string contents with spaces while preserving character count.""" + output = list(line) + quote = None + escaped = False + for index, char in enumerate(line): + if quote: + output[index] = " " + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + elif char in ("'", '"'): + quote = char + output[index] = " " + return "".join(output) + + +def find_block_end(lines: List[str], start_index: int) -> Optional[int]: + """Find a matching closing-brace line, ignoring comments and strings. + + Returns None for a missing opening or closing brace, or malformed nesting. + """ + depth = 0 + opened = False + for index in range(start_index, len(lines)): + code = _mask_quoted_text(strip_inline_comment(lines[index])) + opening = code.count("{") + closing = code.count("}") + if opening: + opened = True + depth += opening - closing + if depth < 0: + return None + if opened and depth == 0: + return index + return None diff --git a/src/linghos/web.py b/src/linghos/web.py index 7247456..32494d7 100644 --- a/src/linghos/web.py +++ b/src/linghos/web.py @@ -9,12 +9,14 @@ import os import sys import webbrowser +from urllib.parse import urlsplit from typing import Dict, Any from .compiler import LINGHOSCompiler, GLOBAL_REGISTRY from .models import SymbolType from .storage import GLOBAL_STORAGE compiler_instance = LINGHOSCompiler() +MAX_REQUEST_BYTES = 1024 * 1024 def get_html_content() -> str: base_dir = getattr(sys, '_MEIPASS', os.path.dirname(__file__)) @@ -33,25 +35,58 @@ class HumOSHTTPRequestHandler(http.server.BaseHTTPRequestHandler): def _send_json(self, data: Any, status: int = 200): self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(json.dumps(data, ensure_ascii=False).encode("utf-8")) + def _is_same_origin(self) -> bool: + """Reject browser requests originating outside this loopback Cockpit.""" + origin = self.headers.get("Origin") + if origin: + try: + parsed = urlsplit(origin) + if not ( + parsed.scheme == "http" + and parsed.hostname in {"127.0.0.1", "localhost"} + and parsed.port == self.server.server_port + and parsed.username is None + and parsed.password is None + ): + return False + except ValueError: + return False + + return self.headers.get("Sec-Fetch-Site", "").lower() != "cross-site" + def _read_json(self) -> Dict[str, Any]: - content_length = int(self.headers.get("Content-Length", 0)) - if content_length <= 0: - return {} - body = self.rfile.read(content_length).decode("utf-8") try: - return json.loads(body) - except Exception: + content_length = int(self.headers.get("Content-Length", "0")) + except (TypeError, ValueError): + raise ValueError("Invalid Content-Length") + + if content_length < 0: + raise ValueError("Invalid Content-Length") + if content_length > MAX_REQUEST_BYTES: + raise OverflowError("Request body exceeds 1 MiB") + if content_length == 0: return {} + body = self.rfile.read(content_length) + if len(body) != content_length: + raise ValueError("Incomplete request body") + + try: + data = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + raise ValueError("Request body must be valid UTF-8 JSON") + if not isinstance(data, dict): + raise ValueError("JSON request body must be an object") + return data + def do_OPTIONS(self): - self.send_response(200) - self.send_header("Access-Control-Allow-Origin", "*") - self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - self.send_header("Access-Control-Allow-Headers", "Content-Type") + # The Cockpit is served from this origin and does not need CORS. + self.send_response(204) self.end_headers() def do_GET(self): @@ -84,7 +119,24 @@ def do_GET(self): def do_POST(self): path = self.path.split("?")[0] - data = self._read_json() + + if not self._is_same_origin(): + self._send_json({"error": "Cross-origin requests are not allowed"}, status=403) + return + + content_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type != "application/json": + self._send_json({"error": "Content-Type must be application/json"}, status=415) + return + + try: + data = self._read_json() + except OverflowError as exc: + self._send_json({"error": str(exc)}, status=413) + return + except ValueError as exc: + self._send_json({"error": str(exc)}, status=400) + return if path == "/api/compile": code = data.get("code", "") diff --git a/src/pyproject.toml b/src/pyproject.toml index 7ea994a..2069b82 100644 --- a/src/pyproject.toml +++ b/src/pyproject.toml @@ -8,7 +8,7 @@ version = "1.0.0" description = "Cognitive Execution Runtime and DSL for HumOS" readme = "README.md" authors = [{ name = "Diego / SystemAdmin01" }] -license = { text = "CC BY-NC-ND 4.0" } +license = { text = "CC BY-NC 4.0" } classifiers = [ "Programming Language :: Python :: 3", "Operating System :: OS Independent", diff --git a/tests/test_parser_boundaries.py b/tests/test_parser_boundaries.py new file mode 100644 index 0000000..5e51d00 --- /dev/null +++ b/tests/test_parser_boundaries.py @@ -0,0 +1,61 @@ +import unittest +from pathlib import Path + +from linghos.syntax import find_block_end, normalize_script +from linghos.parser import LINGHOSParser +from linghos.compiler import LINGHOSCompiler + + +class SyntaxBoundaryTests(unittest.TestCase): + def test_braces_and_semicolons_inside_strings_are_preserved(self): + source = 'Main() { Echo("text {; } is literal"); }' + normalized = normalize_script(source) + self.assertIn('"text {; } is literal"', normalized) + lines = normalized.split("\n") + main_index = next(i for i, line in enumerate(lines) if line.strip() == "Main()") + self.assertEqual(find_block_end(lines, main_index), len(lines) - 2) + + def test_comments_do_not_affect_block_nesting(self): + lines = ["Main()", "{", 'Echo("ok"); // }', "}", ""] + self.assertEqual(find_block_end(lines, 0), 3) + + def test_unclosed_block_returns_none(self): + self.assertIsNone(find_block_end(["@Start>(PRS_VM)", "{", "ON> x;"], 0)) + + + def test_compiler_reports_unclosed_blocks_without_crashing(self): + compiler = LINGHOSCompiler() + malformed_scripts = [ + "@Start>(PRS_VM) {\nON> target;", + "/SET_Lockdown_Mode {\nTake_DOWN(all) > target;", + "IF(CS_EXPOSED) {\nCall >> Ice_shield;", + ] + for source in malformed_scripts: + with self.subTest(source=source): + result = compiler.compile(source) + self.assertTrue( + any(item["level"] == "ERROR" for item in result["compiler_meta"]["diagnostics"]) + ) + + + def test_repository_examples_are_handled_by_compiler(self): + examples_dir = Path(__file__).resolve().parents[1] / "examples" + example_files = sorted( + path for path in examples_dir.rglob("*") + if path.is_file() and path.suffix.lower() in {".lgh", ".lghos"} + ) + self.assertTrue(example_files, "No LINGHOS example scripts were found") + + for path in example_files: + with self.subTest(example=path.name): + result = LINGHOSCompiler().compile(path.read_text(encoding="utf-8")) + self.assertIn("compiler_meta", result) + self.assertIn("diagnostics", result["compiler_meta"]) + + def test_interpreter_reports_unclosed_vm_block_without_crashing(self): + kernel = LINGHOSParser().execute_script("@Start>(PRS_VM) {\nON> target;") + self.assertTrue(any("Unclosed @Start block" in item.message for item in kernel.telemetry_logs)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web_security.py b/tests/test_web_security.py new file mode 100644 index 0000000..df7d0fc --- /dev/null +++ b/tests/test_web_security.py @@ -0,0 +1,104 @@ +import http.client +import json +import threading +import unittest + +from linghos.web import HumOSHTTPRequestHandler, ReusableHTTPServer + + +class CockpitHTTPSecurityTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ReusableHTTPServer(("127.0.0.1", 0), HumOSHTTPRequestHandler) + cls.port = cls.server.server_port + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + cls.thread.join(timeout=2) + + def request(self, method, path, body=None, headers=None): + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=3) + connection.request(method, path, body=body, headers=headers or {}) + response = connection.getresponse() + payload = response.read() + result = (response.status, response.getheaders(), payload) + connection.close() + return result + + def test_rejects_cross_origin_post(self): + status, _, payload = self.request( + "POST", + "/api/compile", + body=json.dumps({"code": "Main() {}"}), + headers={ + "Content-Type": "application/json", + "Origin": "https://attacker.example", + }, + ) + self.assertEqual(status, 403) + self.assertIn(b"Cross-origin", payload) + + def test_requires_json_content_type(self): + status, _, _ = self.request( + "POST", + "/api/compile", + body='{"code":"Main() {}"}', + headers={"Content-Type": "text/plain"}, + ) + self.assertEqual(status, 415) + + def test_rejects_oversized_request_body(self): + status, _, payload = self.request( + "POST", + "/api/compile", + headers={ + "Content-Type": "application/json", + "Content-Length": str(1024 * 1024 + 1), + }, + ) + self.assertEqual(status, 413) + self.assertIn(b"1 MiB", payload) + + def test_rejects_malformed_json(self): + status, _, payload = self.request( + "POST", + "/api/compile", + body="{not-json", + headers={"Content-Type": "application/json"}, + ) + self.assertEqual(status, 400) + self.assertIn(b"valid UTF-8 JSON", payload) + + def test_accepts_same_origin_json_request(self): + status, headers, payload = self.request( + "POST", + "/api/compile", + body=json.dumps({"code": "Main() { Call >> Ice_shield; }"}), + headers={ + "Content-Type": "application/json", + "Origin": f"http://127.0.0.1:{self.port}", + "Sec-Fetch-Site": "same-origin", + }, + ) + self.assertEqual(status, 200) + self.assertTrue(any(k.lower() == "cache-control" and v == "no-store" for k, v in headers)) + result = json.loads(payload.decode("utf-8")) + self.assertIn("compiler_meta", result) + self.assertIn("telemetry", result) + + def test_options_does_not_enable_cross_origin_access(self): + status, headers, _ = self.request( + "OPTIONS", + "/api/compile", + headers={"Origin": "https://attacker.example"}, + ) + self.assertEqual(status, 204) + self.assertFalse(any(k.lower() == "access-control-allow-origin" for k, _ in headers)) + + +if __name__ == "__main__": + unittest.main()