Compare commits
13 Commits
perplexity
...
burn/583-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
794cfc96f9 | ||
| c64eb5e571 | |||
| c73dc96d70 | |||
| 07a9b91a6f | |||
| 9becaa65e7 | |||
| b51a27ff22 | |||
| 8e91e114e6 | |||
| cb95b2567c | |||
| dcf97b5d8f | |||
|
|
4beae6e6c6 | ||
| 9aaabb7d37 | |||
| ac812179bf | |||
| 0cc91443ab |
@@ -20,5 +20,5 @@ jobs:
|
||||
echo "PASS: All files parse"
|
||||
- name: Secret scan
|
||||
run: |
|
||||
if grep -rE 'sk-or-|sk-ant-|ghp_|AKIA' . --include='*.yml' --include='*.py' --include='*.sh' 2>/dev/null | grep -v .gitea; then exit 1; fi
|
||||
if grep -rE 'sk-or-|sk-ant-|ghp_|AKIA' . --include='*.yml' --include='*.py' --include='*.sh' 2>/dev/null | grep -v '.gitea' | grep -v 'detect_secrets' | grep -v 'test_trajectory_sanitize'; then exit 1; fi
|
||||
echo "PASS: No secrets"
|
||||
|
||||
@@ -209,7 +209,7 @@ skills:
|
||||
#
|
||||
# fallback_model:
|
||||
# provider: openrouter
|
||||
# model: anthropic/claude-sonnet-4
|
||||
# model: google/gemini-2.5-pro # was anthropic/claude-sonnet-4 — BANNED
|
||||
#
|
||||
# ── Smart Model Routing ────────────────────────────────────────────────
|
||||
# Optional cheap-vs-strong routing for simple turns.
|
||||
|
||||
75
docs/HERMES_MAXI_MANIFESTO.md
Normal file
75
docs/HERMES_MAXI_MANIFESTO.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Hermes Maxi Manifesto
|
||||
|
||||
_Adopted 2026-04-12. This document is the canonical statement of the Timmy Foundation's infrastructure philosophy._
|
||||
|
||||
## The Decision
|
||||
|
||||
We are Hermes maxis. One harness. One truth. No intermediary gateway layers.
|
||||
|
||||
Hermes handles everything:
|
||||
- **Cognitive core** — reasoning, planning, tool use
|
||||
- **Channels** — Telegram, Discord, Nostr, Matrix (direct, not via gateway)
|
||||
- **Dispatch** — task routing, agent coordination, swarm management
|
||||
- **Memory** — MemPalace, sovereign SQLite+FTS5 store, trajectory export
|
||||
- **Cron** — heartbeat, morning reports, nightly retros
|
||||
- **Health** — process monitoring, fleet status, self-healing
|
||||
|
||||
## What This Replaces
|
||||
|
||||
OpenClaw was evaluated as a gateway layer (March–April 2026). The assessment:
|
||||
|
||||
| Capability | OpenClaw | Hermes Native |
|
||||
|-----------|----------|---------------|
|
||||
| Multi-channel comms | Built-in | Direct integration per channel |
|
||||
| Persistent memory | SQLite (basic) | MemPalace + FTS5 + trajectory export |
|
||||
| Cron/scheduling | Native cron | Huey task queue + launchd |
|
||||
| Multi-agent sessions | Session routing | Wizard fleet + dispatch router |
|
||||
| Procedural memory | None | Sovereign Memory Store |
|
||||
| Model sovereignty | Requires external provider | Ollama local-first |
|
||||
| Identity | Configurable persona | SOUL.md + Bitcoin inscription |
|
||||
|
||||
The governance concern (founder joined OpenAI, Feb 2026) sealed the decision, but the technical case was already clear: OpenClaw adds a layer without adding capability that Hermes doesn't already have or can't build natively.
|
||||
|
||||
## The Principle
|
||||
|
||||
Every external dependency is temporary falsework. If it can be built locally, it must be built locally. The target is a $0 cloud bill with full operational capability.
|
||||
|
||||
This applies to:
|
||||
- **Agent harness** — Hermes, not OpenClaw/Claude Code/Cursor
|
||||
- **Inference** — Ollama + local models, not cloud APIs
|
||||
- **Data** — SQLite + FTS5, not managed databases
|
||||
- **Hosting** — Hermes VPS + Mac M3 Max, not cloud platforms
|
||||
- **Identity** — Bitcoin inscription + SOUL.md, not OAuth providers
|
||||
|
||||
## Exceptions
|
||||
|
||||
Cloud services are permitted as temporary scaffolding when:
|
||||
1. The local alternative doesn't exist yet
|
||||
2. There's a concrete plan (with a Gitea issue) to bring it local
|
||||
3. The dependency is isolated and can be swapped without architectural changes
|
||||
|
||||
Every cloud dependency must have a `[FALSEWORK]` label in the issue tracker.
|
||||
|
||||
## Enforcement
|
||||
|
||||
- `BANNED_PROVIDERS.md` lists permanently banned providers (Anthropic)
|
||||
- Pre-commit hooks scan for banned provider references
|
||||
- The Swarm Governor enforces PR discipline
|
||||
- The Conflict Detector catches sibling collisions
|
||||
- All of these are stdlib-only Python with zero external dependencies
|
||||
|
||||
## History
|
||||
|
||||
- 2026-03-28: OpenClaw evaluation spike filed (timmy-home #19)
|
||||
- 2026-03-28: OpenClaw Bootstrap epic created (timmy-config #51–#63)
|
||||
- 2026-03-28: Governance concern flagged (founder → OpenAI)
|
||||
- 2026-04-09: Anthropic banned (timmy-config PR #440)
|
||||
- 2026-04-12: OpenClaw purged — Hermes maxi directive adopted
|
||||
- timmy-config PR #487 (7 files, merged)
|
||||
- timmy-home PR #595 (3 files, merged)
|
||||
- the-nexus PRs #1278, #1279 (merged)
|
||||
- 2 issues closed, 27 historical issues preserved
|
||||
|
||||
---
|
||||
|
||||
_"The clean pattern is to separate identity, routing, live task state, durable memory, reusable procedure, and artifact truth. Hermes does all six."_
|
||||
70
docs/RUNBOOK_INDEX.md
Normal file
70
docs/RUNBOOK_INDEX.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Operational Runbook Index
|
||||
|
||||
Last updated: 2026-04-13
|
||||
|
||||
Quick-reference index for common operational tasks across the Timmy Foundation infrastructure.
|
||||
|
||||
## Fleet Operations
|
||||
|
||||
| Task | Location | Command/Procedure |
|
||||
|------|----------|-------------------|
|
||||
| Deploy fleet update | fleet-ops | `ansible-playbook playbooks/provision_and_deploy.yml --ask-vault-pass` |
|
||||
| Check fleet health | fleet-ops | `python3 scripts/fleet_readiness.py` |
|
||||
| Agent scorecard | fleet-ops | `python3 scripts/agent_scorecard.py` |
|
||||
| View fleet manifest | fleet-ops | `cat manifest.yaml` |
|
||||
|
||||
## the-nexus (Frontend + Brain)
|
||||
|
||||
| Task | Location | Command/Procedure |
|
||||
|------|----------|-------------------|
|
||||
| Run tests | the-nexus | `pytest tests/` |
|
||||
| Validate repo integrity | the-nexus | `python3 scripts/repo_truth_guard.py` |
|
||||
| Check swarm governor | the-nexus | `python3 bin/swarm_governor.py --status` |
|
||||
| Start dev server | the-nexus | `python3 server.py` |
|
||||
| Run deep dive pipeline | the-nexus | `cd intelligence/deepdive && python3 pipeline.py` |
|
||||
|
||||
## timmy-config (Control Plane)
|
||||
|
||||
| Task | Location | Command/Procedure |
|
||||
|------|----------|-------------------|
|
||||
| Run Ansible deploy | timmy-config | `cd ansible && ansible-playbook playbooks/site.yml` |
|
||||
| Scan for banned providers | timmy-config | `python3 bin/banned_provider_scan.py` |
|
||||
| Check merge conflicts | timmy-config | `python3 bin/conflict_detector.py` |
|
||||
| Muda audit | timmy-config | `bash fleet/muda-audit.sh` |
|
||||
|
||||
## hermes-agent (Agent Framework)
|
||||
|
||||
| Task | Location | Command/Procedure |
|
||||
|------|----------|-------------------|
|
||||
| Start agent | hermes-agent | `python3 run_agent.py` |
|
||||
| Check provider allowlist | hermes-agent | `python3 tools/provider_allowlist.py --check` |
|
||||
| Run test suite | hermes-agent | `pytest` |
|
||||
|
||||
## Incident Response
|
||||
|
||||
### Agent Down
|
||||
1. Check health endpoint: `curl http://<host>:<port>/health`
|
||||
2. Check systemd: `systemctl status hermes-<agent>`
|
||||
3. Check logs: `journalctl -u hermes-<agent> --since "1 hour ago"`
|
||||
4. Restart: `systemctl restart hermes-<agent>`
|
||||
|
||||
### Banned Provider Detected
|
||||
1. Run scanner: `python3 bin/banned_provider_scan.py`
|
||||
2. Check golden state: `cat ansible/inventory/group_vars/wizards.yml`
|
||||
3. Verify BANNED_PROVIDERS.yml is current
|
||||
4. Fix config and redeploy
|
||||
|
||||
### Merge Conflict Cascade
|
||||
1. Run conflict detector: `python3 bin/conflict_detector.py`
|
||||
2. Rebase oldest conflicting PR first
|
||||
3. Merge, then repeat — cascade resolves naturally
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Repo | Purpose |
|
||||
|------|------|---------|
|
||||
| `manifest.yaml` | fleet-ops | Fleet service definitions |
|
||||
| `config.yaml` | timmy-config | Agent runtime config |
|
||||
| `ansible/BANNED_PROVIDERS.yml` | timmy-config | Provider ban enforcement |
|
||||
| `portals.json` | the-nexus | Portal registry |
|
||||
| `vision.json` | the-nexus | Vision system config |
|
||||
94
docs/WASTE_AUDIT_2026-04-13.md
Normal file
94
docs/WASTE_AUDIT_2026-04-13.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Waste Audit — 2026-04-13
|
||||
|
||||
Author: perplexity (automated review agent)
|
||||
Scope: All Timmy Foundation repos, PRs from April 12-13 2026
|
||||
|
||||
## Purpose
|
||||
|
||||
This audit identifies recurring waste patterns across the foundation's recent PR activity. The goal is to focus agent and contributor effort on high-value work and stop repeating costly mistakes.
|
||||
|
||||
## Waste Patterns Identified
|
||||
|
||||
### 1. Merging Over "Request Changes" Reviews
|
||||
|
||||
**Severity: Critical**
|
||||
|
||||
the-door#23 (crisis detection and response system) was merged despite both Rockachopa and Perplexity requesting changes. The blockers included:
|
||||
- Zero tests for code described as "the most important code in the foundation"
|
||||
- Non-deterministic `random.choice` in safety-critical response selection
|
||||
- False-positive risk on common words ("alone", "lost", "down", "tired")
|
||||
- Early-return logic that loses lower-tier keyword matches
|
||||
|
||||
This is safety-critical code that scans for suicide and self-harm signals. Merging untested, non-deterministic code in this domain is the highest-risk misstep the foundation can make.
|
||||
|
||||
**Corrective action:** Enforce branch protection requiring at least 1 approval with no outstanding change requests before merge. No exceptions for safety-critical code.
|
||||
|
||||
### 2. Mega-PRs That Become Unmergeable
|
||||
|
||||
**Severity: High**
|
||||
|
||||
hermes-agent#307 accumulated 569 commits, 650 files changed, +75,361/-14,666 lines. It was closed without merge due to 10 conflicting files. The actual feature (profile-scoped cron) was then rescued into a smaller PR (#335).
|
||||
|
||||
This pattern wastes reviewer time, creates merge conflicts, and delays feature delivery.
|
||||
|
||||
**Corrective action:** PRs must stay under 500 lines changed. If a feature requires more, break it into stacked PRs. Branches older than 3 days without merge should be rebased or split.
|
||||
|
||||
### 3. Pervasive CI Failures Ignored
|
||||
|
||||
**Severity: High**
|
||||
|
||||
Nearly every PR reviewed in the last 24 hours has failing CI (smoke tests, sanity checks, accessibility audits). PRs are being merged despite red CI. This undermines the entire purpose of having CI.
|
||||
|
||||
**Corrective action:** CI must pass before merge. If CI is flaky or misconfigured, fix the CI — do not bypass it. The "Create merge commit (When checks succeed)" button exists for a reason.
|
||||
|
||||
### 4. Applying Fixes to Wrong Code Locations
|
||||
|
||||
**Severity: Medium**
|
||||
|
||||
the-beacon#96 fix #3 changed `G.totalClicks++` to `G.totalAutoClicks++` in `writeCode()` (the manual click handler) instead of `autoType()` (the auto-click handler). This inverts the tracking entirely. Rockachopa caught this in review.
|
||||
|
||||
This pattern suggests agents are pattern-matching on variable names rather than understanding call-site context.
|
||||
|
||||
**Corrective action:** Every bug fix PR must include the reasoning for WHY the fix is in that specific location. Include a before/after trace showing the bug is actually fixed.
|
||||
|
||||
### 5. Duplicated Effort Across Agents
|
||||
|
||||
**Severity: Medium**
|
||||
|
||||
the-testament#45 was closed with 7 conflicting files and replaced by a rescue PR #46. The original work was largely discarded. Multiple PRs across repos show similar patterns of rework: submit, get changes requested, close, resubmit.
|
||||
|
||||
**Corrective action:** Before opening a PR, check if another agent already has a branch touching the same files. Coordinate via issues, not competing PRs.
|
||||
|
||||
### 6. `wip:` Commit Prefixes Shipped to Main
|
||||
|
||||
**Severity: Low**
|
||||
|
||||
the-door#22 shipped 5 commits all prefixed `wip:` to main. This clutters git history and makes bisecting harder.
|
||||
|
||||
**Corrective action:** Squash or rewrite commit messages before merge. No `wip:` prefixes in main branch history.
|
||||
|
||||
## Priority Actions (Ranked)
|
||||
|
||||
1. **Immediately add tests to the-door crisis_detector.py and crisis_responder.py** — this code is live on main with zero test coverage and known false-positive issues
|
||||
2. **Enable branch protection on all repos** — require 1 approval, no outstanding change requests, CI passing
|
||||
3. **Fix CI across all repos** — smoke tests and sanity checks are failing everywhere; this must be the baseline
|
||||
4. **Enforce PR size limits** — reject PRs over 500 lines changed at the CI level
|
||||
5. **Require bug-fix reasoning** — every fix PR must explain why the change is at that specific location
|
||||
|
||||
## Metrics
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Open PRs reviewed | 6 |
|
||||
| PRs merged this run | 1 (the-testament#41) |
|
||||
| PRs blocked | 2 (the-door#22, timmy-config#600) |
|
||||
| Repos with failing CI | 3+ |
|
||||
| PRs with zero test coverage | 4+ |
|
||||
| Estimated rework hours from waste | 20-40h |
|
||||
|
||||
## Conclusion
|
||||
|
||||
The project is moving fast but bleeding quality. The biggest risk is untested code on main — one bad deploy of crisis_detector.py could cause real harm. The priority actions above are ranked by blast radius. Start at #1 and don't skip ahead.
|
||||
|
||||
---
|
||||
*Generated by Perplexity review sweep, 2026-04-13
|
||||
@@ -45,7 +45,8 @@ def append_event(session_id: str, event: dict, base_dir: str | Path = DEFAULT_BA
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = dict(event)
|
||||
payload.setdefault("timestamp", datetime.now(timezone.utc).isoformat())
|
||||
# Optimized for <50ms latency\n with path.open("a", encoding="utf-8", buffering=1024) as f:
|
||||
# Optimized for <50ms latency
|
||||
with path.open("a", encoding="utf-8", buffering=1024) as f:
|
||||
f.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
||||
write_session_metadata(session_id, {"last_event_excerpt": excerpt(json.dumps(payload, ensure_ascii=False), 400)}, base_dir)
|
||||
return path
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
# Let Gemini-Timmy configure itself as Anthropic fallback.
|
||||
# Hermes CLI won't accept --provider custom, so we use hermes setup flow.
|
||||
# But first: prove Gemini works, then manually add fallback_model.
|
||||
# Configure Gemini 2.5 Pro as fallback provider.
|
||||
# Anthropic BANNED per BANNED_PROVIDERS.yml (2026-04-09).
|
||||
# Sets up Google Gemini as custom_provider + fallback_model for Hermes.
|
||||
|
||||
# Add Google Gemini as custom_provider + fallback_model in one shot
|
||||
python3 << 'PYEOF'
|
||||
@@ -39,7 +39,7 @@ else:
|
||||
with open(config_path, "w") as f:
|
||||
yaml.dump(config, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
print("\nDone. When Anthropic quota exhausts, Hermes will failover to Gemini 2.5 Pro.")
|
||||
print("Primary: claude-opus-4-6 (Anthropic)")
|
||||
print("Fallback: gemini-2.5-pro (Google AI)")
|
||||
print("\nDone. Gemini 2.5 Pro configured as fallback. Anthropic is banned.")
|
||||
print("Primary: kimi-k2.5 (Kimi Coding)")
|
||||
print("Fallback: gemini-2.5-pro (Google AI via OpenRouter)")
|
||||
PYEOF
|
||||
|
||||
@@ -271,7 +271,7 @@ Period: Last {hours} hours
|
||||
{chr(10).join([f"- {count} {atype} ({size or 0} bytes)" for count, atype, size in artifacts]) if artifacts else "- None recorded"}
|
||||
|
||||
## Recommendations
|
||||
{""" + self._generate_recommendations(hb_count, avg_latency, uptime_pct)
|
||||
""" + self._generate_recommendations(hb_count, avg_latency, uptime_pct)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
63
research/03-rag-vs-context-framework.md
Normal file
63
research/03-rag-vs-context-framework.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Research: Long Context vs RAG Decision Framework
|
||||
|
||||
**Date**: 2026-04-13
|
||||
**Research Backlog Item**: 4.3 (Impact: 4, Effort: 1, Ratio: 4.0)
|
||||
**Status**: Complete
|
||||
|
||||
## Current State of the Fleet
|
||||
|
||||
### Context Windows by Model/Provider
|
||||
| Model | Context Window | Our Usage |
|
||||
|-------|---------------|-----------|
|
||||
| xiaomi/mimo-v2-pro (Nous) | 128K | Primary workhorse (Hermes) |
|
||||
| gpt-4o (OpenAI) | 128K | Fallback, complex reasoning |
|
||||
| claude-3.5-sonnet (Anthropic) | 200K | Heavy analysis tasks |
|
||||
| gemma-3 (local/Ollama) | 8K | Local inference |
|
||||
| gemma-3-27b (RunPod) | 128K | Sovereign inference |
|
||||
|
||||
### How We Currently Inject Context
|
||||
1. **Hermes Agent**: System prompt (~2K tokens) + memory injection + skill docs + session history. We're doing **hybrid** — system prompt is stuffed, but past sessions are selectively searched via `session_search`.
|
||||
2. **Memory System**: holographic fact_store with SQLite FTS5 — pure keyword search, no embeddings. Effectively RAG without the vector part.
|
||||
3. **Skill Loading**: Skills are loaded on demand based on task relevance — this IS a form of RAG.
|
||||
4. **Session Search**: FTS5-backed keyword search across session transcripts.
|
||||
|
||||
### Analysis: Are We Over-Retrieving?
|
||||
|
||||
**YES for some workloads.** Our models support 128K+ context, but:
|
||||
- Session transcripts are typically 2-8K tokens each
|
||||
- Memory entries are <500 chars each
|
||||
- Skills are 1-3K tokens each
|
||||
- Total typical context: ~8-15K tokens
|
||||
|
||||
We could fit 6-16x more context before needing RAG. But stuffing everything in:
|
||||
- Increases cost (input tokens are billed)
|
||||
- Increases latency
|
||||
- Can actually hurt quality (lost in the middle effect)
|
||||
|
||||
### Decision Framework
|
||||
|
||||
```
|
||||
IF task requires factual accuracy from specific sources:
|
||||
→ Use RAG (retrieve exact docs, cite sources)
|
||||
ELIF total relevant context < 32K tokens:
|
||||
→ Stuff it all (simplest, best quality)
|
||||
ELIF 32K < context < model_limit * 0.5:
|
||||
→ Hybrid: key docs in context, RAG for rest
|
||||
ELIF context > model_limit * 0.5:
|
||||
→ Pure RAG with reranking
|
||||
```
|
||||
|
||||
### Key Insight: We're Mostly Fine
|
||||
Our current approach is actually reasonable:
|
||||
- **Hermes**: System prompt stuffed + selective skill loading + session search = hybrid approach. OK
|
||||
- **Memory**: FTS5 keyword search works but lacks semantic understanding. Upgrade candidate.
|
||||
- **Session recall**: Keyword search is limiting. Embedding-based would find semantically similar sessions.
|
||||
|
||||
### Recommendations (Priority Order)
|
||||
1. **Keep current hybrid approach** — it's working well for 90% of tasks
|
||||
2. **Add semantic search to memory** — replace pure FTS5 with sqlite-vss or similar for the fact_store
|
||||
3. **Don't stuff sessions** — continue using selective retrieval for session history (saves cost)
|
||||
4. **Add context budget tracking** — log how many tokens each context injection uses
|
||||
|
||||
### Conclusion
|
||||
We are NOT over-retrieving in most cases. The main improvement opportunity is upgrading memory from keyword search to semantic search, not changing the overall RAG vs stuffing strategy.
|
||||
@@ -108,7 +108,7 @@ async def call_tool(name: str, arguments: dict):
|
||||
if name == "bind_session":
|
||||
bound = _save_bound_session_id(arguments.get("session_id", "unbound"))
|
||||
result = {"bound_session_id": bound}
|
||||
elif name == "who":
|
||||
elif name == "who":
|
||||
result = {"connected_agents": list(SESSIONS.keys())}
|
||||
elif name == "status":
|
||||
result = {"connected_sessions": sorted(SESSIONS.keys()), "bound_session_id": _load_bound_session_id()}
|
||||
|
||||
224
scripts/twitter_archive/index_timmy_media.py
Normal file
224
scripts/twitter_archive/index_timmy_media.py
Normal file
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Know Thy Father — Phase 1: Media Indexing
|
||||
|
||||
Scans the local Twitter archive for all tweets containing #TimmyTime or #TimmyChain.
|
||||
Maps these tweets to their associated media files and outputs a manifest of media
|
||||
files to be processed in the multimodal analysis pipeline.
|
||||
|
||||
Usage:
|
||||
python index_timmy_media.py # Scan and write manifest
|
||||
python index_timmy_media.py --status # Quick status only
|
||||
python index_timmy_media.py --json # Output manifest as JSON to stdout
|
||||
|
||||
Output:
|
||||
twitter-archive/know-thy-father/media-manifest.jsonl
|
||||
twitter-archive/know-thy-father/media-index-summary.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
# Add parent for common helpers
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from common import (
|
||||
ARCHIVE_DIR,
|
||||
EXTRACTED_DIR,
|
||||
load_jsonl,
|
||||
write_json,
|
||||
)
|
||||
|
||||
TARGET_HASHTAGS = {"timmytime", "timmychain"}
|
||||
|
||||
# Know Thy Father output directory
|
||||
KTF_DIR = ARCHIVE_DIR / "know-thy-father"
|
||||
MEDIA_MANIFEST = KTF_DIR / "media-manifest.jsonl"
|
||||
MEDIA_SUMMARY = KTF_DIR / "media-index-summary.json"
|
||||
|
||||
# Media directories in the archive
|
||||
MEDIA_DIR_NAMES = ("tweets_media", "community_tweet_media", "deleted_tweets_media")
|
||||
|
||||
|
||||
def find_hashtag_tweets(tweets: list[dict], hashtags: set[str]) -> list[dict]:
|
||||
"""Filter tweets that contain any of the target hashtags."""
|
||||
matched = []
|
||||
for tweet in tweets:
|
||||
tweet_tags = {h.lower() for h in tweet.get("hashtags", [])}
|
||||
if tweet_tags & hashtags:
|
||||
matched.append(tweet)
|
||||
return matched
|
||||
|
||||
|
||||
def build_tweet_media_index(
|
||||
hashtag_tweets: list[dict],
|
||||
media_manifest: list[dict],
|
||||
source_dir: Path,
|
||||
) -> list[dict]:
|
||||
"""Map hashtag tweets to their media files.
|
||||
|
||||
Returns a list of manifest entries, one per tweet-media pair.
|
||||
"""
|
||||
# Build tweet_id -> media records lookup
|
||||
tweet_media_map: dict[str, list[dict]] = {}
|
||||
for record in media_manifest:
|
||||
tid = record.get("tweet_id")
|
||||
if tid:
|
||||
tweet_media_map.setdefault(tid, []).append(record)
|
||||
|
||||
entries = []
|
||||
for tweet in hashtag_tweets:
|
||||
tid = tweet["tweet_id"]
|
||||
media_records = tweet_media_map.get(tid, [])
|
||||
|
||||
if not media_records:
|
||||
# Tweet has hashtags but no media — still index it
|
||||
entries.append({
|
||||
"tweet_id": tid,
|
||||
"created_at": tweet.get("created_at"),
|
||||
"full_text": tweet.get("full_text", "")[:280],
|
||||
"hashtags": tweet.get("hashtags", []),
|
||||
"media_type": "none",
|
||||
"media_path": None,
|
||||
"media_id": None,
|
||||
"media_count": 0,
|
||||
"status": "no_media",
|
||||
})
|
||||
continue
|
||||
|
||||
for media in media_records:
|
||||
local_path = media.get("local_media_path")
|
||||
entries.append({
|
||||
"tweet_id": tid,
|
||||
"created_at": tweet.get("created_at"),
|
||||
"full_text": tweet.get("full_text", "")[:280],
|
||||
"hashtags": tweet.get("hashtags", []),
|
||||
"media_type": media.get("media_type", "unknown"),
|
||||
"media_path": local_path,
|
||||
"media_id": media.get("media_id"),
|
||||
"media_count": len(media_records),
|
||||
"media_url": media.get("media_url_https"),
|
||||
"status": "pending" if local_path and Path(local_path).exists() else "missing_file",
|
||||
})
|
||||
|
||||
# Sort by created_at
|
||||
entries.sort(key=lambda e: e.get("created_at") or "")
|
||||
return entries
|
||||
|
||||
|
||||
def write_manifest_jsonl(entries: list[dict]) -> None:
|
||||
"""Write the manifest as JSONL."""
|
||||
KTF_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with open(MEDIA_MANIFEST, "w") as f:
|
||||
for entry in entries:
|
||||
f.write(json.dumps(entry, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def compute_summary(entries: list[dict]) -> dict:
|
||||
"""Compute summary statistics for the manifest."""
|
||||
total = len(entries)
|
||||
by_status = Counter(e["status"] for e in entries)
|
||||
by_type = Counter(e["media_type"] for e in entries)
|
||||
|
||||
# Unique tweets
|
||||
unique_tweets = len(set(e["tweet_id"] for e in entries))
|
||||
|
||||
# Date range
|
||||
dates = [e["created_at"] for e in entries if e.get("created_at")]
|
||||
dates.sort()
|
||||
|
||||
# File existence check
|
||||
files_exist = sum(
|
||||
1 for e in entries
|
||||
if e.get("media_path") and Path(e["media_path"]).exists()
|
||||
)
|
||||
|
||||
return {
|
||||
"total_entries": total,
|
||||
"unique_tweets": unique_tweets,
|
||||
"tweets_with_media": sum(1 for e in entries if e["media_type"] != "none"),
|
||||
"tweets_without_media": sum(1 for e in entries if e["media_type"] == "none"),
|
||||
"files_exist": files_exist,
|
||||
"files_missing": by_status.get("missing_file", 0),
|
||||
"pending_processing": by_status.get("pending", 0),
|
||||
"by_media_type": dict(by_type),
|
||||
"by_status": dict(by_status),
|
||||
"date_range": {
|
||||
"earliest": dates[0] if dates else None,
|
||||
"latest": dates[-1] if dates else None,
|
||||
},
|
||||
"target_hashtags": sorted(TARGET_HASHTAGS),
|
||||
}
|
||||
|
||||
|
||||
def print_status(summary: dict) -> None:
|
||||
"""Print a human-readable status summary."""
|
||||
print("Know Thy Father — Phase 1: Media Index")
|
||||
print("=" * 45)
|
||||
print(f" Target hashtags: {', '.join(summary['target_hashtags'])}")
|
||||
print(f" Unique tweets: {summary['unique_tweets']}")
|
||||
print(f" With media: {summary['tweets_with_media']}")
|
||||
print(f" Without media: {summary['tweets_without_media']}")
|
||||
print(f" Files found: {summary['files_exist']}")
|
||||
print(f" Files missing: {summary['files_missing']}")
|
||||
print(f" Pending process: {summary['pending_processing']}")
|
||||
print()
|
||||
print("Media types:")
|
||||
for media_type, count in summary["by_media_type"].items():
|
||||
print(f" {media_type:20s} {count}")
|
||||
print()
|
||||
if summary["date_range"]["earliest"]:
|
||||
print(f"Date range: {summary['date_range']['earliest'][:10]} → {summary['date_range']['latest'][:10]}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Know Thy Father — Phase 1 Media Indexing")
|
||||
parser.add_argument("--status", action="store_true", help="Quick status only (don't write files)")
|
||||
parser.add_argument("--json", action="store_true", help="Output manifest as JSON to stdout")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Load data
|
||||
tweets = load_jsonl(EXTRACTED_DIR / "tweets.jsonl")
|
||||
if not tweets:
|
||||
print("Error: No tweets found. Run extract_archive.py first.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
media_manifest = load_jsonl(ARCHIVE_DIR / "media" / "manifest.jsonl")
|
||||
if not media_manifest:
|
||||
print("Warning: No media manifest found. Run extract_media_manifest.py first.", file=sys.stderr)
|
||||
print("Continuing with text-only indexing...", file=sys.stderr)
|
||||
|
||||
# Scan for target hashtags
|
||||
hashtag_tweets = find_hashtag_tweets(tweets, TARGET_HASHTAGS)
|
||||
|
||||
# Resolve source dir for media lookup
|
||||
source_dir = Path.home() / "Downloads" / "twitter-2026-03-27-d4471cc6eb6703034d592f870933561ebee374d9d9b90c9b8923abff064afc1e" / "data"
|
||||
|
||||
# Build the media index
|
||||
entries = build_tweet_media_index(hashtag_tweets, media_manifest, source_dir)
|
||||
summary = compute_summary(entries)
|
||||
|
||||
if args.status:
|
||||
print_status(summary)
|
||||
return
|
||||
|
||||
# Write outputs
|
||||
write_manifest_jsonl(entries)
|
||||
write_json(MEDIA_SUMMARY, summary)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(entries, indent=2, sort_keys=True))
|
||||
else:
|
||||
print_status(summary)
|
||||
print()
|
||||
print(f"Manifest written to: {MEDIA_MANIFEST}")
|
||||
print(f"Summary written to: {MEDIA_SUMMARY}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
174
tests/twitter_archive/test_index_timmy_media.py
Normal file
174
tests/twitter_archive/test_index_timmy_media.py
Normal file
@@ -0,0 +1,174 @@
|
||||
"""Tests for Know Thy Father Phase 1: Media Indexing."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "scripts" / "twitter_archive"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_tweets():
|
||||
return [
|
||||
{
|
||||
"tweet_id": "1001",
|
||||
"created_at": "Mon Mar 01 12:00:00 +0000 2026",
|
||||
"full_text": "First #TimmyTime post",
|
||||
"hashtags": ["TimmyTime"],
|
||||
},
|
||||
{
|
||||
"tweet_id": "1002",
|
||||
"created_at": "Tue Mar 02 12:00:00 +0000 2026",
|
||||
"full_text": "#TimmyChain block 1",
|
||||
"hashtags": ["TimmyChain"],
|
||||
},
|
||||
{
|
||||
"tweet_id": "1003",
|
||||
"created_at": "Wed Mar 03 12:00:00 +0000 2026",
|
||||
"full_text": "Unrelated post",
|
||||
"hashtags": ["bitcoin"],
|
||||
},
|
||||
{
|
||||
"tweet_id": "1004",
|
||||
"created_at": "Thu Mar 04 12:00:00 +0000 2026",
|
||||
"full_text": "Both tags #TimmyTime #TimmyChain",
|
||||
"hashtags": ["TimmyTime", "TimmyChain"],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_media():
|
||||
return [
|
||||
{
|
||||
"tweet_id": "1001",
|
||||
"media_id": "m1",
|
||||
"media_type": "video",
|
||||
"local_media_path": "/tmp/media/1001-video.mp4",
|
||||
"media_url_https": "https://pbs.twimg.com/ext_thumb/1001.jpg",
|
||||
},
|
||||
{
|
||||
"tweet_id": "1002",
|
||||
"media_id": "m2",
|
||||
"media_type": "photo",
|
||||
"local_media_path": "/tmp/media/1002-photo.jpg",
|
||||
"media_url_https": "https://pbs.twimg.com/media/1002.jpg",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class TestFindHashtagTweets:
|
||||
def test_finds_timmytime(self, sample_tweets):
|
||||
from index_timmy_media import find_hashtag_tweets
|
||||
result = find_hashtag_tweets(sample_tweets, {"timmytime"})
|
||||
ids = [t["tweet_id"] for t in result]
|
||||
assert "1001" in ids
|
||||
assert "1004" in ids
|
||||
assert "1003" not in ids
|
||||
|
||||
def test_finds_timmychain(self, sample_tweets):
|
||||
from index_timmy_media import find_hashtag_tweets
|
||||
result = find_hashtag_tweets(sample_tweets, {"timmychain"})
|
||||
ids = [t["tweet_id"] for t in result]
|
||||
assert "1002" in ids
|
||||
assert "1004" in ids
|
||||
|
||||
def test_finds_both(self, sample_tweets):
|
||||
from index_timmy_media import find_hashtag_tweets
|
||||
result = find_hashtag_tweets(sample_tweets, {"timmytime", "timmychain"})
|
||||
ids = [t["tweet_id"] for t in result]
|
||||
assert len(ids) == 3
|
||||
assert "1003" not in ids
|
||||
|
||||
def test_case_insensitive(self):
|
||||
from index_timmy_media import find_hashtag_tweets
|
||||
tweets = [
|
||||
{"tweet_id": "1", "hashtags": ["TIMMYTIME"]},
|
||||
{"tweet_id": "2", "hashtags": ["TimmyChain"]},
|
||||
]
|
||||
result = find_hashtag_tweets(tweets, {"timmytime", "timmychain"})
|
||||
assert len(result) == 2
|
||||
|
||||
def test_empty_input(self):
|
||||
from index_timmy_media import find_hashtag_tweets
|
||||
assert find_hashtag_tweets([], {"timmytime"}) == []
|
||||
|
||||
|
||||
class TestBuildTweetMediaIndex:
|
||||
def test_maps_tweets_to_media(self, sample_tweets, sample_media, tmp_path):
|
||||
from index_timmy_media import build_tweet_media_index
|
||||
matched = [t for t in sample_tweets if t["tweet_id"] in ("1001", "1002")]
|
||||
# Create fake media files
|
||||
for m in sample_media:
|
||||
p = Path(m["local_media_path"])
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.touch()
|
||||
|
||||
entries = build_tweet_media_index(matched, sample_media, tmp_path)
|
||||
assert len(entries) == 2
|
||||
|
||||
by_id = {e["tweet_id"]: e for e in entries}
|
||||
assert by_id["1001"]["media_type"] == "video"
|
||||
assert by_id["1002"]["media_type"] == "photo"
|
||||
assert by_id["1001"]["status"] == "pending"
|
||||
assert by_id["1002"]["status"] == "pending"
|
||||
|
||||
def test_handles_no_media(self, sample_tweets, sample_media, tmp_path):
|
||||
from index_timmy_media import build_tweet_media_index
|
||||
# Tweet 1004 has no media record
|
||||
matched = [t for t in sample_tweets if t["tweet_id"] == "1004"]
|
||||
entries = build_tweet_media_index(matched, sample_media, tmp_path)
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["media_type"] == "none"
|
||||
assert entries[0]["status"] == "no_media"
|
||||
|
||||
def test_handles_missing_file(self, sample_tweets, sample_media, tmp_path):
|
||||
from index_timmy_media import build_tweet_media_index
|
||||
matched = [t for t in sample_tweets if t["tweet_id"] == "1001"]
|
||||
# Use a path that definitely doesn't exist
|
||||
fake_media = [{
|
||||
"tweet_id": "1001",
|
||||
"media_id": "m1",
|
||||
"media_type": "video",
|
||||
"local_media_path": "/tmp/nonexistent/1001-FAKE.mp4",
|
||||
"media_url_https": "https://pbs.twimg.com/ext_thumb/1001.jpg",
|
||||
}]
|
||||
entries = build_tweet_media_index(matched, fake_media, tmp_path)
|
||||
assert entries[0]["status"] == "missing_file"
|
||||
|
||||
def test_sorted_by_date(self, sample_tweets, sample_media, tmp_path):
|
||||
from index_timmy_media import build_tweet_media_index
|
||||
matched = [t for t in sample_tweets if t["tweet_id"] in ("1001", "1002")]
|
||||
for m in sample_media:
|
||||
Path(m["local_media_path"]).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(m["local_media_path"]).touch()
|
||||
|
||||
entries = build_tweet_media_index(matched, sample_media, tmp_path)
|
||||
dates = [e["created_at"] for e in entries]
|
||||
assert dates == sorted(dates)
|
||||
|
||||
|
||||
class TestComputeSummary:
|
||||
def test_basic_summary(self):
|
||||
from index_timmy_media import compute_summary
|
||||
entries = [
|
||||
{"tweet_id": "1", "media_type": "video", "media_path": "/fake", "status": "pending"},
|
||||
{"tweet_id": "2", "media_type": "none", "media_path": None, "status": "no_media"},
|
||||
{"tweet_id": "3", "media_type": "photo", "media_path": "/fake2", "status": "pending"},
|
||||
]
|
||||
summary = compute_summary(entries)
|
||||
assert summary["total_entries"] == 3
|
||||
assert summary["unique_tweets"] == 3
|
||||
assert summary["tweets_with_media"] == 2
|
||||
assert summary["tweets_without_media"] == 1
|
||||
assert summary["by_media_type"]["video"] == 1
|
||||
assert summary["by_media_type"]["photo"] == 1
|
||||
assert summary["by_media_type"]["none"] == 1
|
||||
|
||||
def test_empty_entries(self):
|
||||
from index_timmy_media import compute_summary
|
||||
summary = compute_summary([])
|
||||
assert summary["total_entries"] == 0
|
||||
assert summary["unique_tweets"] == 0
|
||||
@@ -24,7 +24,7 @@ class HealthCheckHandler(BaseHTTPRequestHandler):
|
||||
# Suppress default logging
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
def do_GET(self):
|
||||
"""Handle GET requests"""
|
||||
if self.path == '/health':
|
||||
self.send_health_response()
|
||||
|
||||
Reference in New Issue
Block a user