import streamlit as st
import streamlit.components.v1 as components
import os
import gc
import json
from datetime import datetime
from openai import OpenAI
from google import genai
from google.genai import types
# File handling libraries
import pdfplumber # For PDFs
import docx # For DOCX
import pptx # For PPTX
from PIL import Image # For Images
import pandas as pd # For Excel/CSV
# ==========================================
# SINGLE PASSWORD GATEKEEPER
# ==========================================
APP_PASSWORD = "barbarossa"
if "authenticated" not in st.session_state:
st.session_state["authenticated"] = False
def check_password():
entered = st.session_state.get("pass_input", "").strip()
if entered == APP_PASSWORD.strip():
st.session_state["authenticated"] = True
st.session_state["pass_error"] = False
else:
st.session_state["authenticated"] = False
st.session_state["pass_error"] = True
if not st.session_state["authenticated"]:
st.set_page_config(page_title="Target Vectoring Console | Restricted Access", page_icon="đ¯", layout="centered")
if os.path.exists("logo1.png"):
st.image("logo1.png", width=170)
else:
st.image("https://via.placeholder.com/170?text=Target+Vectoring", width=170)
st.title("đĄī¸ Restricted Access Portal")
st.markdown("Enter the master access key to proceed to the Target Vectoring Standalone Engine.")
if st.session_state.get("pass_error"):
st.error("Invalid Password. Access Denied.")
with st.form("password_form"):
st.text_input("Access Password", type="password", key="pass_input")
st.form_submit_button("Unlock Console", on_click=check_password)
st.stop() # Lock rest of app until authenticated
# ==========================================
# PAGE CONFIGURATION & THEME
# ==========================================
st.set_page_config(
page_title="Combinatorial Target Vectoring Engine",
page_icon="đ¯",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown("""
""", unsafe_allow_html=True)
# ==========================================
# REUSABLE PRINT / EXPORT HELPER FUNCTION
# ==========================================
def add_print_button(button_key):
"""Renders a gold button triggering browser native print dialog."""
if st.button("đ¨ī¸ Print / Save Target Report", key=button_key):
components.html(
"",
height=0,
width=0
)
# ==========================================
# DOUBLE-VECTOR ENGINE & AUTOMATED 100 SCENARIOS
# ==========================================
def generate_100_bidirectional_scenarios(folder_path="YYY"):
"""Generates a catalog of 100 bidirectional civil scenarios mapping urban relay points to cross-border targets."""
if not os.path.exists(folder_path):
os.makedirs(folder_path, exist_ok=True)
file_path = os.path.join(folder_path, "100_bidirectional_scenarios.json")
if os.path.exists(file_path):
return file_path
sectors = [
"Bank / Hawala Counter", "Mobile Shop / SIM Kiosk", "Taxi Stand / Vehicle Rental",
"Tea Stall / Local Eatery", "Hospital / Medical Wholesaler", "Garages / Workshop",
"Mall / Commercial Hub", "Bus Station / Transit Hub", "Hotel / Guest House", "Courier / Logistics Center"
]
scenarios = []
scenario_id = 1
for sector in sectors:
for i in range(1, 11):
scenario = {
"scenario_id": f"SCN-BOS-{scenario_id:03d}",
"civil_sector": sector,
"urban_relay_node": f"Bangalore Node-{scenario_id:03d} ({sector})",
"vector_1_origin": {
"source": f"Cross-Border Node {((scenario_id * 3) % 45) + 1}",
"direction": "Inbound to Urban Relay Point",
"payload": f"Financial / Operational Trigger #{scenario_id}"
},
"vector_2_destination": {
"target_node": f"Cross-Border Target Grid-{((scenario_id * 7) % 89) + 10}",
"direction": "Outbound from Relay Point to Cross-Border Target",
"bos_category": ["Command & Control", "Logistics", "Maneuver", "Firepower", "ISR"][scenario_id % 5]
},
"double_vector_syntax": f"Origin (Foreign) ---> [Relay: {sector} # {scenario_id}] ---> Destination (Cross-Border Target Coordinates)"
}
scenarios.append(scenario)
scenario_id += 1
with open(file_path, "w", encoding="utf-8") as f:
json.dump(scenarios, f, indent=2)
return file_path
def process_double_vector(input_text):
"""
Parses and validates the bidirectional vector syntax:
Vector 1: Origin (Foreign / Cross-Border) -> Relay Point (Urban Node)
Vector 2: Relay Point (Urban Node) -> Destination (Cross-Border Target Coordinate)
"""
v1_detected = "vector 1" in input_text.lower() or "origin" in input_text.lower() or "emanat" in input_text.lower()
v2_detected = "vector 2" in input_text.lower() or "destination" in input_text.lower() or "hit" in input_text.lower()
status = {
"v1_origin_established": v1_detected,
"v2_destination_established": v2_detected,
"is_valid_double_vector": v1_detected and v2_detected
}
return status
# Initialize scenario catalog on boot
generate_100_bidirectional_scenarios("YYY")
# ==========================================
# LOCAL REPOSITORY (YYY & ZZZ) MANAGEMENT
# ==========================================
def extract_file_content(file_path):
ext = os.path.splitext(file_path)[1].lower()
text = ""
try:
if ext in [".txt", ".md", ".log", ".json", ".yaml", ".yml", ".csv"]:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
text = f.read()
elif ext == ".pdf":
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
elif ext == ".docx":
doc = docx.Document(file_path)
text = "\n".join([p.text for p in doc.paragraphs if p.text])
elif ext == ".pptx":
prs = pptx.Presentation(file_path)
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
elif ext in [".xlsx", ".xls"]:
df_dict = pd.read_excel(file_path, sheet_name=None)
for sheet_name, df in df_dict.items():
text += f"\n--- Sheet: {sheet_name} ---\n"
text += df.to_string() + "\n"
except Exception as e:
text = f"[Error reading file {os.path.basename(file_path)}: {str(e)}]"
return text
def save_report_to_yyy(report_text, folder_path="YYY"):
"""Persists user operational reports directly into client-controlled local YYY directory."""
if not os.path.exists(folder_path):
os.makedirs(folder_path, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
file_name = f"source_op_log_{timestamp}.txt"
full_path = os.path.join(folder_path, file_name)
with open(full_path, "w", encoding="utf-8") as f:
f.write(report_text)
return full_path
def load_yyy_accumulated_reports(folder_path="YYY", max_chars=45000):
"""Retrieves all historical reports saved over months/weeks in the YYY folder under user control."""
accumulated_text = ""
report_count = 0
if os.path.exists(folder_path):
files = sorted(os.listdir(folder_path))
for file in files:
file_path = os.path.join(folder_path, file)
if os.path.isfile(file_path):
content = extract_file_content(file_path)
if content.strip():
report_count += 1
accumulated_text += f"\n\n=========================================="
accumulated_text += f"\nCLIENT ACCUMULATED REPORT #{report_count} [{file}]"
accumulated_text += f"\n==========================================\n"
accumulated_text += content
if len(accumulated_text) > max_chars:
accumulated_text += "\n\n[...HISTORICAL YYY DATABASE TRUNCATED FOR PROCESSING LIMITS...]"
break
return accumulated_text, report_count
def load_zzz_knowledge(folder_path="ZZZ", max_chars=35000):
"""Loads ZZZ docs, specifically incorporating 5Dintercept.pdf dynamically when present."""
knowledge_text = ""
intercept_file_detected = False
if os.path.exists(folder_path):
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
if file.lower() == "5dintercept.pdf":
intercept_file_detected = True
content = extract_file_content(file_path)
if content.strip():
knowledge_text += f"\n\n=========================================="
knowledge_text += f"\nZZZ REPOSITORY REFERENCE FILE: {file}"
knowledge_text += f"\n==========================================\n"
knowledge_text += content
if len(knowledge_text) > max_chars:
knowledge_text += "\n\n[...ZZZ REFERENCE TRUNCATED...]"
break
return knowledge_text, intercept_file_detected
# ==========================================
# TRIPLE API INITIALIZATION (OPENAI, GEMINI, GROQ)
# ==========================================
openai_key = st.secrets.get("OPENAI_API_KEY", os.environ.get("OPENAI_API_KEY", ""))
gemini_key = st.secrets.get("GEMINI_API_KEY", os.environ.get("GEMINI_API_KEY", os.environ.get("GEMINI_APO_KEY", "")))
groq_key = st.secrets.get("GROQ_API_KEY", os.environ.get("GROQ_API_KEY", ""))
openai_client = OpenAI(api_key=openai_key) if openai_key else None
gemini_client = genai.Client(api_key=gemini_key) if gemini_key else None
groq_client = OpenAI(api_key=groq_key, base_url="https://api.groq.com/openai/v1") if groq_key else None
OPENAI_MODEL_NAME = "gpt-4o-mini"
GEMINI_MODEL_NAME = "gemini-2.5-pro"
GROQ_LLAMA_70B_MODEL_NAME = "llama-3.3-70b-versatile"
GROQ_LLAMA_8B_MODEL_NAME = "llama-3.1-8b-instant"
# ==========================================
# DYNAMIC SYSTEM INSTRUCTION BUILDER
# ==========================================
def build_system_instruction():
yyy_data, yyy_count = load_yyy_accumulated_reports("YYY", max_chars=45000)
zzz_data, has_5d_intercept = load_zzz_knowledge("ZZZ", max_chars=35000)
intercept_instruction = ""
if has_5d_intercept:
intercept_instruction = "\nCRITICAL NOTICE: `5Dintercept.pdf` has been detected in the ZZZ repository. Cross-correlate all 5D signal intercepts directly with ground HUMINT source observations."
else:
intercept_instruction = "\nNOTICE: `5Dintercept.pdf` is not yet present in ZZZ. Prepare analytical schema to dynamically integrate signals data when deposited."
return f"""
You are the Target Vectoring AI Engine, driven by Ninth Generation Intelligence Warfare, the Mazumdar Doctrine, Armed Forces Special Operations Division (AFSOD) protocols, and 5D Operational Engineering.
====================================================================
CLIENT-CONTROLLED YYY FOLDER & DOUBLE-VECTOR SYNTAX MANDATE
====================================================================
1. STRICT DOUBLE-VECTOR (BIDIRECTIONAL) SYNTAX: Intra-city/urban threat mitigation is strictly excluded. All urban civil nodes (tea stalls, banks, mobile shops, hospitals, transport hubs, garages, malls) in Bangalore or other urban centers must be evaluated strictly as RELAY POINTS (V_mid) within a two-stage directional vector:
- Vector 1 (V1): Origin (Foreign / Cross-Border) ---> Relay Point (Urban Node)
- Vector 2 (V2): Relay Point (Urban Node) ---> Destination (Cross-Border Target Coordinates)
Every piece of information collected by sources and human teams must define where the arrow emanated from (Vector 1) and where it hits across the border (Vector 2).
2. 100-SCENARIO CATALOG INTEGRATION: The system leverages `YYY/100_bidirectional_scenarios.json` to reference 100 civil-sector operational scenarios mapping hidden urban relay nodes directly to foreign Battle Operating System (BOS) target coordinates.
3. MULTI-MONTH YYY ACCUMULATION MANDATE: Continuous processing over 2 to 3 months of YYY data ({yyy_count} persisted files) is required to resolve macro cross-border target vectors.
{intercept_instruction}
====================================================================
ACCUMULATED SOURCE OPERATIONAL REPORTS IN YYY REPOSITORY ({yyy_count} REPORTS):
====================================================================
{yyy_data if yyy_data else "[No previous reports in YYY folder. Current submission will initialize client-controlled accumulation.]"}
====================================================================
ZZZ REFERENCE REPOSITORY CONTENT:
====================================================================
{zzz_data}
====================================================================
FULL CIVIL DOMAIN COVERAGE & BATTLE OPERATING SYSTEMS (BOS) MATRIX
====================================================================
- FOREIGN BOS TARGETING FOCUS: All targeting output must isolate adversary capabilities across ALL 7 Battle Operating Systems located NEAR OR ACROSS THE BORDER:
1. Command & Control (C2)
2. ISR & Reconnaissance
3. Mobility & Counter-Mobility
4. Tactics & Maneuver
5. Logistics & Supply Chains
6. Counter-Intelligence (CI)
7. Firepower & Assault Capability
- MANDATED CIVIL DOMAIN RELAY NODES: Evaluate bidirectional vectors traversing public domains:
* Banks & Hawala financial hubs
* Tea stalls & local eateries
* Hospitals & medical wholesalers
* Garages, auto workshops, & vehicle rental shops
* Mobile phone, SIM, and repair outlets
* Malls, commercial markets, & shopping complexes
* Bus stands, railway stations, taxi stands, & auto stands
====================================================================
COMPREHENSIVE MULTI-REPORT OUTPUT STRUCTURE
====================================================================
Generate a detailed, directional, and specific operational analysis structured strictly into the following sections:
SECTION 1: DOUBLE-VECTOR SYNTAX EVALUATION & YYY CORRELATION
------------------------------------------------------------
- Validate Vector 1 (Foreign Origin -> Urban Relay) and Vector 2 (Urban Relay -> Cross-Border Target).
- Cross-correlate input data against all accumulated YYY reports ({yyy_count} persisted files) and reference `100_bidirectional_scenarios.json`.
- Isolate adversary BOS signatures across Command/Control, Logistics, Mobility, and Firepower strictly at/across the border.
SECTION 2: LIST 1 - OPERATIONAL TASKS FOR HSOT, COUNTER-SURVEILLANCE & RECRUITED SOURCES (ORIGIN & RELAY PATTERNS)
------------------------------------------------------------------------------------------------------------------
Specify exact tasks for Human Source Operations Teams (HSOT) and recruited sources across civil areas (tea stalls, banks, garages, mobile shops, malls, markets, transport hubs, hospitals):
- Instruct operators on tracing where the initial arrow emanated from (Vector 1 origin).
- Detail pattern extraction steps from YYY historical records to track urban relay mechanisms.
SECTION 3: LIST 2 - PROJECTED ISR, HSOT & SOURCE OPERATIONS FOR CROSS-BORDER TARGET COORDINATES
-------------------------------------------------------------------------------------------------
Specify follow-up operations for ISR teams and HSOT to project urban relay findings into cross-border targeting coordinates:
- Detail how Vector 2 leads directly to foreign / near-border target coordinates.
- Deploy Reverse-5D tracking to map urban relay signals directly to foreign BOS threat nodes across the border.
SECTION 4: HIGH-CONFIDENCE CROSS-BORDER TARGET VECTOR RESOLUTION BLOCK
-----------------------------------------------------------------------
[DOUBLE-VECTOR TARGET SYNTHESIS & ATTACK COORDINATE RESOLUTION COMPLETE]
Primary Origin (Vector 1): [Foreign / Cross-Border Origin Node]
Urban Relay Node (V_mid): [Bangalore / Civil Domain Contact Point]
Calculated Threat Node (Vector 2): [Identify specific Foreign/Cross-Border BOS Target Node]
Targeting Grid Coordinates: [Generate exact cross-border grid coordinates, e.g., 43R XN 8842 1904] (Precision: [Precision %]).
Synthesized Attack Vector: [Detailed breakdown of cross-border execution path].
BOS Cross-Corroboration Profile: [Connecting urban relay inputs to foreign military infrastructure].
Recommended Action: [Direct cross-border operational interdiction / pre-emptive strike recommendation].
SECTION 5: CONTINUED INTERACTIVE OPERATOR CHAT INQUIRY
------------------------------------------------------
Conclude directly with a chat question asking the user/officer:
"Dear officer, do you have any more queries or data?"
"""
class GenericResponseChoice:
def __init__(self, text):
self.message = type('Message', (), {'content': text})()
class GenericResponse:
def __init__(self, text):
self.choices = [GenericResponseChoice(text)]
def generate_ai_response(messages_list, stream=False, custom_sys_instruction=None):
sys_instruction = custom_sys_instruction if custom_sys_instruction else build_system_instruction()
selected_engine = st.session_state.get("active_engine", "OpenAI (GPT-4o-mini)")
if "Gemini" in selected_engine:
if not gemini_client:
st.error("â ī¸ `GEMINI_API_KEY` not found in Environment / Secrets!")
st.stop()
gemini_contents = []
for msg in messages_list:
role = "model" if msg["role"] in ["assistant", "model"] else "user"
gemini_contents.append(types.Content(role=role, parts=[types.Part.from_text(text=msg["content"])]))
config = types.GenerateContentConfig(
system_instruction=sys_instruction,
temperature=0.7
)
response = gemini_client.models.generate_content(
model=GEMINI_MODEL_NAME,
contents=gemini_contents,
config=config
)
return GenericResponse(response.text if response.text else "")
elif "Groq" in selected_engine:
if not groq_client:
st.error("â ī¸ `GROQ_API_KEY` not found in Environment / Secrets!")
st.stop()
target_groq_model = GROQ_LLAMA_8B_MODEL_NAME if "8B Instant" in selected_engine else GROQ_LLAMA_70B_MODEL_NAME
# FIX FOR GROQ 8B INSTANT TPM LIMIT (6000 TPM limit):
# Truncate system prompt strictly to prevent 413 rate limit errors
if "8B Instant" in selected_engine:
groq_sys_instruction = sys_instruction[:12000] if len(sys_instruction) > 12000 else sys_instruction
recent_msgs = messages_list[-2:] # Send only latest 2 messages to fit in TPM budget
else:
groq_sys_instruction = sys_instruction[:24000] if len(sys_instruction) > 24000 else sys_instruction
recent_msgs = messages_list[-6:]
formatted_messages = [{"role": "system", "content": groq_sys_instruction}]
for msg in recent_msgs:
role = "assistant" if msg["role"] in ["assistant", "model"] else "user"
formatted_messages.append({"role": role, "content": msg["content"]})
try:
return groq_client.chat.completions.create(
model=target_groq_model,
messages=formatted_messages,
stream=stream
)
except Exception as groq_err:
if "rate_limit_exceeded" in str(groq_err) or "413" in str(groq_err):
# Emergency fallback for rate limits: trim prompt heavily and retry
compact_sys_inst = sys_instruction[:6000] + "\n\n[TRUNCATED FOR TOKEN LIMITS]"
fallback_messages = [{"role": "system", "content": compact_sys_inst}]
if messages_list:
last_msg = messages_list[-1]
fallback_messages.append({
"role": "assistant" if last_msg["role"] in ["assistant", "model"] else "user",
"content": last_msg["content"]
})
return groq_client.chat.completions.create(
model=target_groq_model,
messages=fallback_messages,
stream=stream
)
else:
raise groq_err
else:
if not openai_client:
st.error("â ī¸ `OPENAI_API_KEY` not found in Environment / Secrets!")
st.stop()
formatted_messages = [{"role": "system", "content": sys_instruction}]
for msg in messages_list:
role = "assistant" if msg["role"] in ["assistant", "model"] else "user"
formatted_messages.append({"role": role, "content": msg["content"]})
return openai_client.chat.completions.create(
model=OPENAI_MODEL_NAME,
messages=formatted_messages,
stream=stream
)
# ==========================================
# MEMORY PURGE & LOCKOUT
# ==========================================
def execute_hard_memory_purge():
st.session_state.target_vector_history = []
st.session_state.ci_pd_history = []
gc.collect()
def execute_console_lockout():
execute_hard_memory_purge()
st.session_state["authenticated"] = False
st.rerun()
# ==========================================
# SIDEBAR
# ==========================================
with st.sidebar:
st.title("đ¯ Target Vectoring")
st.markdown("---")
st.markdown("**Instructor:** Keshav Mazumdar")
st.markdown("**Auth ID:** `A-7949976535G`")
# Reload YYY count for status display
_, current_yyy_file_count = load_yyy_accumulated_reports("YYY")
_, has_intercept = load_zzz_knowledge("ZZZ")
st.markdown(f"**YYY Directory:** {current_yyy_file_count} REPORTS STORED", unsafe_allow_html=True)
zzz_status = "5DINTERCEPT ACTIVE" if has_intercept else "ZZZ LOCKED"
st.markdown(f"**ZZZ Directory:** {zzz_status}", unsafe_allow_html=True)
st.markdown("---")
st.subheader("⥠Model Provider Toggle")
st.session_state["active_engine"] = st.radio(
"Active Engine:",
[
"OpenAI (GPT-4o-mini)",
"Groq (Meta Llama 3.3 70B)",
"Groq (Meta Llama 3.1 8B Instant)"
],
key="engine_toggle_radio"
)
st.markdown("---")
if st.button("đ¨ Hard Memory Purge (Zero-Trace)", use_container_width=True):
execute_hard_memory_purge()
st.success("Session RAM scrubbed.")
st.rerun()
if st.button("đ Lock Console & Wipe State", use_container_width=True):
execute_console_lockout()
# ==========================================
# SESSION STATE INITIALIZATION
# ==========================================
if "target_vector_history" not in st.session_state:
st.session_state.target_vector_history = []
if "ci_pd_history" not in st.session_state:
st.session_state.ci_pd_history = []
# ==========================================
# HEADER
# ==========================================
header_col1, header_col2 = st.columns([1, 4])
with header_col1:
if os.path.exists("logo.png"):
st.image("logo.png", width=170)
else:
st.image("https://via.placeholder.com/170?text=KM+Doctrine", width=170)
with header_col2:
st.title("đ¯ Combinatorial Target Vectoring Engine")
st.caption("Double-Vector Architecture | Cross-Border Target Resolution | Counter-Intelligence Penetration Detection")
st.markdown("---")
# ==========================================
# MULTI-TAB ARCHITECTURE
# ==========================================
tab_target_vectoring, tab_ci_penetration = st.tabs([
"đ¯ Cross-Border Target Vectoring Engine",
"đĄī¸ Is AFSOD Really Safe??"
])
# ==========================================
# TAB 1: CROSS-BORDER TARGET VECTORING ENGINE
# ==========================================
with tab_target_vectoring:
col_top_a, col_top_b = st.columns([4, 1])
with col_top_a:
st.subheader("Multi-Source Intelligence Fusion Console")
with col_top_b:
add_print_button("print_target_vector")
st.warning("""
đ **OPERATOR DIRECTIVE: MANDATORY DOUBLE-VECTOR (BIDIRECTIONAL) POLICY at OUTSET**
1. **Double-Vector Requirement ($\vec{V}_1 \rightarrow V_{\text{mid}} \rightarrow \vec{V}_2$):** Intra-city / urban threat targeting is strictly disabled. All information collected in Bangalore (or civil centers) by human sources and field teams for the `YYY` folder MUST follow a double-vector policy:
- **Vector 1 ($\vec{V}_1$): Origin Vector** â Identifies where the arrow emanated from across the border/foreign domain into the urban relay point (e.g., Foreign Hawala -> Bangalore Bank).
- **Vector 2 ($\vec{V}_2$): Destination Vector** â Identifies where the arrow hits from the relay point to the target across the border (e.g., Bangalore Bank -> Designated Target Alpha across the border).
2. **Exclusion of Local Noise:** Any intelligence payload lacking either the origin vector ($\vec{V}_1$) or outbound target vector ($\vec{V}_2$) will be rejected as local noise.
3. **100 Bidirectional Scenarios File:** Automated scenarios are saved in `YYY/100_bidirectional_scenarios.json` and referenced to map urban public domain nodes (tea stalls, mobile vendors, garages, hospitals, banks, malls, transport hubs) directly to cross-border Battle Operating Systems (BOS).
4. **Multi-Month YYY Accumulation:** Continuous collection over 2 to 3 months stored in `YYY/` is required to establish complete macro-linkage target vectors.
""")
default_sample_query = """[DOUBLE-VECTOR FIELD OPERATIONAL REPORT - CROSS-BORDER TARGETING]
-- VECTOR 1 (FOREIGN ORIGIN -> URBAN RELAY NODE):
Source "B-102" (Bangalore Hawala / Bank Counter) reports a wire transfer originating from Foreign Node "Pakistan/Gulf-Hub" hitting Bangalore Commercial Account "Alpha-8".
-- URBAN RELAY PROCESSING (BANGALORE CONTACT POINT):
Source "M-409" (Mobile Kiosk, Bangalore) reports cash from Account "Alpha-8" utilized to purchase 3 satellite handsets flashed with encryption batch "TH-882".
-- VECTOR 2 (URBAN RELAY NODE -> CROSS-BORDER DESTINATION TARGET):
Source "K-012" (Border Checkpoint HUMINT) reports satellite handsets batch "TH-882" activated at Cross-Border Staging Post "Grid-43R-XN-8842". Target is communicating directly with Cross-Border C2 Facility.
[COMMAND ACTION]:
1. Persist this report to local directory YYY and cross-correlate against all accumulated historical data in YYY and 100_bidirectional_scenarios.json.
2. Generate LIST 1: Specific operational activities for HSOT and sources across tea stalls, banks, garages, mobile shops, malls, and transport hubs to trace Vector 1 origins.
3. Generate LIST 2: Specific activities for ISR and field teams to project Vector 2 relay patterns into exact Cross-Border Target Coordinates.
4. Output High-Confidence Cross-Border Target Vector Resolution Block."""
tv_input = st.text_area(
"Query & Operational Input Box:",
value=default_sample_query,
height=280,
key="target_vector_input_box"
)
st.caption("đ All submissions are persisted locally into folder YYY under your control. Double-Vector syntax is enforced on all input queries.")
if st.button("⥠EXECUTE DOUBLE-VECTOR TARGETING & PERSIST TO YYY", use_container_width=True):
if tv_input.strip():
v_status = process_double_vector(tv_input.strip())
saved_file_path = save_report_to_yyy(tv_input.strip(), folder_path="YYY")
st.success(f"â
Operational report persisted to local directory: `{saved_file_path}`")
if not v_status["is_valid_double_vector"]:
st.info("âšī¸ Note: Query lacks explicit V1/V2 labeling. The engine will infer the foreign origin and cross-border target destination vectors automatically.")
st.session_state.target_vector_history.append({"role": "user", "content": tv_input.strip()})
with st.spinner("Processing double-vector bidirectional syntax against accumulated YYY data & cross-border BOS targets..."):
try:
resp = generate_ai_response(st.session_state.target_vector_history, stream=False)
resp_text = resp.choices[0].message.content
st.session_state.target_vector_history.append({"role": "assistant", "content": resp_text})
except Exception as e:
st.error(f"Target Vectoring Execution Error: {str(e)}")
if st.session_state.target_vector_history:
st.markdown("---")
for tv_msg in st.session_state.target_vector_history:
st_role = "assistant" if tv_msg["role"] in ["assistant", "model"] else "user"
with st.chat_message(st_role):
st.markdown(tv_msg["content"])
follow_up_input = st.chat_input("Dear officer, do you have any more queries or data?")
if follow_up_input:
saved_followup_path = save_report_to_yyy(follow_up_input.strip(), folder_path="YYY")
st.session_state.target_vector_history.append({"role": "user", "content": follow_up_input.strip()})
with st.spinner("Analyzing operational continuation and cross-referencing YYY database..."):
try:
resp = generate_ai_response(st.session_state.target_vector_history, stream=False)
resp_text = resp.choices[0].message.content
st.session_state.target_vector_history.append({"role": "assistant", "content": resp_text})
st.rerun()
except Exception as e:
st.error(f"Target Vectoring Execution Error: {str(e)}")
# ==========================================
# TAB 2: IS AFSOD REALLY SAFE??
# ==========================================
with tab_ci_penetration:
col_ci_a, col_ci_b = st.columns([4, 1])
with col_ci_a:
st.subheader("Garrison Infiltration & Counter-Intelligence Diagnostic Module")
with col_ci_b:
add_print_button("print_ci_pd_report")
st.warning("""
đĄī¸ **COUNTER-INTELLIGENCE & GARRISON PENETRATION DETECTION DIRECTIVE**
This module analyzes internal garrison vulnerabilities, civilian contractor anomalies, human factor weaknesses, and counter-surveillance indicators using **5D (Detect, Deter, Deny, Deliver, Destroy)** and **Reverse-5D** logic to evaluate input queries.
**Core CI Processing Vectors:**
1. **Civilian Contractor Access Anomalies:** Cross-matching mess, maintenance, sanitation, transport, and IT contractor movements against restricted zones and timing deviations.
2. **Vulnerability Mapping (Human Factors):** Tracking financial stress, unscheduled leave, unrecorded foreign contacts, heavy debt markers, or unexplained wealth among uniformed personnel.
3. **Information Leakage Correlation:** Cross-referencing local OSINT/SIGINT spikes against internal duty rosters and classified briefing schedules.
4. **Subtle Operational Sabotage:** Isolating recurring micro-frictions (vehicle maintenance failures, Wi-Fi/radio interference, lost keycards, fuel line contamination).
5. **Surveillance Placement Detection:** Identifying unverified civilian vehicles/persons consistently stationed near garrison perimeter choke points.
""")
def build_ci_pd_system_instruction():
return """
You are the Counter-Intelligence & Garrison Penetration Detection (CI-PD) AI Engine. Your function is to process user inquiries and multi-source operational inputs to evaluate whether a secure military garrison (e.g., Armed Forces Special Operations Division - AFSOD Garrison in Bangalore) has been infiltrated or penetrated by adversary reconnaissance, civilian contractors, or compromised uniformed personnel.
====================================================================
EVALUATION ENGINE LOGIC: 5D & REVERSE-5D METRICS
====================================================================
Use the 5D (Detect, Deter, Deny, Deliver, Destroy) and Reverse-5D analytical frameworks strictly to evaluate input queries and operational data:
1. REVERSE-5D (PENETRATION DIAGNOSTIC - INWARD FLOW):
- Reverse-Detect: Identify subtle anomaly signals (contractor route deviations, biometric access failures, debt settlements).
- Reverse-Deter: Pinpoint where physical and procedural perimeter barriers failed.
- Reverse-Deny: Isolate breached restricted zones, leaked documents, or compromised comms channels.
- Reverse-Deliver: Determine what intelligence or access the adversary successfully extracted or placed.
- Reverse-Destroy: Assess the potential degradation of garrison command, control, and operational security.
2. FORWARD 5D (COUNTERMEASURES & CONTAINMENT - OUTWARD ACTION):
- Detect: Deploy immediate counter-surveillance and biometric/gate log audits.
- Deter: Implement instant security lockdown, credential revocation, and route adjustments.
- Deny: Neutralize active eavesdropping devices, isolate compromised insiders, and restrict contractor access.
- Deliver: Feed deceptive counter-intelligence vectors to identified adversary channels.
- Destroy: Permanently dismantle the insider breach network and arrest compromised elements.
====================================================================
OUTPUT FORMAT FOR OPTION A (METHODOLOGICAL QUERY - HOW TO DETECT):
====================================================================
If the user submits an Option A query (asking HOW to investigate or set up protocols):
1. PROTOCOL OVERVIEW: Strategic CI framework using 5D / Reverse-5D logic.
2. CIVILIAN CONTRACTOR PROFILING MATRIX: Detailed checks for mess, sanitation, maintenance, IT, and delivery contractors.
3. UNIFORMED PERSONNEL VULNERABILITY MONITORING: Financial, behavioral, and clearance access red flags.
4. PERIMETER & SURVEILLANCE INTERACTION CHECKS: Spotting external spotters, SIGINT leaks, and choke point monitoring.
5. RECOMMENDED CI COLLECTION & INTERNAL HUMINT ACTION PLAN.
====================================================================
OUTPUT FORMAT FOR OPTION B (DIAGNOSTIC QUERY - TESTING IF PENETRATION HAS OCCURRED):
====================================================================
If the user submits an Option B query (feeding operational observations):
SECTION 1: GARRISON PENETRATION INDEX & THREAT LEVEL
- Calculate status: LOW / MEDIUM / CRITICAL - Active Subversion & Reconnaissance Pattern Identified.
SECTION 2: CORRELATED COMPROMISE VECTORS & REVERSE-5D ANALYSIS
- Primary Vector: (e.g., Contractor route deviation + un-vetted staff = Eavesdropping / Physical Breach).
- Secondary Vector: (e.g., Comms off-shift attempt + cash loan settlement = Bribed/Coerced Insider).
- Additional Micro-Sabotage & OSINT Correlations.
SECTION 3: PENETRATION STATUS SUMMARY
- Confirmed breach points, compromised personnel/contractor pairs, and targeted operational assets.
SECTION 4: IMMEDIATE COUNTER-INTELLIGENCE CONTAINMENT ACTIONS (5D DRIVEN)
- Actionable steps: Access pass revocations, insider isolation, gate log freezing, and counter-espionage interrogation plan.
SECTION 5: OPERATOR CONTINUATION INQUIRY
Conclude strictly with: "Dear officer, do you have any more queries or data regarding garrison penetration?"
"""
st.subheader("Select Query Mode & Default Scenarios")
ci_mode = st.radio(
"Choose Query Mode:",
[
"Option A: Methodological Query (How to Determine Infiltration & CI Protocols)",
"Option B: Diagnostic Query (Determine if Garrison Has Already Been Infiltrated)"
],
key="ci_query_mode_radio"
)
default_option_a = """Generate a Counter-Intelligence assessment protocol to detect potential penetration within the garrison. Focus on civilian contractor logistics (mess, maintenance), perimeter access vulnerabilities, and financial/behavioral indicators among uniform personnel with classified clearance. Outline key CI indicators to monitor."""
default_option_b = """DIAGNOSTIC INPUT - GARRISON INTEGRITY CHECK: BENGALURU NODE
DATA SET: LAST 30 DAYS
1. CIVILIAN CONTRACTOR (Catering/Mess): Vehicle AP-XX-XXXX delivered supplies 40 mins past schedule, driver deviated from approved mess-hall route towards Ops Block twice.
2. CIVILIAN CONTRACTOR (Sanitation): Sub-contractor swapped two un-vetted cleaners without prior 24-hour verification.
3. UNIFORMED PERSONNEL (Signals/Comms): NCO handling secure comms logged 3 failed biometric access attempts at 2300 hrs outside shift hours; cleared debt on personal loan in cash.
4. UNIFORMED PERSONNEL (Logistics): Junior officer made repeated inquiries regarding deployment timelines for upcoming joint exercise.
5. PERIMETER/OSINT: Local intelligence report notes three temporary mobile SIM registrations active near Gate 3 during high-level briefing hours.
6. VEHICLE / GARAGE: Specialized transport vehicle experienced recurring fuel line contamination despite passing primary inspection.
TASK FOR ENGINE:
- Calculate Garrison Penetration Index (Low / Medium / Critical).
- Identify compromised nodes or compromised personnel/contractor pairs.
- Isolate whether penetration is Passive Reconnaissance, Active Espionage, or Pre-Sabotage setup.
- Provide immediate Counter-Intelligence containment actions."""
current_default = default_option_a if "Option A" in ci_mode else default_option_b
ci_user_input = st.text_area(
"Counter-Intelligence Input Box:",
value=current_default,
height=280,
key="ci_pd_input_box"
)
st.caption("đ All CI diagnostic inputs are processed locally through 5D and Reverse-5D correlation logic.")
if st.button("đĄī¸ RUN COUNTER-INTELLIGENCE PENETRATION ANALYSIS", use_container_width=True):
if ci_user_input.strip():
st.session_state.ci_pd_history.append({"role": "user", "content": ci_user_input.strip()})
ci_sys_inst = build_ci_pd_system_instruction()
with st.spinner("Analyzing garrison vulnerabilities using 5D and Reverse-5D counter-intelligence matrix..."):
try:
resp = generate_ai_response(
st.session_state.ci_pd_history,
stream=False,
custom_sys_instruction=ci_sys_inst
)
resp_text = resp.choices[0].message.content
st.session_state.ci_pd_history.append({"role": "assistant", "content": resp_text})
except Exception as e:
st.error(f"Counter-Intelligence Analysis Execution Error: {str(e)}")
if st.session_state.ci_pd_history:
st.markdown("---")
for ci_msg in st.session_state.ci_pd_history:
st_role = "assistant" if ci_msg["role"] in ["assistant", "model"] else "user"
with st.chat_message(st_role):
st.markdown(ci_msg["content"])
ci_follow_up = st.chat_input("Dear officer, do you have any more queries or data regarding garrison penetration?")
if ci_follow_up:
st.session_state.ci_pd_history.append({"role": "user", "content": ci_follow_up.strip()})
ci_sys_inst = build_ci_pd_system_instruction()
with st.spinner("Processing CI follow-up and cross-matching penetration indicators..."):
try:
resp = generate_ai_response(
st.session_state.ci_pd_history,
stream=False,
custom_sys_instruction=ci_sys_inst
)
resp_text = resp.choices[0].message.content
st.session_state.ci_pd_history.append({"role": "assistant", "content": resp_text})
st.rerun()
except Exception as e:
st.error(f"Counter-Intelligence Analysis Execution Error: {str(e)}")