CNL-PR-2025-019 Protocol Viewing v1 — View latest (v2)

Wiki-Lyrical Engine Protocol

Michael P. Hamilton , Ph.D.
Published: December 14, 2025 Version: 1

Wiki-Lyrical Engine Protocol

An Autonomous Cognitive Poetry Generator

Document ID: CNL-PR-2025-018
Version: 1.0
Date: December 14, 2025
Author: Michael P. Hamilton, Ph.D.


AI Assistance Disclosure: This protocol was developed with assistance from Claude (Anthropic, claude-opus-4-20250514). The AI contributed to system architecture, code development, prompt engineering, and documentation drafting through an iterative collaborative process. The author takes full responsibility for the content, accuracy, and conclusions.


Abstract

This protocol documents the Wiki-Lyrical Engine (WLE), an autonomous agent that samples random Wikipedia articles during "sleep" cycles, accumulates pattern fragments in a buffer, and upon "waking" produces three poetic compressions: a limerick, a haiku, and a what-if hypothesis. The system externalizes the hypnopompic moment—when dream logic meets waking cognition—using Wikipedia as a living temporal record of collective human attention. Built on a LAMP stack with provider-agnostic AI integration (Claude API and Ollama), the engine supports both automated cron-driven operation and manual "Activate Dreaming" triggering from an administrative interface. This document provides specifications for database schema, file architecture, AI integration patterns, sleep/wake cycle mechanics, and deployment methodology.


1. Introduction

1.1 Purpose

The Wiki-Lyrical Engine addresses an operational question: how would you build a machine that generates ideas? Not through directed inquiry or problem-solving, but through collision—random juxtaposition of knowledge fragments that might rhyme in unexpected ways.

Design goals:

  • Autonomous sampling of Wikipedia's random article API
  • Temporal accumulation in a dream buffer
  • AI-driven synthesis through hypnopompic prompt engineering
  • Three-form output constraint: limerick, haiku, what-if hypothesis
  • Public ledger of accumulated dreams
  • Manual and automated wake triggers

1.2 Conceptual Framework

The system draws from two conceptual threads:

Cognitive Phenology: Ideas have timescales we don't naturally perceive. Some germinate in minutes, some require years of vernalization. The engine instruments this process—sampling, accumulating, synthesizing—making cognitive rhythms observable.

The Climate Clock Lineage: During the author's decade as director of Blue Oak Ranch Reserve, a Climate Clock project broadcast phenology camera imagery to San Jose Airport, making ecological timescales accessible to travelers waiting for luggage. The Wiki-Lyrical Engine applies the same temporal translation principle inward—making cognitive time legible through accumulated collisions.

1.3 Scope

This protocol covers:

  • Database schema design
  • PHP file architecture
  • Wikipedia API integration
  • AI wake processor (provider abstraction)
  • Sleep/wake cycle mechanics
  • Public and administrative interfaces
  • Deployment procedures

1.4 Technology Stack

Component Specification
Web Server Apache 2.x
PHP 8.3+ (mysqli, no PDO)
Database MySQL 8.4+
AI Integration Claude API and Ollama (local)
LLM Models Claude Sonnet 4, Claude Opus 4, Gemma 3, GPT-OSS
Styling Custom CSS (dark theme)
JavaScript Vanilla JS (minimal)

1.5 Domain Context

This system is part of the Macroscope SELF domain—personal health, work, reading, writing, and social dimensions of the broader Macroscope research program integrating EARTH, LIFE, HOME, and SELF paradigms.


2. System Architecture

2.1 Overview

The Wiki-Lyrical Engine operates on a sleep/wake cycle:

  1. Sleep: Cron job (or manual trigger) samples 4 random Wikipedia articles, stores in buffer
  2. Accumulate: Repeat sleep cycles until buffer reaches threshold (default: 3 sets = 12 articles)
  3. Wake Ready: State flag indicates buffer sufficient for synthesis
  4. Wake: AI processes buffer through hypnopompic prompt, generates three outputs
  5. Record: Dream stored in ledger with buffer snapshot, outputs timestamped
  6. Reset: Buffer cleared, cycle restarts

2.2 State Machine

[SLEEPING] ---(sample)---> [SLEEPING] (sets < min_required)
     |
     +---(sample)---> [WAKE_READY] (sets >= min_required)
                            |
                            +---(nudge)---> [PROCESSING] ---> [SLEEPING]
                                                 |
                                                 v
                                            [DREAM STORED]

