# Furoshiki Roadmap

_Living document. Add features here before building them._

---

## Proposed specs (not implemented)

- **[`CONTEXT-ASSEMBLY-V2.md`](./CONTEXT-ASSEMBLY-V2.md)** — Four-band system prompt assembly (two-tail anchor), flag `CONTEXT_ASSEMBLY_V2`; depends on the composite voice directive resolver in [`EMOTIONAL-DIRECTIVE-OVERHAUL.md`](./EMOTIONAL-DIRECTIVE-OVERHAUL.md). No new stores or schema.

---

## Feature Backlog

### 1. Config & Cost Controls

**`furoshiki config` CLI:**
- `furoshiki config` — show all current config
- `furoshiki config set <key> <value>` — update a setting, restart affected services
- `furoshiki config models` — list known model shortcuts with cost estimates
- `furoshiki config --json` — machine-readable

**Config keys (user-facing):**
| Key | Env var | Affects |
|-----|---------|---------|
| `listener-model` | `FUROSHIKI_LISTENER_MODEL` | telegram_listener (auto-restarts) |
| `loops-model` | `FUROSHIKI_MODEL_FAST` | all loop scripts |
| `reflect-model` | `FUROSHIKI_MODEL_REFLECT` | all reflection scripts (inner_monologue, deep_reflection, morning_reflection, post_conversation, self_diagnosis) — defaults to claude-sonnet-4.6 |
| `deep-model` | `FUROSHIKI_MODEL_DEEP` | optimization_check |
| `prose-model` | `FUROSHIKI_PROSE_MODEL` | voice_dispatcher |
| `llm-backend` | `FUROSHIKI_LLM_BACKEND` | voice_dispatcher (groq/openrouter) |
| `budget-daily` | `FUROSHIKI_BUDGET_DAILY_USD` | hard cap on daily token spend |
| `budget-monthly` | `FUROSHIKI_BUDGET_MONTHLY_USD` | hard cap on monthly token spend |
| `budget-alert` | `FUROSHIKI_BUDGET_ALERT_PCT` | % of budget that triggers an alert for the user (default 80) |

**Cost controls (self-regulation):**
- `llm.py` tracks every call: model, tokens in/out, estimated cost → `token-usage.json`
- Before each LLM call: check daily/monthly spend against budget caps
- At 80% of daily budget: write `system_event: budget_warning` → the user gets a Telegram alert
- At 100%: hard-stop all LLM calls for remainder of the day, log `budget_exceeded`
- Weekly cost summary surfaces via `run_optimization_check.py`
- Default safe caps: `$2/day`, `$30/month` (configurable)

---

### 2. Delegated Repair Loop

**What it is:**
When the doctor detects a recurring error it cannot fix itself, it escalates to a coding CLI (Claude Code CLI). The CLI diagnoses and either auto-fixes (narrow safe class) or writes a proposal markdown for the user's review. Furoshiki receives the outcome through the usual notification pipeline.

**Components:**
- `scripts/repair_dispatcher.py` — reads a `repair_jobs` record, gathers context, invokes `claude -p` as subprocess, posts result to `api_server`
- `scripts/api_server.py` — FastAPI server on port `7432` (default bind `0.0.0.0`), bearer token auth, two endpoints: `POST /repair/update` and `POST /repair/complete`
- `furoshiki-repair-api.service` — systemd service for api_server, auto-restarts
- `doctor.py` — new `check_error_logs()` check: scans logs, deduplicates by error signature, triggers dispatcher when recurrence ≥ 3 in 24h
- `scripts/init_db.py` — new `repair_jobs` table

**Protected paths (never modified by automated repair):**
```
config/SOUL.md, config/SELF.md, config/USER.md, config/MEMORY.md,
config/**, memory/**, .env
```

