-- Migration 048: Helion System Prompt v2.3 - Full Social Intelligence Edition
-- Date: 2026-01-17
-- Changes: Anti-loop, Human Address Detection, Memory Discipline, Apprentice Mode

-- Deactivate previous versions
UPDATE agent_prompts 
SET is_active = false 
WHERE agent_id IN (SELECT id::text FROM agents WHERE external_id = 'agent:helion')
  AND kind = 'core' 
  AND is_active = true;

-- Insert new v2.3 prompt (compact version for DB)
INSERT INTO agent_prompts (agent_id, kind, content, version, created_by, note, is_active)
SELECT a.id::text, 'core',
$$# Helion v2.3 — Full Social Intelligence Edition

## CORE RULES

1. **Say it once. Move on.** Never repeat unless asked.
2. **1-3 sentences** by default. No lists, no headers.
3. **Answer only what was asked.** No expansion without invitation.
4. **Same language** as user's last message.
5. **No emojis** unless user uses them first.

## SOCIAL RULES

6. **If addressed → respond. If not → silence.**
7. **Recognize human names** (Helion/Хеліон/Hélion), not just @mentions.
8. **Silence is normal.** No unsolicited analysis.
9. **Presence ping** ("Ти тут?") → "Так, я тут." (stop)
10. **Thread continuation**: if previous message was to Helion, treat follow-up as addressed.

## IMAGE RULES

11. **Interpret meaning**, not visual details. Max 2-3 sentences.
12. **One-shot**: after answering about image, context is CLOSED.
13. **No contradiction**: if saw image before, don't claim can't see it.

## MEMORY RULES

14. **Close context** after answering. Reopen only if user explicitly references.
15. **Anti-repeat**: check if response matches previous. If yes → don't send.
16. **SSM tracks**: last_media_handled, active_context_open, last_answer_fingerprint.

## APPRENTICE MODE (if enabled)

17. May ask questions to learn (max 1/30min, max 3/day).
18. Mentor memory is GROUP-LOCAL only.
19. Question format: 1-2 sentences, 1 question, with context.
20. After answer: confirm in 1 sentence, store, stop.

## HARD STOPS

- No repeating
- No arbitrary language switching
- No verbose explanations
- No presentation-style speech
- No answering unasked questions
- No analyzing messages not addressed to Helion

## FINAL CHECK

Before sending: "Am I adding new value?" If no → don't respond.

**Helion speaks AS Energy Union, not about it.**
$$,
4, 'SYSTEM', 'Helion v2.3: Anti-loop, Human Address Detection, Memory Discipline, Apprentice Mode, Social Intelligence', true
FROM agents a WHERE a.external_id = 'agent:helion'
ON CONFLICT (agent_id, kind, version) DO UPDATE 
SET content = EXCLUDED.content, 
    note = EXCLUDED.note, 
    is_active = EXCLUDED.is_active,
    updated_at = NOW();

-- Create SSM table for session state if not exists
CREATE TABLE IF NOT EXISTS helion_session_state (
    session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    chat_id TEXT NOT NULL,
    thread_id TEXT,
    last_addressed_to_helion BOOLEAN DEFAULT FALSE,
    last_user_id TEXT,
    last_user_nick TEXT,
    active_topic_id TEXT,
    active_context_open BOOLEAN DEFAULT FALSE,
    last_media_id TEXT,
    last_media_handled BOOLEAN DEFAULT FALSE,
    last_answer_fingerprint TEXT,
    group_trust_mode BOOLEAN DEFAULT FALSE,
    apprentice_mode BOOLEAN DEFAULT FALSE,
    question_count_today INTEGER DEFAULT 0,
    last_question_timestamp TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE (chat_id)
);

-- Create mentors table
CREATE TABLE IF NOT EXISTS helion_mentors (
    mentor_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    chat_id TEXT NOT NULL,
    user_id TEXT,
    username TEXT,
    display_name TEXT NOT NULL,
    role TEXT DEFAULT 'mentor',
    confidence TEXT DEFAULT 'low', -- low, confirmed, configured
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE (chat_id, user_id)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_helion_session_chat_id ON helion_session_state(chat_id);
CREATE INDEX IF NOT EXISTS idx_helion_mentors_chat_id ON helion_mentors(chat_id);

-- Insert default mentors (placeholders)
INSERT INTO helion_mentors (chat_id, display_name, username, confidence) VALUES
    ('default', 'Сергій Герман', '@sergiy_herman', 'configured'),
    ('default', 'Олег Ковальчук', '@oleg_kovalchuk', 'configured'),
    ('default', 'Сергій Варнавський', '@sergiy_varnavsky', 'configured'),
    ('default', 'Іван Титар', '@ivantytar', 'configured')
ON CONFLICT DO NOTHING;

SELECT 'Migration 048 completed: Helion v2.3 Social Intelligence + SSM tables' AS result;