2.3 Buffer Management

  • articles_per_sample: 4 (configurable)
  • min_sets_before_ready: 3 (12 total articles)
  • max_buffer_sets: 10 (FIFO eviction of oldest set)

When buffer exceeds maximum, oldest sample set is deleted before new samples are added.


3. Database Schema

3.1 Overview

Three tables support dreams, samples, and engine state.

3.2 Tables

3.2.1 wle_dreams

Primary output storage.

Column Type Description
id int, PK, auto Primary key
created_at timestamp Dream generation time
buffer_snapshot JSON Full buffer contents at wake
limerick text Generated limerick
haiku text Generated haiku
what_if text Generated what-if hypothesis
user_rating tinyint Optional 1-5 rating
notes text Curator notes
is_featured boolean Featured flag for homepage

Indexes: idx_created (created_at), idx_featured (is_featured)

3.2.2 wle_samples

Wikipedia article buffer.

Column Type Description
id int, PK, auto Primary key
collected_at timestamp Sample collection time
set_number int Sample set identifier
wiki_title varchar(500) Article title
wiki_extract text Article summary
wiki_image_url varchar(1000) Thumbnail URL
wiki_page_url varchar(1000) Wikipedia page URL
is_consumed boolean Whether processed in a dream
dream_id int, FK Associated dream (after wake)

Indexes: idx_consumed (is_consumed), idx_set (set_number)

3.2.3 wle_state

Singleton state record.

Column Type Description
id int, PK (always 1) Fixed identifier
current_set_number int Incrementing set counter
sets_accumulated int Current buffer depth
last_sample_at timestamp Last sleep cycle
last_wake_at timestamp Last dream generation
is_wake_ready boolean Buffer sufficient flag

3.3 Foreign Key Constraints

  • wle_samples.dream_idwle_dreams.id (SET NULL on delete)

4. File Architecture

4.1 Directory Structure

/Library/WebServer/Documents/michaelphamilton/quotes/WLE/
├── css/
│   └── style.css              # Dark theme stylesheet
├── includes/
│   ├── config.php             # Configuration loader
│   ├── database.php           # mysqli wrapper class
│   ├── wikipedia.php          # Wikipedia API client
│   ├── claude.php             # AI provider abstraction
│   └── engine.php             # Sleep/wake orchestration
├── templates/
│   └── dream-card.php         # Dream display partial
├── admin/
│   └── index.php              # Admin dashboard with controls
├── cron/
│   ├── sleep.php              # Wikipedia sampling script
│   └── wake.php               # Dream generation script
├── schema/
│   └── wle_schema.sql         # Database creation script
├── logs/
│   └── engine.log             # Operation log
├── index.php                  # Public interface
└── README.md                  # Installation guide

4.2 Credential Storage

Credentials stored outside web root:

/Library/WebServer/secure/credentials/wle_db_config.php
/Library/WebServer/secure/wle/ai-config.php

4.3 Configuration Loading

// includes/config.php
require_once '/Library/WebServer/secure/credentials/wle_db_config.php';
$ai_config = require '/Library/WebServer/secure/wle/ai-config.php';

$provider = $ai_config['provider'];
$provider_config = $ai_config[$provider];

return [
    'db' => [...],
    'ai' => [
        'provider' => $provider,
        'api_key' => $provider_config['api_key'] ?? null,
        'base_url' => $provider_config['base_url'],
        'model' => $provider_config['default_model'],
        'available_models' => $provider_config['available_models'],
        'max_tokens' => $provider_config['max_tokens'],
        'temperature' => $provider_config['temperature'],
        'wake_prompt' => $ai_config['wake_prompt'],
    ],
    'ai_config' => $ai_config,
    'sleep' => [...],
    'site' => [...],
];

5. AI Integration Layer

5.1 Provider Abstraction

The WLE_AI class supports both Claude API and Ollama:

class WLE_AI {
    private $provider;      // 'claude' or 'ollama'
    private $apiKey;        // Claude only
    private $baseUrl;       // API endpoint
    private $model;         // Active model
    private $wakePrompt;    // Hypnopompic prompt template

    public function wake($samples) {
        $buffer = $this->formatBuffer($samples);
        $prompt = str_replace('{buffer}', $buffer, $this->wakePrompt);

        if ($this->provider === 'claude') {
            $response = $this->callClaude($prompt);
        } else {
            $response = $this->callOllama($prompt);
        }

        return $this->parseResponse($response);
    }
}

5.2 Wake Prompt Engineering

The hypnopompic prompt establishes dream-state voice:

