polymath-nodeos 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ import os
2
+ import json
3
+ import sqlite3
4
+ import logging
5
+ from typing import List, Dict, Optional, Tuple
6
+
7
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
8
+ logger = logging.getLogger("GhostWriterEngine")
9
+
10
+ class GhostWriterEngine:
11
+ """
12
+ Advanced Spatial Context Ghost Writing Engine.
13
+ Leverages physical coordinates to resolve contextual dependencies.
14
+ """
15
+ def __init__(self, workspace_root: str, db_name: str = 'agy_nodeos.db'):
16
+ self.workspace_root = workspace_root
17
+ self.db_path = os.path.join(workspace_root, db_name) if not os.path.isabs(db_name) else db_name
18
+
19
+ def calculate_centroid(self, target_filepath: str) -> Optional[Tuple[float, float]]:
20
+ """Calculates the center of mass (centroid) of the target file's AST nodes."""
21
+ logger.info(f"Calculating spatial centroid for {target_filepath}")
22
+ try:
23
+ with sqlite3.connect(self.db_path) as conn:
24
+ cursor = conn.cursor()
25
+ cursor.execute(
26
+ "SELECT AVG(x_coord), AVG(y_coord) FROM nodes WHERE filepath = ?",
27
+ (target_filepath,)
28
+ )
29
+ row = cursor.fetchone()
30
+
31
+ if row and row[0] is not None and row[1] is not None:
32
+ return float(row[0]), float(row[1])
33
+ except sqlite3.Error as e:
34
+ logger.error(f"Database error during centroid calculation: {e}")
35
+
36
+ return None
37
+
38
+ def find_nearest_neighbors(self, cx: float, cy: float, target_filepath: str, k: int = 10) -> List[Tuple[str, str, str]]:
39
+ """Queries the physics engine DB for the K-nearest physical neighbors using squared distance."""
40
+ logger.info(f"Querying top {k} physical neighbors from ({cx:.2f}, {cy:.2f})")
41
+ neighbors = []
42
+ try:
43
+ with sqlite3.connect(self.db_path) as conn:
44
+ cursor = conn.cursor()
45
+ # Optimized Euclidean squared-distance query
46
+ cursor.execute("""
47
+ SELECT node_id, filepath, name,
48
+ ((x_coord - ?)*(x_coord - ?) + (y_coord - ?)*(y_coord - ?)) AS dist
49
+ FROM nodes
50
+ WHERE filepath != ?
51
+ ORDER BY dist ASC
52
+ LIMIT ?
53
+ """, (cx, cx, cy, cy, target_filepath, k))
54
+
55
+ rows = cursor.fetchall()
56
+ for row in rows:
57
+ neighbors.append((row[0], row[1], row[2]))
58
+ except sqlite3.Error as e:
59
+ logger.error(f"Database error during neighbor resolution: {e}")
60
+
61
+ return neighbors
62
+
63
+ def extract_ast_signatures(self, neighbors: List[Tuple[str, str, str]]) -> List[Dict[str, str]]:
64
+ """Extracts AST signatures from .jsagent/schema files for the resolved neighbors."""
65
+ spatial_context = []
66
+ for node_id, filepath, name in neighbors:
67
+ schema_path = os.path.join(self.workspace_root, '.jsagent', 'schema', f"{node_id}.json")
68
+ signature = ""
69
+
70
+ if os.path.exists(schema_path):
71
+ try:
72
+ with open(schema_path, 'r', encoding='utf-8') as f:
73
+ schema_data = json.load(f)
74
+ signature = schema_data.get('source', '')
75
+ except (json.JSONDecodeError, IOError) as e:
76
+ logger.warning(f"Failed to read AST schema for node {node_id}: {e}")
77
+ else:
78
+ logger.debug(f"Schema not found for node {node_id} at {schema_path}")
79
+
80
+ spatial_context.append({
81
+ "node_name": name,
82
+ "filepath": filepath,
83
+ "signature": signature
84
+ })
85
+
86
+ return spatial_context
87
+
88
+ def emit_workflow_intent(self, target_filepath: str, spatial_context: List[Dict[str, str]]) -> bool:
89
+ """Bundles the context payload and drops it into workflow.json for the NodeOS daemon."""
90
+ logger.info(f"Bundling {len(spatial_context)} contextual signatures into workflow intent.")
91
+ workflow_payload = {
92
+ "type": "JSON_Task",
93
+ "status": "pending",
94
+ "action": "ghost_write",
95
+ "target_file": target_filepath,
96
+ "spatial_context": spatial_context
97
+ }
98
+
99
+ workflow_path = os.path.join(self.workspace_root, 'workflow.json')
100
+ try:
101
+ with open(workflow_path, 'w', encoding='utf-8') as f:
102
+ json.dump(workflow_payload, f, indent=4)
103
+ logger.info("Successfully dropped intent into workflow.json")
104
+ return True
105
+ except IOError as e:
106
+ logger.error(f"Failed to emit workflow intent: {e}")
107
+ return False
108
+
109
+ def execute_pipeline(self, target_filepath: str) -> bool:
110
+ """Executes the full Ghost Writer pipeline."""
111
+ centroid = self.calculate_centroid(target_filepath)
112
+ if not centroid:
113
+ logger.warning("Aborting pipeline: Centroid could not be calculated.")
114
+ return False
115
+
116
+ cx, cy = centroid
117
+ neighbors = self.find_nearest_neighbors(cx, cy, target_filepath)
118
+
119
+ if not neighbors:
120
+ logger.warning("No spatial neighbors found for context.")
121
+
122
+ spatial_context = self.extract_ast_signatures(neighbors)
123
+ return self.emit_workflow_intent(target_filepath, spatial_context)
124
+
125
+ if __name__ == "__main__":
126
+ import sys
127
+ import argparse
128
+
129
+ parser = argparse.ArgumentParser(description="Spatial Context Ghost Writer Engine")
130
+ parser.add_argument("target_file", help="The newly created file to ghost write")
131
+ parser.add_argument("--workspace", default=os.getcwd(), help="Root directory of the NodeOS workspace")
132
+ args = parser.parse_args()
133
+
134
+ engine = GhostWriterEngine(workspace_root=args.workspace)
135
+ engine.execute_pipeline(args.target_file)
@@ -0,0 +1,32 @@
1
+ import json
2
+ import os
3
+
4
+ WORKFLOW_FILE = os.path.join(os.getcwd(), "workflow.json")
5
+
6
+ def main():
7
+ if not os.path.exists(WORKFLOW_FILE):
8
+ print("{}")
9
+ return
10
+
11
+ try:
12
+ with open(WORKFLOW_FILE, "r") as f:
13
+ data = json.load(f)
14
+
15
+ status = data.get("status")
16
+ if status == "pending":
17
+ message = f"NodeOS emitted an intent. Please fulfill this workflow:\n{json.dumps(data, indent=2)}"
18
+ response = {
19
+ "injectSteps": [
20
+ {
21
+ "ephemeralMessage": message
22
+ }
23
+ ]
24
+ }
25
+ print(json.dumps(response))
26
+ else:
27
+ print("{}")
28
+ except Exception:
29
+ print("{}")
30
+
31
+ if __name__ == "__main__":
32
+ main()
@@ -0,0 +1,28 @@
1
+ import json
2
+ import os
3
+
4
+ WORKFLOW_FILE = os.path.join(os.getcwd(), "workflow.json")
5
+
6
+ def main():
7
+ if not os.path.exists(WORKFLOW_FILE):
8
+ print("{}")
9
+ return
10
+
11
+ try:
12
+ with open(WORKFLOW_FILE, "r") as f:
13
+ data = json.load(f)
14
+
15
+ status = data.get("status")
16
+ if status in ["pending", "running"]:
17
+ response = {
18
+ "decision": "continue",
19
+ "reason": f"NodeOS has an active intent with status '{status}'. Please process it."
20
+ }
21
+ print(json.dumps(response))
22
+ else:
23
+ print("{}")
24
+ except Exception:
25
+ print("{}")
26
+
27
+ if __name__ == "__main__":
28
+ main()
@@ -0,0 +1,27 @@
1
+ import sys
2
+ from multiprocessing.connection import Client
3
+
4
+ def send_ipc_syscall(command):
5
+ """
6
+ Cross-platform IPC Hook.
7
+ Acts as a syscall client to securely communicate with the invisible AGY-NodeOS background daemon.
8
+ """
9
+ address = ('localhost', 6000)
10
+ try:
11
+ # Connect to the IPC Listener opened by the daemon
12
+ with Client(address, authkey=b'agy-nodeos-secret') as conn:
13
+ conn.send(command)
14
+ response = conn.recv()
15
+ print(f"[IPC Hook Response]: {response}")
16
+ except ConnectionRefusedError:
17
+ print("[IPC Error] Connection refused. Is the background daemon running?")
18
+ except Exception as e:
19
+ print(f"[IPC Error] {e}")
20
+
21
+ if __name__ == "__main__":
22
+ if len(sys.argv) < 2:
23
+ print("Usage: python ipc_hook.py [ping|status]")
24
+ sys.exit(1)
25
+
26
+ syscall_command = sys.argv[1]
27
+ send_ipc_syscall(syscall_command)
@@ -0,0 +1,3 @@
1
+ def calculate_tax(amount):
2
+ print("Calculating heavily optimized legacy tax")
3
+ return amount * 0.12
@@ -0,0 +1,69 @@
1
+ import time
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+ def tail_agent_logs(log_file="daemon.log"):
7
+ """Yields new lines from the log file, filtering only Agent actions."""
8
+ if not os.path.exists(log_file):
9
+ return
10
+ with open(log_file, "r") as f:
11
+ f.seek(0, os.SEEK_END)
12
+ while True:
13
+ line = f.readline()
14
+ if not line:
15
+ time.sleep(0.1)
16
+ yield None
17
+ else:
18
+ # Filter out background OS noise, only show Swarm and Agent actions
19
+ if any(noise in line for noise in ["[Physics Engine]", "[Raw Watchdog]", "[Jage Polyglot]", "[Daemon]", "[NodeOS] Deep Scan"]):
20
+ yield None
21
+ else:
22
+ yield line
23
+
24
+ def track_workflow(workflow_file="workflow.json"):
25
+ if not os.path.exists(workflow_file):
26
+ print("\033[93m[NodeOS] No active workflow detected in workspace.\033[0m")
27
+ return
28
+
29
+ last_status = None
30
+ log_generator = tail_agent_logs()
31
+
32
+ while True:
33
+ # Print filtered agent action logs
34
+ if log_generator:
35
+ log_line = next(log_generator, None)
36
+ while log_line:
37
+ sys.stdout.write(f"\033[90m{log_line}\033[0m")
38
+ sys.stdout.flush()
39
+ log_line = next(log_generator, None)
40
+
41
+ try:
42
+ with open(workflow_file, 'r') as f:
43
+ data = json.load(f)
44
+ status = data.get('status', 'unknown')
45
+
46
+ if status != last_status:
47
+ if status == 'pending':
48
+ agents = ", ".join(data.get('agents', []))
49
+ intent = data.get('action', 'execute_agents')
50
+ print(f"\n\033[96m[NodeOS Swarm] Intent: {intent.upper()} -> [{agents}]\033[0m")
51
+ print("\033[94m[NodeOS] Status: PENDING\033[0m")
52
+ elif status == 'running':
53
+ print("\033[93m[NodeOS] Status: RUNNING\033[0m")
54
+ elif status == 'completed':
55
+ print("\033[92m[NodeOS] Status: COMPLETED\033[0m\n")
56
+ elif status == 'failed_qa':
57
+ print("\033[91m[NodeOS] Status: FAILED\033[0m")
58
+ print(f"\033[91mError: {data.get('error_log', 'Unknown Error')}\033[0m\n")
59
+ last_status = status
60
+
61
+ if status in ['completed', 'failed_qa']:
62
+ break
63
+ except Exception:
64
+ pass
65
+
66
+ time.sleep(0.5)
67
+
68
+ if __name__ == "__main__":
69
+ track_workflow()
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: polymath-nodeos
3
+ Version: 1.0.0
4
+ Summary: A zero-dependency Autonomous Agentic Swarm Operating System.
5
+ Author: Polymath Void
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+
13
+ # 🧠 Polymath-NodeOS: The Autonomous Swarm Operating System
14
+
15
+ [![Zero Dependency](https://img.shields.io/badge/Dependencies-Zero-brightgreen.svg?style=for-the-badge)](#) [![Agent Compatible](https://img.shields.io/badge/Agent-Native-purple.svg?style=for-the-badge)](#) [![Platform](https://img.shields.io/badge/Platform-Cross--Platform-blue.svg?style=for-the-badge)](#) [![Python Version](https://img.shields.io/badge/Python-3.10%2B-blue.svg?style=for-the-badge)](#) [![License](https://img.shields.io/badge/License-MIT-gray.svg?style=for-the-badge)](#)
16
+
17
+ **Polymath-NodeOS** is a zero-dependency Autonomous Agentic Operating System designed specifically to run natively alongside the **Antigravity (AGY)** CLI environment. By intercepting OS events and using advanced mathematical physics—specifically modeling code components using a Native QuadTree matrix, Hooke's Law, and Coulomb Repulsion—Polymath-NodeOS creates a physical environment for LLM swarms to natively understand code structure, dependencies, and blast radiuses instantly.
18
+
19
+ This project is 100% cross-platform and runs flawlessly on **Windows, macOS, Linux, and Android (Termux)**.
20
+
21
+ ---
22
+
23
+ ## 🚀 Key Features & Real-World Use Cases
24
+
25
+ The true value of Polymath-NodeOS is curing the "blind spot" problem that plagues traditional AI coding agents. Instead of blindly modifying files and breaking downstream dependencies, NodeOS mathematically calculates the structural layout of your codebase into a native SQLite database (`agy_nodeos.db`).
26
+
27
+ ### 1. Real-Time Blast Radius Warnings 💥
28
+ * **The Problem:** An agent changes a core utility function without realizing it breaks 14 deeply nested components.
29
+ * **The NodeOS Solution:** The zero-dependency watchdog detects the file save. It instantly runs a recursive SQLite CTE to calculate the transitive dependents. If the "blast radius" is high, it automatically drops an ephemeral warning directly into the agent's memory stream, preventing catastrophic commits.
30
+
31
+ ### 2. Spatial Context Ghost Writer 👻
32
+ * **The Problem:** AI agents waste massive amounts of tokens and time `grep`ing or opening multiple files to memorize function signatures when building new APIs.
33
+ * **The NodeOS Solution:** When a new file is created, NodeOS calculates its QuadTree spatial centroid, locates the 10 closest physical neighbors in the AST matrix, and seamlessly injects their exact code signatures into the agent's context payload. The agent writes flawless code on the first try without a single research tool.
34
+
35
+ ### 3. The Domino Refactor Engine 🎲
36
+ * **The Problem:** Standard refactoring using Regex search-and-replace accidentally corrupts identically named variables or comments across massive projects.
37
+ * **The NodeOS Solution:** NodeOS uses pure Graph Theory (Inner Joins on AST Edges) to locate the precise structural files invoking a specific function hash. It then dynamically dispatches a massive parallel array of Antigravity Swarm agents to deterministically refactor the files.
38
+
39
+ ### 4. Semantic Dead Code Eradication ☠️
40
+ * **The Problem:** Unused code accumulates, polluting the LLM's context window.
41
+ * **The NodeOS Solution:** A native engine queries the graph for orphaned nodes (nodes with 0 incoming AST dependencies) and automatically orchestrates the safe deletion of dead code.
42
+
43
+ ---
44
+
45
+ ## 🛠 Installation Guide (For Users)
46
+
47
+ Polymath-NodeOS is designed for frictionless installation.
48
+
49
+ ### Method 1: The One-Click Auto-Install (Recommended)
50
+ If you are using the Antigravity IDE, simply cloning this repository and opening the workspace will automatically trigger the `.agents/hooks.json` script. The system will seamlessly install itself into your global environment.
51
+
52
+ ### Method 2: Manual Installation
53
+ Navigate to the repository root and run:
54
+ ```bash
55
+ python install.py
56
+ ```
57
+ **What this does:**
58
+ 1. Installs the `nodeos_standard.md` rule globally.
59
+ 2. Deploys the `agy-nodeos-installer` skill.
60
+ 3. Grants your AGY agents immediate global awareness of the NodeOS interaction paradigm.
61
+
62
+ ---
63
+
64
+ ## 📖 Usage Guide
65
+
66
+ Polymath-NodeOS works silently in the background to empower your AI agents.
67
+
68
+ ### Starting the OS
69
+ To initialize NodeOS in a project directory, you or your agent can start the background daemon:
70
+ ```bash
71
+ polymath-nodeos-daemon
72
+ ```
73
+ *Note: In properly configured workspaces, the daemon automatically boots when the agent initializes thanks to the AGY Customization Engine (`PreInvocation` hook).*
74
+
75
+ ### Dispatching Swarm Tasks
76
+ Instead of manually typing prompts, you can add task drops to `workflow.json`:
77
+ ```json
78
+ {
79
+ "type": "JSON_Task",
80
+ "status": "pending",
81
+ "action": "execute_agents",
82
+ "agents": ["architect_designer"]
83
+ }
84
+ ```
85
+ The daemon detects the `pending` state and automatically alerts your agent swarm via lifecycle hooks.
86
+
87
+ ---
88
+
89
+ ## 🤖 Agent Protocol (For AI Agents)
90
+
91
+ If you are an autonomous AI Agent interacting with this workspace, adhere to the **Native Interaction Paradigm**:
92
+ 1. **File Operations**: Use your built-in editing tools (e.g., `view_file`, `replace_file_content`).
93
+ 2. **Spatial Queries**: Use standard SQL queries against `agy_nodeos.db` to trace dependencies.
94
+ 3. **Task Orchestration**: Update the `status` field in `workflow.json` to manage sub-agent queues.
95
+ 4. **Feature Modules**: Do NOT execute standard searches for refactoring. Utilize the pre-built mathematical engines located in the `scripts/` directory.
96
+
97
+ ---
98
+
99
+ ## 🧬 Architectural Workflow & Citations
100
+
101
+ The underlying architecture relies on several foundational concepts adapted for LLM systems:
102
+ 1. **Auto-Boot:** `hooks.json` intercepts `PreInvocation` events, booting the Python daemon `daemon.py` silently in the background.
103
+ 2. **Deep Ingestion:** The daemon scans the project using `jage_engine.py`, mapping semantic `ast.Call` edges natively.
104
+ 3. **Kinetic Simulation:** `nodes_engine.py` hydrates the QuadTree and applies spatial algorithms to physically pull dependent AST blocks into clustered coordinates.
105
+ 4. **Intent Emission:** When a workflow intent is detected, it is logged to `workflow.json`.
106
+ 5. **Telemetry Tracking:** `scripts/telemetry.py` natively tracks Swarm execution intents and state transitions (Pending -> Running -> Completed).
107
+
108
+ > **Citations:**
109
+ > [^1]: Barnes, J., & Hut, P. (1986). A hierarchical O(N log N) force-calculation algorithm (QuadTree application for NodeOS physics).
110
+ > [^2]: SQLite Consortium (2024). ACID-compliant transactional guarantees for embedded graphs.
111
+
112
+ ---
113
+ *Built natively for the Antigravity Agent Swarm Ecosystem. Optimized for speed, context, and zero-dependency portability.*
@@ -0,0 +1,21 @@
1
+ polymath_nodeos/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ polymath_nodeos/daemon.py,sha256=ousmjx2N4B6_e2W9A-1UCbIh6jg-Hxgl3s0sK9uzkT0,14356
3
+ polymath_nodeos/graph_manager.py,sha256=YmRft25KwE8H86IYqWhz-51Hd7lvq1H-pKUasB_XfTw,4219
4
+ polymath_nodeos/jage_engine.py,sha256=RPda49fr5KUI8DsnLbAQuU-aPAo2cYKR5TxFLMdtzhY,7455
5
+ polymath_nodeos/nodes_engine.py,sha256=KnVPFaIGlDAa2alOE9W1F3UWGZnLFK5qm_7nXGDbxyM,10411
6
+ polymath_nodeos/scripts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ polymath_nodeos/scripts/agy_invoke.py,sha256=TDI3A0K4-NnIADa5zmpDXzWwmRgmdyqL9kK9cT5HecU,568
8
+ polymath_nodeos/scripts/blast_radius_engine.py,sha256=mv9bx0adVdtZuXsCQcMkiYKYN_RhL7VmFDGosq1Lvdk,5006
9
+ polymath_nodeos/scripts/dead_code_engine.py,sha256=JQDirPyMNcVZEzd1AUCT_Y3hCp4E9SZ5Tmpi3g6-6nE,3597
10
+ polymath_nodeos/scripts/domino_engine.py,sha256=wFl0CrzEaGqx__qXU4rKaYpbQAmGvyri9_CNknPUDsg,3468
11
+ polymath_nodeos/scripts/ghost_writer_engine.py,sha256=ASj8Kn1xGN_Zt8X0sj4RNb5eIw4iuDfZV8lwqkCAilA,5968
12
+ polymath_nodeos/scripts/intent_injector.py,sha256=rkZoFEwO5xVUN1BvtNLTnLMrR-GrvHL1wHhSUQW6u-Y,803
13
+ polymath_nodeos/scripts/intent_stopper.py,sha256=Z1a8X2dJdYcjtckUZofRdvY1-fSDavTsB3UkoW7dKxY,698
14
+ polymath_nodeos/scripts/ipc_hook.py,sha256=oBnHwZdzqfXc5TJUm67OmOOAkaTuSV0tTJuMMqvZ2rU,917
15
+ polymath_nodeos/scripts/legacy_math.py,sha256=6W2nRVL5wzEDBMi3RU9wYfhRUo7MHnnsUyjT9FKwPcI,106
16
+ polymath_nodeos/scripts/telemetry.py,sha256=gX85QhV_oRVuSznDZlP0Mv9qJjyV5-fFt8KnI3psh2Q,2550
17
+ polymath_nodeos-1.0.0.dist-info/METADATA,sha256=qEWWE5wH9n0HamFCUCil1FRn5BseQpH2qJMwKv-T-d4,6942
18
+ polymath_nodeos-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
19
+ polymath_nodeos-1.0.0.dist-info/entry_points.txt,sha256=Yi4VELV6NdHajn_LbUSXtIX8qZXhgNeji2Z_f-2wmoc,226
20
+ polymath_nodeos-1.0.0.dist-info/top_level.txt,sha256=fQT1yVRXZ_S_luXJ7egaUVkXzILeFjY5Rp9-3KVThnQ,16
21
+ polymath_nodeos-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ polymath-nodeos-daemon = polymath_nodeos.daemon:daemonize_and_run
3
+ polymath-nodeos-injector = polymath_nodeos.scripts.intent_injector:main
4
+ polymath-nodeos-stopper = polymath_nodeos.scripts.intent_stopper:main
@@ -0,0 +1 @@
1
+ polymath_nodeos