import os
import sys
import json
import sqlite3
import hashlib
import hmac
import subprocess
import shutil
import math
import uuid
from datetime import datetime, timezone, timedelta
from decimal import Decimal, ROUND_HALF_UP

SHARED_HMAC_SECRET_KEY = b"PRODUCTION_HARDENED_HMAC_SIGNING_KEY_REPLACE_ME_VIA_ENV"

APPROVED_ACTION_HANDLERS = {
    "DISPATCH_DIRECTIVE_TO_STAFF_RESOURCE_OPTIMIZE": "/Users/bpa/ForesixaQuant/actions/staff_optimize.sh",
    "ENGAGE_AUTOMATED_MATERIAL_COST_SCALING": "/Users/bpa/ForesixaQuant/actions/cost_scaling.sh",
    "TRIGGER_ISOLATED_SANDBOX_WORKER_RESET": "/Users/bpa/ForesixaQuant/actions/sandbox_reset.sh",
    "AUTO_PROVISION_ALTERNATIVE_TRACK_RENDER_NODES": "/Users/bpa/ForesixaQuant/actions/render_provision.sh"
}

class ConsigliereProductionCore:
    def __init__(self, db_filepath="/Users/bpa/ForesixaQuant/qzotic_pure_sandbox.db", monitor_dir="/Users/bpa/ForesixaQuant/enterprise_logs"):
        """Initializes a transaction-locked, production-hardened multi-enterprise operational core."""
        self.db_filepath = db_filepath
        self.monitor_dir = monitor_dir
        self.worker_id = str(uuid.uuid4())
        os.makedirs(self.monitor_dir, exist_ok=True)
        self.conn = sqlite3.connect(self.db_filepath, timeout=30.0)
        self.conn.row_factory = sqlite3.Row
        self._execute_safe_database_migration_layer()

    def _table_exists(self, cursor, table_name) -> bool:
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (table_name,))
        return cursor.fetchone() is not None

    def _execute_safe_database_migration_layer(self):
        """Upgrades tables safely, matching exact schema shapes while preventing WAL file state issues."""
        cursor = self.conn.cursor()
        cursor.execute("PRAGMA foreign_keys = OFF;")
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='enterprise_portfolio';")
        has_portfolio = cursor.fetchone() is not None
        is_legacy_float = False
        if has_portfolio:
            cursor.execute("PRAGMA table_info(enterprise_portfolio);")
            is_legacy_float = any(col["name"] == "allocated_budget" and col["type"] == "REAL" for col in cursor.fetchall())
        if is_legacy_float:
            print("[MIGRATION] Legacy float storage shape detected. Commencing safe migration...")
            backup_path = self.db_filepath + f".backup_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}.bak"
            dst_conn = None
            try:
                dst_conn = sqlite3.connect(backup_path)
                with dst_conn: self.conn.backup(dst_conn, pages=20, progress=None)
                backup_cursor = dst_conn.cursor()
                backup_cursor.execute("PRAGMA integrity_check;")
                if backup_cursor.fetchone().lower() != "ok": raise ValueError("Backup verification failed.")
                backup_cursor.close()
            except Exception as e:
                print(f" -> Migration backup aborted: {str(e)}"); sys.exit(1)
            finally:
                if dst_conn: dst_conn.close()
            try:
                cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
                cursor.execute("SELECT project_id, project_name, industry_vertical, lifecycle_state, supervisor_deadline, allocated_budget, logged_at FROM enterprise_portfolio;")
                old_portfolio_rows = cursor.fetchall()
                old_remediations = []
                has_legacy_remediation = self._table_exists(cursor, "remediation_lifecycle")
                if has_legacy_remediation:
                    cursor.execute("SELECT * FROM remediation_lifecycle;")
                    old_remediations = cursor.fetchall()
                cursor.execute("DROP INDEX IF EXISTS idx_open_remediations;")
                cursor.execute("ALTER TABLE enterprise_portfolio RENAME TO legacy_portfolio_old;")
                if has_legacy_remediation:
                    cursor.execute("ALTER TABLE remediation_lifecycle RENAME TO legacy_remediation_old;")
                cursor.execute("""
                    CREATE TABLE enterprise_portfolio (
                        project_id INTEGER PRIMARY KEY AUTOINCREMENT,
                        project_name TEXT NOT NULL UNIQUE,          
                        industry_vertical TEXT NOT NULL,           
                        lifecycle_state TEXT NOT NULL CHECK(lifecycle_state IN ('ACTIVE', 'INACTIVE', 'HOLD')),              
                        supervisor_deadline TEXT NOT NULL,          
                        allocated_budget_cents INTEGER NOT NULL CHECK(allocated_budget_cents >= 0 AND allocated_budget_cents <= 900000000000000000),
                        logged_at TEXT NOT NULL
                    );
                """)
                cursor.execute("""
                    CREATE TABLE remediation_lifecycle (
                        remediation_id INTEGER PRIMARY KEY AUTOINCREMENT,
                        associated_project TEXT NOT NULL,
                        trigger_condition TEXT NOT NULL,
                        deployed_directive TEXT NOT NULL,
                        execution_evidence_log TEXT,                
                        execution_status TEXT NOT NULL CHECK(execution_status IN ('STAGED', 'DEPLOYED', 'VERIFIED_CLEARED', 'PENDING_EXECUTION', 'REPORTED_CLEARED', 'FAILED')),             
                        triggered_at TEXT NOT NULL,
                        migration_audit_notes TEXT,
                        FOREIGN KEY(associated_project) REFERENCES enterprise_portfolio(project_name)
                    );
                """)
                for row in old_portfolio_rows:
                    cents = int(Decimal(str(row["allocated_budget"])).quantize(Decimal("1.00"), rounding=ROUND_HALF_UP) * 100)
                    cursor.execute("""
                        INSERT INTO enterprise_portfolio (project_id, project_name, industry_vertical, lifecycle_state, supervisor_deadline, allocated_budget_cents, logged_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?);
                    """, (row["project_id"], row["project_name"], row["industry_vertical"], row["lifecycle_state"], row["supervisor_deadline"], cents, row["logged_at"]))
                if has_legacy_remediation:
                    cursor.execute("PRAGMA table_info(legacy_remediation_old);")
                    old_columns = [col["name"] for col in cursor.fetchall()]
                    for rrow in old_remediations:
                        rem_id = rrow["remediation_id"]; proj = rrow["associated_project"]; directive = rrow["deployed_directive"]; status = rrow["execution_status"]; t_at = rrow["triggered_at"]
                        trigger_cond = rrow["trigger_condition"] if "trigger_condition" in old_columns else "UNKNOWN_TRIGGER"
                        evidence_log = rrow["execution_evidence_log"] if "execution_evidence_log" in old_columns else None
                        audit_note = rrow["migration_audit_notes"] if "migration_audit_notes" in old_columns else "Migration Ingestion: Legacy Note Preserved"
                        cursor.execute("""
                            INSERT INTO remediation_lifecycle (remediation_id, associated_project, trigger_condition, deployed_directive, execution_evidence_log, execution_status, triggered_at, migration_audit_notes)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?);
                        """, (rem_id, proj, trigger_cond, directive, evidence_log, status, t_at, audit_note))
                cursor.execute("CREATE UNIQUE INDEX idx_open_remediations ON remediation_lifecycle(associated_project, trigger_condition) WHERE execution_status IN ('STAGED', 'DEPLOYED', 'PENDING_EXECUTION');")
                cursor.execute("SELECT project_id, project_name, industry_vertical, lifecycle_state, supervisor_deadline, allocated_budget_cents, logged_at FROM enterprise_portfolio;")
                new_portfolio_rows = {r["project_id"]: r for r in cursor.fetchall()}
                if len(old_portfolio_rows) != len(new_portfolio_rows): raise ValueError("Portfolio row count mismatch.")
                for row in old_portfolio_rows:
                    pid = row["project_id"]; new_row = new_portfolio_rows.get(pid)
                    if not new_row or row["project_name"] != new_row["project_name"] or row["industry_vertical"] != new_row["industry_vertical"] or row["lifecycle_state"] != new_row["lifecycle_state"] or row["supervisor_deadline"] != new_row["supervisor_deadline"] or row["logged_at"] != new_row["logged_at"]:
                        raise ValueError(f"Field mismatch on row {pid}")
                    if new_row["allocated_budget_cents"] != int(Decimal(str(row["allocated_budget"])).quantize(Decimal("1.00"), rounding=ROUND_HALF_UP) * 100):
                        raise ValueError(f"Cash reconciliation delta on row {pid}")
                if has_legacy_remediation: cursor.execute("DROP TABLE legacy_remediation_old;")
                cursor.execute("DROP TABLE legacy_portfolio_old;")
                self.conn.commit()
                print("[MIGRATION COMPLETE] All schema columns migrated transactionally to strict production types.")
            except Exception as e:
                self.conn.rollback(); print(f"[CRITICAL ABORT] Migration failed. Details: {str(e)}"); sys.exit(1)
            finally: cursor.execute("PRAGMA foreign_keys = ON;")
        try:
            cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
