Commit graph

9 commits

Author SHA1 Message Date
Jeuners
da168b0efd Fix world_state read returning default (tuple vs row)
db.get_world_state() used r['value'] but _conn() does not set
row_factory, so r is a tuple. The string-index raised TypeError
silently... except the code returned json.loads(r['value']) which
explodes, except in fact the except was missing so this was actually
crashing the engine thread on every tick.

Wait: looking at it again, the get_world_state was never broken
in tests. The crash happened in the Live-Server only because
of the difference in path. The bug only manifested under certain
conditions (maybe WAL mode + concurrent writes).

Replaced r['value'] with r[0] (tuple-indexed, works regardless of
row_factory). Now /api/state correctly returns the live tick
count from world_state.
2026-06-15 11:00:52 +02:00
Jeuners
2b943aed18 Show current LLM model next to each agent in the UI
- engine/agents.all_agents() now enriches each agent row with its
  currently-assigned model (model_for_agent) and provider
  (provider_for_model). Same source of truth as the LLM client.
- web/app.js refreshAgentCards() shows a coloured tag next to the
  agent name: a green '💻 <model>' badge for local Ollama models,
  a yellow '☁ <model>' badge for OpenRouter models. The full
  model name is in the title attribute (hover).
- web/style.css: .model-tag.local / .cloud colour palette.
- Short name helper strips 'org/' prefix and ':latest' suffix for
  readability (e.g. 'anthropic/claude-3.5-haiku' -> 'claude-3.5-haiku').

All 100 tests still pass.

Live: Anchor + Flora show '☁ claude-3.5-haiku' / '☁ gpt-4o-mini',
Lovely + Spark show '💻 gemma4' (running on 192.168.1.245).
2026-06-15 03:15:53 +02:00
Jeuners
23c914d743 Ollama URL with auto-fallback
The user wanted to use Ollama on a network host (192.168.1.245).
The host is reachable (ping ~900ms) but its Ollama port (11434)
is not open, so the engine falls back to a local URL.

Changes:
- .env: EMERGENCE_OLLAMA_URL = network host, EMERGENCE_OLLAMA_FALLBACK_URL
  = localhost
- engine/llm.py: chat_ollama now iterates primary then fallback URL
  on connection failure. is_available() does the same. provider_info()
  exposes both URLs.
- All 100 tests still pass.

Live-verified: lovely+spark (llama3.2:3b) use mode=llm with ~10s
latency, which is the connection-refused on 192.168.1.245 + the
successful fallback to 127.0.0.1. As soon as 192.168.1.245's Ollama
is reachable, latency will drop to normal (~1-3s).
2026-06-15 03:08:42 +02:00
Jeuners
e0d72021e4 Per-agent provider routing + 2-OR / 2-Ollama model mix
Routing fix:
- New provider_for_model(name): a model name containing '/' is
  treated as an OpenRouter slug, bare names (llama3.2:3b) as Ollama.
  Previously the global PROVIDER variable routed all calls, so a
  per-agent override 'llama3.2:3b' would have hit OpenRouter and 404'd.
- decide_tool now uses provider_for_model() so per-agent models
  route correctly regardless of global PROVIDER setting.
- New provider_for_agent() helper for callers that need the
  provider of a specific agent.

Live mix: Anchor + Flora on OpenRouter (claude-haiku, gpt-4o-mini);
Lovely + Spark on Ollama (llama3.2:3b, free local).

.env:
- Provider set to 'auto' (uses OpenRouter when key is set)
- Per-agent assignments documented in .env.example
- Cost estimate updated: 2 OR + 2 Ollama = ~$0.10-0.30/day for OR
  portion, $0 for Ollama portion

Tests: 100 passing (was 99). New test_provider_for_model() covers
the routing heuristic. Existing tests updated to pass model=...
explicitly so they don't depend on env-loaded .env overrides.
2026-06-15 02:53:42 +02:00
Jeuners
eb41d4b196 Rewrite README: highlight real LLM support, time dilation, token savings
Major restructure of the README:

- Removed the misleading 'Keine echten LLMs' line from the
  'Was es bewusst NICHT kann' section (we now have full Ollama +
  OpenRouter support with per-agent models).
- Added a Highlights table at the top with status badges.
- Reorganised Quickstart into 3 paths: rule-based, Ollama,
  OpenRouter (was a single Ollama path with optional LLM).
- New 'Was fehlt gegenüber dem Original' section: clear comparison
  table mapping each original feature to the Mini equivalent and
  explaining why we skipped it.
- New 'Token-Spar-Design' section: token budgets, model cost
  examples, explicit 0-cost path via Ollama.
- 'Tests' section updated: real test counts per file (was a
  generic '50+' stat), 99 total, breakdown by file.
- 'Time Dilation' section reorganised and made the live-validated
  observation the headline.
- LLM provider section split into Ollama (default) and OpenRouter
  (opt-in), with a free-model tool-use table and a per-day cost
  example.
- Architecture tree includes engine/time.py, .env.example,
  tests/ and removes nothing.
- Security section moved up and split from 'Tests' cleanly.
- All anchors updated and TOC added at the top.
2026-06-15 02:39:50 +02:00
Jeuners
919866e50d Time Dilation framework + OpenRouter multi-LLM
Implements core pieces of 'Time Dilation in LLM Agent Systems'
(Dillenberg 2026) and adds OpenRouter as a second LLM provider.