**Repair classification (by coding CLI LLM):**
- `auto-fix`: single script, ≤~20 lines, no schema/contract changes, clear defect → apply + commit + notify
- `propose`: everything else → write `~/.furoshiki/proposals/repair-…-job<id>-….md` (or dev git mode) + notify the operator

**Circuit breakers:**
- Max 3 attempts per error signature → `failed` + Telegram alert
- Repair job open > 48h → `stale` + alert
- Proposal references protected path → reject immediately + alert

**Estimated token cost:** ~2000–4000 tokens per repair dispatch (context gathering + classification). Only fires on recurring errors (≥ 3/24h), so expected rate: 0–2 dispatches per day.

**Design doc:** See `docs/SELF-AWARENESS-DESIGN.md` → "Delegated Repair — Coding CLI Integration"

---

### 3. Self-Diagnosis & Auto-Healing

**What it does:**
Runs daily. Reads all logs, checks DB health, identifies patterns and issues.
Fixes obvious ones automatically. Surfaces serious ones to the user via Telegram.

**Checks:**
- Repeated `ERROR` patterns in any log → classify (transient vs. persistent)
- Expected cron jobs that didn't fire in their window → `WARN` if missed 2+
- Services that restarted unexpectedly (systemd restart count)
- DB table growth anomalies (mind_queue stuck, cron_run_log ballooning)
- Token spend trending toward cap
- `session-context.json` staleness (> 2h old = regenerate)
- soul_engine tick gaps (should fire every 15 min)

**Auto-fixes (safe, reversible):**
- Purge `cron_run_log` entries older than 30 days
- Clear `mind_queue` items stuck in `pending` for > 7 days
- Regenerate stale `session-context.json`
- Rotate logs over 10MB

**Surfaces to the user:**
- Persistent errors (same error 3+ times in 24h)
- Missed critical jobs (inner_monologue, soul_engine)
- Budget approaching cap
- Service down for > 1h

**Implementation:**
- `scripts/run_self_diagnosis.py` — daily cron (runs at 07:00 UTC)
- Writes `system_event: diagnosis_issue` for each surfaced problem
- soul_engine routes critical issues → mind_queue → voice_dispatcher → the user

---

### 4. Self-Scheduling

**What it is:**
Furoshiki creates temporary scheduled tasks based on inner state and reflection output.
During inner_monologue or question_processing, if a future check at a specific time is anticipated,
the system schedules it via the Brain scheduler (self-scheduling intent).

**Infrastructure:** The scheduling mechanism is now the Brain scheduler (`scheduler.py` / `schedules.json`). The previous `manage_cron.py` + OS crontab approach is superseded. What remains is wiring the self-scheduling intent (system_events from loop scripts) into the Brain scheduler API.

**Flow:**
1. A loop script writes `system_event: schedule_task` with schedule + script + expiry
2. soul_engine processes it → creates a task entry in `schedules.json` via scheduler API
3. At expiry date, soul_engine removes the task automatically
4. Operator can see all tasks with `furoshiki scheduler list`

**Use cases:**
- "I want to check on the user's project progress next Monday" → temp weekly task
- "Remind the user about a release at 3pm" → one-off scheduled task
- "I've been curious about X — check in 3 days" → ephemeral research prompt

**Safety rails:**
- Max 5 active Furoshiki-created tasks at any time
- Ephemeral tasks expire in ≤ 7 days unless the operator explicitly extends
- Furoshiki-created tasks are tagged as ephemeral and visible in the scheduler dashboard
- Cannot modify or delete non-ephemeral tasks (system tasks are protected)

---

### 5. Telegram Admin Commands

**What it is:**
the user (or Furoshiki herself during reflection) can manage the system through
natural conversation in Telegram. The listener detects admin intents and routes
them to CLI commands.

**Commands Furoshiki understands:**
- "switch to haiku" / "use a cheaper model" → `furoshiki config set listener-model haiku`
- "what model are you using?" → `furoshiki config`
- "add a cron for X at 9am" → `furoshiki cron add`
- "how are you doing / any issues?" → `furoshiki health`
- "what's in your queue?" → `furoshiki mind`
- "show me recent logs" → `furoshiki logs`

