Skip to main content

What are Cognitive Insights?

Cognitive Insights use Google Gemini 2.5 Flash AI to analyze your journal entries and extract structured metadata: themes, emotional tone, life domain, significance scores, and entities (people, places, time references). This transforms unstructured text into searchable, quantifiable data for pattern discovery.

Why Use Cognitive Insights?

Discover Patterns

See recurring themes (growth, loss, connection) and emotional trends over time.

Quantify Significance

AI scores each story’s intensity and life importance (0-100 scale).

Entity Extraction

Automatically tag people, places, and time references for quick filtering.

Searchable Metadata

Query stories by emotional tone (joyful, anxious) or life domain (relationships, work).

How to Generate Insights

1

Save a Story

Insights are available after you save a story to the database. They cannot be generated on unsaved drafts.
2

Open the Story

Navigate to the story’s detail page (from Library or Social Feed). The AI Insights card appears at the bottom.
3

Trigger Analysis

If insights haven’t been generated yet, you’ll see:
“AI Insights Available” card with a Generate Insights button.
Click the button to start analysis. This happens automatically in the background when you save a story, but you can manually trigger it here.
4

Wait for Processing

Analysis typically takes 3-8 seconds. You’ll see:
  • Analyzing… spinner
  • Toast notification: “Analyzing Your Story”
The AI processes up to 10,000 characters per story (longer stories are truncated).
5

Review Insights

The card updates to show:
  • Brief Insight: One-sentence AI observation
  • Emotional Tone: Badge (joyful, anxious, reflective, etc.)
  • Life Domain: Badge (relationships, work, growth, etc.)
  • Themes: Up to 5 key themes (e.g., “discovery”, “connection”)
  • Intensity Score: 0-100% (how emotionally charged)
  • Significance Score: 0-100% (how important to life story)
  • Entities: People, places, time references mentioned
6

Refresh Insights (Optional)

Click the Refresh button (circular arrow icon) to re-analyze. Useful if you edited the story after initial analysis.

Insight Components Explained

Brief Insight

A single sentence AI-generated observation about the story’s meaning. Example:
“This story captures a pivotal moment of self-discovery during a challenging transition.”
Displayed in: Light blue box with lightbulb icon.

Emotional Tone (11 Categories)

Thoughtful, introspective, contemplative. Often appears in stories about past events or lessons learned.
Happy, celebratory, excited. Common in success stories or cherished memories.
Worried, stressed, uncertain. Appears in stories about challenges or upcoming decisions.
Optimistic, forward-looking, aspirational. Stories about goals or positive expectations.
Sad, nostalgic, wistful. Stories about loss, endings, or bittersweet memories.
Appreciative, thankful, content. Stories expressing gratitude or appreciation.
Annoyed, irritated, stuck. Stories about obstacles or unmet expectations.
Calm, serene, balanced. Stories about rest, nature, or resolution.
Energized, enthusiastic, anticipatory. Stories about new opportunities or adventures.
Confused, ambivalent, questioning. Stories exploring doubt or complexity.
Balanced, observational, factual. Default when no strong emotion detected.
Validation: AI must choose from these 11 options. Invalid responses default to neutral.

Life Domain (11 Categories)

DomainDescriptionExamples
WorkCareer, job, professional challengesPromotion, project completion, workplace conflict
RelationshipsRomantic, family, friendshipsBreakup, wedding, family reunion
HealthPhysical/mental wellbeingIllness recovery, fitness milestone, therapy session
IdentitySelf-concept, values, beliefsComing out, cultural heritage, personal transformation
GrowthLearning, skill developmentNew hobby, overcoming fear, mastering skill
CreativityArt, writing, music, expressionPainting, songwriting, creative project launch
SpiritualityFaith, meditation, meaningPrayer, pilgrimage, spiritual awakening
FamilyParenting, siblings, heritageBirth of child, family tradition, ancestry discovery
AdventureTravel, exploration, noveltyBackpacking trip, moving abroad, trying new food
LearningEducation, knowledge acquisitionCourse completion, research breakthrough, reading insight
GeneralEveryday moments, multiple domainsDefault when no specific domain fits
Displayed as: Colored badge with trend icon.

Themes (1-5 per Story)

AI-extracted keywords representing core concepts. Examples:
  • growth | loss | discovery | connection | change
  • resilience | adventure | nostalgia | achievement | uncertainty
Displayed as: Gray pill badges, clickable for future filtering.

Intensity Score (0-100)

How emotionally charged the story is.
Score RangeInterpretation
0-20Calm, factual, low emotion
21-40Mild emotional content
41-60Moderate emotional intensity
61-80Strong emotional experience
81-100Highly intense, peak experience
Displayed as: Progress bar with percentage.

Significance Score (0-100)

How important this event is to your life story.
Score RangeInterpretation
0-20Routine, everyday moment
21-40Noteworthy but minor
41-60Meaningful experience
61-80Major life event
81-100Pivotal, life-changing moment
Special Badge: Stories with significance > 70 get a “Key life moment” badge with star icon. Displayed as: Progress bar with percentage.

Entity Extraction

Proper names of individuals referenced in the story.Examples: Sarah, Dr. Johnson, Mom, Uncle RickIcon: Users icon (multiple people)
Specific locations (cities, buildings, countries).Examples: Paris, Central Park, the coffee shop on Main St.Icon: Map pin icon
Temporal markers from the story.Examples: last summer, when I was 12, three years ago, yesterdayIcon: Clock icon

Analysis States

The Insights card shows different states based on analysis status:

1. Not Started

Visual: Brain icon with gradient backgroundButton: “Generate Insights” (gradient blue/purple)Action: Click to trigger analysis

