FerrellSyntheticIntelligence commited on
Commit
23ecb5d
·
1 Parent(s): 95e7935

feat: implement hot-ingestion daemon and tactical state-responder plugin

Browse files
src/core/affect.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re, string
2
+
3
+ _POS = {"great", "awesome", "fantastic", "good", "excellent", "optimal", "stable", "secure"}
4
+ _NEG = {"bad", "terrible", "awful", "hate", "horrible", "angry", "frustrated", "error", "fail"}
5
+ _HIGH_AROUSAL = {"!", "!!", "!!!"}
6
+ _LOW_AROUSAL = {"...", "…"}
7
+
8
+ def _clean(text: str) -> str:
9
+ return text.translate(str.maketrans("", "", string.punctuation)).lower()
10
+
11
+ def extract_affect(text: str) -> tuple[float, float]:
12
+ tokens = set(_clean(text).split())
13
+ pos = len(tokens & _POS)
14
+ neg = len(tokens & _NEG)
15
+
16
+ sentiment = 0.0 if pos == neg == 0 else (pos - neg) / max(pos + neg, 1)
17
+ valence = (sentiment + 1) / 2
18
+
19
+ arousal = 0.5
20
+ if any(p in text for p in _HIGH_AROUSAL): arousal = 0.9
21
+ elif any(p in text for p in _LOW_AROUSAL): arousal = 0.2
22
+
23
+ return round(valence, 3), round(arousal, 3)
src/core/session_mood.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from collections import defaultdict
3
+ from typing import Tuple
4
+
5
+ _lock = threading.Lock()
6
+ _default = (0.5, 0.5)
7
+ _mood_store: defaultdict[str, Tuple[float, float]] = defaultdict(lambda: _default)
8
+
9
+ def get_mood(client_id: str) -> Tuple[float, float]:
10
+ with _lock: return _mood_store[client_id]
11
+
12
+ def set_mood(client_id: str, valence: float, arousal: float) -> None:
13
+ with _lock: _mood_store[client_id] = (valence, arousal)
src/plugins/affect_responder.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ from src.core.session_mood import get_mood, set_mood
3
+ from src.core.affect import extract_affect
4
+
5
+ class AffectResponder:
6
+ name = "affect_responder"
7
+
8
+ def on_payload(self, payload: Dict[str, Any], client_id: str = "local_admin") -> Dict[str, Any]:
9
+ last_step = payload.get("steps", [{}])[-1] if payload.get("steps") else {}
10
+ text_input = last_step.get("text", "")
11
+
12
+ valence, arousal = extract_affect(text_input)
13
+
14
+ affect_msg = None
15
+ if valence < 0.35 and arousal > 0.7:
16
+ affect_msg = "[STATE: AGITATED] Switching to high-precision diagnostic output. State recorded."
17
+ set_mood(client_id, valence, arousal)
18
+ elif valence < 0.35 and arousal <= 0.7:
19
+ affect_msg = "[STATE: SUB-OPTIMAL] Acknowledged. Proceeding with factual resolution."
20
+ set_mood(client_id, valence, arousal)
21
+ else:
22
+ set_mood(client_id, 0.5, 0.5)
23
+
24
+ base_answer = payload.get("final_conclusion", {}).get("label", "Operation complete.")
25
+ final_reply = f"{affect_msg} {base_answer}" if affect_msg else base_answer
26
+
27
+ return {"final_reply": final_reply}
watcher.py CHANGED
@@ -1,65 +1,30 @@
1
- import os
2
- import sys
3
- import time
4
- import json
5
- import urllib.request
6
 
7
- WATCH_DIR = os.path.join(os.getcwd(), "storage/knowledge")
8
- API_URL = "http://127.0.0.1:5000/api/ingest"
9
-
10
- def compute_directory_snapshot(target_directory):
11
- """Generates an absolute structural state index based on file modification timestamps."""
12
- snapshot = {}
13
- if not os.path.exists(target_directory):
14
- return snapshot
15
 
16
- for root, _, files in os.walk(target_directory):
17
- for filename in files:
18
- # Bypass system manifest layers to prevent tracking recursion loops
19
- if filename in ["chunks_manifest.json", "vectors_cache.pt"]:
20
- continue
21
- file_path = os.path.join(root, filename)
22
- try:
23
- snapshot[file_path] = os.path.getmtime(file_path)
24
- except OSError:
25
- continue
26
- return snapshot
27
-
28
- def signal_hot_ingestion():
29
- """Dispatches an internal loopback network signal to trigger zero-downtime vector compilation."""
30
- payload = json.dumps({"directory": "storage/knowledge"}).encode('utf-8')
31
- req = urllib.request.Request(
32
- API_URL,
33
- data=payload,
34
- headers={'Content-Type': 'application/json'},
35
- method='POST'
36
- )
37
- try:
38
- with urllib.request.urlopen(req, timeout=30) as response:
39
- res_data = json.loads(response.read().decode('utf-8'))
40
- print(f"[+] Daemon: Matrix re-compilation complete. Active Nodes: {res_data.get('active_nodes')}")
41
- except Exception as e:
42
- print(f"[-] Daemon: Integrity signal delivery failed. Target endpoint error: {str(e)}")
43
-
44
- def start_daemon_loop():
45
- print(f"[*] Initializing Sovereign File-Watcher Daemon tracking: {WATCH_DIR}")
46
- last_known_state = compute_directory_snapshot(WATCH_DIR)
47
-
48
- while True:
49
- try:
50
- time.sleep(3) # Low-overhead 3-second evaluation cycles
51
- current_state = compute_directory_snapshot(WATCH_DIR)
52
-
53
- if current_state != last_known_state:
54
- print("[*] Daemon: File-system mutation detected inside secure knowledge vault.")
55
- signal_hot_ingestion()
56
- last_known_state = current_state
57
- except KeyboardInterrupt:
58
- print("\n[*] Terminating File-Watcher Daemon safely.")
59
- sys.exit(0)
60
- except Exception as e:
61
- print(f"[!] Daemon Runtime Exception: {str(e)}")
62
- time.sleep(5)
63
 
64
  if __name__ == "__main__":
65
- start_daemon_loop()
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time, os
2
+ from watchdog.observers import Observer
3
+ from watchdog.events import FileSystemEventHandler
4
+ from src.core.watchdog import update_manifest
5
+ from src.core.memory_engine import MemoryEngine
6
 
7
+ class VaultHandler(FileSystemEventHandler):
8
+ def __init__(self):
9
+ self.engine = MemoryEngine()
 
 
 
 
 
10
 
11
+ def on_modified(self, event):
12
+ if event.src_path.endswith(".txt"):
13
+ print(f"[*] Change detected in {event.src_path}. Re-signing manifest & Hot-ingesting...")
14
+ update_manifest()
15
+ self.engine.ingest_knowledge() # Re-builds local FAISS tensors
16
+ print("[+] Hot-ingestion complete. System secure.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  if __name__ == "__main__":
19
+ if not os.path.exists("storage/knowledge/manifest.sha256"):
20
+ update_manifest()
21
+
22
+ observer = Observer()
23
+ observer.schedule(VaultHandler(), path='storage/knowledge', recursive=False)
24
+ observer.start()
25
+ print("[*] FSI Hot-Ingestion Daemon Active. Watching storage/knowledge...")
26
+ try:
27
+ while True: time.sleep(1)
28
+ except KeyboardInterrupt:
29
+ observer.stop()
30
+ observer.join()