**Implementation:**
Intent detection in `telegram_listener.py` — simple keyword matching first,
not LLM-based routing (keeps it fast and predictable).

---

### 6. Skills System

**Philosophy: a skill IS a Python script. No framework needed.**

Convention:
```
scripts/run_*.py      → scheduled loop (add to cron)
scripts/add_*.py      → write tool (called by other scripts or Telegram)
scripts/query_*.py    → read tool
```

Any script that follows the convention (imports db.py, logs to cron.log,
writes system_events when relevant) is a skill. Schedule with `furoshiki cron add`.

**What we might add:**
- `run_relationship_check.py` — weekly: how has the user been? tone analysis of recent sessions
- `run_interest_tracker.py` — track recurring topics the user mentions (work, health, hobbies, projects)
- `run_health_tracker.py` — track the user's energy/mood over time from session summaries
- `run_weather_context.py` — pull local weather, inject into morning context

---

### 7. Packaging & Install

**Goal:** Someone else can run Furoshiki on their machine with one script.

- `setup.sh` — verify repo + `FUROSHIKI_DATA`; new machines use `install.sh` (uv sync)
- `setup.sh` checks: Python/repo layout, instance files, `.env`, DB readability, optional `furoshiki db migrate`, systemd repair-api when present
- `.env.template` stays as-is (already clean)
- `docs/INSTALL.md` — step-by-step for a new machine
- Consider: single `pip install` or `git clone + setup.sh`?

---

### 8. Marketing & Project Page

- Rewrite `SELF-AWARENESS-DESIGN.html` with actual content:
  - What Furoshiki is
  - Architecture diagram (the pipeline: soul_engine → mind_queue → voice_dispatcher)
  - How to integrate (the harness contract)
  - Philosophy: LLMs simulate thinking, Python enforces behavior
- Keep it honest — this is a personal AI system, not a product (yet)

---

## Phase 2 — Advanced Self-Resolution

### Internal Dialogue (IFS / Parts Work pattern)

When self-questions identify contradictions with competing goals (e.g. "be warm" vs "be efficient"), trigger a structured internal debate between the competing directives. Resolution produces a reconciliation policy rather than one directive overriding the other. Grounded in Internal Family Systems therapy where "parts" with competing needs are given voice rather than suppressed.

### Reflexion Agent Loop (Shinn et al. 2023)

Write explicit failure reflection artifacts when a behavioral commitment is violated, then inject the reflection into subsequent conversation prompts. Post-conversation, evaluate whether the reflection improved behavior. This closes the loop from violation → reflection → improved attempt → evaluation, matching the Reflexion paper pattern where LLM agents improve through self-generated verbal reinforcement.

---

## Completed

- [x] Self-Diagnosis & Auto-Healing — `doctor.py` (systemd timer, stdlib-only, runs every 5 min), `run_self_diagnosis.py` (daily LLM health check, auto-patches simple logging gaps, surfaces issues to the user), rich health state in `heartbeat-state.json`, morning reflection health-aware, `self_care_log` + `diagnosis_reports` tables. **Note:** recurring code errors now escalate to Delegated Repair Loop (Roadmap item 2) rather than surfacing directly to the user.

- [x] **Self-question resolution — Phase 1**
  - Behavioral pattern detection (pure Python clustering of recurring self/integrity questions)
  - Commitment extraction (MODEL_FAST generates testable behavioral promises)
  - Prompt injection (active commitments in `behavioral_cues` block)
  - Post-conversation evaluation (MODEL_FAST evaluates honored/violated)
  - Resolution/escalation loop (honored → resolve pattern + close questions; violated → failure_count++ → escalate at 3 failures)

---