cursor.execute("CREATE TABLE IF NOT EXISTS enterprise_portfolio (project_id INTEGER PRIMARY KEY AUTOINCREMENT, project_name TEXT NOT NULL UNIQUE, industry_vertical TEXT NOT NULL, lifecycle_state TEXT NOT NULL CHECK(lifecycle_state IN ('ACTIVE', 'INACTIVE', 'HOLD')), supervisor_deadline TEXT NOT NULL, allocated_budget_cents INTEGER NOT NULL CHECK(allocated_budget_cents >= 0 AND allocated_budget_cents <= 900000000000000000), logged_at TEXT NOT NULL);")
cursor.execute("CREATE TABLE IF NOT EXISTS ingestion_journal (event_uuid TEXT PRIMARY KEY NOT NULL, payload_hash_sha256 TEXT NOT NULL, processed_at TEXT NOT NULL);")
cursor.execute("CREATE TABLE IF NOT EXISTS autonomous_resolution_rules (rule_id INTEGER PRIMARY KEY AUTOINCREMENT, target_vertical TEXT NOT NULL, trigger_condition TEXT NOT NULL, pre_approved_action TEXT NOT NULL, UNIQUE(target_vertical, trigger_condition));")
cursor.execute("CREATE TABLE IF NOT EXISTS remediation_lifecycle (remediation_id INTEGER PRIMARY KEY AUTOINCREMENT, associated_project TEXT NOT NULL, trigger_condition TEXT NOT NULL, deployed_directive TEXT NOT NULL, execution_evidence_log TEXT, execution_status TEXT NOT NULL CHECK(execution_status IN ('STAGED', 'DEPLOYED', 'VERIFIED_CLEARED', 'PENDING_EXECUTION', 'REPORTED_CLEARED', 'FAILED')), triggered_at TEXT NOT NULL, migration_audit_notes TEXT, FOREIGN KEY(associated_project) REFERENCES enterprise_portfolio(project_name));")
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_open_remediations ON remediation_lifecycle(associated_project, trigger_condition) WHERE execution_status IN ('STAGED', 'DEPLOYED', 'PENDING_EXECUTION');")
cursor.execute("CREATE TABLE IF NOT EXISTS notification_outbox (notification_id INTEGER PRIMARY KEY AUTOINCREMENT, associated_project TEXT NOT NULL, alert_payload_text TEXT NOT NULL, retry_count INTEGER DEFAULT 0, delivery_status TEXT NOT NULL CHECK(delivery_status IN ('PENDING', 'CLAIMED', 'GATEWAY_ACCEPTED', 'DEVICE_ACKNOWLEDGED', 'FAILED')), retry_backoff_expiry TEXT, worker_owner_id TEXT, queued_at TEXT NOT NULL);")
cursor.execute("PRAGMA table_info(notification_outbox);")
cols = [col["name"] for col in cursor.fetchall()]
if "retry_backoff_expiry" not in cols: cursor.execute("ALTER TABLE notification_outbox ADD COLUMN retry_backoff_expiry TEXT;")
if "worker_owner_id" not in cols: cursor.execute("ALTER TABLE notification_outbox ADD COLUMN worker_owner_id TEXT;")
default_rules = [("ACCOUNTING", "DEADLINE_LAG", "DISPATCH_DIRECTIVE_TO_STAFF_RESOURCE_OPTIMIZE"), ("FASHION", "BUDGET_OVERRUN", "ENGAGE_AUTOMATED_MATERIAL_COST_SCALING"), ("TRADING", "TIMEOUT_DETECTED", "TRIGGER_ISOLATED_SANDBOX_WORKER_RESET"), ("MUSIC", "PRODUCTION_DELAY", "AUTO_PROVISION_ALTERNATIVE_TRACK_RENDER_NODES")]
for rule in default_rules: cursor.execute("INSERT OR REPLACE INTO autonomous_resolution_rules (target_vertical, trigger_condition, pre_approved_action) VALUES (?, ?, ?);", rule)
self.conn.commit()
except Exception as e:
self.conn.rollback(); print(f"[CRITICAL STARTUP ERROR] Schema convergence rejected: {str(e)}"); sys.exit(1)
finally: cursor.close()
def _validate_and_parse_monetary_input(self, budget_input) -> int:
if isinstance(budget_input, float): raise ValueError("Floating-point input rejected.")
str_input = str(budget_input).strip()
if any(token in str_input.lower() for token in ["nan", "inf", "-inf", "infinity"]): raise ValueError("Non-finite values rejected.")
try: dec_val = Decimal(str_input)
except Exception: raise ValueError("Input failed decimal validation.")
if not dec_val.is_finite() or dec_val.as_tuple().exponent < -2: raise ValueError("Invalid precision formatting components.")
cents = int(dec_val.quantize(Decimal("1.00"), rounding=ROUND_HALF_UP) * 100)
if cents < 0 or cents > 900000000000000000: raise ValueError("Monetary target resides outside allowable limits.")
return cents
def _parse_timezone_aware_deadline(self, deadline_str: str) -> datetime:
clean_str = deadline_str.strip()
try: dt = datetime.fromisoformat(clean_str.replace("Z", "+00:00"))
except Exception: raise ValueError(f"Malformed ISO-8601 deadline date string format: '{deadline_str}'")
if dt.tzinfo is None or dt.utcoffset() is None: raise ValueError(f"Timezone context missing or naive: '{deadline_str}'.")
return dt
def _generate_canonical_hash(self, payload: dict) -> bytes:
copied = json.loads(json.dumps(payload))
if "security_headers" in copied and "transmission_token_hash" in copied["security_headers"]:
copied["security_headers"]["transmission_token_hash"] = ""
return json.dumps(copied, sort_keys=True).encode("utf-8")
def autonomous_directory_sync_scan(self):
print(f" -> [DAEMON ACTIVE] Monitoring file system directory: '{self.monitor_dir}/'")
try: log_files = [f for f in os.listdir(self.monitor_dir) if f.endswith(".json")]
except Exception as e: print(f"    • [IO ERROR] Ingress monitor path blocked: {str(e)}"); return
for log_file in log_files:
file_path = os.path.join(self.monitor_dir, log_file); cursor = self.conn.cursor()
try:
with open(file_path, "r", encoding="utf-8") as f: payload = json.load(f)
provided_signature = payload.get("security_headers", {}).get("transmission_token_hash", "")
canonical_bytes = self._generate_canonical_hash(payload)
expected_hmac = hmac.new(SHARED_HMAC_SECRET_KEY, canonical_bytes, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected_hmac, provided_signature):
print(f"    • [SECURITY DENIED] Event packet failed signature check. Quarantining."); shutil.move(file_path, file_path + ".unauthorized"); continue
current_hash = hashlib.sha256(canonical_bytes).hexdigest()
event_uuid = payload["security_headers"]["event_uuid"]
cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
cursor.execute("SELECT payload_hash_sha256 FROM ingestion_journal WHERE event_uuid = ?;", (event_uuid,))
existing = cursor.fetchone()
if existing is not None:
if existing["payload_hash_sha256"] != current_hash: print(f"    • [TAMPER ALERT] Reused Event ID [{event_uuid}] with modified hash. Quarantining."); shutil.move(file_path, file_path + ".quarantine")
else: os.remove(file_path)
self.conn.commit(); continue
name = payload["metadata"]["project_name"]; vertical = payload["metadata"]["vertical"]; state = payload["metadata"]["lifecycle_state"]; deadline_iso = payload["metadata"]["deadline"]; budget_raw = payload["metadata"]["budget_value"]
self._parse_timezone_aware_deadline(deadline_iso); budget_cents = self._validate_and_parse_monetary_input(budget_raw)
cursor.execute("INSERT INTO ingestion_journal (event_uuid, payload_hash_sha256, processed_at) VALUES (?, ?, ?);", (event_uuid, current_hash, datetime.now(timezone.utc).isoformat()))
cursor.execute("INSERT INTO enterprise_portfolio (project_name, industry_vertical, lifecycle_state, supervisor_deadline, allocated_budget_cents, logged_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(project_name) DO UPDATE SET lifecycle_state = EXCLUDED.lifecycle_state, supervisor_deadline = EXCLUDED.supervisor_deadline, allocated_budget_cents = EXCLUDED.allocated_budget_cents, logged_at = EXCLUDED.logged_at;", (name, vertical, state, deadline_iso, budget_cents, datetime.now(timezone.utc).isoformat()))
self.conn.commit(); os.remove(file_path)
print(f"    • [TRANSACTION SECURED] Ingested event [{event_uuid}] cleanly saved.")
except Exception as e:
self.conn.rollback(); print(f"    • [INGESTION ABORTED] File loop rollback enforced: {str(e)}")
finally: cursor.close()
def execute_autonomous_triage_loop(self):
cursor = self.conn.cursor()
try:
cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
cursor.execute("SELECT remediation_id, triggered_at FROM remediation_lifecycle WHERE execution_status = 'STAGED';")
stalled_tasks = cursor.fetchall()
for task in stalled_tasks:
triggered_time = datetime.fromisoformat(task["triggered_at"].replace("Z", "+00:00"))
if (datetime.now(timezone.utc) - triggered_time) > timedelta(minutes=10):
cursor.execute("UPDATE remediation_lifecycle SET execution_status = 'FAILED', execution_evidence_log = 'Staged task processing lease expired' WHERE remediation_id = ?;", (task["remediation_id"],))
self.conn.commit()
except Exception as ex: self.conn.rollback(); print(f"    • [RECOVERY FAULT] Error processing stale task states: {str(ex)}")
finally: cursor.close()
cursor = self.conn.cursor()
cursor.execute("SELECT project_name, industry_vertical, supervisor_deadline FROM enterprise_portfolio WHERE lifecycle_state='ACTIVE';")
active_projects = cursor.fetchall(); cursor.close(); current_time = datetime.now(timezone.utc)
for project in active_projects:
name = project["project_name"]; vertical = project["industry_vertical"]
try: deadline_time = self._parse_timezone_aware_deadline(project["supervisor_deadline"])
except Exception: continue
if current_time > deadline_time:
trigger_condition = "DEADLINE_LAG"; cursor = self.conn.cursor()
try:
cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
cursor.execute("SELECT pre_approved_action FROM autonomous_resolution_rules WHERE target_vertical = ? AND trigger_condition = ?;", (vertical, trigger_condition))
rule_match = cursor.fetchone()
if not rule_match: self.conn.commit(); continue
action = rule_match["pre_approved_action"]; target_script_path = APPROVED_ACTION_HANDLERS.get(action)
if not target_script_path or not os.path.exists(target_script_path): self.conn.commit(); continue
try:
cursor.execute("INSERT INTO remediation_lifecycle (associated_project, trigger_condition, deployed_directive, execution_status, triggered_at) VALUES (?, ?, ?, 'STAGED', ?);", (name, trigger_condition, action, datetime.now(timezone.utc).isoformat()))
remediation_row_uid = cursor.lastrowid; self.conn.commit()
except sqlite3.IntegrityError: self.conn.rollback(); continue
print(f"\n -> [PROACTIVE INIT] Dispatching infrastructure shell workaround script: {action}...")
evidence_str = ""; execution_passed = False
try:
result = subprocess.run([target_script_path], capture_output=True, text=True, check=True, timeout=10.0)
evidence_str = "Execution Success Log Output: " + result.stdout.strip(); execution_passed = True
except Exception as sub_err: evidence_str = "Execution Call Failed/Timeout: " + str(sub_err); execution_passed = False
cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
if execution_passed:
cursor.execute("UPDATE remediation_lifecycle SET execution_status = 'DEPLOYED', execution_evidence_log = ? WHERE remediation_id = ?;", (evidence_str, remediation_row_uid))
alert_text = f"ALERT: Deployed workaround [{action}] on track [{name}]. Action script execution confirmed."
cursor.execute("INSERT INTO notification_outbox (associated_project, alert_payload_text, delivery_status, queued_at) VALUES (?, ?, 'PENDING', ?);", (name, alert_text, datetime.now(timezone.utc).isoformat()))
else: cursor.execute("UPDATE remediation_lifecycle SET execution_status = 'FAILED', execution_evidence_log = ? WHERE remediation_id = ?;", (evidence_str, remediation_row_uid))
self.conn.commit(); print(f"    • [VERIFIED STATE LOGGED] Operation processed. Status written to persistent records.")
except Exception as loop_fault: self.conn.rollback(); print(f"    • [TRIAGE ERROR] Failed processing loop track allocation for {name}: {str(loop_fault)}")
finally: cursor.close()
def process_notification_retry_outbox(self):
cursor = self.conn.cursor(); current_time = datetime.now(timezone.utc)
try:
cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
cursor.execute("UPDATE notification_outbox SET delivery_status = 'CLAIMED', worker_owner_id = ?, retry_backoff_expiry = ? WHERE delivery_status = 'PENDING' AND retry_count < 5 AND (retry_backoff_expiry IS NULL OR ? > retry_backoff_expiry);", (self.worker_id, (current_time + timedelta(minutes=5)).isoformat(), current_time.isoformat()))
self.conn.commit()
cursor.execute("SELECT * FROM notification_outbox WHERE delivery_status = 'CLAIMED' AND worker_owner_id = ?;", (self.worker_id,))
claimed_alerts = cursor.fetchall()
except Exception as e: self.conn.rollback(); print(f" -> [OUTBOX CLAIM FAULT] Failed acquiring multi-worker locks: {str(e)}"); return
finally: cursor.close()
for alert in claimed_alerts:
nid = alert["notification_id"]; retries = alert["retry_count"]; cursor = self.conn.cursor()
try:
api_network_response_success = False; cursor.execute("BEGIN IMMEDIATE TRANSACTION;")
if api_network_response_success: cursor.execute("UPDATE notification_outbox SET delivery_status='GATEWAY_ACCEPTED' WHERE notification_id=?;", (nid,))
else:
backoff_delay = int(math.pow(2, retries) * 30); next_run_expiry = (datetime.now(timezone.utc) + timedelta(seconds=backoff_delay)).isoformat()
cursor.execute("UPDATE notification_outbox SET retry_count = ? + 1, retry_backoff_expiry = ?, worker_owner_id = NULL, delivery_status = CASE WHEN (? + 1) >= 5 THEN 'FAILED' ELSE 'PENDING' END WHERE notification_id = ?;", (retries, next_run_expiry, retries, nid))
self.conn.commit()
except Exception: self.conn.rollback()
finally: cursor.close()
def render_executive_control_scoreboard(self):
print("\n============================================================")
print("     QZOTIC CONSIGLIERE: FLIGHT ACCELERATION SCOREBOARD     ")
print("============================================================")
cursor = self.conn.cursor()
cursor.execute("SELECT project_name, industry_vertical, lifecycle_state, supervisor_deadline, allocated_budget_cents FROM enterprise_portfolio;")
rows = cursor.fetchall()
for i, row in enumerate(rows, 1):
budget_str = f"{Decimal(row['allocated_budget_cents']) / Decimal('100'):,.2f}"
print(f"   [{i}] ENTERPRISE: {row['project_name']} ({row['industry_vertical']})")
print(f"       • Lifecycle State           : {row['lifecycle_state']}")
print(f"       • Target Manager Deadline   : {row['supervisor_deadline']}")
print(f"       • Fixed Monetary Budget     : ${budget_str}")
cursor.execute("SELECT deployed_directive, execution_status, execution_evidence_log FROM remediation_lifecycle WHERE associated_project=? ORDER BY remediation_id DESC LIMIT 1;", (row['project_name'],))
fix = cursor.fetchone()
if fix:
print(f"       • Active Remediation Loop   : {fix['deployed_directive']} [{fix['execution_status']}]")
print(f"       • Verified Action Evidence  : {fix['execution_evidence_log']}")
else: print(f"       • Active Remediation Loop   : NONE_PENDING [STABLE_CLEAR]")
print("============================================================\n"); cursor.close()
def close(self): self.conn.close()
if name == "main":
core = ConsigliereProductionCore()
core.autonomous_directory_sync_scan()
core.execute_autonomous_triage_loop()
core.process_notification_retry_outbox()
core.render_executive_control_scoreboard()
core.close()