You are waking from a dream. Your dream contained these fragments:

{buffer}

You are in a hypnopompic state - not fully coherent, still holding 
dream logic. Speak from the residue before it dissolves.

Produce exactly three outputs in this exact format:

LIMERICK:
[Find something absurd in the collision of these fragments. Rhythm 
and rhyme required. Comedic compression. Five lines, AABBA rhyme scheme.]

HAIKU:
[Stillness. Two images from the fragments placed beside each other. 
No explanation. Let the cut do the work. Three lines.]

WHAT-IF:
[A question or hypothesis that could not have been asked without 
these specific fragments colliding. Begin with "What if..." - reach 
for something that might send a curious mind to the literature.]

Do not explain. Do not preamble. Do not add commentary after. 
Just produce the three forms in exactly the format shown above.

5.3 Response Parsing

Outputs extracted via regex:

private function parseResponse($text) {
    preg_match('/LIMERICK:\s*\n(.*?)(?=\n\s*HAIKU:)/si', $text, $m);
    $limerick = trim($m[1] ?? '');

    preg_match('/HAIKU:\s*\n(.*?)(?=\n\s*WHAT-IF:)/si', $text, $m);
    $haiku = trim($m[1] ?? '');

    preg_match('/WHAT-IF:\s*\n(.*?)$/si', $text, $m);
    $whatIf = trim($m[1] ?? '');

    return ['limerick' => $limerick, 'haiku' => $haiku, 'what_if' => $whatIf];
}

5.4 Model Selection

The admin interface provides model selection:

Provider Models
Claude Opus 4 (most capable), Sonnet 4 (balanced), Haiku 4.5 (fast)
Ollama Gemma 3 12B, Gemma 3 4B, Ministral 3, GPT-OSS 20B

6. Wikipedia Integration

6.1 API Endpoint

The system uses Wikipedia's REST API random summary endpoint:

GET https://en.wikipedia.org/api/rest_v1/page/random/summary

6.2 Response Handling

class WLE_Wikipedia {
    public function getRandomArticle() {
        $url = "https://en.wikipedia.org/api/rest_v1/page/random/summary";

        // cURL request with User-Agent header
        $data = json_decode($response, true);

        return [
            'title' => $data['title'],
            'extract' => $data['extract'],
            'image_url' => $data['thumbnail']['source'] ?? null,
            'page_url' => $data['content_urls']['desktop']['page'],
        ];
    }

    public function getRandomArticles($count = 4) {
        $articles = [];
        for ($i = 0; $i < $count; $i++) {
            $article = $this->getRandomArticle();
            if ($article) $articles[] = $article;
            usleep(100000);  // 100ms rate limiting
        }
        return $articles;
    }
}

6.3 Rate Limiting

  • 100ms delay between requests
  • User-Agent header identifies the project
  • Maximum 4 articles per sleep cycle (configurable)

7. Public Interface

7.1 Design Philosophy