2. Pending

Visual: Hourglass icon with yellow backgroundMessage: “Analysis Queued — Your story is waiting to be analyzed. This usually takes a few moments.”No action available (wait for processing)

3. Processing

Visual: Spinning loader with purple backgroundMessage: “Analyzing Your Story — AI is extracting themes, emotions, and patterns from your story…”Wait time: 3-8 seconds

4. Failed

Visual: Warning triangle with red backgroundMessage: “Analysis Failed — Something went wrong while analyzing your story. Please try again.”Button: “Retry Analysis” (red outline)

5. Completed

Visual: Full insights card with all metadataRefresh Button: Top-right circular arrow (re-analyze)

Technical Implementation

Analysis API

POST /api/ai/analyze
Authorization: Bearer <token>
Content-Type: application/json

{
  "storyId": "uuid-of-story",
  "storyText": "Your story content..."
}

Response

{
  "success": true,
  "metadata": {
    "themes": ["growth", "connection"],
    "emotional_tone": "hopeful",
    "life_domain": "relationships",
    "intensity_score": 0.65,
    "significance_score": 0.72,
    "people_mentioned": ["Sarah", "Mom"],
    "places_mentioned": ["Central Park"],
    "time_references": ["last summer"],
    "brief_insight": "A turning point in understanding the value of vulnerability."
  },
  "insight": "A turning point in understanding the value of vulnerability."
}

Rate Limiting

30 requests per minute per user (enforced by in-memory rate limiter).Exceeding this returns 429 status with Retry-After header.

Retry Logic

The API includes exponential backoff for Gemini API failures:
  • Attempt 1: Immediate
  • Attempt 2: 1 second delay
  • Attempt 3: 2 second delay
Max retries: 3 attempts Code reference: /app/api/ai/analyze/route.ts:120-166

Concurrent Analysis Prevention

Only one analysis can run per story at a time. Duplicate requests return 409 Conflict: "Analysis already in progress for this story".

Content Truncation

Stories longer than 10,000 characters are truncated at word boundaries:
if (text.length > 10000) {
  // Truncate at last space before 10,000
  text = text.slice(0, lastSpace) + " [truncated]"
}
Minimum length: 50 characters (shorter stories rejected with 400 error).

Database Schema

Insights are stored in story_metadata table:
CREATE TABLE story_metadata (
  story_id UUID PRIMARY KEY REFERENCES stories(id),
  themes TEXT[],
  emotional_tone TEXT,
  life_domain TEXT,
  intensity_score NUMERIC(3,2),
  significance_score NUMERIC(3,2),
  people_mentioned TEXT[],
  places_mentioned TEXT[],
  time_references TEXT[],
  brief_insight TEXT,
  analysis_status TEXT DEFAULT 'pending',
  updated_at TIMESTAMPTZ
);
Key columns:
  • story_id: One-to-one relationship with stories
  • analysis_status: pending | processing | completed | failed
  • Arrays (themes, people_mentioned) stored as PostgreSQL arrays

Use Cases

Query all stories from the past week with emotional_tone = 'grateful' to see what you appreciated.
Filter by life_domain = 'work' to analyze career-related stress trends over months.
Search people_mentioned to find all stories featuring a specific person (e.g., “Sarah”).
Sort by significance_score DESC to create a timeline of your most important life moments.
Plot intensity_score over time to visualize emotional volatility or stability.
For public stories, you can request blockchain-attested insights via Chainlink CRE (Compute Runtime Environment):
1

Trigger CRE Workflow

Call /api/cre/trigger with your story ID. This sends the story to Chainlink DON (Decentralized Oracle Network).
2

Off-Chain Computation

Chainlink nodes run the analysis in a trusted enclave (same Gemini AI prompts).
3

On-Chain Attestation

Results are written to PrivateVerifiedMetrics.sol on Base Sepolia:
struct MinimalMetrics {
  bool meetsQualityThreshold; // qualityScore >= 70
  uint8 qualityTier;          // 1-5 (0-20, 21-40, 41-60, 61-80, 81-100)
  bytes32 metricsHash;        // keccak256(full scores + themes)
  bytes32 authorCommitment;   // keccak256(wallet + storyId)
  bytes32 attestationId;
  uint256 verifiedAt;
}
Privacy: Only tier/threshold stored on-chain. Full scores in Supabase (author-only access).
4

Retrieve Verified Metrics

Call /api/cre/check?storyId=<id> to get:
  • If you’re the author: Full metrics + blockchain proof
  • If you’re public viewer: Proof only (tier + threshold)
Use case: Prove your story has high-quality insights without revealing the details. Code reference: contracts/PrivateVerifiedMetrics.sol, app/api/cre/trigger/route.ts

Error Handling

Cause: Story too short for meaningful analysis.Solution: Add more content before analyzing.
Cause: More than 30 analysis requests in 1 minute.Solution: Wait 60 seconds before retrying. Check Retry-After header for exact time.
Cause: Gemini API returned malformed response (rare).Solution: Retry analysis. If persistent, check server logs for prompt issues.
Cause: Migration not run.Solution: Run migrations/add_story_metadata.sql on Supabase.

Best Practices

For best insights quality:
  • Write at least 200-300 words (more context = better analysis)
  • Be specific about people, places, and times
  • Express emotions explicitly (“I felt anxious” vs. vague language)
  • Avoid overly cryptic or abstract writing

Next Steps

Library Management

Use insights to find recurring themes in your journal (Phase 2 feature)

AI Enhancement

Improve story quality before analysis for richer insights

Blockchain Verification

Understand how CRE creates tamper-proof insight attestations

Build docs developers (and LLMs) love