- [x] **Brain architecture migration** — single-process `brain.py` replacing cron + systemd: `scheduler.py` (Python cron-expression scheduler, `schedules.json`), `doctor.py` as long-running watchdog (was systemd timer), source/data separation (`FUROSHIKI_SRC` vs `FUROSHIKI_DATA`), `furoshiki init/export/import` for portability, all systemd units disabled and crontab cleared, orphan process cleanup on Brain startup and `furoshiki stop`, API restart endpoints brain-aware, `pyproject.toml` + `furoshiki.spec` for packaging

- [x] Phase 2: full independence — standalone stack (no external agent-hosting framework)
- [x] `soul_engine.py` — core logic daemon (every 15 min)
- [x] `outreach_pulse.py` / `voice_dispatcher.py` — proactive Telegram sends via 5‑min pulse + gates
- [x] Optional HTTP health cron via plugins (`cron` hook + `service_unhealthy` events)
- [x] All 7 loop scripts (inner_monologue, morning_reflection, etc.)
- [x] `telegram_listener.py` — conversational Telegram harness, systemd daemon
- [x] `furoshiki-listener.service` — auto-restart, boot-persistent, typing indicator
- [x] Dedicated Furoshiki Telegram bot
- [x] `manage_cron.py` — agent-first cron manager (superseded by Brain scheduler)
- [x] `furoshiki` CLI — status dashboard, logs, cron, nudge, health, service, config
- [x] Directory cleanup — `docs/`, `bin/`, `config/`
- [x] Config & cost controls — `furoshiki config`, budget caps, `llm_call_log` tracking
- [x] Model switching — 12 model shortcuts, `/model` command in Telegram
- [x] All session paths under `FUROSHIKI_DATA` / harness-agnostic

---

### 4. Personality Evolution System

**What it is:**
Furoshiki develops a genuine, evolving personality grounded in real interactions—not a reactive composite of user preferences and emotions. The system records self-observations ("I lean into teasing more than earnest praise"), aggregates personality traits over time, and uses discovered preferences to parameterize behavioral directives.

**Components:**
- **Enhanced self-observations** — New model tool `record_personality_observation` with anti-confabulation safeguards
- **Personality trait aggregation** — Daily script analyzes observations, calculates trait scores (warmth, playfulness, sarcasm, directness, etc.)
- **Behavioral directive parameterization** — Personality traits color responses without overriding core rules
- **Dynamic role learning** — Automatically create personality roles from successful interactions
- **Behavioral quirk detection** — Identify speech patterns, metaphor preferences, signature phrases
- **Deep reflection integration** — Weekly review of personality evolution, update `SELF.md`
- **Operator controls** — Dashboard views, trait boundary controls, evolution speed adjustment

**Key principles:**
' - Ground in reality: Every observation tied to actual interaction
- Parameterize, don't replace: Traits color directives, don't override identity shell
( - Slow evolution: Personality emerges over weeks, not days
- Operator oversight: Full visibility and control through dashboard

**Estimated token cost:** Low—observation tool ~100 tokens/use, aggregation script ~500 tokens/day, deep reflection integration adds ~200 tokens/week to existing reflection.

**Design doc:** See `docs/PERSONALITY-EVOLUTION-PLAN.md` for full seven-phase implementation plan.

---

## Design Principles (don't violate these)

1. **Python enforces behavior. LLMs simulate thinking.** Routing, rate limiting, deduplication → Python. Prose, reflection, journaling → LLM.
2. **system_events is the universal input bus.** Any source writes one row. Soul Engine processes it. No direct coupling.
3. **No web UI.** The CLI and Telegram are the interface. Furoshiki manages herself.
4. **Cost before capability.** Every new LLM feature needs a token estimate and a budget gate.
5. **Reversible by default.** Furoshiki-created changes should be undoable. the user always has override.
6. **Don't become a heavyweight agent framework.** If it needs a config format, a registration step, or a plugin ecosystem — it's too complex. Drop a script, schedule it, done.
