Compare commits
9 Commits
fix/test-l
...
claude/iss
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13212b92b5 | ||
| 9e8e0f8552 | |||
| e09082a8a8 | |||
| 3349948f7f | |||
| c3f1598c78 | |||
| 298b585689 | |||
| 92dfddfa90 | |||
| 4ec4558a2f | |||
| 4f8df32882 |
201
docs/SOVEREIGNTY_INTEGRATION.md
Normal file
201
docs/SOVEREIGNTY_INTEGRATION.md
Normal file
@@ -0,0 +1,201 @@
|
||||
# Sovereignty Loop — Integration Guide
|
||||
|
||||
How to use the sovereignty subsystem in new code and existing modules.
|
||||
|
||||
> "The measure of progress is not features added. It is model calls eliminated."
|
||||
|
||||
Refs: #953 (The Sovereignty Loop)
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
Every model call must follow the sovereignty protocol:
|
||||
**check cache → miss → infer → crystallize → return**
|
||||
|
||||
### Perception Layer (VLM calls)
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_perceive
|
||||
from timmy.sovereignty.perception_cache import PerceptionCache
|
||||
|
||||
cache = PerceptionCache("data/templates.json")
|
||||
|
||||
state = await sovereign_perceive(
|
||||
screenshot=frame,
|
||||
cache=cache,
|
||||
vlm=my_vlm_client,
|
||||
session_id="session_001",
|
||||
)
|
||||
```
|
||||
|
||||
### Decision Layer (LLM calls)
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_decide
|
||||
|
||||
result = await sovereign_decide(
|
||||
context={"health": 25, "enemy_count": 3},
|
||||
llm=my_llm_client,
|
||||
session_id="session_001",
|
||||
)
|
||||
# result["action"] could be "heal" from a cached rule or fresh LLM reasoning
|
||||
```
|
||||
|
||||
### Narration Layer
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_narrate
|
||||
|
||||
text = await sovereign_narrate(
|
||||
event={"type": "combat_start", "enemy": "Cliff Racer"},
|
||||
llm=my_llm_client, # optional — None for template-only
|
||||
session_id="session_001",
|
||||
)
|
||||
```
|
||||
|
||||
### General Purpose (Decorator)
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.sovereignty_loop import sovereignty_enforced
|
||||
|
||||
@sovereignty_enforced(
|
||||
layer="decision",
|
||||
cache_check=lambda a, kw: rule_store.find_matching(kw.get("ctx")),
|
||||
crystallize=lambda result, a, kw: rule_store.add(extract_rules(result)),
|
||||
)
|
||||
async def my_expensive_function(ctx):
|
||||
return await llm.reason(ctx)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Auto-Crystallizer
|
||||
|
||||
Automatically extracts rules from LLM reasoning chains:
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning, get_rule_store
|
||||
|
||||
# After any LLM call with reasoning output:
|
||||
rules = crystallize_reasoning(
|
||||
llm_response="I chose heal because health was below 30%.",
|
||||
context={"game": "morrowind"},
|
||||
)
|
||||
|
||||
store = get_rule_store()
|
||||
added = store.add_many(rules)
|
||||
```
|
||||
|
||||
### Rule Lifecycle
|
||||
|
||||
1. **Extracted** — confidence 0.5, not yet reliable
|
||||
2. **Applied** — confidence increases (+0.05 per success, -0.10 per failure)
|
||||
3. **Reliable** — confidence ≥ 0.8 + ≥3 applications + ≥60% success rate
|
||||
4. **Autonomous** — reliably bypasses LLM calls
|
||||
|
||||
---
|
||||
|
||||
## Three-Strike Detector
|
||||
|
||||
Enforces automation for repetitive manual work:
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.three_strike import get_detector, ThreeStrikeError
|
||||
|
||||
detector = get_detector()
|
||||
|
||||
try:
|
||||
detector.record("vlm_prompt_edit", "health_bar_template")
|
||||
except ThreeStrikeError:
|
||||
# Must register an automation before continuing
|
||||
detector.register_automation(
|
||||
"vlm_prompt_edit",
|
||||
"health_bar_template",
|
||||
"scripts/auto_health_bar.py",
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Falsework Checklist
|
||||
|
||||
Before any cloud API call, complete the checklist:
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.three_strike import FalseworkChecklist, falsework_check
|
||||
|
||||
checklist = FalseworkChecklist(
|
||||
durable_artifact="embedding vectors for UI element foo",
|
||||
artifact_storage_path="data/vlm/foo_embeddings.json",
|
||||
local_rule_or_cache="vlm_cache",
|
||||
will_repeat=False,
|
||||
sovereignty_delta="eliminates repeated VLM call",
|
||||
)
|
||||
falsework_check(checklist) # raises ValueError if incomplete
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Graduation Test
|
||||
|
||||
Run the five-condition test to evaluate sovereignty readiness:
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.graduation import run_graduation_test
|
||||
|
||||
report = run_graduation_test(
|
||||
sats_earned=100.0,
|
||||
sats_spent=50.0,
|
||||
uptime_hours=24.0,
|
||||
human_interventions=0,
|
||||
)
|
||||
print(report.to_markdown())
|
||||
```
|
||||
|
||||
API endpoint: `GET /sovereignty/graduation/test`
|
||||
|
||||
---
|
||||
|
||||
## Metrics
|
||||
|
||||
Record sovereignty events throughout the codebase:
|
||||
|
||||
```python
|
||||
from timmy.sovereignty.metrics import emit_sovereignty_event
|
||||
|
||||
# Perception hits
|
||||
await emit_sovereignty_event("perception_cache_hit", session_id="s1")
|
||||
await emit_sovereignty_event("perception_vlm_call", session_id="s1")
|
||||
|
||||
# Decision hits
|
||||
await emit_sovereignty_event("decision_rule_hit", session_id="s1")
|
||||
await emit_sovereignty_event("decision_llm_call", session_id="s1")
|
||||
|
||||
# Narration hits
|
||||
await emit_sovereignty_event("narration_template", session_id="s1")
|
||||
await emit_sovereignty_event("narration_llm", session_id="s1")
|
||||
|
||||
# Crystallization
|
||||
await emit_sovereignty_event("skill_crystallized", metadata={"layer": "perception"})
|
||||
```
|
||||
|
||||
Dashboard WebSocket: `ws://localhost:8000/ws/sovereignty`
|
||||
|
||||
---
|
||||
|
||||
## Module Map
|
||||
|
||||
| Module | Purpose | Issue |
|
||||
|--------|---------|-------|
|
||||
| `timmy.sovereignty.metrics` | SQLite event store + sovereignty % | #954 |
|
||||
| `timmy.sovereignty.perception_cache` | OpenCV template matching | #955 |
|
||||
| `timmy.sovereignty.auto_crystallizer` | LLM reasoning → local rules | #961 |
|
||||
| `timmy.sovereignty.sovereignty_loop` | Core orchestration wrappers | #953 |
|
||||
| `timmy.sovereignty.graduation` | Five-condition graduation test | #953 |
|
||||
| `timmy.sovereignty.session_report` | Markdown scorecard + Gitea commit | #957 |
|
||||
| `timmy.sovereignty.three_strike` | Automation enforcement | #962 |
|
||||
| `infrastructure.sovereignty_metrics` | Research sovereignty tracking | #981 |
|
||||
| `dashboard.routes.sovereignty_metrics` | HTMX + API endpoints | #960 |
|
||||
| `dashboard.routes.sovereignty_ws` | WebSocket real-time stream | #960 |
|
||||
| `dashboard.routes.graduation` | Graduation test API | #953 |
|
||||
35
memory/research/task.md
Normal file
35
memory/research/task.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Research Report: Task #1341
|
||||
|
||||
**Date:** 2026-03-23
|
||||
**Issue:** [#1341](http://143.198.27.163:3000/Rockachopa/Timmy-time-dashboard/issues/1341)
|
||||
**Priority:** normal
|
||||
**Delegated by:** Timmy via Kimi delegation pipeline
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
This issue was submitted as a placeholder via the Kimi delegation pipeline with unfilled template fields:
|
||||
|
||||
- **Research Question:** `Q?` (template default — no actual question provided)
|
||||
- **Background / Context:** `ctx` (template default — no context provided)
|
||||
- **Task:** `Task` (template default — no task specified)
|
||||
|
||||
## Findings
|
||||
|
||||
No actionable research question was specified. The issue appears to be a test or
|
||||
accidental submission of an unfilled delegation template.
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. **Re-open with a real question** if there is a specific topic to research.
|
||||
2. **Review the delegation pipeline** to add validation that prevents empty/template-default
|
||||
submissions from reaching the backlog (e.g. reject issues where the body contains
|
||||
literal placeholder strings like `Q?` or `ctx`).
|
||||
3. **Add a pipeline guard** in the Kimi delegation script to require non-empty, non-default
|
||||
values for `Research Question` and `Background / Context` before creating an issue.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [ ] Add input validation to Kimi delegation pipeline
|
||||
- [ ] Re-file with a concrete research question if needed
|
||||
@@ -571,6 +571,11 @@ class Settings(BaseSettings):
|
||||
content_meilisearch_url: str = "http://localhost:7700"
|
||||
content_meilisearch_api_key: str = ""
|
||||
|
||||
# ── SEO / Public Site ──────────────────────────────────────────────────
|
||||
# Canonical base URL used in sitemap.xml, canonical link tags, and OG tags.
|
||||
# Override with SITE_URL env var, e.g. "https://alexanderwhitestone.com".
|
||||
site_url: str = "https://alexanderwhitestone.com"
|
||||
|
||||
# ── Scripture / Biblical Integration ──────────────────────────────
|
||||
# Enable the biblical text module.
|
||||
scripture_enabled: bool = True
|
||||
|
||||
@@ -49,6 +49,7 @@ from dashboard.routes.monitoring import router as monitoring_router
|
||||
from dashboard.routes.nexus import router as nexus_router
|
||||
from dashboard.routes.quests import router as quests_router
|
||||
from dashboard.routes.scorecards import router as scorecards_router
|
||||
from dashboard.routes.legal import router as legal_router
|
||||
from dashboard.routes.self_correction import router as self_correction_router
|
||||
from dashboard.routes.sovereignty_metrics import router as sovereignty_metrics_router
|
||||
from dashboard.routes.sovereignty_ws import router as sovereignty_ws_router
|
||||
@@ -62,6 +63,7 @@ from dashboard.routes.tools import router as tools_router
|
||||
from dashboard.routes.tower import router as tower_router
|
||||
from dashboard.routes.voice import router as voice_router
|
||||
from dashboard.routes.work_orders import router as work_orders_router
|
||||
from dashboard.routes.seo import router as seo_router
|
||||
from dashboard.routes.world import matrix_router
|
||||
from dashboard.routes.world import router as world_router
|
||||
from timmy.workshop_state import PRESENCE_FILE
|
||||
@@ -663,6 +665,7 @@ if static_dir.exists():
|
||||
from dashboard.templating import templates # noqa: E402
|
||||
|
||||
# Include routers
|
||||
app.include_router(seo_router)
|
||||
app.include_router(health_router)
|
||||
app.include_router(agents_router)
|
||||
app.include_router(voice_router)
|
||||
@@ -700,6 +703,7 @@ app.include_router(sovereignty_metrics_router)
|
||||
app.include_router(sovereignty_ws_router)
|
||||
app.include_router(three_strike_router)
|
||||
app.include_router(self_correction_router)
|
||||
app.include_router(legal_router)
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
@@ -758,7 +762,13 @@ async def swarm_agents_sidebar():
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def root(request: Request):
|
||||
"""Serve the main dashboard page."""
|
||||
"""Serve the public landing page (homepage value proposition)."""
|
||||
return templates.TemplateResponse(request, "landing.html", {})
|
||||
|
||||
|
||||
@app.get("/dashboard", response_class=HTMLResponse)
|
||||
async def dashboard(request: Request):
|
||||
"""Serve the main mission-control dashboard."""
|
||||
return templates.TemplateResponse(request, "index.html", {})
|
||||
|
||||
|
||||
|
||||
58
src/dashboard/routes/graduation.py
Normal file
58
src/dashboard/routes/graduation.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Graduation test dashboard routes.
|
||||
|
||||
Provides API endpoints for running and viewing the five-condition
|
||||
graduation test from the Sovereignty Loop (#953).
|
||||
|
||||
Refs: #953 (Graduation Test)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(prefix="/sovereignty/graduation", tags=["sovereignty"])
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/test")
|
||||
async def run_graduation_test_api(
|
||||
sats_earned: float = 0.0,
|
||||
sats_spent: float = 0.0,
|
||||
uptime_hours: float = 0.0,
|
||||
human_interventions: int = 0,
|
||||
) -> dict[str, Any]:
|
||||
"""Run the full graduation test and return results.
|
||||
|
||||
Query parameters supply the external metrics (Lightning, heartbeat)
|
||||
that aren't tracked in the sovereignty metrics DB.
|
||||
"""
|
||||
from timmy.sovereignty.graduation import run_graduation_test
|
||||
|
||||
report = run_graduation_test(
|
||||
sats_earned=sats_earned,
|
||||
sats_spent=sats_spent,
|
||||
uptime_hours=uptime_hours,
|
||||
human_interventions=human_interventions,
|
||||
)
|
||||
return report.to_dict()
|
||||
|
||||
|
||||
@router.get("/report")
|
||||
async def graduation_report_markdown(
|
||||
sats_earned: float = 0.0,
|
||||
sats_spent: float = 0.0,
|
||||
uptime_hours: float = 0.0,
|
||||
human_interventions: int = 0,
|
||||
) -> dict[str, str]:
|
||||
"""Run graduation test and return a markdown report."""
|
||||
from timmy.sovereignty.graduation import run_graduation_test
|
||||
|
||||
report = run_graduation_test(
|
||||
sats_earned=sats_earned,
|
||||
sats_spent=sats_spent,
|
||||
uptime_hours=uptime_hours,
|
||||
human_interventions=human_interventions,
|
||||
)
|
||||
return {"markdown": report.to_markdown(), "passed": str(report.all_passed)}
|
||||
33
src/dashboard/routes/legal.py
Normal file
33
src/dashboard/routes/legal.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""Legal documentation routes — ToS, Privacy Policy, Risk Disclaimers.
|
||||
|
||||
Part of the Whitestone legal foundation for the Lightning payment-adjacent service.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from dashboard.templating import templates
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/legal", tags=["legal"])
|
||||
|
||||
|
||||
@router.get("/tos", response_class=HTMLResponse)
|
||||
async def terms_of_service(request: Request) -> HTMLResponse:
|
||||
"""Terms of Service page."""
|
||||
return templates.TemplateResponse(request, "legal/tos.html", {})
|
||||
|
||||
|
||||
@router.get("/privacy", response_class=HTMLResponse)
|
||||
async def privacy_policy(request: Request) -> HTMLResponse:
|
||||
"""Privacy Policy page."""
|
||||
return templates.TemplateResponse(request, "legal/privacy.html", {})
|
||||
|
||||
|
||||
@router.get("/risk", response_class=HTMLResponse)
|
||||
async def risk_disclaimers(request: Request) -> HTMLResponse:
|
||||
"""Risk Disclaimers page."""
|
||||
return templates.TemplateResponse(request, "legal/risk.html", {})
|
||||
73
src/dashboard/routes/seo.py
Normal file
73
src/dashboard/routes/seo.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""SEO endpoints: robots.txt, sitemap.xml, and structured-data helpers.
|
||||
|
||||
These endpoints make alexanderwhitestone.com crawlable by search engines.
|
||||
All pages listed in the sitemap are server-rendered HTML (not SPA-only).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import PlainTextResponse, Response
|
||||
|
||||
from config import settings
|
||||
|
||||
router = APIRouter(tags=["seo"])
|
||||
|
||||
# Public-facing pages included in the sitemap.
|
||||
# Format: (path, change_freq, priority)
|
||||
_SITEMAP_PAGES: list[tuple[str, str, str]] = [
|
||||
("/", "daily", "1.0"),
|
||||
("/briefing", "daily", "0.9"),
|
||||
("/tasks", "daily", "0.8"),
|
||||
("/calm", "weekly", "0.7"),
|
||||
("/thinking", "weekly", "0.7"),
|
||||
("/swarm/mission-control", "weekly", "0.7"),
|
||||
("/monitoring", "weekly", "0.6"),
|
||||
("/nexus", "weekly", "0.6"),
|
||||
("/spark/ui", "weekly", "0.6"),
|
||||
("/memory", "weekly", "0.6"),
|
||||
("/marketplace/ui", "weekly", "0.8"),
|
||||
("/models", "weekly", "0.5"),
|
||||
("/tools", "weekly", "0.5"),
|
||||
("/scorecards", "weekly", "0.6"),
|
||||
]
|
||||
|
||||
|
||||
@router.get("/robots.txt", response_class=PlainTextResponse)
|
||||
async def robots_txt() -> str:
|
||||
"""Allow all search engines; point to sitemap."""
|
||||
base = settings.site_url.rstrip("/")
|
||||
return (
|
||||
"User-agent: *\n"
|
||||
"Allow: /\n"
|
||||
"\n"
|
||||
f"Sitemap: {base}/sitemap.xml\n"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/sitemap.xml")
|
||||
async def sitemap_xml() -> Response:
|
||||
"""Generate XML sitemap for all crawlable pages."""
|
||||
base = settings.site_url.rstrip("/")
|
||||
today = date.today().isoformat()
|
||||
|
||||
url_entries: list[str] = []
|
||||
for path, changefreq, priority in _SITEMAP_PAGES:
|
||||
url_entries.append(
|
||||
f" <url>\n"
|
||||
f" <loc>{base}{path}</loc>\n"
|
||||
f" <lastmod>{today}</lastmod>\n"
|
||||
f" <changefreq>{changefreq}</changefreq>\n"
|
||||
f" <priority>{priority}</priority>\n"
|
||||
f" </url>"
|
||||
)
|
||||
|
||||
xml = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
|
||||
+ "\n".join(url_entries)
|
||||
+ "\n</urlset>\n"
|
||||
)
|
||||
return Response(content=xml, media_type="application/xml")
|
||||
@@ -6,7 +6,103 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="theme-color" content="#080412" />
|
||||
<title>{% block title %}Timmy Time — Mission Control{% endblock %}</title>
|
||||
<title>{% block title %}Timmy AI Workshop | Lightning-Powered AI Jobs — Pay Per Task with Bitcoin{% endblock %}</title>
|
||||
|
||||
{# SEO: description #}
|
||||
<meta name="description" content="{% block meta_description %}Run AI jobs in seconds — pay per task in sats over Bitcoin Lightning. No subscription, no waiting, instant results. Timmy AI Workshop powers your workflow.{% endblock %}" />
|
||||
<meta name="robots" content="{% block meta_robots %}index, follow{% endblock %}" />
|
||||
|
||||
{# Canonical URL — override per-page via {% block canonical_url %} #}
|
||||
{% block canonical_url %}
|
||||
<link rel="canonical" href="{{ site_url }}" />
|
||||
{% endblock %}
|
||||
|
||||
{# Open Graph #}
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="Timmy AI Workshop" />
|
||||
<meta property="og:title" content="{% block og_title %}Timmy AI Workshop | Lightning-Powered AI Jobs — Pay Per Task with Bitcoin{% endblock %}" />
|
||||
<meta property="og:description" content="{% block og_description %}Pay-per-task AI jobs over Bitcoin Lightning. No subscriptions — just instant, sovereign AI results priced in sats.{% endblock %}" />
|
||||
<meta property="og:url" content="{% block og_url %}{{ site_url }}{% endblock %}" />
|
||||
<meta property="og:image" content="{% block og_image %}{{ site_url }}/static/og-workshop.png{% endblock %}" />
|
||||
<meta property="og:image:alt" content="Timmy AI Workshop — 3D lightning-powered AI task engine" />
|
||||
|
||||
{# Twitter / X Card #}
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="{% block twitter_title %}Timmy AI Workshop | Lightning-Powered AI Jobs{% endblock %}" />
|
||||
<meta name="twitter:description" content="Pay-per-task AI over Bitcoin Lightning. No subscription — just sats and instant results." />
|
||||
<meta name="twitter:image" content="{% block twitter_image %}{{ site_url }}/static/og-workshop.png{% endblock %}" />
|
||||
|
||||
{# JSON-LD Structured Data #}
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@graph": [
|
||||
{
|
||||
"@type": "SoftwareApplication",
|
||||
"name": "Timmy AI Workshop",
|
||||
"applicationCategory": "BusinessApplication",
|
||||
"operatingSystem": "Web",
|
||||
"url": "{{ site_url }}",
|
||||
"description": "Lightning-powered AI task engine. Pay per task in sats — no subscription required.",
|
||||
"offers": {
|
||||
"@type": "Offer",
|
||||
"price": "0",
|
||||
"priceCurrency": "SAT",
|
||||
"description": "Pay-per-task pricing over Bitcoin Lightning Network"
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Service",
|
||||
"name": "Timmy AI Workshop",
|
||||
"serviceType": "AI Task Automation",
|
||||
"description": "On-demand AI jobs priced in satoshis. Instant results, no subscription.",
|
||||
"provider": {
|
||||
"@type": "Organization",
|
||||
"name": "Alexander Whitestone",
|
||||
"url": "{{ site_url }}"
|
||||
},
|
||||
"paymentAccepted": "Bitcoin Lightning",
|
||||
"url": "{{ site_url }}"
|
||||
},
|
||||
{
|
||||
"@type": "Organization",
|
||||
"name": "Alexander Whitestone",
|
||||
"url": "{{ site_url }}",
|
||||
"description": "Sovereign AI infrastructure powered by Bitcoin Lightning."
|
||||
},
|
||||
{
|
||||
"@type": "FAQPage",
|
||||
"mainEntity": [
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "How do I pay for AI tasks?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "Tasks are priced in satoshis (sats) and settled instantly over the Bitcoin Lightning Network. No credit card or subscription required."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "Is there a subscription fee?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "No. Timmy AI Workshop is strictly pay-per-task — you only pay for what you use, in sats."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "How fast are results?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "AI jobs run on local sovereign infrastructure and return results in seconds, with no cloud round-trips."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
</script>
|
||||
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin />
|
||||
@@ -31,7 +127,7 @@
|
||||
<body>
|
||||
<header class="mc-header">
|
||||
<div class="mc-header-left">
|
||||
<a href="/" class="mc-title">MISSION CONTROL</a>
|
||||
<a href="/dashboard" class="mc-title">MISSION CONTROL</a>
|
||||
<span class="mc-subtitle">MISSION CONTROL</span>
|
||||
<span class="mc-conn-status" id="conn-status">
|
||||
<span class="mc-conn-dot amber" id="conn-dot"></span>
|
||||
@@ -42,6 +138,7 @@
|
||||
<!-- Desktop nav — grouped dropdowns matching mobile sections -->
|
||||
<div class="mc-header-right mc-desktop-nav">
|
||||
<a href="/" class="mc-test-link">HOME</a>
|
||||
<a href="/dashboard" class="mc-test-link">DASHBOARD</a>
|
||||
<div class="mc-nav-dropdown">
|
||||
<button class="mc-test-link mc-dropdown-toggle" aria-expanded="false">CORE ▾</button>
|
||||
<div class="mc-dropdown-menu">
|
||||
@@ -94,6 +191,10 @@
|
||||
<a href="/voice/settings" class="mc-test-link">VOICE SETTINGS</a>
|
||||
<a href="/mobile" class="mc-test-link" title="Mobile-optimized view">MOBILE</a>
|
||||
<a href="/mobile/local" class="mc-test-link" title="Local AI on iPhone">LOCAL AI</a>
|
||||
<div class="mc-dropdown-divider"></div>
|
||||
<a href="/legal/tos" class="mc-test-link">TERMS</a>
|
||||
<a href="/legal/privacy" class="mc-test-link">PRIVACY</a>
|
||||
<a href="/legal/risk" class="mc-test-link">RISK</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mc-nav-dropdown" id="notif-dropdown">
|
||||
@@ -121,6 +222,7 @@
|
||||
<span class="mc-time" id="clock-mobile"></span>
|
||||
</div>
|
||||
<a href="/" class="mc-mobile-link">HOME</a>
|
||||
<a href="/dashboard" class="mc-mobile-link">DASHBOARD</a>
|
||||
<div class="mc-mobile-section-label">CORE</div>
|
||||
<a href="/calm" class="mc-mobile-link">CALM</a>
|
||||
<a href="/tasks" class="mc-mobile-link">TASKS</a>
|
||||
@@ -153,6 +255,10 @@
|
||||
<a href="/voice/settings" class="mc-mobile-link">VOICE SETTINGS</a>
|
||||
<a href="/mobile" class="mc-mobile-link">MOBILE</a>
|
||||
<a href="/mobile/local" class="mc-mobile-link">LOCAL AI</a>
|
||||
<div class="mc-mobile-section-label">LEGAL</div>
|
||||
<a href="/legal/tos" class="mc-mobile-link">TERMS OF SERVICE</a>
|
||||
<a href="/legal/privacy" class="mc-mobile-link">PRIVACY POLICY</a>
|
||||
<a href="/legal/risk" class="mc-mobile-link">RISK DISCLAIMERS</a>
|
||||
<div class="mc-mobile-menu-footer">
|
||||
<button id="enable-notifications-mobile" class="mc-mobile-link mc-mobile-notif-btn">🔔 NOTIFICATIONS</button>
|
||||
</div>
|
||||
@@ -168,6 +274,14 @@
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer class="mc-footer">
|
||||
<a href="/legal/tos" class="mc-footer-link">Terms</a>
|
||||
<span class="mc-footer-sep">·</span>
|
||||
<a href="/legal/privacy" class="mc-footer-link">Privacy</a>
|
||||
<span class="mc-footer-sep">·</span>
|
||||
<a href="/legal/risk" class="mc-footer-link">Risk Disclaimers</a>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// ── Magical floating particles ──
|
||||
(function() {
|
||||
@@ -395,7 +509,7 @@
|
||||
if (!dot || !label) return;
|
||||
if (!wsConnected) {
|
||||
dot.className = 'mc-conn-dot red';
|
||||
label.textContent = 'OFFLINE';
|
||||
label.textContent = 'Reconnecting...';
|
||||
} else if (ollamaOk === false) {
|
||||
dot.className = 'mc-conn-dot amber';
|
||||
label.textContent = 'NO LLM';
|
||||
@@ -431,7 +545,12 @@
|
||||
var ws;
|
||||
try {
|
||||
ws = new WebSocket(protocol + '//' + window.location.host + '/swarm/live');
|
||||
} catch(e) { return; }
|
||||
} catch(e) {
|
||||
// WebSocket constructor failed (e.g. invalid environment) — retry
|
||||
setTimeout(connectStatusWs, reconnectDelay);
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
|
||||
return;
|
||||
}
|
||||
|
||||
ws.onopen = function() {
|
||||
wsConnected = true;
|
||||
|
||||
207
src/dashboard/templates/landing.html
Normal file
207
src/dashboard/templates/landing.html
Normal file
@@ -0,0 +1,207 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Timmy AI Workshop | Lightning-Powered AI Jobs — Pay Per Task with Bitcoin{% endblock %}
|
||||
{% block meta_description %}Pay sats, get AI work done. No subscription. No signup. Instant global access. Timmy AI Workshop — Lightning-powered agents by Alexander Whitestone.{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="lp-wrap">
|
||||
|
||||
<!-- ══ HERO — 3-second glance ══════════════════════════════════════ -->
|
||||
<section class="lp-hero">
|
||||
<div class="lp-hero-eyebrow">LIGHTNING-POWERED AI WORKSHOP</div>
|
||||
<h1 class="lp-hero-title">Hire Timmy,<br>the AI that takes Bitcoin.</h1>
|
||||
<p class="lp-hero-sub">
|
||||
Pay sats, get AI work done.<br>
|
||||
No subscription. No signup. Instant global access.
|
||||
</p>
|
||||
<div class="lp-hero-cta-row">
|
||||
<a href="/dashboard" class="lp-btn lp-btn-primary">TRY NOW →</a>
|
||||
<a href="/docs/api" class="lp-btn lp-btn-secondary">API DOCS</a>
|
||||
<a href="/lightning/ledger" class="lp-btn lp-btn-ghost">VIEW LEDGER</a>
|
||||
</div>
|
||||
<div class="lp-hero-badge">
|
||||
<span class="lp-badge-dot"></span>
|
||||
AI tasks from <strong>200 sats</strong> — no account, no waiting
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══ VALUE PROP — 10-second scan ═════════════════════════════════ -->
|
||||
<section class="lp-section lp-value">
|
||||
<div class="lp-value-grid">
|
||||
<div class="lp-value-card">
|
||||
<span class="lp-value-icon">⚡</span>
|
||||
<h3>Instant Settlement</h3>
|
||||
<p>Jobs complete in seconds. Pay over Bitcoin Lightning — no credit card, no banking required.</p>
|
||||
</div>
|
||||
<div class="lp-value-card">
|
||||
<span class="lp-value-icon">🔒</span>
|
||||
<h3>Sovereign & Private</h3>
|
||||
<p>All inference runs locally. No cloud round-trips. Your prompts never leave the workshop.</p>
|
||||
</div>
|
||||
<div class="lp-value-card">
|
||||
<span class="lp-value-icon">🌐</span>
|
||||
<h3>Global Access</h3>
|
||||
<p>Anyone with a Lightning wallet can hire Timmy. No KYC. No geo-blocks. Pure open access.</p>
|
||||
</div>
|
||||
<div class="lp-value-card">
|
||||
<span class="lp-value-icon">💰</span>
|
||||
<h3>Pay Per Task</h3>
|
||||
<p>Zero subscription. Pay only for what you use, priced in sats. Start from 200 sats per job.</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══ CAPABILITIES — 30-second exploration ════════════════════════ -->
|
||||
<section class="lp-section lp-caps">
|
||||
<h2 class="lp-section-title">What Timmy Can Do</h2>
|
||||
<p class="lp-section-sub">Four core capability domains — each backed by sovereign local inference.</p>
|
||||
|
||||
<div class="lp-caps-list">
|
||||
|
||||
<details class="lp-cap-item" open>
|
||||
<summary class="lp-cap-summary">
|
||||
<span class="lp-cap-icon">💻</span>
|
||||
<span class="lp-cap-label">Code</span>
|
||||
<span class="lp-cap-chevron">▾</span>
|
||||
</summary>
|
||||
<div class="lp-cap-body">
|
||||
<p>Generate, review, refactor, and debug code across any language. Timmy can write tests, explain legacy systems, and auto-fix issues through self-correction loops.</p>
|
||||
<ul class="lp-cap-bullets">
|
||||
<li>Code generation & refactoring</li>
|
||||
<li>Automated test writing</li>
|
||||
<li>Bug diagnosis & self-correction</li>
|
||||
<li>Architecture review & documentation</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="lp-cap-item">
|
||||
<summary class="lp-cap-summary">
|
||||
<span class="lp-cap-icon">🔍</span>
|
||||
<span class="lp-cap-label">Research</span>
|
||||
<span class="lp-cap-chevron">▾</span>
|
||||
</summary>
|
||||
<div class="lp-cap-body">
|
||||
<p>Deep-dive research on any topic. Synthesise sources, extract key insights, produce structured reports — all without leaving the workshop.</p>
|
||||
<ul class="lp-cap-bullets">
|
||||
<li>Topic deep-dives & literature synthesis</li>
|
||||
<li>Competitive & market intelligence</li>
|
||||
<li>Structured report generation</li>
|
||||
<li>Source extraction & citation</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="lp-cap-item">
|
||||
<summary class="lp-cap-summary">
|
||||
<span class="lp-cap-icon">✍</span>
|
||||
<span class="lp-cap-label">Creative</span>
|
||||
<span class="lp-cap-chevron">▾</span>
|
||||
</summary>
|
||||
<div class="lp-cap-body">
|
||||
<p>Copywriting, ideation, storytelling, brand voice — Timmy brings creative horsepower on demand, priced to the job.</p>
|
||||
<ul class="lp-cap-bullets">
|
||||
<li>Marketing copy & brand messaging</li>
|
||||
<li>Long-form content & articles</li>
|
||||
<li>Naming, taglines & ideation</li>
|
||||
<li>Script & narrative writing</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="lp-cap-item">
|
||||
<summary class="lp-cap-summary">
|
||||
<span class="lp-cap-icon">📊</span>
|
||||
<span class="lp-cap-label">Analysis</span>
|
||||
<span class="lp-cap-chevron">▾</span>
|
||||
</summary>
|
||||
<div class="lp-cap-body">
|
||||
<p>Data interpretation, strategic analysis, financial modelling, and executive briefings — structured intelligence from raw inputs.</p>
|
||||
<ul class="lp-cap-bullets">
|
||||
<li>Data interpretation & visualisation briefs</li>
|
||||
<li>Strategic frameworks & SWOT</li>
|
||||
<li>Financial modelling support</li>
|
||||
<li>Executive summaries & board decks</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══ SOCIAL PROOF ═════════════════════════════════════════════════ -->
|
||||
<section class="lp-section lp-stats">
|
||||
<h2 class="lp-section-title">Built on Sovereign Infrastructure</h2>
|
||||
<div class="lp-stats-grid">
|
||||
<div class="lp-stat-card"
|
||||
hx-get="/api/stats/jobs_completed"
|
||||
hx-trigger="load"
|
||||
hx-swap="innerHTML">
|
||||
<div class="lp-stat-num">—</div>
|
||||
<div class="lp-stat-label">JOBS COMPLETED</div>
|
||||
</div>
|
||||
<div class="lp-stat-card"
|
||||
hx-get="/api/stats/sats_settled"
|
||||
hx-trigger="load"
|
||||
hx-swap="innerHTML">
|
||||
<div class="lp-stat-num">—</div>
|
||||
<div class="lp-stat-label">SATS SETTLED</div>
|
||||
</div>
|
||||
<div class="lp-stat-card"
|
||||
hx-get="/api/stats/agents_live"
|
||||
hx-trigger="load"
|
||||
hx-swap="innerHTML">
|
||||
<div class="lp-stat-num">—</div>
|
||||
<div class="lp-stat-label">AGENTS ONLINE</div>
|
||||
</div>
|
||||
<div class="lp-stat-card"
|
||||
hx-get="/api/stats/uptime"
|
||||
hx-trigger="load"
|
||||
hx-swap="innerHTML">
|
||||
<div class="lp-stat-num">—</div>
|
||||
<div class="lp-stat-label">UPTIME</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══ AUDIENCE CTAs ════════════════════════════════════════════════ -->
|
||||
<section class="lp-section lp-audiences">
|
||||
<h2 class="lp-section-title">Choose Your Path</h2>
|
||||
<div class="lp-audience-grid">
|
||||
|
||||
<div class="lp-audience-card">
|
||||
<div class="lp-audience-icon">🧑‍💻</div>
|
||||
<h3>Developers</h3>
|
||||
<p>Integrate Timmy into your stack. REST API, WebSocket streams, and Lightning payment hooks — all documented.</p>
|
||||
<a href="/docs/api" class="lp-btn lp-btn-primary lp-btn-sm">API DOCS →</a>
|
||||
</div>
|
||||
|
||||
<div class="lp-audience-card lp-audience-featured">
|
||||
<div class="lp-audience-badge">MOST POPULAR</div>
|
||||
<div class="lp-audience-icon">⚡</div>
|
||||
<h3>Get Work Done</h3>
|
||||
<p>Open the workshop, describe your task, pay in sats. Results in seconds. No account required.</p>
|
||||
<a href="/dashboard" class="lp-btn lp-btn-primary lp-btn-sm">TRY NOW →</a>
|
||||
</div>
|
||||
|
||||
<div class="lp-audience-card">
|
||||
<div class="lp-audience-icon">📈</div>
|
||||
<h3>Investors & Partners</h3>
|
||||
<p>Lightning-native AI marketplace. Sovereign infrastructure, global reach, pay-per-task economics.</p>
|
||||
<a href="/lightning/ledger" class="lp-btn lp-btn-secondary lp-btn-sm">VIEW LEDGER →</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ══ FINAL CTA ════════════════════════════════════════════════════ -->
|
||||
<section class="lp-section lp-final-cta">
|
||||
<h2 class="lp-final-cta-title">Ready to hire Timmy?</h2>
|
||||
<p class="lp-final-cta-sub">
|
||||
Timmy AI Workshop — Lightning-Powered Agents by Alexander Whitestone
|
||||
</p>
|
||||
<a href="/dashboard" class="lp-btn lp-btn-primary lp-btn-lg">ENTER THE WORKSHOP →</a>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
{% endblock %}
|
||||
200
src/dashboard/templates/legal/privacy.html
Normal file
200
src/dashboard/templates/legal/privacy.html
Normal file
@@ -0,0 +1,200 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Privacy Policy — Timmy Time{% endblock %}
|
||||
{% block content %}
|
||||
<div class="legal-page">
|
||||
<div class="legal-header">
|
||||
<div class="legal-breadcrumb"><a href="/" class="mc-test-link">HOME</a> / LEGAL</div>
|
||||
<h1 class="legal-title">// PRIVACY POLICY</h1>
|
||||
<p class="legal-effective">Effective Date: March 2026 · Last Updated: March 2026</p>
|
||||
</div>
|
||||
|
||||
<div class="legal-toc card mc-panel">
|
||||
<div class="card-header mc-panel-header">// TABLE OF CONTENTS</div>
|
||||
<div class="card-body p-3">
|
||||
<ol class="legal-toc-list">
|
||||
<li><a href="#collect" class="mc-test-link">Data We Collect</a></li>
|
||||
<li><a href="#processing" class="mc-test-link">How We Process Your Data</a></li>
|
||||
<li><a href="#retention" class="mc-test-link">Data Retention</a></li>
|
||||
<li><a href="#rights" class="mc-test-link">Your Rights</a></li>
|
||||
<li><a href="#lightning" class="mc-test-link">Lightning Network Data</a></li>
|
||||
<li><a href="#third-party" class="mc-test-link">Third-Party Services</a></li>
|
||||
<li><a href="#security" class="mc-test-link">Security</a></li>
|
||||
<li><a href="#contact" class="mc-test-link">Contact</a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="legal-summary card mc-panel">
|
||||
<div class="card-header mc-panel-header">// PLAIN LANGUAGE SUMMARY</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Timmy Time runs primarily on your local machine. Most data never leaves your device. We collect minimal operational data. AI inference happens locally via Ollama. Lightning payment data is stored locally in a SQLite database. You can delete your data at any time.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="collect">
|
||||
<div class="card-header mc-panel-header">// 1. DATA WE COLLECT</div>
|
||||
<div class="card-body p-3">
|
||||
<h4 class="legal-subhead">1.1 Data You Provide</h4>
|
||||
<ul>
|
||||
<li><strong>Chat messages</strong> — conversations with the AI assistant, stored locally</li>
|
||||
<li><strong>Tasks and work orders</strong> — task descriptions, priorities, and status</li>
|
||||
<li><strong>Voice input</strong> — audio processed locally via browser Web Speech API or local Piper TTS; not transmitted to cloud services</li>
|
||||
<li><strong>Configuration settings</strong> — preferences and integration tokens (stored in local config files)</li>
|
||||
</ul>
|
||||
<h4 class="legal-subhead">1.2 Automatically Collected Data</h4>
|
||||
<ul>
|
||||
<li><strong>System health metrics</strong> — CPU, memory, service status; stored locally</li>
|
||||
<li><strong>Request logs</strong> — HTTP request paths and status codes for debugging; retained locally</li>
|
||||
<li><strong>WebSocket session data</strong> — connection state; held in memory only, not persisted</li>
|
||||
</ul>
|
||||
<h4 class="legal-subhead">1.3 Data We Do NOT Collect</h4>
|
||||
<ul>
|
||||
<li>We do not collect personal identifying information beyond what you explicitly configure</li>
|
||||
<li>We do not use tracking cookies or analytics beacons</li>
|
||||
<li>We do not sell or share your data with advertisers</li>
|
||||
<li>AI inference is local-first — your queries go to Ollama running on your own hardware, not to cloud AI providers (unless you explicitly configure an external API key)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="processing">
|
||||
<div class="card-header mc-panel-header">// 2. HOW WE PROCESS YOUR DATA</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Data processing purposes:</p>
|
||||
<ul>
|
||||
<li><strong>Service operation</strong> — delivering AI responses, managing tasks, executing automations</li>
|
||||
<li><strong>System integrity</strong> — health monitoring, error detection, rate limiting</li>
|
||||
<li><strong>Agent memory</strong> — contextual memory stored locally to improve AI continuity across sessions</li>
|
||||
<li><strong>Notifications</strong> — push notifications via configured integrations (Telegram, Discord) when you opt in</li>
|
||||
</ul>
|
||||
<p>Legal basis for processing: legitimate interest in operating the Service and fulfilling your requests. You control all data by controlling the self-hosted service.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="retention">
|
||||
<div class="card-header mc-panel-header">// 3. DATA RETENTION</div>
|
||||
<div class="card-body p-3">
|
||||
<table class="legal-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Data Type</th>
|
||||
<th>Retention Period</th>
|
||||
<th>Location</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Chat messages</td>
|
||||
<td>Until manually deleted</td>
|
||||
<td>Local SQLite database</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Task records</td>
|
||||
<td>Until manually deleted</td>
|
||||
<td>Local SQLite database</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Lightning payment records</td>
|
||||
<td>Until manually deleted</td>
|
||||
<td>Local SQLite database</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Request logs</td>
|
||||
<td>Rotating 7-day window</td>
|
||||
<td>Local log files</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>WebSocket session state</td>
|
||||
<td>Duration of session only</td>
|
||||
<td>In-memory, never persisted</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Agent memory / semantic index</td>
|
||||
<td>Until manually cleared</td>
|
||||
<td>Local vector store</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>You can delete all local data by removing the application data directory. Since the service is self-hosted, you have full control.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="rights">
|
||||
<div class="card-header mc-panel-header">// 4. YOUR RIGHTS</div>
|
||||
<div class="card-body p-3">
|
||||
<p>As the operator of a self-hosted service, you have complete rights over your data:</p>
|
||||
<ul>
|
||||
<li><strong>Access</strong> — all data is stored locally in SQLite; you can inspect it directly</li>
|
||||
<li><strong>Deletion</strong> — delete records via the dashboard UI or directly from the database</li>
|
||||
<li><strong>Export</strong> — data is in standard SQLite format; export tools are available via the DB Explorer</li>
|
||||
<li><strong>Correction</strong> — edit any stored record directly</li>
|
||||
<li><strong>Portability</strong> — your data is local; move it with you by copying the database files</li>
|
||||
</ul>
|
||||
<p>If you use cloud-connected features (external API keys, Telegram/Discord bots), those third-party services have their own privacy policies which apply separately.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="lightning">
|
||||
<div class="card-header mc-panel-header">// 5. LIGHTNING NETWORK DATA</div>
|
||||
<div class="card-body p-3">
|
||||
<div class="legal-warning">
|
||||
<strong>⚡ LIGHTNING PRIVACY CONSIDERATIONS</strong><br>
|
||||
Bitcoin Lightning Network transactions have limited on-chain privacy. Payment hashes, channel identifiers, and routing information may be visible to channel peers and routing nodes.
|
||||
</div>
|
||||
<p>Lightning-specific data handling:</p>
|
||||
<ul>
|
||||
<li><strong>Payment records</strong> — invoices, payment hashes, and amounts stored locally in SQLite</li>
|
||||
<li><strong>Node identity</strong> — your Lightning node public key is visible to channel peers by design</li>
|
||||
<li><strong>Channel data</strong> — channel opens and closes are recorded on the Bitcoin blockchain (public)</li>
|
||||
<li><strong>Routing information</strong> — intermediate routing nodes can see payment amounts and timing (not destination)</li>
|
||||
</ul>
|
||||
<p>We do not share your Lightning payment data with third parties. Local storage only.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="third-party">
|
||||
<div class="card-header mc-panel-header">// 6. THIRD-PARTY SERVICES</div>
|
||||
<div class="card-body p-3">
|
||||
<p>When you configure optional integrations, data flows to those services under their own privacy policies:</p>
|
||||
<ul>
|
||||
<li><strong>Telegram</strong> — messages sent via Telegram bot are processed by Telegram's servers</li>
|
||||
<li><strong>Discord</strong> — messages sent via Discord bot are processed by Discord's servers</li>
|
||||
<li><strong>Nostr</strong> — Nostr events are broadcast to public relays and are publicly visible by design</li>
|
||||
<li><strong>Ollama</strong> — when using a remote Ollama instance, your prompts are sent to that server</li>
|
||||
<li><strong>Anthropic Claude API</strong> — if configured as LLM fallback, prompts are subject to Anthropic's privacy policy</li>
|
||||
</ul>
|
||||
<p>All third-party integrations are opt-in and require explicit configuration. None are enabled by default.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="security">
|
||||
<div class="card-header mc-panel-header">// 7. SECURITY</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Security measures in place:</p>
|
||||
<ul>
|
||||
<li>CSRF protection on all state-changing requests</li>
|
||||
<li>Rate limiting on API endpoints</li>
|
||||
<li>Security headers (X-Frame-Options, X-Content-Type-Options, CSP)</li>
|
||||
<li>No hardcoded secrets — all credentials via environment variables</li>
|
||||
<li>XSS prevention — DOMPurify on all rendered user content</li>
|
||||
</ul>
|
||||
<p>As a self-hosted service, network security (TLS, firewall) is your responsibility. We strongly recommend running behind a reverse proxy with TLS if the service is accessible beyond localhost.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="contact">
|
||||
<div class="card-header mc-panel-header">// 8. CONTACT</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Privacy questions or data deletion requests: file an issue in the project repository or contact the service operator directly. Since this is self-hosted software, the operator is typically you.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="legal-footer-links">
|
||||
<a href="/legal/tos" class="mc-test-link">Terms of Service</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/legal/risk" class="mc-test-link">Risk Disclaimers</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/" class="mc-test-link">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
137
src/dashboard/templates/legal/risk.html
Normal file
137
src/dashboard/templates/legal/risk.html
Normal file
@@ -0,0 +1,137 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Risk Disclaimers — Timmy Time{% endblock %}
|
||||
{% block content %}
|
||||
<div class="legal-page">
|
||||
<div class="legal-header">
|
||||
<div class="legal-breadcrumb"><a href="/" class="mc-test-link">HOME</a> / LEGAL</div>
|
||||
<h1 class="legal-title">// RISK DISCLAIMERS</h1>
|
||||
<p class="legal-effective">Effective Date: March 2026 · Last Updated: March 2026</p>
|
||||
</div>
|
||||
|
||||
<div class="legal-summary card mc-panel legal-risk-banner">
|
||||
<div class="card-header mc-panel-header">// ⚠ READ BEFORE USING LIGHTNING PAYMENTS</div>
|
||||
<div class="card-body p-3">
|
||||
<p><strong>Timmy Time includes optional Lightning Network payment functionality. This is experimental software. You can lose money. By using payment features, you acknowledge all risks described on this page.</strong></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="volatility">
|
||||
<div class="card-header mc-panel-header">// CRYPTOCURRENCY VOLATILITY RISK</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Bitcoin and satoshis (the units used in Lightning payments) are highly volatile assets:</p>
|
||||
<ul>
|
||||
<li>The value of Bitcoin can decrease by 50% or more in a short period</li>
|
||||
<li>Satoshi amounts in Lightning channels may be worth significantly less in fiat terms by the time you close channels</li>
|
||||
<li>No central bank, government, or institution guarantees the value of Bitcoin</li>
|
||||
<li>Past performance of Bitcoin price is not indicative of future results</li>
|
||||
<li>You may receive no return on any Bitcoin held in payment channels</li>
|
||||
</ul>
|
||||
<p class="legal-callout">Only put into Lightning channels what you can afford to lose entirely.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="experimental">
|
||||
<div class="card-header mc-panel-header">// EXPERIMENTAL TECHNOLOGY RISK</div>
|
||||
<div class="card-body p-3">
|
||||
<p>The Lightning Network and this software are experimental:</p>
|
||||
<ul>
|
||||
<li><strong>Software bugs</strong> — Timmy Time is pre-production software. Bugs may cause unintended payment behavior, data loss, or service interruptions</li>
|
||||
<li><strong>Protocol risk</strong> — Lightning Network protocols are under active development; implementations may have bugs, including security vulnerabilities</li>
|
||||
<li><strong>AI agent actions</strong> — AI agents and automations may take unintended actions. Review all agent-initiated payments before confirming</li>
|
||||
<li><strong>No audit</strong> — this software has not been independently security audited</li>
|
||||
<li><strong>Dependency risk</strong> — third-party libraries, Ollama, and connected services may have their own vulnerabilities</li>
|
||||
</ul>
|
||||
<p class="legal-callout">Treat all payment functionality as beta. Do not use for high-value transactions.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="lightning-specific">
|
||||
<div class="card-header mc-panel-header">// LIGHTNING NETWORK SPECIFIC RISKS</div>
|
||||
<div class="card-body p-3">
|
||||
<h4 class="legal-subhead">Payment Finality</h4>
|
||||
<p>Lightning payments that successfully complete are <strong>irreversible</strong>. There is no chargeback mechanism, no dispute process, and no third party who can reverse a settled payment. Verify all payment details before confirming.</p>
|
||||
|
||||
<h4 class="legal-subhead">Channel Force-Closure Risk</h4>
|
||||
<p>Lightning channels can be force-closed under certain conditions:</p>
|
||||
<ul>
|
||||
<li>If your Lightning node goes offline for an extended period, your counterparty may force-close the channel</li>
|
||||
<li>Force-closure requires an on-chain Bitcoin transaction with associated mining fees</li>
|
||||
<li>Force-closure locks your funds for a time-lock period (typically 144–2016 blocks)</li>
|
||||
<li>During high Bitcoin network congestion, on-chain fees to recover funds may be substantial</li>
|
||||
</ul>
|
||||
|
||||
<h4 class="legal-subhead">Routing Failure Risk</h4>
|
||||
<p>Lightning payments can fail to route:</p>
|
||||
<ul>
|
||||
<li>Insufficient liquidity in the payment path means your payment may fail</li>
|
||||
<li>Failed payments are not charged, but repeated failures indicate a network or balance issue</li>
|
||||
<li>Large payments are harder to route than small ones due to channel capacity constraints</li>
|
||||
</ul>
|
||||
|
||||
<h4 class="legal-subhead">Liquidity Risk</h4>
|
||||
<ul>
|
||||
<li>Inbound and outbound liquidity must be actively managed</li>
|
||||
<li>You cannot receive payments if you have no inbound capacity</li>
|
||||
<li>You cannot send payments if you have no outbound capacity</li>
|
||||
<li>Channel rebalancing has costs (routing fees or on-chain fees)</li>
|
||||
</ul>
|
||||
|
||||
<h4 class="legal-subhead">Watchtower Risk</h4>
|
||||
<p>Without an active watchtower service, you are vulnerable to channel counterparties broadcasting outdated channel states while your node is offline. This could result in loss of funds.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="regulatory">
|
||||
<div class="card-header mc-panel-header">// REGULATORY & LEGAL RISK</div>
|
||||
<div class="card-body p-3">
|
||||
<p>The legal and regulatory status of Lightning Network payments is uncertain:</p>
|
||||
<ul>
|
||||
<li><strong>Money transmission laws</strong> — in some jurisdictions, routing Lightning payments may constitute unlicensed money transmission. Consult a lawyer before running a routing node</li>
|
||||
<li><strong>Tax obligations</strong> — cryptocurrency transactions may be taxable events in your jurisdiction. You are solely responsible for your tax obligations</li>
|
||||
<li><strong>Regulatory change</strong> — cryptocurrency regulations are evolving rapidly. Actions that are legal today may become restricted or prohibited</li>
|
||||
<li><strong>Sanctions</strong> — you are responsible for ensuring your Lightning payments do not violate applicable sanctions laws</li>
|
||||
<li><strong>KYC/AML</strong> — this software does not perform identity verification. You are responsible for your own compliance obligations</li>
|
||||
</ul>
|
||||
<p class="legal-callout">Consult a qualified legal professional before using Lightning payments for commercial purposes.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="no-guarantees">
|
||||
<div class="card-header mc-panel-header">// NO GUARANTEED OUTCOMES</div>
|
||||
<div class="card-body p-3">
|
||||
<p>We make no guarantees about:</p>
|
||||
<ul>
|
||||
<li>The continuous availability of the Service or any connected node</li>
|
||||
<li>The successful routing of any specific payment</li>
|
||||
<li>The recovery of funds from a force-closed channel</li>
|
||||
<li>The accuracy, completeness, or reliability of AI-generated responses</li>
|
||||
<li>The outcome of any automation or agent-initiated action</li>
|
||||
<li>The future value of any Bitcoin or satoshis</li>
|
||||
<li>Compatibility with future versions of the Lightning Network protocol</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="acknowledgment">
|
||||
<div class="card-header mc-panel-header">// RISK ACKNOWLEDGMENT</div>
|
||||
<div class="card-body p-3">
|
||||
<p>By using the Lightning payment features of Timmy Time, you acknowledge that:</p>
|
||||
<ol>
|
||||
<li>You have read and understood all risks described on this page</li>
|
||||
<li>You are using the Service voluntarily and at your own risk</li>
|
||||
<li>You have conducted your own due diligence</li>
|
||||
<li>You will not hold Timmy Time or its operators liable for any losses</li>
|
||||
<li>You will comply with all applicable laws and regulations in your jurisdiction</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="legal-footer-links">
|
||||
<a href="/legal/tos" class="mc-test-link">Terms of Service</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/legal/privacy" class="mc-test-link">Privacy Policy</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/" class="mc-test-link">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
146
src/dashboard/templates/legal/tos.html
Normal file
146
src/dashboard/templates/legal/tos.html
Normal file
@@ -0,0 +1,146 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Terms of Service — Timmy Time{% endblock %}
|
||||
{% block content %}
|
||||
<div class="legal-page">
|
||||
<div class="legal-header">
|
||||
<div class="legal-breadcrumb"><a href="/" class="mc-test-link">HOME</a> / LEGAL</div>
|
||||
<h1 class="legal-title">// TERMS OF SERVICE</h1>
|
||||
<p class="legal-effective">Effective Date: March 2026 · Last Updated: March 2026</p>
|
||||
</div>
|
||||
|
||||
<div class="legal-toc card mc-panel">
|
||||
<div class="card-header mc-panel-header">// TABLE OF CONTENTS</div>
|
||||
<div class="card-body p-3">
|
||||
<ol class="legal-toc-list">
|
||||
<li><a href="#service" class="mc-test-link">Service Description</a></li>
|
||||
<li><a href="#eligibility" class="mc-test-link">Eligibility</a></li>
|
||||
<li><a href="#payments" class="mc-test-link">Payment Terms & Lightning Finality</a></li>
|
||||
<li><a href="#liability" class="mc-test-link">Limitation of Liability</a></li>
|
||||
<li><a href="#disputes" class="mc-test-link">Dispute Resolution</a></li>
|
||||
<li><a href="#termination" class="mc-test-link">Termination</a></li>
|
||||
<li><a href="#governing" class="mc-test-link">Governing Law</a></li>
|
||||
<li><a href="#changes" class="mc-test-link">Changes to Terms</a></li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="legal-summary card mc-panel">
|
||||
<div class="card-header mc-panel-header">// PLAIN LANGUAGE SUMMARY</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Timmy Time is an AI assistant and automation dashboard. If you use Lightning Network payments through this service, those payments are <strong>final and cannot be reversed</strong>. We are not a bank, broker, or financial institution. Use this service at your own risk. By using Timmy Time you agree to these terms.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="service">
|
||||
<div class="card-header mc-panel-header">// 1. SERVICE DESCRIPTION</div>
|
||||
<div class="card-body p-3">
|
||||
<p>Timmy Time ("Service," "we," "us") provides an AI-powered personal productivity and automation dashboard. The Service may include:</p>
|
||||
<ul>
|
||||
<li>AI chat and task management tools</li>
|
||||
<li>Agent orchestration and workflow automation</li>
|
||||
<li>Optional Lightning Network payment functionality for in-app micropayments</li>
|
||||
<li>Integration with third-party services (Ollama, Nostr, Telegram, Discord)</li>
|
||||
</ul>
|
||||
<p>The Service is provided on an "as-is" and "as-available" basis. Features are experimental and subject to change without notice.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="eligibility">
|
||||
<div class="card-header mc-panel-header">// 2. ELIGIBILITY</div>
|
||||
<div class="card-body p-3">
|
||||
<p>You must be at least 18 years of age to use this Service. By using the Service, you represent and warrant that:</p>
|
||||
<ul>
|
||||
<li>You are of legal age in your jurisdiction to enter into binding contracts</li>
|
||||
<li>Your use of the Service does not violate any applicable law or regulation in your jurisdiction</li>
|
||||
<li>You are not located in a jurisdiction where cryptocurrency or Lightning Network payments are prohibited</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="payments">
|
||||
<div class="card-header mc-panel-header">// 3. PAYMENT TERMS & LIGHTNING FINALITY</div>
|
||||
<div class="card-body p-3">
|
||||
<div class="legal-warning">
|
||||
<strong>⚡ IMPORTANT — LIGHTNING PAYMENT FINALITY</strong><br>
|
||||
Lightning Network payments are final and irreversible by design. Once a Lightning payment is sent and settled, it <strong>cannot be reversed, recalled, or charged back</strong>. There are no refunds on settled Lightning payments except at our sole discretion.
|
||||
</div>
|
||||
<h4 class="legal-subhead">3.1 Payment Processing</h4>
|
||||
<p>All payments processed through this Service use the Bitcoin Lightning Network. You are solely responsible for:</p>
|
||||
<ul>
|
||||
<li>Verifying payment amounts before confirming</li>
|
||||
<li>Ensuring you have sufficient Lightning channel capacity</li>
|
||||
<li>Understanding that routing fees may apply</li>
|
||||
</ul>
|
||||
<h4 class="legal-subhead">3.2 No Chargebacks</h4>
|
||||
<p>Unlike credit card payments, Lightning Network payments do not support chargebacks. By initiating a Lightning payment, you acknowledge and accept the irreversibility of that payment.</p>
|
||||
<h4 class="legal-subhead">3.3 Regulatory Uncertainty</h4>
|
||||
<p>The regulatory status of Lightning Network payments varies by jurisdiction and is subject to ongoing change. You are responsible for determining whether your use of Lightning payments complies with applicable laws in your jurisdiction. We are not a licensed money transmitter, exchange, or financial services provider.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="liability">
|
||||
<div class="card-header mc-panel-header">// 4. LIMITATION OF LIABILITY</div>
|
||||
<div class="card-body p-3">
|
||||
<div class="legal-warning">
|
||||
<strong>DISCLAIMER OF WARRANTIES</strong><br>
|
||||
THE SERVICE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. WE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
|
||||
</div>
|
||||
<p>TO THE MAXIMUM EXTENT PERMITTED BY LAW:</p>
|
||||
<ul>
|
||||
<li>We are not liable for any lost profits, lost data, or indirect, incidental, special, consequential, or punitive damages</li>
|
||||
<li>Our total aggregate liability shall not exceed the greater of $50 USD or amounts paid by you in the preceding 30 days</li>
|
||||
<li>We are not liable for losses arising from Lightning channel force-closures, routing failures, or Bitcoin network congestion</li>
|
||||
<li>We are not liable for actions taken by AI agents or automation workflows</li>
|
||||
<li>We are not liable for losses from market volatility or cryptocurrency price changes</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="disputes">
|
||||
<div class="card-header mc-panel-header">// 5. DISPUTE RESOLUTION</div>
|
||||
<div class="card-body p-3">
|
||||
<h4 class="legal-subhead">5.1 Informal Resolution</h4>
|
||||
<p>Before initiating formal proceedings, please contact us to attempt informal resolution. Most disputes can be resolved quickly through direct communication.</p>
|
||||
<h4 class="legal-subhead">5.2 Binding Arbitration</h4>
|
||||
<p>Any dispute not resolved informally within 30 days shall be resolved by binding arbitration under the rules of the American Arbitration Association (AAA). Arbitration shall be conducted on an individual basis — no class actions.</p>
|
||||
<h4 class="legal-subhead">5.3 Exceptions</h4>
|
||||
<p>Either party may seek injunctive relief in a court of competent jurisdiction to prevent irreparable harm pending arbitration.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="termination">
|
||||
<div class="card-header mc-panel-header">// 6. TERMINATION</div>
|
||||
<div class="card-body p-3">
|
||||
<p>We reserve the right to suspend or terminate your access to the Service at any time, with or without cause, with or without notice. You may stop using the Service at any time.</p>
|
||||
<p>Upon termination:</p>
|
||||
<ul>
|
||||
<li>Your right to access the Service immediately ceases</li>
|
||||
<li>Sections on Limitation of Liability, Dispute Resolution, and Governing Law survive termination</li>
|
||||
<li>We are not liable for any Lightning funds in-flight at the time of termination; ensure channels are settled before discontinuing use</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="governing">
|
||||
<div class="card-header mc-panel-header">// 7. GOVERNING LAW</div>
|
||||
<div class="card-body p-3">
|
||||
<p>These Terms are governed by the laws of the applicable jurisdiction without regard to conflict-of-law principles. You consent to the personal jurisdiction of courts located in that jurisdiction for any matters not subject to arbitration.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mc-panel" id="changes">
|
||||
<div class="card-header mc-panel-header">// 8. CHANGES TO TERMS</div>
|
||||
<div class="card-body p-3">
|
||||
<p>We may modify these Terms at any time by posting updated terms on this page. Material changes will be communicated via the dashboard notification system. Continued use of the Service after changes take effect constitutes acceptance of the revised Terms.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="legal-footer-links">
|
||||
<a href="/legal/privacy" class="mc-test-link">Privacy Policy</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/legal/risk" class="mc-test-link">Risk Disclaimers</a>
|
||||
<span class="legal-sep">·</span>
|
||||
<a href="/" class="mc-test-link">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -4,4 +4,9 @@ from pathlib import Path
|
||||
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
from config import settings
|
||||
|
||||
templates = Jinja2Templates(directory=str(Path(__file__).parent / "templates"))
|
||||
|
||||
# Inject site_url into every template so SEO tags and canonical URLs work.
|
||||
templates.env.globals["site_url"] = settings.site_url
|
||||
|
||||
@@ -9,7 +9,7 @@ import re
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from timmy.memory.crud import recall_last_reflection, recall_personal_facts
|
||||
from timmy.memory.crud import recall_last_activity_time, recall_last_reflection, recall_personal_facts
|
||||
from timmy.memory.db import HOT_MEMORY_PATH, VAULT_PATH
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -89,25 +89,41 @@ class HotMemory:
|
||||
"""Read hot memory — computed view of top facts + last reflection from DB."""
|
||||
try:
|
||||
facts = recall_personal_facts()
|
||||
lines = ["# Timmy Hot Memory\n"]
|
||||
|
||||
if facts:
|
||||
lines.append("## Known Facts\n")
|
||||
for f in facts[:15]:
|
||||
lines.append(f"- {f}")
|
||||
|
||||
# Include the last reflection if available
|
||||
reflection = recall_last_reflection()
|
||||
if reflection:
|
||||
lines.append("\n## Last Reflection\n")
|
||||
lines.append(reflection)
|
||||
|
||||
if len(lines) > 1:
|
||||
if facts or reflection:
|
||||
last_ts = recall_last_activity_time()
|
||||
try:
|
||||
updated_date = datetime.fromisoformat(last_ts).strftime("%Y-%m-%d %H:%M UTC")
|
||||
except (TypeError, ValueError):
|
||||
updated_date = datetime.now(UTC).strftime("%Y-%m-%d %H:%M UTC")
|
||||
|
||||
lines = [
|
||||
"# Timmy Hot Memory",
|
||||
"",
|
||||
"> Working RAM — always loaded, ~300 lines max, pruned monthly",
|
||||
f"> Last updated: {updated_date}",
|
||||
"",
|
||||
]
|
||||
|
||||
if facts:
|
||||
lines.append("## Known Facts")
|
||||
lines.append("")
|
||||
for f in facts[:15]:
|
||||
lines.append(f"- {f}")
|
||||
|
||||
if reflection:
|
||||
lines.append("")
|
||||
lines.append("## Last Reflection")
|
||||
lines.append("")
|
||||
lines.append(reflection)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
except Exception:
|
||||
logger.debug("DB context read failed, falling back to file")
|
||||
|
||||
# Fallback to file if DB unavailable
|
||||
# Fallback to file if DB unavailable or empty
|
||||
if self.path.exists():
|
||||
return self.path.read_text()
|
||||
|
||||
|
||||
@@ -393,3 +393,12 @@ def recall_last_reflection() -> str | None:
|
||||
"ORDER BY created_at DESC LIMIT 1"
|
||||
).fetchone()
|
||||
return row["content"] if row else None
|
||||
|
||||
|
||||
def recall_last_activity_time() -> str | None:
|
||||
"""Return the ISO timestamp of the most recently stored memory, or None."""
|
||||
with get_connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT created_at FROM memories ORDER BY created_at DESC LIMIT 1"
|
||||
).fetchone()
|
||||
return row["created_at"] if row else None
|
||||
|
||||
@@ -27,6 +27,7 @@ from timmy.memory.crud import ( # noqa: F401
|
||||
get_memory_context,
|
||||
get_memory_stats,
|
||||
prune_memories,
|
||||
recall_last_activity_time,
|
||||
recall_last_reflection,
|
||||
recall_personal_facts,
|
||||
recall_personal_facts_with_ids,
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
"""Sovereignty metrics for the Bannerlord loop.
|
||||
"""Sovereignty subsystem for the Timmy agent.
|
||||
|
||||
Tracks how much of each AI layer (perception, decision, narration)
|
||||
runs locally vs. calls out to an LLM. Feeds the sovereignty dashboard.
|
||||
Implements the Sovereignty Loop governing architecture (#953):
|
||||
Discover → Crystallize → Replace → Measure → Repeat
|
||||
|
||||
Refs: #954, #953
|
||||
Modules:
|
||||
- metrics: SQLite-backed event store for sovereignty %
|
||||
- perception_cache: OpenCV template matching for VLM replacement
|
||||
- auto_crystallizer: Rule extraction from LLM reasoning chains
|
||||
- sovereignty_loop: Core orchestration (sovereign_perceive/decide/narrate)
|
||||
- graduation: Five-condition graduation test runner
|
||||
- session_report: Markdown scorecard generator + Gitea commit
|
||||
- three_strike: Automation enforcement (3-strike detector)
|
||||
|
||||
Three-strike detector and automation enforcement.
|
||||
|
||||
Refs: #962
|
||||
|
||||
Session reporting: auto-generates markdown scorecards at session end
|
||||
and commits them to the Gitea repo for institutional memory.
|
||||
|
||||
Refs: #957 (Session Sovereignty Report Generator)
|
||||
Refs: #953, #954, #955, #956, #957, #961, #962
|
||||
"""
|
||||
|
||||
from timmy.sovereignty.session_report import (
|
||||
@@ -23,6 +23,7 @@ from timmy.sovereignty.session_report import (
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Session reporting
|
||||
"generate_report",
|
||||
"commit_report",
|
||||
"generate_and_commit_report",
|
||||
|
||||
409
src/timmy/sovereignty/auto_crystallizer.py
Normal file
409
src/timmy/sovereignty/auto_crystallizer.py
Normal file
@@ -0,0 +1,409 @@
|
||||
"""Auto-Crystallizer for Groq/cloud reasoning chains.
|
||||
|
||||
Automatically analyses LLM reasoning output and extracts durable local
|
||||
rules that can preempt future cloud API calls. Each extracted rule is
|
||||
persisted to ``data/strategy.json`` with confidence tracking.
|
||||
|
||||
Workflow:
|
||||
1. LLM returns a reasoning chain (e.g. "I chose heal because HP < 30%")
|
||||
2. ``crystallize_reasoning()`` extracts condition → action rules
|
||||
3. Rules are stored locally with initial confidence 0.5
|
||||
4. Successful rule applications increase confidence; failures decrease it
|
||||
5. Rules with confidence > 0.8 bypass the LLM entirely
|
||||
|
||||
Rule format (JSON)::
|
||||
|
||||
{
|
||||
"id": "rule_abc123",
|
||||
"condition": "health_pct < 30",
|
||||
"action": "heal",
|
||||
"source": "groq_reasoning",
|
||||
"confidence": 0.5,
|
||||
"times_applied": 0,
|
||||
"times_succeeded": 0,
|
||||
"created_at": "2026-03-23T...",
|
||||
"updated_at": "2026-03-23T...",
|
||||
"reasoning_excerpt": "I chose to heal because health was below 30%"
|
||||
}
|
||||
|
||||
Refs: #961, #953 (The Sovereignty Loop — Section III.5)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
STRATEGY_PATH = Path(settings.repo_root) / "data" / "strategy.json"
|
||||
|
||||
#: Minimum confidence for a rule to bypass the LLM.
|
||||
CONFIDENCE_THRESHOLD = 0.8
|
||||
|
||||
#: Minimum successful applications before a rule is considered reliable.
|
||||
MIN_APPLICATIONS = 3
|
||||
|
||||
#: Confidence adjustment on successful application.
|
||||
CONFIDENCE_BOOST = 0.05
|
||||
|
||||
#: Confidence penalty on failed application.
|
||||
CONFIDENCE_PENALTY = 0.10
|
||||
|
||||
# ── Regex patterns for extracting conditions from reasoning ───────────────────
|
||||
|
||||
_CONDITION_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
|
||||
# "because X was below/above/less than/greater than Y"
|
||||
(
|
||||
"threshold",
|
||||
re.compile(
|
||||
r"because\s+(\w[\w\s]*?)\s+(?:was|is|were)\s+"
|
||||
r"(?:below|above|less than|greater than|under|over)\s+"
|
||||
r"(\d+(?:\.\d+)?)\s*%?",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
),
|
||||
# "when X is/was Y" or "if X is/was Y"
|
||||
(
|
||||
"state_check",
|
||||
re.compile(
|
||||
r"(?:when|if|since)\s+(\w[\w\s]*?)\s+(?:is|was|were)\s+"
|
||||
r"(\w[\w\s]*?)(?:\.|,|$)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
),
|
||||
# "X < Y" or "X > Y" or "X <= Y" or "X >= Y"
|
||||
(
|
||||
"comparison",
|
||||
re.compile(
|
||||
r"(\w[\w_.]*)\s*(<=?|>=?|==|!=)\s*(\d+(?:\.\d+)?)",
|
||||
),
|
||||
),
|
||||
# "chose X because Y"
|
||||
(
|
||||
"choice_reason",
|
||||
re.compile(
|
||||
r"(?:chose|selected|picked|decided on)\s+(\w+)\s+because\s+(.+?)(?:\.|$)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
),
|
||||
# "always X when Y" or "never X when Y"
|
||||
(
|
||||
"always_never",
|
||||
re.compile(
|
||||
r"(always|never)\s+(\w+)\s+when\s+(.+?)(?:\.|,|$)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ── Data classes ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rule:
|
||||
"""A crystallised decision rule extracted from LLM reasoning."""
|
||||
|
||||
id: str
|
||||
condition: str
|
||||
action: str
|
||||
source: str = "groq_reasoning"
|
||||
confidence: float = 0.5
|
||||
times_applied: int = 0
|
||||
times_succeeded: int = 0
|
||||
created_at: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
|
||||
updated_at: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
|
||||
reasoning_excerpt: str = ""
|
||||
pattern_type: str = ""
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def success_rate(self) -> float:
|
||||
"""Fraction of successful applications."""
|
||||
if self.times_applied == 0:
|
||||
return 0.0
|
||||
return self.times_succeeded / self.times_applied
|
||||
|
||||
@property
|
||||
def is_reliable(self) -> bool:
|
||||
"""True when the rule is reliable enough to bypass the LLM."""
|
||||
return (
|
||||
self.confidence >= CONFIDENCE_THRESHOLD
|
||||
and self.times_applied >= MIN_APPLICATIONS
|
||||
and self.success_rate >= 0.6
|
||||
)
|
||||
|
||||
|
||||
# ── Rule store ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RuleStore:
|
||||
"""Manages the persistent collection of crystallised rules.
|
||||
|
||||
Rules are stored as a JSON list in ``data/strategy.json``.
|
||||
Thread-safe for read-only; writes should be serialised by the caller.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path | None = None) -> None:
|
||||
self._path = path or STRATEGY_PATH
|
||||
self._rules: dict[str, Rule] = {}
|
||||
self._load()
|
||||
|
||||
# ── persistence ───────────────────────────────────────────────────────
|
||||
|
||||
def _load(self) -> None:
|
||||
"""Load rules from disk."""
|
||||
if not self._path.exists():
|
||||
self._rules = {}
|
||||
return
|
||||
try:
|
||||
with self._path.open() as f:
|
||||
data = json.load(f)
|
||||
self._rules = {}
|
||||
for entry in data:
|
||||
rule = Rule(**{k: v for k, v in entry.items() if k in Rule.__dataclass_fields__})
|
||||
self._rules[rule.id] = rule
|
||||
logger.debug("Loaded %d crystallised rules from %s", len(self._rules), self._path)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to load strategy rules: %s", exc)
|
||||
self._rules = {}
|
||||
|
||||
def persist(self) -> None:
|
||||
"""Write current rules to disk."""
|
||||
try:
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self._path.open("w") as f:
|
||||
json.dump(
|
||||
[asdict(r) for r in self._rules.values()],
|
||||
f,
|
||||
indent=2,
|
||||
default=str,
|
||||
)
|
||||
logger.debug("Persisted %d rules to %s", len(self._rules), self._path)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to persist strategy rules: %s", exc)
|
||||
|
||||
# ── CRUD ──────────────────────────────────────────────────────────────
|
||||
|
||||
def add(self, rule: Rule) -> None:
|
||||
"""Add or update a rule and persist."""
|
||||
self._rules[rule.id] = rule
|
||||
self.persist()
|
||||
|
||||
def add_many(self, rules: list[Rule]) -> int:
|
||||
"""Add multiple rules. Returns count of new rules added."""
|
||||
added = 0
|
||||
for rule in rules:
|
||||
if rule.id not in self._rules:
|
||||
self._rules[rule.id] = rule
|
||||
added += 1
|
||||
else:
|
||||
# Update confidence if existing rule seen again
|
||||
existing = self._rules[rule.id]
|
||||
existing.confidence = min(1.0, existing.confidence + CONFIDENCE_BOOST)
|
||||
existing.updated_at = datetime.now(UTC).isoformat()
|
||||
if rules:
|
||||
self.persist()
|
||||
return added
|
||||
|
||||
def get(self, rule_id: str) -> Rule | None:
|
||||
"""Retrieve a rule by ID."""
|
||||
return self._rules.get(rule_id)
|
||||
|
||||
def find_matching(self, context: dict[str, Any]) -> list[Rule]:
|
||||
"""Find rules whose conditions match the given context.
|
||||
|
||||
A simple keyword match: if the condition string contains keys
|
||||
from the context, and the rule is reliable, it is included.
|
||||
|
||||
This is intentionally simple — a production implementation would
|
||||
use embeddings or structured condition evaluation.
|
||||
"""
|
||||
matching = []
|
||||
context_str = json.dumps(context).lower()
|
||||
for rule in self._rules.values():
|
||||
if not rule.is_reliable:
|
||||
continue
|
||||
# Simple keyword overlap check
|
||||
condition_words = set(rule.condition.lower().split())
|
||||
if any(word in context_str for word in condition_words if len(word) > 2):
|
||||
matching.append(rule)
|
||||
return sorted(matching, key=lambda r: r.confidence, reverse=True)
|
||||
|
||||
def record_application(self, rule_id: str, succeeded: bool) -> None:
|
||||
"""Record a rule application outcome (success or failure)."""
|
||||
rule = self._rules.get(rule_id)
|
||||
if rule is None:
|
||||
return
|
||||
rule.times_applied += 1
|
||||
if succeeded:
|
||||
rule.times_succeeded += 1
|
||||
rule.confidence = min(1.0, rule.confidence + CONFIDENCE_BOOST)
|
||||
else:
|
||||
rule.confidence = max(0.0, rule.confidence - CONFIDENCE_PENALTY)
|
||||
rule.updated_at = datetime.now(UTC).isoformat()
|
||||
self.persist()
|
||||
|
||||
@property
|
||||
def all_rules(self) -> list[Rule]:
|
||||
"""Return all stored rules."""
|
||||
return list(self._rules.values())
|
||||
|
||||
@property
|
||||
def reliable_rules(self) -> list[Rule]:
|
||||
"""Return only reliable rules (above confidence threshold)."""
|
||||
return [r for r in self._rules.values() if r.is_reliable]
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._rules)
|
||||
|
||||
|
||||
# ── Extraction logic ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _make_rule_id(condition: str, action: str) -> str:
|
||||
"""Deterministic rule ID from condition + action."""
|
||||
key = f"{condition.strip().lower()}:{action.strip().lower()}"
|
||||
return f"rule_{hashlib.sha256(key.encode()).hexdigest()[:12]}"
|
||||
|
||||
|
||||
def crystallize_reasoning(
|
||||
llm_response: str,
|
||||
context: dict[str, Any] | None = None,
|
||||
source: str = "groq_reasoning",
|
||||
) -> list[Rule]:
|
||||
"""Extract actionable rules from an LLM reasoning chain.
|
||||
|
||||
Scans the response text for recognisable patterns (threshold checks,
|
||||
state comparisons, explicit choices) and converts them into ``Rule``
|
||||
objects that can replace future LLM calls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
llm_response:
|
||||
The full text of the LLM's reasoning output.
|
||||
context:
|
||||
Optional context dict for metadata enrichment.
|
||||
source:
|
||||
Identifier for the originating model/service.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[Rule]
|
||||
Extracted rules (may be empty if no patterns found).
|
||||
"""
|
||||
rules: list[Rule] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
for pattern_type, pattern in _CONDITION_PATTERNS:
|
||||
for match in pattern.finditer(llm_response):
|
||||
groups = match.groups()
|
||||
|
||||
if pattern_type == "threshold" and len(groups) >= 2:
|
||||
variable = groups[0].strip().replace(" ", "_").lower()
|
||||
threshold = groups[1]
|
||||
# Determine direction from surrounding text
|
||||
action = _extract_nearby_action(llm_response, match.end())
|
||||
if "below" in match.group().lower() or "less" in match.group().lower():
|
||||
condition = f"{variable} < {threshold}"
|
||||
else:
|
||||
condition = f"{variable} > {threshold}"
|
||||
|
||||
elif pattern_type == "comparison" and len(groups) >= 3:
|
||||
variable = groups[0].strip()
|
||||
operator = groups[1]
|
||||
value = groups[2]
|
||||
condition = f"{variable} {operator} {value}"
|
||||
action = _extract_nearby_action(llm_response, match.end())
|
||||
|
||||
elif pattern_type == "choice_reason" and len(groups) >= 2:
|
||||
action = groups[0].strip()
|
||||
condition = groups[1].strip()
|
||||
|
||||
elif pattern_type == "always_never" and len(groups) >= 3:
|
||||
modifier = groups[0].strip().lower()
|
||||
action = groups[1].strip()
|
||||
condition = f"{modifier}: {groups[2].strip()}"
|
||||
|
||||
elif pattern_type == "state_check" and len(groups) >= 2:
|
||||
variable = groups[0].strip().replace(" ", "_").lower()
|
||||
state = groups[1].strip().lower()
|
||||
condition = f"{variable} == {state}"
|
||||
action = _extract_nearby_action(llm_response, match.end())
|
||||
|
||||
else:
|
||||
continue
|
||||
|
||||
if not action:
|
||||
action = "unknown"
|
||||
|
||||
rule_id = _make_rule_id(condition, action)
|
||||
if rule_id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(rule_id)
|
||||
|
||||
# Extract a short excerpt around the match for provenance
|
||||
start = max(0, match.start() - 20)
|
||||
end = min(len(llm_response), match.end() + 50)
|
||||
excerpt = llm_response[start:end].strip()
|
||||
|
||||
rules.append(
|
||||
Rule(
|
||||
id=rule_id,
|
||||
condition=condition,
|
||||
action=action,
|
||||
source=source,
|
||||
pattern_type=pattern_type,
|
||||
reasoning_excerpt=excerpt,
|
||||
metadata=context or {},
|
||||
)
|
||||
)
|
||||
|
||||
if rules:
|
||||
logger.info(
|
||||
"Auto-crystallizer extracted %d rule(s) from %s response",
|
||||
len(rules),
|
||||
source,
|
||||
)
|
||||
|
||||
return rules
|
||||
|
||||
|
||||
def _extract_nearby_action(text: str, position: int) -> str:
|
||||
"""Try to extract an action verb/noun near a match position."""
|
||||
# Look at the next 100 chars for action-like words
|
||||
snippet = text[position : position + 100].strip()
|
||||
action_patterns = [
|
||||
re.compile(r"(?:so|then|thus)\s+(?:I\s+)?(\w+)", re.IGNORECASE),
|
||||
re.compile(r"→\s*(\w+)", re.IGNORECASE),
|
||||
re.compile(r"action:\s*(\w+)", re.IGNORECASE),
|
||||
]
|
||||
for pat in action_patterns:
|
||||
m = pat.search(snippet)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
return ""
|
||||
|
||||
|
||||
# ── Module-level singleton ────────────────────────────────────────────────────
|
||||
|
||||
_store: RuleStore | None = None
|
||||
|
||||
|
||||
def get_rule_store() -> RuleStore:
|
||||
"""Return (or lazily create) the module-level rule store."""
|
||||
global _store
|
||||
if _store is None:
|
||||
_store = RuleStore()
|
||||
return _store
|
||||
341
src/timmy/sovereignty/graduation.py
Normal file
341
src/timmy/sovereignty/graduation.py
Normal file
@@ -0,0 +1,341 @@
|
||||
"""Graduation Test — Falsework Removal Criteria.
|
||||
|
||||
Evaluates whether the agent meets all five graduation conditions
|
||||
simultaneously. All conditions must be met within a single 24-hour
|
||||
period for the system to be considered sovereign.
|
||||
|
||||
Conditions:
|
||||
1. Perception Independence — 1 hour with no VLM calls after minute 15
|
||||
2. Decision Independence — Full session with <5 cloud API calls
|
||||
3. Narration Independence — All narration from local templates + local LLM
|
||||
4. Economic Independence — sats_earned > sats_spent
|
||||
5. Operational Independence — 24 hours unattended, no human intervention
|
||||
|
||||
Each condition returns a :class:`GraduationResult` with pass/fail,
|
||||
the actual measured value, and the target.
|
||||
|
||||
"The arch must hold after the falsework is removed."
|
||||
|
||||
Refs: #953 (The Sovereignty Loop — Graduation Test)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── Data classes ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConditionResult:
|
||||
"""Result of a single graduation condition evaluation."""
|
||||
|
||||
name: str
|
||||
passed: bool
|
||||
actual: float | int
|
||||
target: float | int
|
||||
unit: str = ""
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GraduationReport:
|
||||
"""Full graduation test report."""
|
||||
|
||||
timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
|
||||
all_passed: bool = False
|
||||
conditions: list[ConditionResult] = field(default_factory=list)
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialize to a JSON-safe dict."""
|
||||
return {
|
||||
"timestamp": self.timestamp,
|
||||
"all_passed": self.all_passed,
|
||||
"conditions": [asdict(c) for c in self.conditions],
|
||||
"metadata": self.metadata,
|
||||
}
|
||||
|
||||
def to_markdown(self) -> str:
|
||||
"""Render the report as a markdown string."""
|
||||
status = "PASSED ✓" if self.all_passed else "NOT YET"
|
||||
lines = [
|
||||
"# Graduation Test Report",
|
||||
"",
|
||||
f"**Status:** {status}",
|
||||
f"**Evaluated:** {self.timestamp}",
|
||||
"",
|
||||
"| # | Condition | Target | Actual | Result |",
|
||||
"|---|-----------|--------|--------|--------|",
|
||||
]
|
||||
for i, c in enumerate(self.conditions, 1):
|
||||
result_str = "PASS" if c.passed else "FAIL"
|
||||
actual_str = f"{c.actual}{c.unit}" if c.unit else str(c.actual)
|
||||
target_str = f"{c.target}{c.unit}" if c.unit else str(c.target)
|
||||
lines.append(f"| {i} | {c.name} | {target_str} | {actual_str} | {result_str} |")
|
||||
|
||||
lines.append("")
|
||||
for c in self.conditions:
|
||||
if c.detail:
|
||||
lines.append(f"- **{c.name}**: {c.detail}")
|
||||
|
||||
lines.append("")
|
||||
lines.append('> "The arch must hold after the falsework is removed."')
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ── Evaluation functions ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def evaluate_perception_independence(
|
||||
time_window_seconds: float = 3600.0,
|
||||
warmup_seconds: float = 900.0,
|
||||
) -> ConditionResult:
|
||||
"""Test 1: No VLM calls after the first 15 minutes of a 1-hour window.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
time_window_seconds:
|
||||
Total window to evaluate (default: 1 hour).
|
||||
warmup_seconds:
|
||||
Initial warmup period where VLM calls are expected (default: 15 min).
|
||||
"""
|
||||
from timmy.sovereignty.metrics import get_metrics_store
|
||||
|
||||
store = get_metrics_store()
|
||||
|
||||
# Count VLM calls in the post-warmup period
|
||||
# We query all events in the window, then filter by timestamp
|
||||
try:
|
||||
from contextlib import closing
|
||||
|
||||
from timmy.sovereignty.metrics import _seconds_ago_iso
|
||||
|
||||
cutoff_total = _seconds_ago_iso(time_window_seconds)
|
||||
cutoff_warmup = _seconds_ago_iso(time_window_seconds - warmup_seconds)
|
||||
|
||||
with closing(store._connect()) as conn:
|
||||
vlm_calls_after_warmup = conn.execute(
|
||||
"SELECT COUNT(*) FROM events WHERE event_type = 'perception_vlm_call' "
|
||||
"AND timestamp >= ? AND timestamp < ?",
|
||||
(cutoff_total, cutoff_warmup),
|
||||
).fetchone()[0]
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to evaluate perception independence: %s", exc)
|
||||
vlm_calls_after_warmup = -1
|
||||
|
||||
passed = vlm_calls_after_warmup == 0
|
||||
return ConditionResult(
|
||||
name="Perception Independence",
|
||||
passed=passed,
|
||||
actual=vlm_calls_after_warmup,
|
||||
target=0,
|
||||
unit=" VLM calls",
|
||||
detail=f"VLM calls in last {int((time_window_seconds - warmup_seconds) / 60)} min: {vlm_calls_after_warmup}",
|
||||
)
|
||||
|
||||
|
||||
def evaluate_decision_independence(
|
||||
max_api_calls: int = 5,
|
||||
) -> ConditionResult:
|
||||
"""Test 2: Full session with <5 cloud API calls total.
|
||||
|
||||
Counts ``decision_llm_call`` events in the current session.
|
||||
"""
|
||||
from timmy.sovereignty.metrics import get_metrics_store
|
||||
|
||||
store = get_metrics_store()
|
||||
|
||||
try:
|
||||
from contextlib import closing
|
||||
|
||||
with closing(store._connect()) as conn:
|
||||
# Count LLM calls in the last 24 hours
|
||||
from timmy.sovereignty.metrics import _seconds_ago_iso
|
||||
|
||||
cutoff = _seconds_ago_iso(86400.0)
|
||||
api_calls = conn.execute(
|
||||
"SELECT COUNT(*) FROM events WHERE event_type IN "
|
||||
"('decision_llm_call', 'api_call') AND timestamp >= ?",
|
||||
(cutoff,),
|
||||
).fetchone()[0]
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to evaluate decision independence: %s", exc)
|
||||
api_calls = -1
|
||||
|
||||
passed = 0 <= api_calls < max_api_calls
|
||||
return ConditionResult(
|
||||
name="Decision Independence",
|
||||
passed=passed,
|
||||
actual=api_calls,
|
||||
target=max_api_calls,
|
||||
unit=" calls",
|
||||
detail=f"Cloud API calls in last 24h: {api_calls} (target: <{max_api_calls})",
|
||||
)
|
||||
|
||||
|
||||
def evaluate_narration_independence() -> ConditionResult:
|
||||
"""Test 3: All narration from local templates + local LLM (zero cloud calls).
|
||||
|
||||
Checks that ``narration_llm`` events are zero in the last 24 hours
|
||||
while ``narration_template`` events are non-zero.
|
||||
"""
|
||||
from timmy.sovereignty.metrics import get_metrics_store
|
||||
|
||||
store = get_metrics_store()
|
||||
|
||||
try:
|
||||
from contextlib import closing
|
||||
|
||||
from timmy.sovereignty.metrics import _seconds_ago_iso
|
||||
|
||||
cutoff = _seconds_ago_iso(86400.0)
|
||||
|
||||
with closing(store._connect()) as conn:
|
||||
cloud_narrations = conn.execute(
|
||||
"SELECT COUNT(*) FROM events WHERE event_type = 'narration_llm' AND timestamp >= ?",
|
||||
(cutoff,),
|
||||
).fetchone()[0]
|
||||
local_narrations = conn.execute(
|
||||
"SELECT COUNT(*) FROM events WHERE event_type = 'narration_template' "
|
||||
"AND timestamp >= ?",
|
||||
(cutoff,),
|
||||
).fetchone()[0]
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to evaluate narration independence: %s", exc)
|
||||
cloud_narrations = -1
|
||||
local_narrations = 0
|
||||
|
||||
passed = cloud_narrations == 0 and local_narrations > 0
|
||||
return ConditionResult(
|
||||
name="Narration Independence",
|
||||
passed=passed,
|
||||
actual=cloud_narrations,
|
||||
target=0,
|
||||
unit=" cloud calls",
|
||||
detail=f"Cloud narration calls: {cloud_narrations}, local: {local_narrations}",
|
||||
)
|
||||
|
||||
|
||||
def evaluate_economic_independence(
|
||||
sats_earned: float = 0.0,
|
||||
sats_spent: float = 0.0,
|
||||
) -> ConditionResult:
|
||||
"""Test 4: sats_earned > sats_spent.
|
||||
|
||||
Parameters are passed in because sat tracking may live in a separate
|
||||
ledger (Lightning, #851).
|
||||
"""
|
||||
passed = sats_earned > sats_spent and sats_earned > 0
|
||||
net = sats_earned - sats_spent
|
||||
return ConditionResult(
|
||||
name="Economic Independence",
|
||||
passed=passed,
|
||||
actual=net,
|
||||
target=0,
|
||||
unit=" sats net",
|
||||
detail=f"Earned: {sats_earned} sats, spent: {sats_spent} sats, net: {net}",
|
||||
)
|
||||
|
||||
|
||||
def evaluate_operational_independence(
|
||||
uptime_hours: float = 0.0,
|
||||
target_hours: float = 23.5,
|
||||
human_interventions: int = 0,
|
||||
) -> ConditionResult:
|
||||
"""Test 5: 24 hours unattended, no human intervention.
|
||||
|
||||
Uptime and intervention count are passed in from the heartbeat
|
||||
system (#872).
|
||||
"""
|
||||
passed = uptime_hours >= target_hours and human_interventions == 0
|
||||
return ConditionResult(
|
||||
name="Operational Independence",
|
||||
passed=passed,
|
||||
actual=uptime_hours,
|
||||
target=target_hours,
|
||||
unit=" hours",
|
||||
detail=f"Uptime: {uptime_hours}h (target: {target_hours}h), interventions: {human_interventions}",
|
||||
)
|
||||
|
||||
|
||||
# ── Full graduation test ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def run_graduation_test(
|
||||
sats_earned: float = 0.0,
|
||||
sats_spent: float = 0.0,
|
||||
uptime_hours: float = 0.0,
|
||||
human_interventions: int = 0,
|
||||
) -> GraduationReport:
|
||||
"""Run the full 5-condition graduation test.
|
||||
|
||||
Parameters for economic and operational independence must be supplied
|
||||
by the caller since they depend on external systems (Lightning ledger,
|
||||
heartbeat monitor).
|
||||
|
||||
Returns
|
||||
-------
|
||||
GraduationReport
|
||||
Full report with per-condition results and overall pass/fail.
|
||||
"""
|
||||
conditions = [
|
||||
evaluate_perception_independence(),
|
||||
evaluate_decision_independence(),
|
||||
evaluate_narration_independence(),
|
||||
evaluate_economic_independence(sats_earned, sats_spent),
|
||||
evaluate_operational_independence(uptime_hours, human_interventions=human_interventions),
|
||||
]
|
||||
|
||||
all_passed = all(c.passed for c in conditions)
|
||||
|
||||
report = GraduationReport(
|
||||
all_passed=all_passed,
|
||||
conditions=conditions,
|
||||
metadata={
|
||||
"sats_earned": sats_earned,
|
||||
"sats_spent": sats_spent,
|
||||
"uptime_hours": uptime_hours,
|
||||
"human_interventions": human_interventions,
|
||||
},
|
||||
)
|
||||
|
||||
if all_passed:
|
||||
logger.info("GRADUATION TEST PASSED — all 5 conditions met simultaneously")
|
||||
else:
|
||||
failed = [c.name for c in conditions if not c.passed]
|
||||
logger.info(
|
||||
"Graduation test: %d/5 passed. Failed: %s",
|
||||
len(conditions) - len(failed),
|
||||
", ".join(failed),
|
||||
)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def persist_graduation_report(report: GraduationReport) -> Path:
|
||||
"""Save a graduation report to ``data/graduation_reports/``."""
|
||||
reports_dir = Path(settings.repo_root) / "data" / "graduation_reports"
|
||||
reports_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
|
||||
path = reports_dir / f"graduation_{timestamp}.json"
|
||||
|
||||
try:
|
||||
with path.open("w") as f:
|
||||
json.dump(report.to_dict(), f, indent=2, default=str)
|
||||
logger.info("Graduation report saved to %s", path)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to persist graduation report: %s", exc)
|
||||
|
||||
return path
|
||||
@@ -1,7 +1,21 @@
|
||||
"""OpenCV template-matching cache for sovereignty perception (screen-state recognition)."""
|
||||
"""OpenCV template-matching cache for sovereignty perception.
|
||||
|
||||
Implements "See Once, Template Forever" from the Sovereignty Loop (#953).
|
||||
|
||||
First encounter: VLM analyses screenshot (3-6 sec) → structured JSON.
|
||||
Crystallized as: OpenCV template + bounding box → templates.json (3 ms).
|
||||
|
||||
The ``crystallize_perception()`` function converts VLM output into
|
||||
reusable OpenCV templates, and ``PerceptionCache.match()`` retrieves
|
||||
them without calling the VLM again.
|
||||
|
||||
Refs: #955, #953 (Section III.1 — Perception)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -9,85 +23,266 @@ from typing import Any
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Template:
|
||||
"""A reusable visual template extracted from VLM analysis."""
|
||||
|
||||
name: str
|
||||
image: np.ndarray
|
||||
threshold: float = 0.85
|
||||
bbox: tuple[int, int, int, int] | None = None # (x1, y1, x2, y2)
|
||||
metadata: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class CacheResult:
|
||||
"""Result of a template match against a screenshot."""
|
||||
|
||||
confidence: float
|
||||
state: Any | None
|
||||
|
||||
|
||||
class PerceptionCache:
|
||||
def __init__(self, templates_path: Path | str = "data/templates.json"):
|
||||
"""OpenCV-based visual template cache.
|
||||
|
||||
Stores templates extracted from VLM responses and matches them
|
||||
against future screenshots using template matching, eliminating
|
||||
the need for repeated VLM calls on known visual patterns.
|
||||
"""
|
||||
|
||||
def __init__(self, templates_path: Path | str = "data/templates.json") -> None:
|
||||
self.templates_path = Path(templates_path)
|
||||
self.templates: list[Template] = []
|
||||
self.load()
|
||||
|
||||
def match(self, screenshot: np.ndarray) -> CacheResult:
|
||||
"""
|
||||
Matches templates against the screenshot.
|
||||
Returns the confidence and the name of the best matching template.
|
||||
"""Match stored templates against a screenshot.
|
||||
|
||||
Returns the highest-confidence match. If confidence exceeds
|
||||
the template's threshold, the cached state is returned.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
screenshot:
|
||||
The current frame as a numpy array (BGR or grayscale).
|
||||
|
||||
Returns
|
||||
-------
|
||||
CacheResult
|
||||
Confidence score and cached state (or None if no match).
|
||||
"""
|
||||
best_match_confidence = 0.0
|
||||
best_match_name = None
|
||||
best_match_metadata = None
|
||||
|
||||
for template in self.templates:
|
||||
res = cv2.matchTemplate(screenshot, template.image, cv2.TM_CCOEFF_NORMED)
|
||||
_, max_val, _, _ = cv2.minMaxLoc(res)
|
||||
if max_val > best_match_confidence:
|
||||
best_match_confidence = max_val
|
||||
best_match_name = template.name
|
||||
if template.image.size == 0:
|
||||
continue
|
||||
|
||||
if best_match_confidence > 0.85: # TODO: Make this configurable per template
|
||||
try:
|
||||
# Convert to grayscale if needed for matching
|
||||
if len(screenshot.shape) == 3 and len(template.image.shape) == 2:
|
||||
frame = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
|
||||
elif len(screenshot.shape) == 2 and len(template.image.shape) == 3:
|
||||
frame = screenshot
|
||||
# skip mismatched template
|
||||
continue
|
||||
else:
|
||||
frame = screenshot
|
||||
|
||||
# Ensure template is smaller than frame
|
||||
if (
|
||||
template.image.shape[0] > frame.shape[0]
|
||||
or template.image.shape[1] > frame.shape[1]
|
||||
):
|
||||
continue
|
||||
|
||||
res = cv2.matchTemplate(frame, template.image, cv2.TM_CCOEFF_NORMED)
|
||||
_, max_val, _, _ = cv2.minMaxLoc(res)
|
||||
|
||||
if max_val > best_match_confidence:
|
||||
best_match_confidence = max_val
|
||||
best_match_name = template.name
|
||||
best_match_metadata = template.metadata
|
||||
except cv2.error:
|
||||
logger.debug("Template match failed for '%s'", template.name)
|
||||
continue
|
||||
|
||||
if best_match_confidence >= 0.85 and best_match_name is not None:
|
||||
return CacheResult(
|
||||
confidence=best_match_confidence, state={"template_name": best_match_name}
|
||||
confidence=best_match_confidence,
|
||||
state={"template_name": best_match_name, **(best_match_metadata or {})},
|
||||
)
|
||||
else:
|
||||
return CacheResult(confidence=best_match_confidence, state=None)
|
||||
return CacheResult(confidence=best_match_confidence, state=None)
|
||||
|
||||
def add(self, templates: list[Template]):
|
||||
def add(self, templates: list[Template]) -> None:
|
||||
"""Add new templates to the cache."""
|
||||
self.templates.extend(templates)
|
||||
|
||||
def persist(self):
|
||||
self.templates_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Note: This is a simplified persistence mechanism.
|
||||
# A more robust solution would store templates as images and metadata in JSON.
|
||||
with self.templates_path.open("w") as f:
|
||||
json.dump(
|
||||
[{"name": t.name, "threshold": t.threshold} for t in self.templates], f, indent=2
|
||||
)
|
||||
def persist(self) -> None:
|
||||
"""Write template metadata to disk.
|
||||
|
||||
def load(self):
|
||||
if self.templates_path.exists():
|
||||
Note: actual template images are stored alongside as .npy files
|
||||
for fast loading. The JSON file stores metadata only.
|
||||
"""
|
||||
self.templates_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
entries = []
|
||||
for t in self.templates:
|
||||
entry: dict[str, Any] = {"name": t.name, "threshold": t.threshold}
|
||||
if t.bbox is not None:
|
||||
entry["bbox"] = list(t.bbox)
|
||||
if t.metadata:
|
||||
entry["metadata"] = t.metadata
|
||||
|
||||
# Save non-empty template images as .npy
|
||||
if t.image.size > 0:
|
||||
img_path = self.templates_path.parent / f"template_{t.name}.npy"
|
||||
try:
|
||||
np.save(str(img_path), t.image)
|
||||
entry["image_path"] = str(img_path.name)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to save template image for '%s': %s", t.name, exc)
|
||||
|
||||
entries.append(entry)
|
||||
|
||||
with self.templates_path.open("w") as f:
|
||||
json.dump(entries, f, indent=2)
|
||||
logger.debug("Persisted %d templates to %s", len(entries), self.templates_path)
|
||||
|
||||
def load(self) -> None:
|
||||
"""Load templates from disk."""
|
||||
if not self.templates_path.exists():
|
||||
return
|
||||
|
||||
try:
|
||||
with self.templates_path.open("r") as f:
|
||||
templates_data = json.load(f)
|
||||
# This is a simplified loading mechanism and assumes template images are stored elsewhere.
|
||||
# For now, we are not loading the actual images.
|
||||
self.templates = [
|
||||
Template(name=t["name"], image=np.array([]), threshold=t["threshold"])
|
||||
for t in templates_data
|
||||
]
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
logger.warning("Failed to load templates: %s", exc)
|
||||
return
|
||||
|
||||
self.templates = []
|
||||
for t in templates_data:
|
||||
# Try to load the image from .npy if available
|
||||
image = np.array([])
|
||||
image_path = t.get("image_path")
|
||||
if image_path:
|
||||
full_path = self.templates_path.parent / image_path
|
||||
if full_path.exists():
|
||||
try:
|
||||
image = np.load(str(full_path))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
bbox = tuple(t["bbox"]) if "bbox" in t else None
|
||||
|
||||
self.templates.append(
|
||||
Template(
|
||||
name=t["name"],
|
||||
image=image,
|
||||
threshold=t.get("threshold", 0.85),
|
||||
bbox=bbox,
|
||||
metadata=t.get("metadata"),
|
||||
)
|
||||
)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Remove all templates."""
|
||||
self.templates.clear()
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.templates)
|
||||
|
||||
|
||||
def crystallize_perception(screenshot: np.ndarray, vlm_response: Any) -> list[Template]:
|
||||
def crystallize_perception(
|
||||
screenshot: np.ndarray,
|
||||
vlm_response: Any,
|
||||
) -> list[Template]:
|
||||
"""Extract reusable OpenCV templates from a VLM response.
|
||||
|
||||
Converts VLM-identified UI elements into cropped template images
|
||||
that can be matched in future frames without calling the VLM.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
screenshot:
|
||||
The full screenshot that was analysed by the VLM.
|
||||
vlm_response:
|
||||
Structured VLM output. Expected formats:
|
||||
- dict with ``"items"`` list, each having ``"name"`` and ``"bounding_box"``
|
||||
- dict with ``"elements"`` list (same structure)
|
||||
- list of dicts with ``"name"`` and ``"bbox"`` or ``"bounding_box"``
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[Template]
|
||||
Extracted templates ready to be added to a PerceptionCache.
|
||||
"""
|
||||
Extracts reusable patterns from VLM output and generates OpenCV templates.
|
||||
This is a placeholder and needs to be implemented based on the actual VLM response format.
|
||||
"""
|
||||
# Example implementation:
|
||||
# templates = []
|
||||
# for item in vlm_response.get("items", []):
|
||||
# bbox = item.get("bounding_box")
|
||||
# template_name = item.get("name")
|
||||
# if bbox and template_name:
|
||||
# x1, y1, x2, y2 = bbox
|
||||
# template_image = screenshot[y1:y2, x1:x2]
|
||||
# templates.append(Template(name=template_name, image=template_image))
|
||||
# return templates
|
||||
return []
|
||||
templates: list[Template] = []
|
||||
|
||||
# Normalize the response format
|
||||
items: list[dict[str, Any]] = []
|
||||
if isinstance(vlm_response, dict):
|
||||
items = vlm_response.get("items", vlm_response.get("elements", []))
|
||||
elif isinstance(vlm_response, list):
|
||||
items = vlm_response
|
||||
|
||||
for item in items:
|
||||
name = item.get("name") or item.get("label") or item.get("type")
|
||||
bbox = item.get("bounding_box") or item.get("bbox")
|
||||
|
||||
if not name or not bbox:
|
||||
continue
|
||||
|
||||
try:
|
||||
if len(bbox) == 4:
|
||||
x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
|
||||
else:
|
||||
continue
|
||||
|
||||
# Validate bounds
|
||||
h, w = screenshot.shape[:2]
|
||||
x1 = max(0, min(x1, w - 1))
|
||||
y1 = max(0, min(y1, h - 1))
|
||||
x2 = max(x1 + 1, min(x2, w))
|
||||
y2 = max(y1 + 1, min(y2, h))
|
||||
|
||||
template_image = screenshot[y1:y2, x1:x2].copy()
|
||||
|
||||
if template_image.size == 0:
|
||||
continue
|
||||
|
||||
metadata = {
|
||||
k: v for k, v in item.items() if k not in ("name", "label", "bounding_box", "bbox")
|
||||
}
|
||||
|
||||
templates.append(
|
||||
Template(
|
||||
name=name,
|
||||
image=template_image,
|
||||
bbox=(x1, y1, x2, y2),
|
||||
metadata=metadata if metadata else None,
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
"Crystallized perception template '%s' (%dx%d)",
|
||||
name,
|
||||
x2 - x1,
|
||||
y2 - y1,
|
||||
)
|
||||
|
||||
except (ValueError, IndexError, TypeError) as exc:
|
||||
logger.debug("Failed to crystallize item '%s': %s", name, exc)
|
||||
continue
|
||||
|
||||
if templates:
|
||||
logger.info(
|
||||
"Crystallized %d perception template(s) from VLM response",
|
||||
len(templates),
|
||||
)
|
||||
|
||||
return templates
|
||||
|
||||
379
src/timmy/sovereignty/sovereignty_loop.py
Normal file
379
src/timmy/sovereignty/sovereignty_loop.py
Normal file
@@ -0,0 +1,379 @@
|
||||
"""The Sovereignty Loop — core orchestration.
|
||||
|
||||
Implements the governing pattern from issue #953:
|
||||
|
||||
check cache → miss → infer → crystallize → return
|
||||
|
||||
This module provides wrapper functions that enforce the crystallization
|
||||
protocol for each AI layer (perception, decision, narration) and a
|
||||
decorator for general-purpose sovereignty enforcement.
|
||||
|
||||
Every function follows the same contract:
|
||||
1. Check local cache / rule store for a cached answer.
|
||||
2. On hit → record sovereign event, return cached answer.
|
||||
3. On miss → call the expensive model.
|
||||
4. Crystallize the model output into a durable local artifact.
|
||||
5. Record the model-call event + any new crystallizations.
|
||||
6. Return the result.
|
||||
|
||||
Refs: #953 (The Sovereignty Loop), #955, #956, #961
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from timmy.sovereignty.metrics import emit_sovereignty_event, get_metrics_store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
# ── Perception Layer ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def sovereign_perceive(
|
||||
screenshot: Any,
|
||||
cache: Any, # PerceptionCache
|
||||
vlm: Any,
|
||||
*,
|
||||
session_id: str = "",
|
||||
parse_fn: Callable[..., Any] | None = None,
|
||||
crystallize_fn: Callable[..., Any] | None = None,
|
||||
) -> Any:
|
||||
"""Sovereignty-wrapped perception: cache check → VLM → crystallize.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
screenshot:
|
||||
The current frame / screenshot (numpy array or similar).
|
||||
cache:
|
||||
A :class:`~timmy.sovereignty.perception_cache.PerceptionCache`.
|
||||
vlm:
|
||||
An object with an async ``analyze(screenshot)`` method.
|
||||
session_id:
|
||||
Current session identifier for metrics.
|
||||
parse_fn:
|
||||
Optional function to parse the VLM response into game state.
|
||||
Signature: ``parse_fn(vlm_response) -> state``.
|
||||
crystallize_fn:
|
||||
Optional function to extract templates from VLM output.
|
||||
Signature: ``crystallize_fn(screenshot, state) -> list[Template]``.
|
||||
Defaults to ``perception_cache.crystallize_perception``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Any
|
||||
The parsed game state (from cache or fresh VLM analysis).
|
||||
"""
|
||||
# Step 1: check cache
|
||||
cached = cache.match(screenshot)
|
||||
if cached.confidence > 0.85 and cached.state is not None:
|
||||
await emit_sovereignty_event("perception_cache_hit", session_id=session_id)
|
||||
return cached.state
|
||||
|
||||
# Step 2: cache miss — call VLM
|
||||
await emit_sovereignty_event("perception_vlm_call", session_id=session_id)
|
||||
raw = await vlm.analyze(screenshot)
|
||||
|
||||
# Step 3: parse
|
||||
if parse_fn is not None:
|
||||
state = parse_fn(raw)
|
||||
else:
|
||||
state = raw
|
||||
|
||||
# Step 4: crystallize
|
||||
if crystallize_fn is not None:
|
||||
new_templates = crystallize_fn(screenshot, state)
|
||||
else:
|
||||
from timmy.sovereignty.perception_cache import crystallize_perception
|
||||
|
||||
new_templates = crystallize_perception(screenshot, state)
|
||||
|
||||
if new_templates:
|
||||
cache.add(new_templates)
|
||||
cache.persist()
|
||||
for _ in new_templates:
|
||||
await emit_sovereignty_event(
|
||||
"skill_crystallized",
|
||||
metadata={"layer": "perception"},
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
return state
|
||||
|
||||
|
||||
# ── Decision Layer ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def sovereign_decide(
|
||||
context: dict[str, Any],
|
||||
llm: Any,
|
||||
*,
|
||||
session_id: str = "",
|
||||
rule_store: Any | None = None,
|
||||
confidence_threshold: float = 0.8,
|
||||
) -> dict[str, Any]:
|
||||
"""Sovereignty-wrapped decision: rule check → LLM → crystallize.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
context:
|
||||
Current game state / decision context.
|
||||
llm:
|
||||
An object with an async ``reason(context)`` method that returns
|
||||
a dict with at least ``"action"`` and ``"reasoning"`` keys.
|
||||
session_id:
|
||||
Current session identifier for metrics.
|
||||
rule_store:
|
||||
Optional :class:`~timmy.sovereignty.auto_crystallizer.RuleStore`.
|
||||
If ``None``, the module-level singleton is used.
|
||||
confidence_threshold:
|
||||
Minimum confidence for a rule to be used without LLM.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, Any]
|
||||
The decision result, with at least an ``"action"`` key.
|
||||
"""
|
||||
from timmy.sovereignty.auto_crystallizer import (
|
||||
crystallize_reasoning,
|
||||
get_rule_store,
|
||||
)
|
||||
|
||||
store = rule_store if rule_store is not None else get_rule_store()
|
||||
|
||||
# Step 1: check rules
|
||||
matching_rules = store.find_matching(context)
|
||||
if matching_rules:
|
||||
best = matching_rules[0]
|
||||
if best.confidence >= confidence_threshold:
|
||||
await emit_sovereignty_event(
|
||||
"decision_rule_hit",
|
||||
metadata={"rule_id": best.id, "confidence": best.confidence},
|
||||
session_id=session_id,
|
||||
)
|
||||
return {
|
||||
"action": best.action,
|
||||
"source": "crystallized_rule",
|
||||
"rule_id": best.id,
|
||||
"confidence": best.confidence,
|
||||
}
|
||||
|
||||
# Step 2: rule miss — call LLM
|
||||
await emit_sovereignty_event("decision_llm_call", session_id=session_id)
|
||||
result = await llm.reason(context)
|
||||
|
||||
# Step 3: crystallize the reasoning
|
||||
reasoning_text = result.get("reasoning", "")
|
||||
if reasoning_text:
|
||||
new_rules = crystallize_reasoning(reasoning_text, context=context)
|
||||
added = store.add_many(new_rules)
|
||||
for _ in range(added):
|
||||
await emit_sovereignty_event(
|
||||
"skill_crystallized",
|
||||
metadata={"layer": "decision"},
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ── Narration Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def sovereign_narrate(
|
||||
event: dict[str, Any],
|
||||
llm: Any | None = None,
|
||||
*,
|
||||
session_id: str = "",
|
||||
template_store: Any | None = None,
|
||||
) -> str:
|
||||
"""Sovereignty-wrapped narration: template check → LLM → crystallize.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
event:
|
||||
The game event to narrate (must have at least ``"type"`` key).
|
||||
llm:
|
||||
An optional LLM for novel narration. If ``None`` and no template
|
||||
matches, returns a default string.
|
||||
session_id:
|
||||
Current session identifier for metrics.
|
||||
template_store:
|
||||
Optional narration template store (dict-like mapping event types
|
||||
to template strings with ``{variable}`` slots). If ``None``,
|
||||
tries to load from ``data/narration.json``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The narration text.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from config import settings
|
||||
|
||||
# Load template store
|
||||
if template_store is None:
|
||||
narration_path = Path(settings.repo_root) / "data" / "narration.json"
|
||||
if narration_path.exists():
|
||||
try:
|
||||
with narration_path.open() as f:
|
||||
template_store = json.load(f)
|
||||
except Exception:
|
||||
template_store = {}
|
||||
else:
|
||||
template_store = {}
|
||||
|
||||
event_type = event.get("type", "unknown")
|
||||
|
||||
# Step 1: check templates
|
||||
if event_type in template_store:
|
||||
template = template_store[event_type]
|
||||
try:
|
||||
text = template.format(**event)
|
||||
await emit_sovereignty_event("narration_template", session_id=session_id)
|
||||
return text
|
||||
except (KeyError, IndexError):
|
||||
# Template doesn't match event variables — fall through to LLM
|
||||
pass
|
||||
|
||||
# Step 2: no template — call LLM if available
|
||||
if llm is not None:
|
||||
await emit_sovereignty_event("narration_llm", session_id=session_id)
|
||||
narration = await llm.narrate(event)
|
||||
|
||||
# Step 3: crystallize — add template for this event type
|
||||
_crystallize_narration_template(event_type, narration, event, template_store)
|
||||
|
||||
return narration
|
||||
|
||||
# No LLM available — return minimal default
|
||||
await emit_sovereignty_event("narration_template", session_id=session_id)
|
||||
return f"[{event_type}]"
|
||||
|
||||
|
||||
def _crystallize_narration_template(
|
||||
event_type: str,
|
||||
narration: str,
|
||||
event: dict[str, Any],
|
||||
template_store: dict[str, str],
|
||||
) -> None:
|
||||
"""Attempt to crystallize a narration into a reusable template.
|
||||
|
||||
Replaces concrete values in the narration with format placeholders
|
||||
based on event keys, then saves to ``data/narration.json``.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from config import settings
|
||||
|
||||
template = narration
|
||||
for key, value in event.items():
|
||||
if key == "type":
|
||||
continue
|
||||
if isinstance(value, str) and value and value in template:
|
||||
template = template.replace(value, f"{{{key}}}")
|
||||
|
||||
template_store[event_type] = template
|
||||
|
||||
narration_path = Path(settings.repo_root) / "data" / "narration.json"
|
||||
try:
|
||||
narration_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with narration_path.open("w") as f:
|
||||
json.dump(template_store, f, indent=2)
|
||||
logger.info("Crystallized narration template for event type '%s'", event_type)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to persist narration template: %s", exc)
|
||||
|
||||
|
||||
# ── Sovereignty decorator ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def sovereignty_enforced(
|
||||
layer: str,
|
||||
cache_check: Callable[..., Any] | None = None,
|
||||
crystallize: Callable[..., Any] | None = None,
|
||||
) -> Callable:
|
||||
"""Decorator that enforces the sovereignty protocol on any async function.
|
||||
|
||||
Wraps an async function with the check-cache → miss → infer →
|
||||
crystallize → return pattern. If ``cache_check`` returns a non-None
|
||||
result, the wrapped function is skipped entirely.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
layer:
|
||||
The sovereignty layer name (``"perception"``, ``"decision"``,
|
||||
``"narration"``). Used for metric event names.
|
||||
cache_check:
|
||||
A callable ``(args, kwargs) -> cached_result | None``.
|
||||
If it returns non-None, the decorated function is not called.
|
||||
crystallize:
|
||||
A callable ``(result, args, kwargs) -> None`` called after the
|
||||
decorated function returns, to persist the result as a local artifact.
|
||||
|
||||
Example
|
||||
-------
|
||||
::
|
||||
|
||||
@sovereignty_enforced(
|
||||
layer="decision",
|
||||
cache_check=lambda a, kw: rule_store.find_matching(kw.get("ctx")),
|
||||
crystallize=lambda result, a, kw: rule_store.add(extract_rules(result)),
|
||||
)
|
||||
async def decide(ctx):
|
||||
return await llm.reason(ctx)
|
||||
"""
|
||||
|
||||
sovereign_event = (
|
||||
f"{layer}_cache_hit"
|
||||
if layer in ("perception", "decision", "narration")
|
||||
else f"{layer}_sovereign"
|
||||
)
|
||||
miss_event = {
|
||||
"perception": "perception_vlm_call",
|
||||
"decision": "decision_llm_call",
|
||||
"narration": "narration_llm",
|
||||
}.get(layer, f"{layer}_model_call")
|
||||
|
||||
def decorator(fn: Callable) -> Callable:
|
||||
@functools.wraps(fn)
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
# Check cache
|
||||
if cache_check is not None:
|
||||
cached = cache_check(args, kwargs)
|
||||
if cached is not None:
|
||||
store = get_metrics_store()
|
||||
store.record(sovereign_event, session_id=kwargs.get("session_id", ""))
|
||||
return cached
|
||||
|
||||
# Cache miss — run the model
|
||||
store = get_metrics_store()
|
||||
store.record(miss_event, session_id=kwargs.get("session_id", ""))
|
||||
result = await fn(*args, **kwargs)
|
||||
|
||||
# Crystallize
|
||||
if crystallize is not None:
|
||||
try:
|
||||
crystallize(result, args, kwargs)
|
||||
store.record(
|
||||
"skill_crystallized",
|
||||
metadata={"layer": layer},
|
||||
session_id=kwargs.get("session_id", ""),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Crystallization failed for %s: %s", layer, exc)
|
||||
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -2902,3 +2902,520 @@
|
||||
padding-top: 0.5rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
Legal pages — ToS, Privacy Policy, Risk Disclaimers
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
.legal-page {
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 1rem 3rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.legal-header {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.legal-breadcrumb {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 0.5rem;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.legal-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--purple);
|
||||
letter-spacing: 0.1em;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.legal-effective {
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.legal-toc-list {
|
||||
margin: 0;
|
||||
padding-left: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.legal-toc-list li {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.legal-warning {
|
||||
background: rgba(249, 115, 22, 0.08);
|
||||
border: 1px solid rgba(249, 115, 22, 0.35);
|
||||
border-radius: 4px;
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.legal-risk-banner .card-header {
|
||||
color: var(--orange);
|
||||
}
|
||||
|
||||
.legal-subhead {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-bright);
|
||||
margin: 1rem 0 0.4rem;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.legal-callout {
|
||||
background: rgba(168, 85, 247, 0.08);
|
||||
border-left: 3px solid var(--purple);
|
||||
padding: 0.5rem 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.legal-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.82rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.legal-table th {
|
||||
text-align: left;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(168, 85, 247, 0.1);
|
||||
color: var(--text-bright);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.legal-table td {
|
||||
padding: 0.45rem 0.75rem;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.04);
|
||||
color: var(--text);
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.legal-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.legal-footer-links {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
font-size: 0.8rem;
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
|
||||
.legal-sep {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
/* Dropdown divider */
|
||||
.mc-dropdown-divider {
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
|
||||
/* ── Footer ── */
|
||||
.mc-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.75rem 1rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--text-dim);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-deep);
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.mc-footer-link {
|
||||
color: var(--text-dim);
|
||||
text-decoration: none;
|
||||
transition: color 0.15s;
|
||||
}
|
||||
|
||||
.mc-footer-link:hover {
|
||||
color: var(--purple);
|
||||
}
|
||||
|
||||
.mc-footer-sep {
|
||||
color: var(--border);
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.legal-page {
|
||||
padding: 1rem 0.75rem 2rem;
|
||||
}
|
||||
|
||||
.legal-table {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.legal-table th,
|
||||
.legal-table td {
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ── Landing page (homepage value proposition) ────────────────── */
|
||||
|
||||
.lp-wrap {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1.5rem 4rem;
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.lp-hero {
|
||||
text-align: center;
|
||||
padding: 4rem 0 3rem;
|
||||
}
|
||||
.lp-hero-eyebrow {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.18em;
|
||||
color: var(--purple);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.lp-hero-title {
|
||||
font-size: clamp(2rem, 6vw, 3.5rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.1;
|
||||
color: var(--text-bright);
|
||||
margin-bottom: 1.25rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.lp-hero-sub {
|
||||
font-size: 1.1rem;
|
||||
color: var(--text);
|
||||
line-height: 1.7;
|
||||
max-width: 480px;
|
||||
margin: 0 auto 2rem;
|
||||
}
|
||||
.lp-hero-cta-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
justify-content: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.lp-hero-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--text-dim);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 5px 14px;
|
||||
}
|
||||
.lp-badge-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 6px var(--green);
|
||||
animation: lp-pulse 2s infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@keyframes lp-pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.35; }
|
||||
}
|
||||
|
||||
/* Shared buttons */
|
||||
.lp-btn {
|
||||
display: inline-block;
|
||||
font-family: var(--font);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 10px 22px;
|
||||
text-decoration: none;
|
||||
transition: background 0.2s, color 0.2s, border-color 0.2s, box-shadow 0.2s;
|
||||
cursor: pointer;
|
||||
}
|
||||
.lp-btn-primary {
|
||||
background: var(--purple);
|
||||
color: #fff;
|
||||
border: 1px solid var(--purple);
|
||||
}
|
||||
.lp-btn-primary:hover {
|
||||
background: #a855f7;
|
||||
border-color: #a855f7;
|
||||
box-shadow: 0 0 14px rgba(168, 85, 247, 0.45);
|
||||
color: #fff;
|
||||
}
|
||||
.lp-btn-secondary {
|
||||
background: transparent;
|
||||
color: var(--text-bright);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.lp-btn-secondary:hover {
|
||||
border-color: var(--purple);
|
||||
color: var(--purple);
|
||||
}
|
||||
.lp-btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--text-dim);
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.lp-btn-ghost:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
.lp-btn-sm {
|
||||
font-size: 10px;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
.lp-btn-lg {
|
||||
font-size: 13px;
|
||||
padding: 14px 32px;
|
||||
}
|
||||
|
||||
/* Shared section */
|
||||
.lp-section {
|
||||
padding: 3.5rem 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.lp-section-title {
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-bright);
|
||||
letter-spacing: -0.01em;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.lp-section-sub {
|
||||
color: var(--text-dim);
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
/* Value cards */
|
||||
.lp-value-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1.25rem;
|
||||
}
|
||||
.lp-value-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.5rem 1.25rem;
|
||||
}
|
||||
.lp-value-icon {
|
||||
font-size: 1.6rem;
|
||||
display: block;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.lp-value-card h3 {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-bright);
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 0.5rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.lp-value-card p {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Capability accordion */
|
||||
.lp-caps-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.lp-cap-item {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: hidden;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
.lp-cap-item[open] {
|
||||
border-color: var(--purple);
|
||||
}
|
||||
.lp-cap-summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
user-select: none;
|
||||
}
|
||||
.lp-cap-summary::-webkit-details-marker { display: none; }
|
||||
.lp-cap-icon {
|
||||
font-size: 1.25rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.lp-cap-label {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--text-bright);
|
||||
text-transform: uppercase;
|
||||
flex: 1;
|
||||
}
|
||||
.lp-cap-chevron {
|
||||
font-size: 0.7rem;
|
||||
color: var(--text-dim);
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
.lp-cap-item[open] .lp-cap-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.lp-cap-body {
|
||||
padding: 0 1.25rem 1.25rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.lp-cap-body p {
|
||||
font-size: 0.875rem;
|
||||
color: var(--text);
|
||||
line-height: 1.65;
|
||||
margin: 0.875rem 0 0.75rem;
|
||||
}
|
||||
.lp-cap-bullets {
|
||||
margin: 0;
|
||||
padding-left: 1.1rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-dim);
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* Stats */
|
||||
.lp-stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: 1.25rem;
|
||||
}
|
||||
.lp-stat-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.5rem 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
.lp-stat-num {
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--purple);
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 1;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.lp-stat-label {
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
color: var(--text-dim);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* Audience CTAs */
|
||||
.lp-audience-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
|
||||
gap: 1.25rem;
|
||||
}
|
||||
.lp-audience-card {
|
||||
position: relative;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.75rem 1.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.lp-audience-featured {
|
||||
border-color: var(--purple);
|
||||
background: rgba(124, 58, 237, 0.07);
|
||||
}
|
||||
.lp-audience-badge {
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--purple);
|
||||
color: #fff;
|
||||
font-size: 8px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.lp-audience-icon {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
.lp-audience-card h3 {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-bright);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
margin: 0;
|
||||
}
|
||||
.lp-audience-card p {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
line-height: 1.65;
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Final CTA */
|
||||
.lp-final-cta {
|
||||
text-align: center;
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 4rem 0 2rem;
|
||||
}
|
||||
.lp-final-cta-title {
|
||||
font-size: clamp(1.5rem, 4vw, 2.5rem);
|
||||
font-weight: 700;
|
||||
color: var(--text-bright);
|
||||
margin-bottom: 0.75rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.lp-final-cta-sub {
|
||||
color: var(--text-dim);
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0.04em;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 600px) {
|
||||
.lp-hero { padding: 2.5rem 0 2rem; }
|
||||
.lp-hero-cta-row { flex-direction: column; align-items: center; }
|
||||
.lp-value-grid { grid-template-columns: 1fr; }
|
||||
.lp-stats-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.lp-audience-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@@ -103,6 +103,28 @@
|
||||
<div id="submit-job-backdrop" class="submit-job-backdrop"></div>
|
||||
</div>
|
||||
|
||||
<!-- GPU context loss overlay -->
|
||||
<div id="gpu-error-overlay" class="hidden">
|
||||
<div class="gpu-error-icon">🔮</div>
|
||||
<div class="gpu-error-title">Timmy is taking a quick break</div>
|
||||
<div class="gpu-error-msg">
|
||||
The 3D workshop lost its connection to the GPU.<br>
|
||||
Attempting to restore the scene…
|
||||
</div>
|
||||
<div class="gpu-error-retry" id="gpu-retry-msg">Reconnecting automatically…</div>
|
||||
</div>
|
||||
|
||||
<!-- WebGL / mobile fallback -->
|
||||
<div id="webgl-fallback" class="hidden">
|
||||
<div class="fallback-title">Timmy</div>
|
||||
<div class="fallback-subtitle">The Workshop</div>
|
||||
<div class="fallback-status">
|
||||
<div class="mood-line" id="fallback-mood">focused</div>
|
||||
<p id="fallback-detail">Pondering the arcane arts of code…</p>
|
||||
</div>
|
||||
<a href="/" class="fallback-link">Open Mission Control</a>
|
||||
</div>
|
||||
|
||||
<!-- About Panel -->
|
||||
<div id="about-panel" class="about-panel">
|
||||
<div class="about-panel-content">
|
||||
@@ -157,6 +179,38 @@
|
||||
import { StateReader } from "./state.js";
|
||||
import { messageQueue } from "./queue.js";
|
||||
|
||||
// --- Mobile detection: redirect to text interface on small touch devices ---
|
||||
const isMobile = window.matchMedia("(pointer: coarse)").matches
|
||||
&& window.innerWidth < 768;
|
||||
if (isMobile) {
|
||||
const fallback = document.getElementById("webgl-fallback");
|
||||
if (fallback) fallback.classList.remove("hidden");
|
||||
// Don't initialise the 3D scene on mobile
|
||||
throw new Error("Mobile device — 3D scene skipped");
|
||||
}
|
||||
|
||||
// --- WebGL support detection ---
|
||||
function _hasWebGL() {
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
return !!(
|
||||
canvas.getContext("webgl2") ||
|
||||
canvas.getContext("webgl") ||
|
||||
canvas.getContext("experimental-webgl")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!_hasWebGL()) {
|
||||
const fallback = document.getElementById("webgl-fallback");
|
||||
const detail = document.getElementById("fallback-detail");
|
||||
if (fallback) fallback.classList.remove("hidden");
|
||||
if (detail) detail.textContent =
|
||||
"Your device doesn\u2019t support WebGL. Use a modern browser to see the 3D workshop.";
|
||||
throw new Error("WebGL not supported");
|
||||
}
|
||||
|
||||
// --- Renderer ---
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
@@ -167,6 +221,26 @@
|
||||
renderer.toneMappingExposure = 0.8;
|
||||
document.body.prepend(renderer.domElement);
|
||||
|
||||
// --- WebGL context loss / restore ---
|
||||
const _gpuOverlay = document.getElementById("gpu-error-overlay");
|
||||
const _gpuRetryMsg = document.getElementById("gpu-retry-msg");
|
||||
let _animating = true;
|
||||
|
||||
renderer.domElement.addEventListener("webglcontextlost", (ev) => {
|
||||
ev.preventDefault();
|
||||
_animating = false;
|
||||
if (_gpuOverlay) _gpuOverlay.classList.remove("hidden");
|
||||
if (_gpuRetryMsg) _gpuRetryMsg.textContent = "Reconnecting automatically\u2026";
|
||||
console.warn("[Workshop] WebGL context lost — waiting for restore");
|
||||
}, false);
|
||||
|
||||
renderer.domElement.addEventListener("webglcontextrestored", () => {
|
||||
_animating = true;
|
||||
if (_gpuOverlay) _gpuOverlay.classList.add("hidden");
|
||||
console.info("[Workshop] WebGL context restored — resuming");
|
||||
animate();
|
||||
}, false);
|
||||
|
||||
// --- Scene ---
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(0x0a0a14);
|
||||
@@ -195,6 +269,13 @@
|
||||
if (moodEl) {
|
||||
moodEl.textContent = state.timmyState.mood;
|
||||
}
|
||||
// Keep fallback view in sync when it's visible
|
||||
const fallbackMood = document.getElementById("fallback-mood");
|
||||
const fallbackDetail = document.getElementById("fallback-detail");
|
||||
if (fallbackMood) fallbackMood.textContent = state.timmyState.mood;
|
||||
if (fallbackDetail && state.timmyState.activity) {
|
||||
fallbackDetail.textContent = state.timmyState.activity + "\u2026";
|
||||
}
|
||||
});
|
||||
|
||||
// Replay queued jobs whenever the server comes back online.
|
||||
@@ -537,6 +618,7 @@
|
||||
const clock = new THREE.Clock();
|
||||
|
||||
function animate() {
|
||||
if (!_animating) return;
|
||||
requestAnimationFrame(animate);
|
||||
const dt = clock.getDelta();
|
||||
|
||||
|
||||
@@ -715,3 +715,116 @@ canvas {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* GPU context loss overlay */
|
||||
#gpu-error-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(10, 10, 20, 0.95);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 200;
|
||||
text-align: center;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
#gpu-error-overlay.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gpu-error-icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 16px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.gpu-error-title {
|
||||
font-size: 20px;
|
||||
color: #daa520;
|
||||
margin-bottom: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.gpu-error-msg {
|
||||
font-size: 14px;
|
||||
color: #aaa;
|
||||
line-height: 1.6;
|
||||
max-width: 400px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.gpu-error-retry {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* WebGL / mobile fallback — text-only mode */
|
||||
#webgl-fallback {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #0a0a14;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 200;
|
||||
text-align: center;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
#webgl-fallback.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.fallback-title {
|
||||
font-size: 22px;
|
||||
color: #daa520;
|
||||
margin-bottom: 8px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.fallback-subtitle {
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
margin-bottom: 32px;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.fallback-status {
|
||||
font-size: 15px;
|
||||
color: #aaa;
|
||||
line-height: 1.7;
|
||||
max-width: 400px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.fallback-status .mood-line {
|
||||
color: #daa520;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.fallback-link {
|
||||
display: inline-block;
|
||||
padding: 10px 24px;
|
||||
border: 1px solid rgba(218, 165, 32, 0.4);
|
||||
border-radius: 6px;
|
||||
color: #daa520;
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.fallback-link:hover {
|
||||
background: rgba(218, 165, 32, 0.1);
|
||||
border-color: rgba(218, 165, 32, 0.7);
|
||||
}
|
||||
|
||||
598
tests/infrastructure/test_models_budget.py
Normal file
598
tests/infrastructure/test_models_budget.py
Normal file
@@ -0,0 +1,598 @@
|
||||
"""Unit tests for models/budget.py — comprehensive coverage for budget management.
|
||||
|
||||
Tests budget allocation, tracking, limit enforcement, and edge cases including:
|
||||
- Zero budget scenarios
|
||||
- Over-budget handling
|
||||
- Budget reset behavior
|
||||
- In-memory fallback when DB is unavailable
|
||||
"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from infrastructure.models.budget import (
|
||||
BudgetTracker,
|
||||
SpendRecord,
|
||||
estimate_cost_usd,
|
||||
get_budget_tracker,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
# ── Test SpendRecord dataclass ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestSpendRecord:
|
||||
"""Tests for the SpendRecord dataclass."""
|
||||
|
||||
def test_spend_record_creation(self):
|
||||
"""Test creating a SpendRecord with all fields."""
|
||||
ts = time.time()
|
||||
record = SpendRecord(
|
||||
ts=ts,
|
||||
provider="anthropic",
|
||||
model="claude-haiku-4-5",
|
||||
tokens_in=100,
|
||||
tokens_out=200,
|
||||
cost_usd=0.001,
|
||||
tier="cloud",
|
||||
)
|
||||
assert record.ts == ts
|
||||
assert record.provider == "anthropic"
|
||||
assert record.model == "claude-haiku-4-5"
|
||||
assert record.tokens_in == 100
|
||||
assert record.tokens_out == 200
|
||||
assert record.cost_usd == 0.001
|
||||
assert record.tier == "cloud"
|
||||
|
||||
def test_spend_record_with_zero_tokens(self):
|
||||
"""Test SpendRecord with zero tokens."""
|
||||
ts = time.time()
|
||||
record = SpendRecord(ts=ts, provider="openai", model="gpt-4o", tokens_in=0, tokens_out=0, cost_usd=0.0, tier="cloud")
|
||||
assert record.tokens_in == 0
|
||||
assert record.tokens_out == 0
|
||||
|
||||
|
||||
# ── Test estimate_cost_usd function ───────────────────────────────────────────
|
||||
|
||||
|
||||
class TestEstimateCostUsd:
|
||||
"""Tests for the estimate_cost_usd function."""
|
||||
|
||||
def test_haiku_cheaper_than_sonnet(self):
|
||||
"""Haiku should be cheaper than Sonnet for same tokens."""
|
||||
haiku_cost = estimate_cost_usd("claude-haiku-4-5", 1000, 1000)
|
||||
sonnet_cost = estimate_cost_usd("claude-sonnet-4-5", 1000, 1000)
|
||||
assert haiku_cost < sonnet_cost
|
||||
|
||||
def test_zero_tokens_is_zero_cost(self):
|
||||
"""Zero tokens should result in zero cost."""
|
||||
assert estimate_cost_usd("gpt-4o", 0, 0) == 0.0
|
||||
|
||||
def test_only_input_tokens(self):
|
||||
"""Cost calculation with only input tokens."""
|
||||
cost = estimate_cost_usd("gpt-4o", 1000, 0)
|
||||
expected = (1000 * 0.0025) / 1000.0 # $0.0025 per 1K input tokens
|
||||
assert cost == pytest.approx(expected)
|
||||
|
||||
def test_only_output_tokens(self):
|
||||
"""Cost calculation with only output tokens."""
|
||||
cost = estimate_cost_usd("gpt-4o", 0, 1000)
|
||||
expected = (1000 * 0.01) / 1000.0 # $0.01 per 1K output tokens
|
||||
assert cost == pytest.approx(expected)
|
||||
|
||||
def test_unknown_model_uses_default(self):
|
||||
"""Unknown model should use conservative default cost."""
|
||||
cost = estimate_cost_usd("some-unknown-model-xyz", 1000, 1000)
|
||||
assert cost > 0 # Uses conservative default, not zero
|
||||
# Default is 0.003 input, 0.015 output per 1K
|
||||
expected = (1000 * 0.003 + 1000 * 0.015) / 1000.0
|
||||
assert cost == pytest.approx(expected)
|
||||
|
||||
def test_versioned_model_name_matches(self):
|
||||
"""Versioned model names should match base model rates."""
|
||||
cost1 = estimate_cost_usd("claude-haiku-4-5-20251001", 1000, 0)
|
||||
cost2 = estimate_cost_usd("claude-haiku-4-5", 1000, 0)
|
||||
assert cost1 == cost2
|
||||
|
||||
def test_gpt4o_mini_cheaper_than_gpt4o(self):
|
||||
"""GPT-4o mini should be cheaper than GPT-4o."""
|
||||
mini = estimate_cost_usd("gpt-4o-mini", 1000, 1000)
|
||||
full = estimate_cost_usd("gpt-4o", 1000, 1000)
|
||||
assert mini < full
|
||||
|
||||
def test_opus_most_expensive_claude(self):
|
||||
"""Opus should be the most expensive Claude model."""
|
||||
opus = estimate_cost_usd("claude-opus-4-5", 1000, 1000)
|
||||
sonnet = estimate_cost_usd("claude-sonnet-4-5", 1000, 1000)
|
||||
haiku = estimate_cost_usd("claude-haiku-4-5", 1000, 1000)
|
||||
assert opus > sonnet > haiku
|
||||
|
||||
def test_grok_variants(self):
|
||||
"""Test Grok model cost estimation."""
|
||||
cost = estimate_cost_usd("grok-3", 1000, 1000)
|
||||
assert cost > 0
|
||||
cost_fast = estimate_cost_usd("grok-3-fast", 1000, 1000)
|
||||
assert cost_fast > 0
|
||||
|
||||
def test_case_insensitive_matching(self):
|
||||
"""Model name matching should be case insensitive."""
|
||||
cost_lower = estimate_cost_usd("claude-haiku-4-5", 1000, 0)
|
||||
cost_upper = estimate_cost_usd("CLAUDE-HAIKU-4-5", 1000, 0)
|
||||
cost_mixed = estimate_cost_usd("Claude-Haiku-4-5", 1000, 0)
|
||||
assert cost_lower == cost_upper == cost_mixed
|
||||
|
||||
def test_returns_float(self):
|
||||
"""Function should always return a float."""
|
||||
assert isinstance(estimate_cost_usd("haiku", 100, 200), float)
|
||||
assert isinstance(estimate_cost_usd("unknown-model", 100, 200), float)
|
||||
assert isinstance(estimate_cost_usd("haiku", 0, 0), float)
|
||||
|
||||
|
||||
# ── Test BudgetTracker initialization ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerInit:
|
||||
"""Tests for BudgetTracker initialization."""
|
||||
|
||||
def test_creates_with_memory_db(self):
|
||||
"""Tracker should initialize with in-memory database."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
assert tracker._db_ok is True
|
||||
|
||||
def test_in_memory_fallback_empty_on_creation(self):
|
||||
"""In-memory fallback should start empty."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
assert tracker._in_memory == []
|
||||
|
||||
def test_custom_db_path(self, tmp_path):
|
||||
"""Tracker should use custom database path."""
|
||||
db_file = tmp_path / "custom_budget.db"
|
||||
tracker = BudgetTracker(db_path=str(db_file))
|
||||
assert tracker._db_ok is True
|
||||
assert tracker._db_path == str(db_file)
|
||||
assert db_file.exists()
|
||||
|
||||
def test_db_path_directory_creation(self, tmp_path):
|
||||
"""Tracker should create parent directories if needed."""
|
||||
db_file = tmp_path / "nested" / "dirs" / "budget.db"
|
||||
tracker = BudgetTracker(db_path=str(db_file))
|
||||
assert tracker._db_ok is True
|
||||
assert db_file.parent.exists()
|
||||
|
||||
def test_invalid_db_path_fallback(self):
|
||||
"""Tracker should fallback to in-memory on invalid path."""
|
||||
# Use a path that cannot be created (e.g., permission denied simulation)
|
||||
tracker = BudgetTracker.__new__(BudgetTracker)
|
||||
tracker._db_path = "/nonexistent/invalid/path/budget.db"
|
||||
tracker._lock = threading.Lock()
|
||||
tracker._in_memory = []
|
||||
tracker._db_ok = False
|
||||
# Should still work with in-memory fallback
|
||||
cost = tracker.record_spend("test", "model", cost_usd=0.01)
|
||||
assert cost == 0.01
|
||||
|
||||
|
||||
# ── Test BudgetTracker record_spend ───────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerRecordSpend:
|
||||
"""Tests for recording spend events."""
|
||||
|
||||
def test_record_spend_returns_cost(self):
|
||||
"""record_spend should return the calculated cost."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("anthropic", "claude-haiku-4-5", 100, 200)
|
||||
assert cost > 0
|
||||
|
||||
def test_record_spend_explicit_cost(self):
|
||||
"""record_spend should use explicit cost when provided."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("anthropic", "model", cost_usd=1.23)
|
||||
assert cost == pytest.approx(1.23)
|
||||
|
||||
def test_record_spend_accumulates(self):
|
||||
"""Multiple spend records should accumulate correctly."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("openai", "gpt-4o", cost_usd=0.01)
|
||||
tracker.record_spend("openai", "gpt-4o", cost_usd=0.02)
|
||||
assert tracker.get_daily_spend() == pytest.approx(0.03, abs=1e-9)
|
||||
|
||||
def test_record_spend_with_tier_label(self):
|
||||
"""record_spend should accept custom tier labels."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("anthropic", "haiku", tier="cloud_api")
|
||||
assert cost >= 0
|
||||
|
||||
def test_record_spend_with_provider(self):
|
||||
"""record_spend should track provider correctly."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("openai", "gpt-4o", cost_usd=0.01)
|
||||
tracker.record_spend("anthropic", "claude-haiku", cost_usd=0.02)
|
||||
assert tracker.get_daily_spend() == pytest.approx(0.03, abs=1e-9)
|
||||
|
||||
def test_record_zero_cost(self):
|
||||
"""Recording zero cost should work correctly."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("test", "model", cost_usd=0.0)
|
||||
assert cost == 0.0
|
||||
assert tracker.get_daily_spend() == 0.0
|
||||
|
||||
def test_record_negative_cost(self):
|
||||
"""Recording negative cost (refund) should work."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("test", "model", cost_usd=-0.50)
|
||||
assert cost == -0.50
|
||||
assert tracker.get_daily_spend() == -0.50
|
||||
|
||||
|
||||
# ── Test BudgetTracker daily/monthly spend queries ────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerSpendQueries:
|
||||
"""Tests for daily and monthly spend queries."""
|
||||
|
||||
def test_monthly_spend_includes_daily(self):
|
||||
"""Monthly spend should be >= daily spend."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("anthropic", "haiku", cost_usd=5.00)
|
||||
assert tracker.get_monthly_spend() >= tracker.get_daily_spend()
|
||||
|
||||
def test_get_daily_spend_empty(self):
|
||||
"""Daily spend should be zero when no records."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
assert tracker.get_daily_spend() == 0.0
|
||||
|
||||
def test_get_monthly_spend_empty(self):
|
||||
"""Monthly spend should be zero when no records."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
assert tracker.get_monthly_spend() == 0.0
|
||||
|
||||
def test_daily_spend_isolation(self):
|
||||
"""Daily spend should only include today's records, not old ones."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
# Force use of in-memory fallback
|
||||
tracker._db_ok = False
|
||||
|
||||
# Add record for today
|
||||
today_ts = datetime.combine(date.today(), datetime.min.time(), tzinfo=UTC).timestamp()
|
||||
tracker._in_memory.append(
|
||||
SpendRecord(today_ts + 3600, "test", "model", 0, 0, 1.0, "cloud")
|
||||
)
|
||||
|
||||
# Add old record (2 days ago)
|
||||
old_ts = (datetime.now(UTC) - timedelta(days=2)).timestamp()
|
||||
tracker._in_memory.append(
|
||||
SpendRecord(old_ts, "test", "old_model", 0, 0, 2.0, "cloud")
|
||||
)
|
||||
|
||||
# Daily should only include today's 1.0
|
||||
assert tracker.get_daily_spend() == pytest.approx(1.0, abs=1e-9)
|
||||
# Monthly should include both (both are in current month)
|
||||
assert tracker.get_monthly_spend() == pytest.approx(3.0, abs=1e-9)
|
||||
|
||||
|
||||
# ── Test BudgetTracker cloud_allowed ──────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerCloudAllowed:
|
||||
"""Tests for cloud budget limit enforcement."""
|
||||
|
||||
def test_allowed_when_no_spend(self):
|
||||
"""Cloud should be allowed when no spend recorded."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
assert tracker.cloud_allowed() is True
|
||||
|
||||
def test_blocked_when_daily_limit_exceeded(self):
|
||||
"""Cloud should be blocked when daily limit exceeded."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("anthropic", "haiku", cost_usd=999.0)
|
||||
# With default daily limit of 5.0, 999 should block
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
def test_allowed_when_daily_limit_zero(self):
|
||||
"""Cloud should be allowed when daily limit is 0 (disabled)."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("anthropic", "haiku", cost_usd=999.0)
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0 # disabled
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 0 # disabled
|
||||
assert tracker.cloud_allowed() is True
|
||||
|
||||
def test_blocked_when_monthly_limit_exceeded(self):
|
||||
"""Cloud should be blocked when monthly limit exceeded."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("anthropic", "haiku", cost_usd=999.0)
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0 # daily disabled
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 10.0
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
def test_allowed_at_exact_daily_limit(self):
|
||||
"""Cloud should be allowed when exactly at daily limit."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 5.0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 0
|
||||
# Record exactly at limit
|
||||
tracker.record_spend("test", "model", cost_usd=5.0)
|
||||
# At exactly the limit, it should return False (blocked)
|
||||
# because spend >= limit
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
def test_allowed_below_daily_limit(self):
|
||||
"""Cloud should be allowed when below daily limit."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 5.0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 0
|
||||
tracker.record_spend("test", "model", cost_usd=4.99)
|
||||
assert tracker.cloud_allowed() is True
|
||||
|
||||
def test_zero_budget_blocks_all(self):
|
||||
"""Zero budget should block all cloud usage."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0.01 # Very small budget
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 0
|
||||
tracker.record_spend("test", "model", cost_usd=0.02)
|
||||
# Over the tiny budget, should be blocked
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
def test_both_limits_checked(self):
|
||||
"""Both daily and monthly limits should be checked."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 100.0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 10.0
|
||||
tracker.record_spend("test", "model", cost_usd=15.0)
|
||||
# Under daily but over monthly
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
|
||||
# ── Test BudgetTracker summary ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerSummary:
|
||||
"""Tests for budget summary functionality."""
|
||||
|
||||
def test_summary_keys_present(self):
|
||||
"""Summary should contain all expected keys."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
summary = tracker.get_summary()
|
||||
assert "daily_usd" in summary
|
||||
assert "monthly_usd" in summary
|
||||
assert "daily_limit_usd" in summary
|
||||
assert "monthly_limit_usd" in summary
|
||||
assert "daily_ok" in summary
|
||||
assert "monthly_ok" in summary
|
||||
|
||||
def test_summary_daily_ok_true_on_empty(self):
|
||||
"""daily_ok and monthly_ok should be True when empty."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
summary = tracker.get_summary()
|
||||
assert summary["daily_ok"] is True
|
||||
assert summary["monthly_ok"] is True
|
||||
|
||||
def test_summary_daily_ok_false_when_exceeded(self):
|
||||
"""daily_ok should be False when daily limit exceeded."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("openai", "gpt-4o", cost_usd=999.0)
|
||||
summary = tracker.get_summary()
|
||||
assert summary["daily_ok"] is False
|
||||
|
||||
def test_summary_monthly_ok_false_when_exceeded(self):
|
||||
"""monthly_ok should be False when monthly limit exceeded."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 10.0
|
||||
tracker.record_spend("openai", "gpt-4o", cost_usd=15.0)
|
||||
summary = tracker.get_summary()
|
||||
assert summary["monthly_ok"] is False
|
||||
|
||||
def test_summary_values_rounded(self):
|
||||
"""Summary values should be rounded appropriately."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("test", "model", cost_usd=1.123456789)
|
||||
summary = tracker.get_summary()
|
||||
# daily_usd should be rounded to 6 decimal places
|
||||
assert summary["daily_usd"] == 1.123457
|
||||
|
||||
def test_summary_with_disabled_limits(self):
|
||||
"""Summary should handle disabled limits (0)."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 0
|
||||
tracker.record_spend("test", "model", cost_usd=100.0)
|
||||
summary = tracker.get_summary()
|
||||
assert summary["daily_limit_usd"] == 0
|
||||
assert summary["monthly_limit_usd"] == 0
|
||||
assert summary["daily_ok"] is True
|
||||
assert summary["monthly_ok"] is True
|
||||
|
||||
|
||||
# ── Test BudgetTracker in-memory fallback ─────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerInMemoryFallback:
|
||||
"""Tests for in-memory fallback when DB is unavailable."""
|
||||
|
||||
def test_in_memory_records_persisted(self):
|
||||
"""Records should be stored in memory when DB is unavailable."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
# Force DB to appear unavailable
|
||||
tracker._db_ok = False
|
||||
tracker.record_spend("test", "model", cost_usd=0.01)
|
||||
assert len(tracker._in_memory) == 1
|
||||
assert tracker._in_memory[0].cost_usd == 0.01
|
||||
|
||||
def test_in_memory_query_spend(self):
|
||||
"""Query spend should work with in-memory fallback."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker._db_ok = False
|
||||
tracker.record_spend("test", "model", cost_usd=0.01)
|
||||
# Query should work from in-memory
|
||||
since_ts = (datetime.now(UTC) - timedelta(hours=1)).timestamp()
|
||||
result = tracker._query_spend(since_ts)
|
||||
assert result == 0.01
|
||||
|
||||
def test_in_memory_older_records_not_counted(self):
|
||||
"""In-memory records older than since_ts should not be counted."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker._db_ok = False
|
||||
old_ts = (datetime.now(UTC) - timedelta(days=2)).timestamp()
|
||||
tracker._in_memory.append(
|
||||
SpendRecord(old_ts, "test", "model", 0, 0, 1.0, "cloud")
|
||||
)
|
||||
# Query for records in last day
|
||||
since_ts = (datetime.now(UTC) - timedelta(days=1)).timestamp()
|
||||
result = tracker._query_spend(since_ts)
|
||||
assert result == 0.0
|
||||
|
||||
|
||||
# ── Test BudgetTracker thread safety ──────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerThreadSafety:
|
||||
"""Tests for thread-safe operations."""
|
||||
|
||||
def test_concurrent_record_spend(self):
|
||||
"""Multiple threads should safely record spend concurrently."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
def record_spends():
|
||||
try:
|
||||
for _ in range(10):
|
||||
cost = tracker.record_spend("test", "model", cost_usd=0.01)
|
||||
results.append(cost)
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [threading.Thread(target=record_spends) for _ in range(5)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert len(errors) == 0
|
||||
assert len(results) == 50
|
||||
assert tracker.get_daily_spend() == pytest.approx(0.50, abs=1e-9)
|
||||
|
||||
|
||||
# ── Test BudgetTracker edge cases ─────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerEdgeCases:
|
||||
"""Tests for edge cases and boundary conditions."""
|
||||
|
||||
def test_very_small_cost(self):
|
||||
"""Tracker should handle very small costs."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("test", "model", cost_usd=0.000001)
|
||||
assert tracker.get_daily_spend() == pytest.approx(0.000001, abs=1e-9)
|
||||
|
||||
def test_very_large_cost(self):
|
||||
"""Tracker should handle very large costs."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
tracker.record_spend("test", "model", cost_usd=1_000_000.0)
|
||||
assert tracker.get_daily_spend() == pytest.approx(1_000_000.0, abs=1e-9)
|
||||
|
||||
def test_many_records(self):
|
||||
"""Tracker should handle many records efficiently."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
for i in range(100):
|
||||
tracker.record_spend(f"provider_{i}", f"model_{i}", cost_usd=0.01)
|
||||
assert tracker.get_daily_spend() == pytest.approx(1.0, abs=1e-9)
|
||||
|
||||
def test_empty_provider_name(self):
|
||||
"""Tracker should handle empty provider name."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("", "model", cost_usd=0.01)
|
||||
assert cost == 0.01
|
||||
|
||||
def test_empty_model_name(self):
|
||||
"""Tracker should handle empty model name."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
cost = tracker.record_spend("provider", "", cost_usd=0.01)
|
||||
assert cost == 0.01
|
||||
|
||||
|
||||
# ── Test get_budget_tracker singleton ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestGetBudgetTrackerSingleton:
|
||||
"""Tests for the module-level BudgetTracker singleton."""
|
||||
|
||||
def test_returns_budget_tracker(self):
|
||||
"""Singleton should return a BudgetTracker instance."""
|
||||
import infrastructure.models.budget as bmod
|
||||
|
||||
bmod._budget_tracker = None
|
||||
tracker = get_budget_tracker()
|
||||
assert isinstance(tracker, BudgetTracker)
|
||||
|
||||
def test_returns_same_instance(self):
|
||||
"""Singleton should return the same instance."""
|
||||
import infrastructure.models.budget as bmod
|
||||
|
||||
bmod._budget_tracker = None
|
||||
t1 = get_budget_tracker()
|
||||
t2 = get_budget_tracker()
|
||||
assert t1 is t2
|
||||
|
||||
def test_singleton_persists_state(self):
|
||||
"""Singleton should persist state across calls."""
|
||||
import infrastructure.models.budget as bmod
|
||||
|
||||
bmod._budget_tracker = None
|
||||
tracker1 = get_budget_tracker()
|
||||
# Record spend
|
||||
tracker1.record_spend("test", "model", cost_usd=1.0)
|
||||
# Get singleton again
|
||||
tracker2 = get_budget_tracker()
|
||||
assert tracker1 is tracker2
|
||||
|
||||
|
||||
# ── Test BudgetTracker with mocked settings ───────────────────────────────────
|
||||
|
||||
|
||||
class TestBudgetTrackerWithMockedSettings:
|
||||
"""Tests using mocked settings for different scenarios."""
|
||||
|
||||
def test_high_daily_limit(self):
|
||||
"""Test with high daily limit."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 1000.0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 10000.0
|
||||
tracker.record_spend("test", "model", cost_usd=500.0)
|
||||
assert tracker.cloud_allowed() is True
|
||||
|
||||
def test_low_daily_limit(self):
|
||||
"""Test with low daily limit."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 1.0
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 100.0
|
||||
tracker.record_spend("test", "model", cost_usd=2.0)
|
||||
assert tracker.cloud_allowed() is False
|
||||
|
||||
def test_only_monthly_limit_enabled(self):
|
||||
"""Test with only monthly limit enabled."""
|
||||
tracker = BudgetTracker(db_path=":memory:")
|
||||
with patch("infrastructure.models.budget.settings") as mock_settings:
|
||||
mock_settings.tier_cloud_daily_budget_usd = 0 # Disabled
|
||||
mock_settings.tier_cloud_monthly_budget_usd = 50.0
|
||||
tracker.record_spend("test", "model", cost_usd=30.0)
|
||||
assert tracker.cloud_allowed() is True
|
||||
tracker.record_spend("test", "model", cost_usd=25.0)
|
||||
assert tracker.cloud_allowed() is False
|
||||
@@ -56,10 +56,12 @@ def test_run_triage(mock_gitea_client, mock_llm_client, mock_files):
|
||||
}
|
||||
}
|
||||
|
||||
with patch("scripts.llm_triage.PROMPT_PATH", mock_files / "scripts/deep_triage_prompt.md"), \
|
||||
patch("scripts.llm_triage.QUEUE_PATH", mock_files / ".loop/queue.json"), \
|
||||
patch("scripts.llm_triage.SUMMARY_PATH", mock_files / ".loop/retro/summary.json"), \
|
||||
patch("scripts.llm_triage.RETRO_PATH", mock_files / ".loop/retro/deep-triage.jsonl"):
|
||||
with (
|
||||
patch("scripts.llm_triage.PROMPT_PATH", mock_files / "scripts/deep_triage_prompt.md"),
|
||||
patch("scripts.llm_triage.QUEUE_PATH", mock_files / ".loop/queue.json"),
|
||||
patch("scripts.llm_triage.SUMMARY_PATH", mock_files / ".loop/retro/summary.json"),
|
||||
patch("scripts.llm_triage.RETRO_PATH", mock_files / ".loop/retro/deep-triage.jsonl"),
|
||||
):
|
||||
run_triage()
|
||||
|
||||
# Check that the queue and retro files were written
|
||||
|
||||
238
tests/sovereignty/test_auto_crystallizer.py
Normal file
238
tests/sovereignty/test_auto_crystallizer.py
Normal file
@@ -0,0 +1,238 @@
|
||||
"""Tests for the auto-crystallizer module.
|
||||
|
||||
Refs: #961, #953
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestCrystallizeReasoning:
|
||||
"""Tests for rule extraction from LLM reasoning chains."""
|
||||
|
||||
def test_extracts_threshold_rule(self):
|
||||
"""Extracts threshold-based rules from reasoning text."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
reasoning = "I chose to heal because health was below 30%. So I used a healing potion."
|
||||
rules = crystallize_reasoning(reasoning)
|
||||
assert len(rules) >= 1
|
||||
# Should detect the threshold pattern
|
||||
found = any("health" in r.condition.lower() and "30" in r.condition for r in rules)
|
||||
assert found, f"Expected threshold rule, got: {[r.condition for r in rules]}"
|
||||
|
||||
def test_extracts_comparison_rule(self):
|
||||
"""Extracts comparison operators from reasoning."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
reasoning = "The stamina_pct < 20 so I decided to rest."
|
||||
rules = crystallize_reasoning(reasoning)
|
||||
assert len(rules) >= 1
|
||||
found = any("stamina_pct" in r.condition and "<" in r.condition for r in rules)
|
||||
assert found, f"Expected comparison rule, got: {[r.condition for r in rules]}"
|
||||
|
||||
def test_extracts_choice_reason_rule(self):
|
||||
"""Extracts 'chose X because Y' patterns."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
reasoning = "I chose retreat because the enemy outnumbered us."
|
||||
rules = crystallize_reasoning(reasoning)
|
||||
assert len(rules) >= 1
|
||||
found = any(r.action == "retreat" for r in rules)
|
||||
assert found, f"Expected 'retreat' action, got: {[r.action for r in rules]}"
|
||||
|
||||
def test_deduplicates_rules(self):
|
||||
"""Same pattern extracted once, not twice."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
reasoning = (
|
||||
"I chose heal because health was below 30%. Again, health was below 30% so I healed."
|
||||
)
|
||||
rules = crystallize_reasoning(reasoning)
|
||||
ids = [r.id for r in rules]
|
||||
# Duplicate condition+action should produce same ID
|
||||
assert len(ids) == len(set(ids)), "Duplicate rules detected"
|
||||
|
||||
def test_empty_reasoning_returns_no_rules(self):
|
||||
"""Empty or unstructured text produces no rules."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
rules = crystallize_reasoning("")
|
||||
assert rules == []
|
||||
|
||||
rules = crystallize_reasoning("The weather is nice today.")
|
||||
assert rules == []
|
||||
|
||||
def test_rule_has_excerpt(self):
|
||||
"""Extracted rules include a reasoning excerpt for provenance."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
reasoning = "I chose attack because the enemy health was below 50%."
|
||||
rules = crystallize_reasoning(reasoning)
|
||||
assert len(rules) >= 1
|
||||
assert rules[0].reasoning_excerpt != ""
|
||||
|
||||
def test_context_stored_in_metadata(self):
|
||||
"""Context dict is stored in rule metadata."""
|
||||
from timmy.sovereignty.auto_crystallizer import crystallize_reasoning
|
||||
|
||||
context = {"game": "morrowind", "location": "balmora"}
|
||||
reasoning = "I chose to trade because gold_amount > 100."
|
||||
rules = crystallize_reasoning(reasoning, context=context)
|
||||
assert len(rules) >= 1
|
||||
assert rules[0].metadata.get("game") == "morrowind"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestRule:
|
||||
"""Tests for the Rule dataclass."""
|
||||
|
||||
def test_initial_state(self):
|
||||
"""New rules start with default confidence and no applications."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule
|
||||
|
||||
rule = Rule(id="test", condition="hp < 30", action="heal")
|
||||
assert rule.confidence == 0.5
|
||||
assert rule.times_applied == 0
|
||||
assert rule.times_succeeded == 0
|
||||
assert not rule.is_reliable
|
||||
|
||||
def test_success_rate(self):
|
||||
"""Success rate is calculated correctly."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule
|
||||
|
||||
rule = Rule(id="test", condition="hp < 30", action="heal")
|
||||
rule.times_applied = 10
|
||||
rule.times_succeeded = 8
|
||||
assert rule.success_rate == 0.8
|
||||
|
||||
def test_is_reliable(self):
|
||||
"""Rule becomes reliable with high confidence + enough applications."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule
|
||||
|
||||
rule = Rule(
|
||||
id="test",
|
||||
condition="hp < 30",
|
||||
action="heal",
|
||||
confidence=0.85,
|
||||
times_applied=5,
|
||||
times_succeeded=4,
|
||||
)
|
||||
assert rule.is_reliable
|
||||
|
||||
def test_not_reliable_low_confidence(self):
|
||||
"""Rule is not reliable with low confidence."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule
|
||||
|
||||
rule = Rule(
|
||||
id="test",
|
||||
condition="hp < 30",
|
||||
action="heal",
|
||||
confidence=0.5,
|
||||
times_applied=10,
|
||||
times_succeeded=8,
|
||||
)
|
||||
assert not rule.is_reliable
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestRuleStore:
|
||||
"""Tests for the RuleStore persistence layer."""
|
||||
|
||||
def test_add_and_retrieve(self, tmp_path):
|
||||
"""Rules can be added and retrieved."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
rule = Rule(id="r1", condition="hp < 30", action="heal")
|
||||
store.add(rule)
|
||||
|
||||
retrieved = store.get("r1")
|
||||
assert retrieved is not None
|
||||
assert retrieved.condition == "hp < 30"
|
||||
|
||||
def test_persist_and_reload(self, tmp_path):
|
||||
"""Rules survive persist → reload cycle."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
path = tmp_path / "strategy.json"
|
||||
store = RuleStore(path=path)
|
||||
store.add(Rule(id="r1", condition="hp < 30", action="heal"))
|
||||
store.add(Rule(id="r2", condition="mana > 50", action="cast"))
|
||||
|
||||
# Create a new store from the same file
|
||||
store2 = RuleStore(path=path)
|
||||
assert len(store2) == 2
|
||||
assert store2.get("r1") is not None
|
||||
assert store2.get("r2") is not None
|
||||
|
||||
def test_record_application_success(self, tmp_path):
|
||||
"""Recording a successful application boosts confidence."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
store.add(Rule(id="r1", condition="hp < 30", action="heal", confidence=0.5))
|
||||
|
||||
store.record_application("r1", succeeded=True)
|
||||
rule = store.get("r1")
|
||||
assert rule.times_applied == 1
|
||||
assert rule.times_succeeded == 1
|
||||
assert rule.confidence > 0.5
|
||||
|
||||
def test_record_application_failure(self, tmp_path):
|
||||
"""Recording a failed application penalizes confidence."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
store.add(Rule(id="r1", condition="hp < 30", action="heal", confidence=0.8))
|
||||
|
||||
store.record_application("r1", succeeded=False)
|
||||
rule = store.get("r1")
|
||||
assert rule.times_applied == 1
|
||||
assert rule.times_succeeded == 0
|
||||
assert rule.confidence < 0.8
|
||||
|
||||
def test_add_many_counts_new(self, tmp_path):
|
||||
"""add_many returns count of genuinely new rules."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
store.add(Rule(id="r1", condition="hp < 30", action="heal"))
|
||||
|
||||
new_rules = [
|
||||
Rule(id="r1", condition="hp < 30", action="heal"), # existing
|
||||
Rule(id="r2", condition="mana > 50", action="cast"), # new
|
||||
]
|
||||
added = store.add_many(new_rules)
|
||||
assert added == 1
|
||||
assert len(store) == 2
|
||||
|
||||
def test_find_matching_returns_reliable_only(self, tmp_path):
|
||||
"""find_matching only returns rules above confidence threshold."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
store.add(
|
||||
Rule(
|
||||
id="r1",
|
||||
condition="health low",
|
||||
action="heal",
|
||||
confidence=0.9,
|
||||
times_applied=5,
|
||||
times_succeeded=4,
|
||||
)
|
||||
)
|
||||
store.add(
|
||||
Rule(
|
||||
id="r2",
|
||||
condition="health low",
|
||||
action="flee",
|
||||
confidence=0.3,
|
||||
times_applied=1,
|
||||
times_succeeded=0,
|
||||
)
|
||||
)
|
||||
|
||||
matches = store.find_matching({"health": "low"})
|
||||
assert len(matches) == 1
|
||||
assert matches[0].id == "r1"
|
||||
165
tests/sovereignty/test_graduation.py
Normal file
165
tests/sovereignty/test_graduation.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""Tests for the graduation test runner.
|
||||
|
||||
Refs: #953 (Graduation Test)
|
||||
"""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestConditionResults:
|
||||
"""Tests for individual graduation condition evaluations."""
|
||||
|
||||
def test_economic_independence_pass(self):
|
||||
"""Passes when sats earned exceeds sats spent."""
|
||||
from timmy.sovereignty.graduation import evaluate_economic_independence
|
||||
|
||||
result = evaluate_economic_independence(sats_earned=100.0, sats_spent=50.0)
|
||||
assert result.passed is True
|
||||
assert result.actual == 50.0 # net
|
||||
assert "Earned: 100.0" in result.detail
|
||||
|
||||
def test_economic_independence_fail_net_negative(self):
|
||||
"""Fails when spending exceeds earnings."""
|
||||
from timmy.sovereignty.graduation import evaluate_economic_independence
|
||||
|
||||
result = evaluate_economic_independence(sats_earned=10.0, sats_spent=50.0)
|
||||
assert result.passed is False
|
||||
|
||||
def test_economic_independence_fail_zero_earnings(self):
|
||||
"""Fails when earnings are zero even if spending is zero."""
|
||||
from timmy.sovereignty.graduation import evaluate_economic_independence
|
||||
|
||||
result = evaluate_economic_independence(sats_earned=0.0, sats_spent=0.0)
|
||||
assert result.passed is False
|
||||
|
||||
def test_operational_independence_pass(self):
|
||||
"""Passes when uptime meets threshold and no interventions."""
|
||||
from timmy.sovereignty.graduation import evaluate_operational_independence
|
||||
|
||||
result = evaluate_operational_independence(uptime_hours=24.0, human_interventions=0)
|
||||
assert result.passed is True
|
||||
|
||||
def test_operational_independence_fail_low_uptime(self):
|
||||
"""Fails when uptime is below threshold."""
|
||||
from timmy.sovereignty.graduation import evaluate_operational_independence
|
||||
|
||||
result = evaluate_operational_independence(uptime_hours=20.0, human_interventions=0)
|
||||
assert result.passed is False
|
||||
|
||||
def test_operational_independence_fail_interventions(self):
|
||||
"""Fails when there are human interventions."""
|
||||
from timmy.sovereignty.graduation import evaluate_operational_independence
|
||||
|
||||
result = evaluate_operational_independence(uptime_hours=24.0, human_interventions=2)
|
||||
assert result.passed is False
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestGraduationReport:
|
||||
"""Tests for the GraduationReport rendering."""
|
||||
|
||||
def test_to_dict(self):
|
||||
"""Report serializes to dict correctly."""
|
||||
from timmy.sovereignty.graduation import ConditionResult, GraduationReport
|
||||
|
||||
report = GraduationReport(
|
||||
all_passed=False,
|
||||
conditions=[
|
||||
ConditionResult(name="Test", passed=True, actual=0, target=0, unit=" calls")
|
||||
],
|
||||
)
|
||||
d = report.to_dict()
|
||||
assert d["all_passed"] is False
|
||||
assert len(d["conditions"]) == 1
|
||||
assert d["conditions"][0]["name"] == "Test"
|
||||
|
||||
def test_to_markdown(self):
|
||||
"""Report renders to readable markdown."""
|
||||
from timmy.sovereignty.graduation import ConditionResult, GraduationReport
|
||||
|
||||
report = GraduationReport(
|
||||
all_passed=True,
|
||||
conditions=[
|
||||
ConditionResult(name="Perception", passed=True, actual=0, target=0),
|
||||
ConditionResult(name="Decision", passed=True, actual=3, target=5),
|
||||
],
|
||||
)
|
||||
md = report.to_markdown()
|
||||
assert "PASSED" in md
|
||||
assert "Perception" in md
|
||||
assert "Decision" in md
|
||||
assert "falsework" in md.lower()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestRunGraduationTest:
|
||||
"""Tests for the full graduation test runner."""
|
||||
|
||||
@patch("timmy.sovereignty.graduation.evaluate_perception_independence")
|
||||
@patch("timmy.sovereignty.graduation.evaluate_decision_independence")
|
||||
@patch("timmy.sovereignty.graduation.evaluate_narration_independence")
|
||||
def test_all_pass(self, mock_narr, mock_dec, mock_perc):
|
||||
"""Full graduation passes when all 5 conditions pass."""
|
||||
from timmy.sovereignty.graduation import ConditionResult, run_graduation_test
|
||||
|
||||
mock_perc.return_value = ConditionResult(name="Perception", passed=True, actual=0, target=0)
|
||||
mock_dec.return_value = ConditionResult(name="Decision", passed=True, actual=3, target=5)
|
||||
mock_narr.return_value = ConditionResult(name="Narration", passed=True, actual=0, target=0)
|
||||
|
||||
report = run_graduation_test(
|
||||
sats_earned=100.0,
|
||||
sats_spent=50.0,
|
||||
uptime_hours=24.0,
|
||||
human_interventions=0,
|
||||
)
|
||||
|
||||
assert report.all_passed is True
|
||||
assert len(report.conditions) == 5
|
||||
assert all(c.passed for c in report.conditions)
|
||||
|
||||
@patch("timmy.sovereignty.graduation.evaluate_perception_independence")
|
||||
@patch("timmy.sovereignty.graduation.evaluate_decision_independence")
|
||||
@patch("timmy.sovereignty.graduation.evaluate_narration_independence")
|
||||
def test_partial_fail(self, mock_narr, mock_dec, mock_perc):
|
||||
"""Graduation fails when any single condition fails."""
|
||||
from timmy.sovereignty.graduation import ConditionResult, run_graduation_test
|
||||
|
||||
mock_perc.return_value = ConditionResult(name="Perception", passed=True, actual=0, target=0)
|
||||
mock_dec.return_value = ConditionResult(name="Decision", passed=False, actual=10, target=5)
|
||||
mock_narr.return_value = ConditionResult(name="Narration", passed=True, actual=0, target=0)
|
||||
|
||||
report = run_graduation_test(
|
||||
sats_earned=100.0,
|
||||
sats_spent=50.0,
|
||||
uptime_hours=24.0,
|
||||
human_interventions=0,
|
||||
)
|
||||
|
||||
assert report.all_passed is False
|
||||
|
||||
def test_persist_report(self, tmp_path):
|
||||
"""Graduation report persists to JSON file."""
|
||||
from timmy.sovereignty.graduation import (
|
||||
ConditionResult,
|
||||
GraduationReport,
|
||||
persist_graduation_report,
|
||||
)
|
||||
|
||||
report = GraduationReport(
|
||||
all_passed=False,
|
||||
conditions=[ConditionResult(name="Test", passed=False, actual=5, target=0)],
|
||||
)
|
||||
|
||||
with patch("timmy.sovereignty.graduation.settings") as mock_settings:
|
||||
mock_settings.repo_root = str(tmp_path)
|
||||
path = persist_graduation_report(report)
|
||||
|
||||
assert path.exists()
|
||||
import json
|
||||
|
||||
with open(path) as f:
|
||||
data = json.load(f)
|
||||
assert data["all_passed"] is False
|
||||
@@ -196,9 +196,10 @@ class TestPerceptionCacheMatch:
|
||||
screenshot = np.array([[5, 6], [7, 8]])
|
||||
result = cache.match(screenshot)
|
||||
|
||||
# Note: current implementation uses > 0.85, so exactly 0.85 returns None state
|
||||
# Implementation uses >= 0.85 (inclusive threshold)
|
||||
assert result.confidence == 0.85
|
||||
assert result.state is None
|
||||
assert result.state is not None
|
||||
assert result.state["template_name"] == "threshold_match"
|
||||
|
||||
@patch("timmy.sovereignty.perception_cache.cv2")
|
||||
def test_match_just_above_threshold(self, mock_cv2, tmp_path):
|
||||
@@ -283,10 +284,12 @@ class TestPerceptionCachePersist:
|
||||
|
||||
templates_path = tmp_path / "templates.json"
|
||||
cache = PerceptionCache(templates_path=templates_path)
|
||||
cache.add([
|
||||
Template(name="template1", image=np.array([[1]]), threshold=0.85),
|
||||
Template(name="template2", image=np.array([[2]]), threshold=0.90),
|
||||
])
|
||||
cache.add(
|
||||
[
|
||||
Template(name="template1", image=np.array([[1]]), threshold=0.85),
|
||||
Template(name="template2", image=np.array([[2]]), threshold=0.90),
|
||||
]
|
||||
)
|
||||
|
||||
cache.persist()
|
||||
|
||||
@@ -312,8 +315,10 @@ class TestPerceptionCachePersist:
|
||||
with open(templates_path) as f:
|
||||
data = json.load(f)
|
||||
|
||||
assert "image" not in data[0]
|
||||
assert set(data[0].keys()) == {"name", "threshold"}
|
||||
assert "image" not in data[0] # raw image array is NOT in JSON
|
||||
# image_path is stored for .npy file reference
|
||||
assert "name" in data[0]
|
||||
assert "threshold" in data[0]
|
||||
|
||||
|
||||
class TestPerceptionCacheLoad:
|
||||
@@ -338,8 +343,8 @@ class TestPerceptionCacheLoad:
|
||||
assert len(cache2.templates) == 1
|
||||
assert cache2.templates[0].name == "loaded"
|
||||
assert cache2.templates[0].threshold == 0.88
|
||||
# Note: images are loaded as empty arrays per current implementation
|
||||
assert cache2.templates[0].image.size == 0
|
||||
# Images are now persisted as .npy files and loaded back
|
||||
assert cache2.templates[0].image.size > 0
|
||||
|
||||
def test_load_empty_file(self, tmp_path):
|
||||
"""Load handles empty template list in file."""
|
||||
|
||||
239
tests/sovereignty/test_sovereignty_loop.py
Normal file
239
tests/sovereignty/test_sovereignty_loop.py
Normal file
@@ -0,0 +1,239 @@
|
||||
"""Tests for the sovereignty loop orchestrator.
|
||||
|
||||
Refs: #953
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
class TestSovereignPerceive:
|
||||
"""Tests for sovereign_perceive (perception layer)."""
|
||||
|
||||
async def test_cache_hit_skips_vlm(self):
|
||||
"""When cache has high-confidence match, VLM is not called."""
|
||||
from timmy.sovereignty.perception_cache import CacheResult
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_perceive
|
||||
|
||||
cache = MagicMock()
|
||||
cache.match.return_value = CacheResult(
|
||||
confidence=0.95, state={"template_name": "health_bar"}
|
||||
)
|
||||
|
||||
vlm = AsyncMock()
|
||||
screenshot = MagicMock()
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
) as mock_emit:
|
||||
result = await sovereign_perceive(screenshot, cache, vlm)
|
||||
|
||||
assert result == {"template_name": "health_bar"}
|
||||
vlm.analyze.assert_not_called()
|
||||
mock_emit.assert_called_once_with("perception_cache_hit", session_id="")
|
||||
|
||||
async def test_cache_miss_calls_vlm_and_crystallizes(self):
|
||||
"""On cache miss, VLM is called and output is crystallized."""
|
||||
from timmy.sovereignty.perception_cache import CacheResult
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_perceive
|
||||
|
||||
cache = MagicMock()
|
||||
cache.match.return_value = CacheResult(confidence=0.3, state=None)
|
||||
|
||||
vlm = AsyncMock()
|
||||
vlm.analyze.return_value = {"items": []}
|
||||
|
||||
screenshot = MagicMock()
|
||||
crystallize_fn = MagicMock(return_value=[])
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
):
|
||||
await sovereign_perceive(screenshot, cache, vlm, crystallize_fn=crystallize_fn)
|
||||
|
||||
vlm.analyze.assert_called_once_with(screenshot)
|
||||
crystallize_fn.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
class TestSovereignDecide:
|
||||
"""Tests for sovereign_decide (decision layer)."""
|
||||
|
||||
async def test_rule_hit_skips_llm(self, tmp_path):
|
||||
"""Reliable rule match bypasses the LLM."""
|
||||
from timmy.sovereignty.auto_crystallizer import Rule, RuleStore
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_decide
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
store.add(
|
||||
Rule(
|
||||
id="r1",
|
||||
condition="health low",
|
||||
action="heal",
|
||||
confidence=0.9,
|
||||
times_applied=5,
|
||||
times_succeeded=4,
|
||||
)
|
||||
)
|
||||
|
||||
llm = AsyncMock()
|
||||
context = {"health": "low", "mana": 50}
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
):
|
||||
result = await sovereign_decide(context, llm, rule_store=store)
|
||||
|
||||
assert result["action"] == "heal"
|
||||
assert result["source"] == "crystallized_rule"
|
||||
llm.reason.assert_not_called()
|
||||
|
||||
async def test_no_rule_calls_llm_and_crystallizes(self, tmp_path):
|
||||
"""Without matching rules, LLM is called and reasoning is crystallized."""
|
||||
from timmy.sovereignty.auto_crystallizer import RuleStore
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_decide
|
||||
|
||||
store = RuleStore(path=tmp_path / "strategy.json")
|
||||
|
||||
llm = AsyncMock()
|
||||
llm.reason.return_value = {
|
||||
"action": "attack",
|
||||
"reasoning": "I chose attack because enemy_health was below 50%.",
|
||||
}
|
||||
|
||||
context = {"enemy_health": 45}
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
):
|
||||
result = await sovereign_decide(context, llm, rule_store=store)
|
||||
|
||||
assert result["action"] == "attack"
|
||||
llm.reason.assert_called_once_with(context)
|
||||
# The reasoning should have been crystallized (threshold pattern detected)
|
||||
assert len(store) > 0
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
class TestSovereignNarrate:
|
||||
"""Tests for sovereign_narrate (narration layer)."""
|
||||
|
||||
async def test_template_hit_skips_llm(self):
|
||||
"""Known event type uses template without LLM."""
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_narrate
|
||||
|
||||
template_store = {
|
||||
"combat_start": "Battle begins against {enemy}!",
|
||||
}
|
||||
|
||||
llm = AsyncMock()
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
) as mock_emit:
|
||||
result = await sovereign_narrate(
|
||||
{"type": "combat_start", "enemy": "Cliff Racer"},
|
||||
llm=llm,
|
||||
template_store=template_store,
|
||||
)
|
||||
|
||||
assert result == "Battle begins against Cliff Racer!"
|
||||
llm.narrate.assert_not_called()
|
||||
mock_emit.assert_called_once_with("narration_template", session_id="")
|
||||
|
||||
async def test_unknown_event_calls_llm(self):
|
||||
"""Unknown event type falls through to LLM and crystallizes template."""
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_narrate
|
||||
|
||||
template_store = {}
|
||||
|
||||
llm = AsyncMock()
|
||||
llm.narrate.return_value = "You discovered a hidden cave in the mountains."
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
):
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop._crystallize_narration_template"
|
||||
) as mock_cryst:
|
||||
result = await sovereign_narrate(
|
||||
{"type": "discovery", "location": "mountains"},
|
||||
llm=llm,
|
||||
template_store=template_store,
|
||||
)
|
||||
|
||||
assert result == "You discovered a hidden cave in the mountains."
|
||||
llm.narrate.assert_called_once()
|
||||
mock_cryst.assert_called_once()
|
||||
|
||||
async def test_no_llm_returns_default(self):
|
||||
"""Without LLM and no template, returns a default narration."""
|
||||
from timmy.sovereignty.sovereignty_loop import sovereign_narrate
|
||||
|
||||
with patch(
|
||||
"timmy.sovereignty.sovereignty_loop.emit_sovereignty_event",
|
||||
new_callable=AsyncMock,
|
||||
):
|
||||
result = await sovereign_narrate(
|
||||
{"type": "unknown_event"},
|
||||
llm=None,
|
||||
template_store={},
|
||||
)
|
||||
|
||||
assert "[unknown_event]" in result
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
class TestSovereigntyEnforcedDecorator:
|
||||
"""Tests for the @sovereignty_enforced decorator."""
|
||||
|
||||
async def test_cache_hit_skips_function(self):
|
||||
"""Decorator returns cached value without calling the wrapped function."""
|
||||
from timmy.sovereignty.sovereignty_loop import sovereignty_enforced
|
||||
|
||||
call_count = 0
|
||||
|
||||
@sovereignty_enforced(
|
||||
layer="decision",
|
||||
cache_check=lambda a, kw: "cached_result",
|
||||
)
|
||||
async def expensive_fn():
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
return "expensive_result"
|
||||
|
||||
with patch("timmy.sovereignty.sovereignty_loop.get_metrics_store") as mock_store:
|
||||
mock_store.return_value = MagicMock()
|
||||
result = await expensive_fn()
|
||||
|
||||
assert result == "cached_result"
|
||||
assert call_count == 0
|
||||
|
||||
async def test_cache_miss_runs_function(self):
|
||||
"""Decorator calls function when cache returns None."""
|
||||
from timmy.sovereignty.sovereignty_loop import sovereignty_enforced
|
||||
|
||||
@sovereignty_enforced(
|
||||
layer="decision",
|
||||
cache_check=lambda a, kw: None,
|
||||
)
|
||||
async def expensive_fn():
|
||||
return "computed_result"
|
||||
|
||||
with patch("timmy.sovereignty.sovereignty_loop.get_metrics_store") as mock_store:
|
||||
mock_store.return_value = MagicMock()
|
||||
result = await expensive_fn()
|
||||
|
||||
assert result == "computed_result"
|
||||
@@ -287,6 +287,148 @@ class TestJotNote:
|
||||
assert "body is empty" in jot_note("title", " ")
|
||||
|
||||
|
||||
class TestHotMemoryTimestamp:
|
||||
"""Tests for Working RAM auto-updating timestamp (issue #10)."""
|
||||
|
||||
def test_read_includes_last_updated_when_facts_exist(self, tmp_path):
|
||||
"""HotMemory.read() includes a 'Last updated' timestamp when DB has facts."""
|
||||
db_path = tmp_path / "memory.db"
|
||||
|
||||
with (
|
||||
patch("timmy.memory.db.DB_PATH", db_path),
|
||||
patch("timmy.memory.crud.get_connection") as mock_conn,
|
||||
):
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
|
||||
real_conn = sqlite3.connect(str(db_path))
|
||||
real_conn.row_factory = sqlite3.Row
|
||||
real_conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
memory_type TEXT NOT NULL DEFAULT 'fact',
|
||||
source TEXT NOT NULL DEFAULT 'agent',
|
||||
embedding TEXT, metadata TEXT, source_hash TEXT,
|
||||
agent_id TEXT, task_id TEXT, session_id TEXT,
|
||||
confidence REAL NOT NULL DEFAULT 0.8,
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
last_accessed TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
""")
|
||||
real_conn.execute(
|
||||
"INSERT INTO memories (id, content, memory_type, source, created_at) "
|
||||
"VALUES ('1', 'User prefers dark mode', 'fact', 'system', '2026-03-20T10:00:00+00:00')"
|
||||
)
|
||||
real_conn.commit()
|
||||
|
||||
@contextmanager
|
||||
def fake_get_connection():
|
||||
yield real_conn
|
||||
|
||||
mock_conn.side_effect = fake_get_connection
|
||||
|
||||
hot = HotMemory()
|
||||
result = hot.read()
|
||||
|
||||
assert "> Last updated:" in result
|
||||
assert "2026-03-20" in result
|
||||
assert "User prefers dark mode" in result
|
||||
|
||||
def test_read_timestamp_reflects_most_recent_memory(self, tmp_path):
|
||||
"""The timestamp in HotMemory.read() matches the latest memory's created_at."""
|
||||
db_path = tmp_path / "memory.db"
|
||||
|
||||
with patch("timmy.memory.crud.get_connection") as mock_conn:
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
|
||||
real_conn = sqlite3.connect(str(db_path))
|
||||
real_conn.row_factory = sqlite3.Row
|
||||
real_conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
memory_type TEXT NOT NULL DEFAULT 'fact',
|
||||
source TEXT NOT NULL DEFAULT 'agent',
|
||||
embedding TEXT, metadata TEXT, source_hash TEXT,
|
||||
agent_id TEXT, task_id TEXT, session_id TEXT,
|
||||
confidence REAL NOT NULL DEFAULT 0.8,
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
last_accessed TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
""")
|
||||
# Older fact
|
||||
real_conn.execute(
|
||||
"INSERT INTO memories (id, content, memory_type, source, created_at) "
|
||||
"VALUES ('1', 'old fact', 'fact', 'system', '2026-03-15T08:00:00+00:00')"
|
||||
)
|
||||
# Newer fact — this should be reflected in the timestamp
|
||||
real_conn.execute(
|
||||
"INSERT INTO memories (id, content, memory_type, source, created_at) "
|
||||
"VALUES ('2', 'new fact', 'fact', 'system', '2026-03-23T14:30:00+00:00')"
|
||||
)
|
||||
real_conn.commit()
|
||||
|
||||
@contextmanager
|
||||
def fake_get_connection():
|
||||
yield real_conn
|
||||
|
||||
mock_conn.side_effect = fake_get_connection
|
||||
|
||||
hot = HotMemory()
|
||||
result = hot.read()
|
||||
|
||||
assert "2026-03-23" in result
|
||||
assert "> Last updated:" in result
|
||||
|
||||
def test_read_falls_back_to_file_when_db_empty(self, tmp_path):
|
||||
"""HotMemory.read() falls back to MEMORY.md when DB has no facts or reflections."""
|
||||
mem_file = tmp_path / "MEMORY.md"
|
||||
mem_file.write_text("# Timmy Hot Memory\n\n## Current Status\n\nOperational\n")
|
||||
|
||||
with patch("timmy.memory.crud.get_connection") as mock_conn:
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
|
||||
db_path = tmp_path / "empty.db"
|
||||
real_conn = sqlite3.connect(str(db_path))
|
||||
real_conn.row_factory = sqlite3.Row
|
||||
real_conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
content TEXT NOT NULL,
|
||||
memory_type TEXT NOT NULL DEFAULT 'fact',
|
||||
source TEXT NOT NULL DEFAULT 'agent',
|
||||
embedding TEXT, metadata TEXT, source_hash TEXT,
|
||||
agent_id TEXT, task_id TEXT, session_id TEXT,
|
||||
confidence REAL NOT NULL DEFAULT 0.8,
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
last_accessed TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
""")
|
||||
real_conn.commit()
|
||||
|
||||
@contextmanager
|
||||
def fake_get_connection():
|
||||
yield real_conn
|
||||
|
||||
mock_conn.side_effect = fake_get_connection
|
||||
|
||||
hot = HotMemory()
|
||||
hot.path = mem_file
|
||||
result = hot.read()
|
||||
|
||||
assert "Operational" in result
|
||||
assert "> Last updated:" not in result
|
||||
|
||||
|
||||
class TestLogDecision:
|
||||
"""Tests for log_decision() artifact tool."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user