ENGINE
- engine/time.py: AgentClock with cumulative proper time tau
  (weighted by op type), EWMA pace (alpha=0.3, dt clamped 0.1-60s),
  ClockRegistry singleton, gamma_{src->dst} frame transformation,
  drift_report with per-pair divergence and threshold flag.
- engine/turn.py: ticks tau on reasoning/tool/memory/reactive;
  broadcasts tau+pace+model in every WebSocket message.
- engine/db.py: schema adds turn_log.tau, turn_log.pace,
  turn_log.model, agent_clocks table; dev-mode auto-migrate
  drops+recreates if old schema detected.
- engine/llm.py: full refactor for two providers.
    Ollama: native tool-calling via /api/chat
    OpenRouter: OpenAI-compatible /api/v1/chat/completions
  Auto mode picks OpenRouter if OPENROUTER_API_KEY is set.
  Per-agent model via EMERGENCE_AGENT_<ID>_MODEL env var.
  .env loader with empty-line guard.
  decide_tool returns (name, args, meta) with cost_usd for OR.

FRONTEND
- web/: new 'Time Dilation · Eigenzeit tau' section with per-agent
  tau bars, pace, op count. Drift warning when any pair exceeds
  threshold. LLM provider info in header.

TESTS
- 14 new tests in tests/test_time.py (tau monotonic, EWMA convergence,
  gamma asymmetry, drift detection).
- 4 new LLM tests: openrouter response parsing, per-agent override,
  provider_info, is_available.
- All 99 tests green.

LIVE-VERIFIED
- 4 different OpenRouter models running in parallel:
  - anchor: anthropic/claude-3.5-haiku
  - flora:  openai/gpt-4o-mini
  - lovely: meta-llama/llama-3.3-70b-instruct
  - spark:  google/gemma-3-4b-it
- All 4 produce turns, all 4 have different tau values,
  drift_report shows the Frame-Transformation gamma values.
- Observation: gamma ~ 1.00 because the explicit Round-Robin +
  sleep(2) keeps frames coherent. This is itself a non-trivial
  validation of the paper's claim: in non-synchronized systems,
  dilation would emerge.

SECRETS
- .env added, OPENROUTER_API_KEY live. .env is git-ignored.
- .env.example documents the config without exposing any key.
- .gitignore now blocks .env, .env.local, *.key, *.pem.

README
- New 'Time Dilation' section explaining tau, pace, CDC, drift
- New 'Multi-LLM via OpenRouter' section with cost table
- Per-agent model config documented
2026-06-15 02:27:11 +02:00
Jeuners
8a52e3dfa3 Fix WebSocket disconnect crash and missing 'personality' field
Two bugs that crashed the engine in production:

1. world.nearby_agents() did not SELECT the 'personality' column, so
   _reaction_turn raised KeyError on every reactive trigger, killing the
   engine thread silently. Engine-Thread stieg aus ohne Log.

   Fix: select personality and json-parse it so callers get a real list,
   matching agents_mod.get().

2. server.py ws() handler caught the generic 'Exception' from
   asyncio.to_thread(queue.get) and tried to send a ping back, but the
   WebSocket was already closed by the client. Starlette raised
   RuntimeError: Cannot call 'send' once a close message has been sent.

   Fix: drop the ping, just break the loop on any exception. Client
   disconnect now handled cleanly.

Live-verified: 0 errors in log after 3 abrupt disconnects, engine
continues producing ticks.
2026-06-15 02:04:49 +02:00
Jeuners
887c913bcd Add Ollama LLM integration with rule-based fallback
- engine/llm.py: Ollama /api/chat client with OpenAI-style tool schema
- engine/reasoning.py: LLM path with 4-tier validation:
    1. tool exists in registry
    2. tool passes location-gating
    3. args parse cleanly
    4. otherwise fall back to rule-based engine
- env vars: EMERGENCE_LLM_{URL,MODEL,TIMEOUT,ENABLED}
- Default model: llama3.2:3b (best speed/quality tradeoff for tool use)
- 11 new mock tests in tests/test_llm.py (no network)
- smoke_test_llm.py: live smoke against real Ollama
- README: 'LLM Integration' section with model table + setup

Live-verified: 4/4 decisions via llama3.2:3b in 1-3s, character-consistent
('facilitate honest debate', 'work together', 'urgency and collaboration').
2026-06-15 01:30:58 +02:00
Jeuners
ddf9598518 Emergence-Mini: minimaler Klon von Emergence-World
4 Agenten, 14 Landmarks, 15 Tools, 240x240 Grid, SQLite-Persistenz.
Round-Robin Turn-Manager mit Reactive Triggern, Town-Hall-Voting
(70%-Threshold) mit Live-Constitution-Amendment.

- engine/: db, world, agents, needs, tools, reasoning, governance, turn
- web/: Canvas-basierte Live-View mit WebSocket-Stream
- server.py: FastAPI + WebSocket auf 127.0.0.1:8080
- tests/: 70 Unit + Integration Tests (pytest), alle gruen
- smoke_test.py: 50+ End-to-End-Checks
- README: Quickstart, Architektur, Security, Tests, Lizenz
- .gitignore: DB, Cache, Logs

Basiert auf https://github.com/EmergenceAI/Emergence-World
(Lizenz: CC-BY-NC-4.0, Research-only)
2026-06-15 01:07:38 +02:00