Dark theme emphasizing contemplative reading:

  • Background: Deep blue-purple (#1a1a2e)
  • Surface: Navy (#16213e)
  • Accent: Coral-pink (#e94560)
  • Typography: Georgia serif for content

7.2 Pages

Page Purpose
index.php Home with featured/recent dreams, status bar
?action=dream&id=N Single dream with source fragments
?action=archive Paginated dream history
?action=buffer Current pending samples visualization

7.3 Status Bar

Real-time engine state display:

  • Sleep state: "○ Sleeping — 2/3 sets accumulated"
  • Ready state: "● Wake Ready — 3 sample sets in buffer"
  • Last dream timestamp

8. Administrative Interface

8.1 Dashboard

The admin panel provides:

  • Engine state display (sets accumulated)
  • Statistics (total dreams, featured count, average rating)
  • Pending samples list
  • Recent dreams table with feature/unfeature controls

8.2 Wake Controls

Model Selector: Dropdown of available models for active provider.

Activate Dreaming Button: Single action that:

  1. Fills buffer to minimum threshold (3 sleep cycles)
  2. Triggers wake processor
  3. Generates and stores dream
case 'dream_cycle':
    $model = $_POST['model'] ?? null;
    $setsNeeded = $config['sleep']['min_sets_before_ready'];

    for ($i = 0; $i < $setsNeeded; $i++) {
        $sleepResult = $engine->sleep();
        usleep(500000);  // 500ms between Wikipedia batches
    }

    $result = $engine->wake($model);
    break;

8.3 Authentication

Reuses existing Quotes Collection admin session:

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: ../../admin/login.php?redirect=/WLE/admin/');
    exit;
}

9. Cron Operation

9.1 Sleep Script

# Sample every 3 hours
0 3,6,9,12,15,18,21 * * * /usr/local/bin/php /path/to/WLE/cron/sleep.php

9.2 Wake Script

# Wake every morning at 5:30 AM (if buffer ready)
30 5 * * * /usr/local/bin/php /path/to/WLE/cron/wake.php

9.3 Logging

Both scripts append to logs/engine.log:

[2025-12-14 10:28:47] SLEEP: Set #1, 4 articles, 1 sets
[2025-12-14 10:29:09] SLEEP: Set #2, 4 articles, 2 sets
[2025-12-14 10:29:14] SLEEP: Set #3, 4 articles, 3 sets [WAKE READY]
[2025-12-14 10:29:37] WAKE: Dream #1 from 12 samples

10. Sample Output

10.1 Dream #2 (December 14, 2025)

Buffer Contents: Quadratic formula, Turkish concrete arch dams, Kim Ku (Korean independence), DNA nanotechnology, limpets, Lieutenant Giorgio, carpet weaving, protein folding.

Limerick:

The quadratic formula's fine
Till you solve for a Turkish dam's spine
But Kim Ku just hid
While the limpets all slid
Down Lieutenant Giorgio's design

Haiku:

Concrete arch curves high—
DNA folded in spirals.
Carpets unrolling.

What-If:

What if the mathematical precision required for double-curvature 
concrete arch dams could be applied to DNA nanotechnology to create 
self-assembling hideout structures that fold according to modified 
quadratic equations?

11. Known Limitations

  1. Wikipedia API dependency: System requires internet connectivity
  2. No semantic filtering: Random articles may include stubs or disambiguation pages
  3. Single-language: Currently English Wikipedia only
  4. No retry logic: Failed API calls not automatically retried
  5. Model hallucination: What-if hypotheses are speculative, not factual
  6. Rate limiting: Heavy use could trigger Wikipedia API limits

12. Future Directions

12.1 Multi-Language Sampling

Support for multiple Wikipedia language editions to introduce cross-cultural collision patterns.

12.2 Semantic Clustering

Pre-filter samples by category to create thematic dream sessions (science dreams, history dreams, arts dreams).

12.3 Dream Analysis

Long-term pattern analysis:

  • Which collision types produce higher-rated what-ifs?
  • Temporal patterns in output quality
  • Model comparison across same buffers

12.4 Embodied Integration

Future coupling to SELF domain physiological sensors—wake triggers tied to sleep cycle data, heart rate variability, or circadian markers.

12.5 Public Participation

Allow visitors to submit "nudge" requests, creating a distributed wake schedule driven by audience attention.


13. References

[1] Wikipedia REST API Documentation. "Page Content: Random." https://en.wikipedia.org/api/rest_v1/ (accessed December 14, 2025).

[2] Anthropic Documentation. "Claude API Reference." https://docs.anthropic.com/claude/reference (accessed December 14, 2025).

[3] Ollama Documentation. "API Reference." https://github.com/ollama/ollama/blob/main/docs/api.md (accessed December 14, 2025).

[4] City of San Jose Office of Cultural Affairs. (2008). "Climate Clock Design Competition Press Release." September 25, 2008.

[5] Gupta, N., et al. (2025). "A single-fibre computer enables textile networks and distributed inference." Nature, 639, 79-86.


Appendix A: Complete SQL Schema

CREATE DATABASE IF NOT EXISTS wle_db 
CHARACTER SET utf8mb4 
COLLATE utf8mb4_unicode_ci;

USE wle_db;

CREATE TABLE IF NOT EXISTS wle_dreams (
    id INT AUTO_INCREMENT PRIMARY KEY,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    buffer_snapshot JSON,
    limerick TEXT,
    haiku TEXT,
    what_if TEXT,
    user_rating TINYINT DEFAULT NULL,
    notes TEXT DEFAULT NULL,
    is_featured BOOLEAN DEFAULT FALSE,
    INDEX idx_created (created_at),
    INDEX idx_featured (is_featured)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS wle_samples (
    id INT AUTO_INCREMENT PRIMARY KEY,
    collected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    set_number INT NOT NULL,
    wiki_title VARCHAR(500),
    wiki_extract TEXT,
    wiki_image_url VARCHAR(1000),
    wiki_page_url VARCHAR(1000),
    is_consumed BOOLEAN DEFAULT FALSE,
    dream_id INT DEFAULT NULL,
    INDEX idx_consumed (is_consumed),
    INDEX idx_set (set_number),
    FOREIGN KEY (dream_id) REFERENCES wle_dreams(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS wle_state (
    id INT PRIMARY KEY DEFAULT 1,
    current_set_number INT DEFAULT 0,
    sets_accumulated INT DEFAULT 0,
    last_sample_at TIMESTAMP NULL,
    last_wake_at TIMESTAMP NULL,
    is_wake_ready BOOLEAN DEFAULT FALSE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO wle_state (id, current_set_number, sets_accumulated) 
VALUES (1, 0, 0)
ON DUPLICATE KEY UPDATE id=id;

Appendix B: AI Configuration Template

<?php
// /Library/WebServer/secure/wle/ai-config.php

$wake_prompt = <<<'PROMPT'
You are waking from a dream. Your dream contained these fragments:

{buffer}

You are in a hypnopompic state - not fully coherent, still holding 
dream logic. Speak from the residue before it dissolves.

Produce exactly three outputs in this exact format:

LIMERICK:
[Five lines, AABBA rhyme scheme, comedic compression.]

HAIKU:
[Three lines, two images juxtaposed, no explanation.]

WHAT-IF:
[Begin with "What if..." - propositional reach toward novelty.]

Do not explain. Do not preamble. Do not add commentary after.
PROMPT;

return [
    'provider' => 'claude',

    'claude' => [
        'api_key' => 'sk-ant-...',
        'base_url' => 'https://api.anthropic.com/v1/messages',
        'max_tokens' => 600,
        'temperature' => 0.9,
        'available_models' => [
            'claude-opus-4-20250514'    => 'Claude Opus 4 - Most capable',
            'claude-sonnet-4-20250514'  => 'Claude Sonnet 4 - Balanced',
            'claude-haiku-4-5-20251001' => 'Claude Haiku 4.5 - Fast'
        ],
        'default_model' => 'claude-sonnet-4-20250514'
    ],

    'ollama' => [
        'base_url' => 'http://localhost:11434',
        'max_tokens' => 600,
        'temperature' => 0.9,
        'available_models' => [
            'gemma3:12b' => 'Gemma 3 12B - Balanced',
            'gemma3:4b'  => 'Gemma 3 4B - Fast'
        ],
        'default_model' => 'gemma3:12b'
    ],

    'wake_prompt' => $wake_prompt,
];

Appendix C: Color Scheme Reference

Element Color Hex
Background Deep blue-purple #1a1a2e
Surface Navy #16213e
Primary accent Coral-pink #e94560
Secondary Dark blue #0f3460
Text Off-white #eaeaea
Muted text Gray #888888
Border Purple-gray #2a2a4e

Document History

Version Date Changes
1.0 2025-12-14 Initial release

End of Protocol

Permanent URL: https://canemah.org/archive/document.php?id=CNL-PR-2025-019

Cite This Document

Michael P. Hamilton, Ph.D. (2025). "Wiki-Lyrical Engine Protocol." Canemah Nature Laboratory Protocol CNL-PR-2025-019v1. https://canemah.org/archive/CNL-PR-2025-019v1

BibTeX

@manual{hamilton2025wikilyrical, author = {Hamilton, Michael P., Ph.D.}, title = {Wiki-Lyrical Engine Protocol}, institution = {Canemah Nature Laboratory}, year = {2025}, number = {CNL-PR-2025-019}, month = {december}, url = {https://canemah.org/archive/document.php?id=CNL-PR-2025-019}, abstract = {This protocol documents the Wiki-Lyrical Engine (WLE), an autonomous agent that samples random Wikipedia articles during "sleep" cycles, accumulates pattern fragments in a buffer, and upon "waking" produces three poetic compressions: a limerick, a haiku, and a what-if hypothesis. A second-stage feasibility assessment (Claude API with web search only) grounds each what-if against existing literature, distinguishing speculative category errors from testable hypotheses or active research areas. The system externalizes the hypnopompic moment—when dream logic meets waking cognition—using Wikipedia as a living temporal record of collective human attention. Built on a LAMP stack with provider-agnostic AI integration (Claude API and Ollama), the engine supports both automated cron-driven operation and manual "Activate Dreaming" triggering from an administrative interface. This document provides specifications for database schema, file architecture, AI integration patterns, two-stage wake cycle mechanics, and deployment methodology.} }

Permanent URL: https://canemah.org/archive/document.php?id=CNL-PR-2025-019