Skip to content

Latest commit

 

History

History
111 lines (72 loc) · 71.2 KB

AGENTS.md

File metadata and controls

111 lines (72 loc) · 71.2 KB

AGENTS.md

This file provides guidance to coding agents (opencode, Claude Code, ...) when working with code in this repository.

Working style

Use mise for binaries, including checks (mise exec uv -- uv run pytest tests/ -v and mise exec uv -- uv run ruff check src/ tests/ from assistant/).

No spec documents. When a Superpowers skill (brainstorming, writing-plans, executing-plans, ...) calls for writing a spec or plan file, skip that step and go straight to implementation. Discussing the approach in the conversation first is still fine — writing it out as a document is not. This is a user instruction and overrides those skills' own workflow.

What this is

Noxide is a self-hosted personal assistant: private web app (PWA) → GitHub Copilot API → markdown vault. Durable knowledge lives in markdown; state_dir/companion.sqlite3 archives conversation text and restores completed context after restart. Unfinished tool protocol is in-memory only. Operational state also includes durable outage retries and consumed inbox snapshots; losing or restoring older state can lose queued work or replay already-processed data. No LLM frameworks.

The web app is the only interface (Telegram support was removed on 2026-09-21; see History at the end). There is deliberately no second input platform and no abstraction for one: one conversation, one archive space, threads as the unit of context.

All Python code lives in assistant/; vault.template/ at the repo root is the seed a user copies to start their own vault — its AGENTS.md is a skeleton of the bot's runtime system prompt, not instructions for the coding agent (that's this file, at the repo root). A real vault never lives in the repo (/vault/ and assistant/vault/ are gitignored).

Commands

All commands run from assistant/:

mise exec uv -- uv sync --dev              # install deps
mise exec uv -- uv run pytest tests/ -v    # run tests (make test)
mise exec uv -- uv run pytest tests/test_agent.py -k test_name   # run a single test
mise exec uv -- uv run ruff check src/ tests/                    # lint (make lint)

Pytest runs with asyncio_mode = "auto" — async tests need no decorator. HTTP is mocked with respx; the companion tests bind a local aiohttp test server. Ruff: line-length 100, target py312, rules E,F,I,UP,B,C4 (E501 ignored).

Running locally requires a one-time Copilot device-flow auth (make auth) and a config.toml (copy config.example.toml); make run starts the assistant natively and serves the app at pwa.origin.

Deployment is documented, not shipped. There are no Compose or search-backend files in this repo — docs/deployment.md holds them as fenced blocks for users to copy, and it is the single source of truth for them. Don't add a Compose file back "for convenience": the duplication is what let stop_grace_period go missing from both copies. Deployment details also stay out of the code — vault_path/state_dir default to ./vault and ./state relative to the working directory, and the container layout is declared as VAULT_PATH/STATE_DIR in the Dockerfile. Don't reintroduce /data/... paths, Compose settings, or make targets into Python source or runtime error strings.

Docs

README.md is the shop window: pitch, feature tour, quick start, links out. Reference material lives in docs/ — deployment.md (setup, Compose blocks, operations), configuration.md (every key and env var), vault.md (vault design and operations, for humans), development.md (dev workflow, layout), ideas/ (backlog). Keep the README short; when a section grows past a few paragraphs it belongs in docs/.

docs/vault.md and src/assistant/prompts/wiki.md describe the same design — the prompt is the authority (the bot actually reads it), the doc is the human explanation. Change one, check the other.

Architecture

Entry point __main__.py:_run() wires everything together. The agent needs a sender at construction and the web app (Companion) needs the agent, so the sender is a closure over the companion name assigned right after the agent is built.

  • conversations.py — ConversationArchive owns the SQLite archive at state_dir/companion.sqlite3. There is one conversation, SPACE ("general"); every message row and context record carries that space. Do not reintroduce chat ids, a thread_id in tool schemas, or per-transport spaces. An archive from the Telegram era may hold rows of other spaces (telegram:<chat>) and the legacy source/delivery columns; they stay untouched and are never queried, and the Telegram lookup tables (telegram_inputs, telegram_outputs) and the old pending_notes mirror are dropped on open. The one-time space migrations of 2026-09-17 (threaded spaces, forum rooms, project chats) ran on every existing deployment and were removed with Telegram. Threads (2026-09-18): every message row carries a thread — the root message's id; a row inserted with reply_to joins its parent's thread, anything else starts one. Context records carry the thread too (NULL for pre-thread records, which stay searchable but belong to no thread). recent_threads feeds the agent's ambient block. Persisted conversation content is text, never reasoning/tool protocol or image bytes. Reset (the app's Reset context) increments the generation, retains searchable archived text, and dismisses pending work; the web timeline draws a divider wherever a message's generation differs from its predecessor's, and after the last message when the space's current generation is newer (/api/messages returns it), so a fresh reset is visible before anything follows it. There is no delete: archived text is only ever removed by hand. Completed context, final reply and request completion publish atomically (save_context).
  • history.py — ConversationHistory is one per thread (thread= the root id) and restores that thread's completed text exchanges across generations, capped at history_exchanges (5) exchanges and 6k content characters per exchange plus explicit truncation markers; a history with no thread and no archive (scheduled jobs, tests without an archive) is plain in-memory. A thread rooted in a scheduled-run delivery opens on that delivery as its first assistant message (_root, from the message row, since deliveries never get a context record, never stored again and never windowed out): without it a reply to a reminder restored an empty thread and ran blind to the reminder it answered — "Hecho" on a pill reminder got "the pills, the stock check, or both?" (2026-09-20). Successful completion retains user text and final replies, discarding completed tool calls/results and reasoning payloads. Older archived text remains available through agent-owned get_history (message IDs, older-page cursor, character-offset reads) and literal search_history, including after restart or reset. Dispatch receives the current history explicitly; no model-controlled conversation IDs and no worker access. A live-turn coverage marker says only this thread and the ambient background are shown, without changing the system prompt. The space-wide transcript behind the history tools loads lazily on first use. Current, cancelled, iteration-capped and outage-pending protocol stays intact in memory only, never restored after restart. Terminal rejections retain their real pending tail; only that tail's tool outputs permit 2k compaction at the next run, never fabricating a successful reply. The old history_size / HISTORY_SIZE is ignored with a migration warning.
  • agent.py — the core loop: send messages+tools to Copilot, execute returned tool calls, append results, repeat until no tool calls (max 20 iterations, 60s per tool). At the cap (2026-09-23) the model gets one live-only note (_CAP_NOTE) and one tool-less call to say what it completed and what remains; that text is the reply, the run finishes normally (context saved, thread settled, row done, metadata.capped shown by the app as "Stopped at the tool-call limit. Reply to continue"), and a job delivers it as its message and counts as completed. Only when the closing call yields no text does MAX_ITERATIONS_REPLY remain — the history then stays unfinished for resume, the web row is marked failed with Retry, and a job delivers the plain _JOB_CAP_NOTICE. run_job returns a JobResult(reply, capped) so inbox ingestion can refuse to checkpoint a capped run whatever its text. Holds one ConversationHistory and one asyncio.Lock per thread key. Threads are the unit of context and concurrency (2026-09-18): run(user_message, message_id=…, reply_to=…) archives the message (unless the app pre-inserted it and passes its id), resolves its thread, and runs under that thread's lock. A reply continues its thread and runs with the thread's exchanges plus the ambient block; anything else is a new thread and runs with the ambient block alone — _ambient_context, the newest 5 threads of the past 24h in the current generation (root plus latest reply, 600 chars each, scheduled-run deliveries included, unanswered copies of a reminder that is newer, answered or the run's own thread left out), riding the live turn like a job snapshot and never stored. Scheduled runs get it too (2026-10-11), over the last 15 minutes only (_JOB_AMBIENT_WINDOW_SECONDS, measured when the run takes the jobs lock): a job that delivered through send_message leaves only a null close in the shared jobs history, so the compile catching up beside the stock check could not see its reminder and sent its own (2026-10-04; that compile's message list was closed by prompt the same day, but any two jobs firing together shared the blindness). Duplicates come from runs firing together, and a longer look-back would show a recurring job — a daily one, or one firing every two hours — its own previous delivery under the header's "do not repeat them". Key None is the one unthreaded history: scheduled jobs (run_job, never archived, serialized among themselves) and every run when there is no archive at all (tests). A settled thread history is dropped after its run (_release_thread) and rebuilt from the archive on the next reply; unfinished (failed, iteration-capped) ones stay for resume. Runs on one thread are serialized FIFO — concurrent appends into one history would interleave tool messages into orderings the API rejects — while different threads and jobs proceed in parallel; the vault's version guard handles two threads touching one page. resume(message_id) picks a failed turn (an outage, or the rare cap whose closing call produced nothing) up in place (a note is appended, never the text again, so a mid-run outage does not redo vault writes); it stands down when the history is empty (reset) or ends in a plain assistant reply (a later run covered it), and unwinds its note on another outage so repeated retries do not stack notes. Receipts and the empty-write guard (2026-09-23): _run_locked returns a RunResult — the reply, touched (every path a write may have changed, for the backup commit, over-reporting harmless) and wrote (only the paths whose tool result was not an error string), which _run records on the reply row as metadata.wrote so the app can show "Saved: …" under the reply (the 2026-08/09 usage audit found six cases of a confirmed write that never landed, each discovered days later from now.md). At the turn the model stops calling tools, a reply matching _CLAIM_RX (Spanish/English stems of the confirmation verbs — anot, apunt, guardad, registr, cerrad, program, cancel, saved, noted, scheduled…; generic closers like hecho/done deliberately excluded, they follow read-only work too) with nothing written and no send_message sent goes to a one-shot classification call (_claims_change, 2026-10-11: tool-less, agent-initiated, the reply read against the user's message — does it say something they reported or asked for was saved or changed, or already was?). The stems are only its prefilter: every flag of the 2026-09/10 audit was a reply that claimed nothing (notes "ya estaban apuntados" listed in answer to a question, edits suggested to a draft, a proofread's "erratas corregidas"), each costing a re-prompt and a false "Nothing was saved". A failed call or an unreadable verdict counts as a claim, the guard's behaviour before the classification. A claim is withdrawn from the history and the model gets one live-only user note quoting the draft (_GUARD_NOTE, never stored) and one more turn; a second no-write reply that is still classified as a claim is accepted and flagged metadata.guard = "unsaved", which the app renders as "Nothing was saved". Scheduled runs get the same guard. The system prompt is assembled on every run: an embedded capability prompt (src/assistant/prompts/*.md, sections gated by which features are wired) + vault/AGENTS.md — vault instructions take precedence by coming later. The assembled prompt must stay byte-stable across runs (a changing prefix defeats the provider's prompt cache); the current time rides on each user message as a [YYYY-MM-DD HH:MM local] prefix (converted to tz_name), stamped once and frozen in history. The stamp is deliberately local: stamping UTC left the model converting in its head, and UTC clock times leaked into vault fields that must be local. Scheduled-run deliveries are thread roots: every delivery path in run_job (the send_message tool, the JSON-close message, the raw fallback) goes through counting_send to the injected sender, which is the app's deliver — archive the text as an assistant row in SPACE, then push. A user reply to the reminder continues that thread with the reminder in context; a message typed on its own sees it through the ambient block. This replaced the pending-notes mirror queue (2026-09-18); the ambient block must keep including assistant-rooted threads, because without any such context the model once acknowledged a medication registration without performing it (2026-08-04).
  • copilot.py — auth chain (device flow → persisted OAuth token in state_dir/oauth_token → short-lived bearer, refreshed 2 min before expiry) and chat completions. Streaming is mandatory: the non-streaming endpoint drops tool calls for reasoning models. _read_sse_message aggregates the SSE stream back into a non-streaming-shaped response dict; reasoning_text/reasoning_opaque fields must round-trip through history for thinking models. Every request carries an X-Initiator: user|agent header (agent when the last message is a tool result) — Copilot counts premium requests only for user-initiated calls, so agent-loop follow-ups must not be marked user. Module-level singleton via copilot.init() / copilot.get_client(). list_models fetches the selectable-model catalog from /models (filtering and merging with the config aliases live in models.py as pure functions); it feeds the app's model picker (ModelPicker, also in models.py: options, the selected alias, a best-effort refresh that keeps the current and default aliases and keeps the cached list on failure) and, when default_family is configured, startup promotes the newest model of that family to default. The same response refreshes the per-model capability cache (ModelCapabilities: structured-output support and supported_endpoints), which chat consults on every turn — fetched lazily if startup's catalog call failed, retried a minute after a failed fetch rather than cached (a cached failure would pin a Responses-only model to the wrong endpoint until restart), and an unknown or unlisted model gets today's defaults (chat completions, no response_format). Two wire dialects, one internal shape. Newer OpenAI models (gpt-5.5, gpt-6-astra, …) are served only on /responses, and sending them to /chat/completions is a 400 unsupported_api_for_model (2026-09-05). chat routes a model to /responses only when the catalog lists that endpoint without chat completions, and responses.py translates at that boundary in both directions — build_payload (system → instructions, tool_calls → function_call items, role: tool → function_call_output, flattened tool schemas, response_format → text.format, image_url → input_image, always store: false with encrypted reasoning included) and read_sse/parse_response (only the terminal event matters — response.completed, or response.incomplete for a length-capped reply, which maps to finish_reason: length like the chat path and must not be mistaken for an outage; its output array becomes one chat-shaped assistant message, including refusal text, usage renamed to the chat field names). Stream error/response.failed events are retryable only for explicit server_error, internal_server_error or service_unavailable codes; other or unknown rejections raise RequestError without outage retries or durable queueing. Truncated or malformed streams remain retryable StreamErrors. A model refusal is reply content, not an outage. Everything above the client — history, compaction, retry queue, sub-agents, usage — stays chat-completions shaped and unaware. The raw output array a /responses turn produced is stashed verbatim on the assistant message under responses.OUTPUT_KEY and replayed verbatim — not rebuilt from content/tool_calls, because the API requires each reasoning item to be immediately followed by the item it produced, and a preamble-then-call turn interleaves them; the chat path strips that key from outgoing messages and the Responses path ignores chat's reasoning_text/reasoning_opaque, so a conversation can switch models across endpoints mid-way. The picker keeps models listing either endpoint. Not done: no reasoning-effort setting, no websocket variant, no server-side state (previous_response_id).
  • tools.py — VaultTools: read/create/rewrite/edit/append/move/list/search, all jailed to the vault root (_safe_path raises PermissionError on escape; the agent loop converts tool exceptions to error strings returned to the model, never crashes). edit_file replaces one exact snippet and refuses ambiguous edits (0 or >1 matches) — it exists so the wiki's now.md line patches cost a line instead of a full-file rewrite. Full rewrites are optimistic-concurrency guarded: the read_file tool output ends with a [version: <sha256[:8]>] token (added in dispatch, so internal Python callers see bare content; capped display and token derive from the same full snapshot), rewrite_file requires it back and refuses when the file changed in between, and create_file refuses to overwrite — so parallel threads cannot silently clobber each other's writes. Creates, rewrites, edits and internal write_file publish complete files through atomic_write_text (unique temporary file, fsync, then replace or exclusive hard-link create); appends remain direct appends. Atomic publication prevents partial-file reads, not races with uncoordinated external editors. The content writers (create_file/rewrite_file/append_file) strip a trailing [version: …] line from incoming content — a model pasting a read result back as new content otherwise bakes the token into the file (a production framer.md ended with one) — and check_vault flags whole-line tokens that got in anyway; interior occurrences are left to the check because only the trailing position is unambiguously the read suffix. edit_file/rewrite_file/move_file also refuse targets under raw/journal/ and wiki/log.md — append-only history, corrected by new entries, never edited — with the predicate on the resolved path so wiki/../raw/journal/… cannot slip past (append/create/read stay allowed). write_file still exists as a Python method for internal writes (schedule table) but is deliberately not a tool. read_file_full is an uncapped, vault-jailed internal read for parsers such as the scheduler that must not rewrite a truncated view; model-facing reads remain capped. save_attachment stores an uploaded image under attachments/<date>-<hex>.<ext>.
  • vault_check.py — deterministic wiki consistency checks behind the read-only check_vault tool (dispatched through VaultTools, which passes the local date): the task mirror (every open task on a live wiki page vs now.md's Tasks section, both directions); the event mirror (vault_check_events.py: every - YYYY-MM-DD — text bullet on a live page dated within the next 14 days needs a now.md line carrying its text and its date as a label, leading or parenthesized — a date mid-sentence in a Last 7 days bullet or inside a task's (due …) marker pairs nothing; ranges count by start date; text is compared with [reminder:…] markers dropped and links reduced to their text; an event dated today is matched by text against the section whose ## heading carries today's date, since Today lines have no date of their own, or against dateless lines when no heading does; a Decisions bullet dated today is the accepted residual; a school calendar sat on areas/familia.md for three weeks without any compile surfacing its first day, and the ingest that then heard "tomorrow is the first day of school" read only the dashboard and announced the fact as new, 2026-09-07); weekday names beside ISO dates vs the calendar (vault_check_weekdays.py: en/ca/es names; adjacency is punctuation-only, so "Monday standup (due 2026-08-01)" pairs nothing — except on now.md, where a flat bullet opening with a weekday and closing with (YYYY-MM-DD), the Upcoming form before day groups, is paired across the text between them); Upcoming day groups (2026-10-22: the next 7 days sit under one bold line per day, - **Saturday**, tomorrow's reading - **Tomorrow — Friday** with the en/ca/es tomorrow word; a label names exactly one date — today + 1, or that weekday's next occurrence after today — and every item nested one level below it must carry that date as its closing (YYYY-MM-DD), (start → end) or (due …); when all of a group's dated items agree on another date the label is reported, otherwise each misfiled item, and an item with no date or tomorrow's group without the tomorrow label is a finding too; deeper bullets are notes on an item; the event mirror reads (~date) and (start → end) as labels); reminder markers vs system/schedule.md both directions — every pending one-off job needs a [reminder:<id>] marker on a wiki page (so ingest trips over the reminder right where it edits the fact that obsoletes it), and a marker whose job is gone is stale; routine due-date arithmetic (Next due = last done + frequency for parseable en/es frequencies — daily, weekly incl. weekday-anchored, every N/N–M days, monthly — approximate/paused/blank rows skipped); index reconciliation (every wiki page linked from wiki/index.md or a nested subtree index, every index link resolving to a page on disk; skipped when no top index exists); schedule hygiene (rows hand-writing [scheduled run], restating the [silent] close contract, or using numeric cron weekdays — the schedule tool refuses these in new jobs, the check catches pre-existing and hand-edited rows); leaked [version: …] token lines; overdue open tasks — (due|para|per YYYY-MM-DD) before the user's local date, which run_checks(root, today=…) receives from VaultTools' configured timezone (the container clock is UTC) — reported from the owning page only, with the ones that lapsed since the last compile entry in wiki/log.md marked, under a heading that says escalate rather than fix because the user decides (the compile's prompt-enforced "flag lapsed deadlines" rule was followed on one night in nine, 2026-08); maintenance freshness (the last compile entry in wiki/log.md more than 2 days old, or the last lint entry more than 14 days old — entries the model wrote as a list item, - ## [date] compile, count too: four such compiles in 2026-09 made a running compile look stale and the 09-18 one announced it had not run — only for jobs enabled in config, which VaultTools receives as maintenance=, and only when an entry exists at all: a fresh vault has compile entries days before its first Sunday lint, and a job disabled in config is not held to a cadence; a vault once went 41 days without a lint because its row was never scheduled and nothing noticed); the Someday mirror (2026-09-23: a task marked (someday) — or the localized (sin prisa)/(algún día) — instead of a date is wanted-but-not-now: it must not also carry a date, must be listed under now.md's ## Someday section, and a line there must be such a task on a page; the marker exists so soft-dated tasks stop sitting in Today and being escalated every Sunday without an answer, and the lint reads the list out weekly instead); and, in vault_check_pages.py, the page hygiene a hand lint found on 2026-09-02: dead relative links on any page (the index check keeps its own wording for index files, so a missing page is reported once), empty ##-or-deeper sections, duplicate bullets, more than 15 done tasks outside an archive section, and empty or stub Status paragraphs — judged only on pages that carry the label, so a template stashed under projects/ cannot nag forever, and with now.md exempt from the empty-section and duplicate checks because it duplicates by design; fenced code blocks are skipped throughout. Schedule-reading checks parse only the first three table columns, so prompt-cell pipes can't corrupt them, and skip entirely when system/schedule.md is absent. Findings are path:line strings for the agent to fix — the compile/lint prompts call the tool so those sweeps are enumerated by code instead of sampled by the model, which is the design's point: turning prompt-enforced invariants into checked ones. Edit scope excludes raw/, system/ and wiki/log.md (append-only or bot-managed — a finding asking to edit them would nag forever); system/schedule.md and wiki/log.md are still read as inputs (pending jobs, last compile date, maintenance freshness), and findings about them say what to run or check, never what line to edit. wiki/archive/ is exempt from the mirror. Report caps at 100 findings and says so.
  • web.py — optional web research (enabled by [web] fourget_url in config). A quarantined Researcher sub-agent (fresh context per call, only web_search/fetch_page tools, no vault/schedule/send access) answers a ≤400-char research question from the main agent. Its loop caps at 8 turns; at the cap it gets one tool-less call (_RESEARCH_CAP_NOTE) to answer from what it found and name what it could not verify, and only an empty closing answer is the [tool error: research hit the iteration limit…] string (three company lookups in one day had returned that error with useful pages already fetched, 2026-09-22). Search goes through a self-hosted 4get the user runs alongside the bot (no published ports; the Compose service is in docs/deployment.md). 4get queries one upstream scraper per request (its default, DuckDuckGo) and reports scraper failures as a non-"ok" status string; web_search retries once through the brave scraper on an error or empty result before returning the first failure — upstream engines captcha/rate-limit scrapers intermittently, and that fallback is what SearXNG's engine-merging used to provide (4get replaced SearXNG 2026-08 because its browser-impersonating scrapers survive residential-IP captcha walls that had reduced SearXNG to one engine). Page fetches are SSRF-guarded (non-global addresses blocked, redirects re-checked per hop, size/char caps). Raw web content never enters the main agent's context — the only vault→web channel is the logged question string.
  • extract.py — extract_attachment tool backend: text files read directly, digital PDFs via the pypdf text layer (detected by an average-chars-per-page heuristic), scanned PDFs rendered with pypdfium2 and transcribed by the Copilot vision model, stored images described via vision. Output capped at 20k chars (20 text pages / 8 vision pages); sync parsing and rendering run in asyncio.to_thread. Images arrive through the app; other files reach attachments/ only by the user placing them there.
  • fanout.py — FanOut: the fan_out tool backend for bulk work (one instruction applied to ≤50 independent items). Each item gets a fresh-context worker sub-agent in the Researcher mould, run concurrently under a semaphore (4). Workers are deliberately read-only — vault read/list/search, load_skill, research when enabled, never write/schedule/send — because concurrent writers would race on vault files across their model turns; the main agent integrates results and does any writes. Per-item results cap at 2k chars so a full batch stays at or below read_file's 100k; one item's failure/timeout becomes an [item error: ...] block instead of sinking the batch. Worker calls are initiator="agent" (no premium requests) and recorded as usage.record("fanout", ...).
  • skills.py — SkillLibrary: stored procedures as markdown, discovered from two sources — shipped src/assistant/skills/*.md and vault system/skills/*.md, the vault shadowing the repo on slug collision (so the agent "edits" a shipped skill by writing a full copy to the vault). Each file's slug is its filename stem and its first **Use when:** line is the trigger; menu() renders slug+trigger only and Agent._load_system_prompt appends it last, so refining a skill body never changes the prompt (the prompt cache survives). Bodies load on demand through the load_skill tool, since repo skills live inside the package and read_file is vault-jailed. Model-supplied slugs are validated against [a-z0-9-]+ before any path join.
  • schedule.py — APScheduler (in-memory job store) with vault/system/schedule.md (a markdown table) as the source of truth. Re-parsed on startup and every 60s by a poll task, so hand edits work. One-off jobs overdue < 12h fire on restart; older ones are dropped. Recurring rows carry a next column — the next computed occurrence, advanced only after a run succeeds (a crash or failed run leaves it past, so the next startup retries; one-off rows are still removed even on failure, because the reload poll would hot-loop a failing one-off every minute) — and startup's catch_up() fires one coalesced late run, prefixed [catch-up: due at <local time>, offline], for any row whose next is past, however old; next is downtime bookkeeping only, the live trigger is still the cron expression, and reload() backfills it (from empty or garbage) without ever moving a parseable past value forward, since that would erase the missed-run evidence. Scheduled jobs re-enter the agent via run_job_fn, except [routine: …] rows (routines.py), which the scheduler runs itself. _fire registers its own task in _inflight so drain() can wait for a mid-run job at shutdown — these run outside the web app's request tasks, so nothing else covers them. The nightly compile and weekly lint are built-in jobs (maintenance.py), not rows: registered beside the table's jobs under the reserved ids compile/lint, crons from [maintenance] config (empty disables one; config.validate_for_run rejects a bad cron or numeric weekdays via schedule.cron_problem), shipped one-line prompts that point at the wiki.md procedures and never restate them, and last-success bookkeeping in state_dir/maintenance.json — the built-in twin of next: written only after a completed run, catch_up() fires one coalesced late run when the first cron occurrence after the last success is already past, and a first start with no record establishes a baseline instead of firing (the next backfill's mirror). They never touch schedule.md (so reload() cannot drop them), list as [built-in], and cancel_scheduled refuses them pointing at the config. They replaced user-created rows because a vault ran 41 days without a lint nobody had scheduled; a vault upgraded from rows must cancel its old compile/lint rows or the job runs twice.
  • routines.py — routine check-ins (2026-09-23): a system/schedule.md row whose prompt is [routine: <name>; every N min; until HH:MM] <message> is run by the scheduler, never by the model. Scheduler._fire recognizes the form (is_routine_prompt), _run_routine reads wiki/routines.md through read_file_full, matches the name against the first column (whitespace-insensitive, case-folded) and, unless Last done is today or Next due is a later day (routine_dates; a skipped occurrence — "Iré el jueves solamente" moved the gym's to Thursday and the Tuesday check-in asked anyway when only Last done was read, 2026-10-13; a blank, prose or past Next due still reminds, and the loop re-checks both each tick, so "hoy no voy" ends the repeats; the wiki prompt has ingest move Next due for a skip and the compile keep it; check_vault's routine arithmetic still flags a moved Next due for the frequencies it parses, so a skip holds only for the ones it doesn't, like "2x/semana", and a wrong future date on the daily pill row is corrected by the 03:00 compile), calls the injected remind_fn(text, thread) — Companion.remind: every call is a deliver(text, routine=True), a new archived thread root at the end of the chat pushed through the ordinary seen gate, and returns its thread; thread is the previous check-in's, and a repeat is skipped (the next tick re-checks) inside quiet hours, rather than held, so the window's end releases no burst, and while a web run is in flight, because a "Tomadas" being processed updates the table only when its run ends and a check-in landing meanwhile would post a reminder right after the confirmation. Each nag is a visible message, as the LLM pill job's re-avisos were: the first routine design (2026-09-23) re-pushed the 08:30 row instead, so a forgotten pill showed one reminder in the chat all morning and the repeats read as missing (2026-10-02), and before that its re-push had been dropped by the seen gate, which compares against the newest assistant row in the space (2026-09-26) — a check-in is now that newest row, so the ordinary gate is right for it. The row carries metadata.routine, which nudge_unseen skips: the routine's own repeats nag and stop when the table says done, which the nudge cannot see; a single-push routine is not nudged either, since a single push is what it promises. Each tick also ends the loop when its row was cancelled or edited (_routine_row_live): only drain() used to cancel loops, so a row re-created the same morning ran a second loop beside the first, two messages per interval. The ambient block leaves out an unanswered delivery when a newer identical one is listed, was answered, or is the thread being run (recent_threads), or a forgotten morning's copies would fill it or read as still pending — then spawns _routine_loop (_routine_tasks, sleeping every between checks, ending at until or the moment the row is updated by the user's reply through the normal ingest). drain() cancels the loops outright (nothing is lost by cutting a nag short) and catch_up() restarts a routine whose window (cron time … until, today) is still open rather than firing a [catch-up] prefixed run, whether its cron moment was missed (next past) or a restart cut its loop short after it fired (next already tomorrow: a deploy mid-morning used to end the day's nagging with the pill untaken, 2026-10-02); a single-push routine that already fired is not re-sent, and a resumed one posts its check-in at startup and repeats from there (a deploy mid-window can bring one check-in early; accepted); a name with no row delivers the text once with a WARNING and is a check_vault schedule-hygiene finding. The schedule tool refuses the form unless recurring, with a fixed-minute-and-hour cron (fixed_time) and a parseable body (every ≥ 5 min, every/until together). _local_now and _routine_sleep are the injectable clock the tests drive. It replaced the LLM pill job, which had cost up to nine Opus runs a morning (10% of all tokens over two months), drifted in wording daily, and once nagged after the pill was confirmed (2026-08-04); a vault upgrading from such a row replaces it by hand or through the bot.
  • lifecycle.py — signal traps and the graceful shutdown sequence, kept out of __main__ and the app so process lifecycle is nobody else's business. First SIGTERM/SIGINT drains, a second abandons the drain. graceful_shutdown stops the app accepting messages, pushes a "Restarting…" notice (with the count of runs in progress), then drains the app's in-flight runs and pushes and the scheduler's in-flight jobs concurrently under DRAIN_BUDGET (270s, under the stop_grace_period of 5m that docs/deployment.md requires the Compose service to set). A drain cut short pushes an important notice to every device saying how many messages were interrupted; nothing is lost — the app marks them interrupted and offers Retry — but a job mid-run may have partially completed (its recurring row keeps a past next, so the next start retries it). __main__ then closes the app and flushes usage and backup under a final 10s budget.
  • transcribe.py — voice via the ElevenLabs speech-to-text API (Scribe), since Copilot has no audio modality (and GitHub Models, the previous backend, was retired in 2026-08). Requires optional ELEVENLABS_API_KEY; the app's microphone button uploads a browser recording and gets text back, which the client puts in the composer rather than sending. Audio bytes are uploaded as-is — no local conversion, no ffmpeg, no chunking.
  • config.py — pydantic-settings; TOML file flattened into flat keys, env vars override (DEFAULT_MODEL, TIMEZONE, PWA_ORIGIN, ...). Unknown keys — including a leftover [telegram] section or PWA_ENABLED — are ignored. validate_for_run() fails fast listing all problems.
  • usage.py — token usage tracking: record() queues events in memory (zero critical-path I/O); a background task appends them to monthly JSONL files in state_dir/usage/ and regenerates a rolling 7-day system/usage.md view in the vault. Module singleton via usage.init() / module-level usage.record() (no-op when uninitialized, so tests need no setup).
  • backup.py — optional local-only git history of the vault ([backup] enabled). The git dir lives outside the vault (default state_dir/vault.git; the vault is typically inside iCloud Drive, whose sync engine corrupts git internals) and every git call passes --git-dir/--work-tree explicitly — never reintroduce a .git dir, gitfile, or symlink inside the vault. One commit per agent run that mutated the vault, staged by path from the run's tool calls (_paths_touched in agent.py — over-reporting is safe, staging an unchanged path is a no-op) so parallel threads don't leak in-flight writes into each other's commits; the message carries the triggering exchange, truncated. Residual race, accepted: a same-file write from another thread landing between a run's last write and its background commit rides along in that commit (and can leave the other run's commit empty) — attribution blurs, content is never lost or wrong; docs/ideas/backup-attribution-race.md records why locking was rejected and when to revisit. Commits are fire-and-forget tasks (schedule_commit) so replies are never delayed; VaultBackup.lock serializes them with vault-mutating tool dispatch (_VAULT_MUTATING_TOOLS). A slow sweep (5 min + startup) commits unattributed changes (other-device edits via iCloud, crash leftovers) but refuses while *.icloud eviction placeholders are present — an evicted file must not become a committed deletion. system/usage.md is excluded via the repo's info/exclude (regenerated derived data). Never pushes; git failures are logged, never raised.
  • inbox.py — startup ingestion of inbox.md at the vault root (offline capture: the user writes entries there while the bot is down). Startup ingestion never clears or rewrites the inbox: state_dir/inbox.processed.md stores the exact consumed snapshot. An unchanged inbox skips the run; an appended inbox contributes only its new suffix; divergent edits cause full reprocessing, accepting duplicates rather than losing captures. New content goes through one run_job call (so the close contract in prompts/schedule.md applies unchanged), then the observed snapshot is checkpointed atomically, leaving external appends or edits for the next startup. Failed, cancelled and iteration-capped runs leave the checkpoint unchanged (run_job returns the raw reply so ingestion can recognize MAX_ITERATIONS_REPLY). With backup enabled, commit_run must succeed before checkpointing, but git may see later external edits: the checkpoint, not the git commit, preserves the exact consumed input. Losing or restoring an older checkpoint can replay entries. This is a once-per-startup path, not an automatic checkpoint for chat-driven inbox processing. The task starts in __main__ only after backup.init_repo(), the scheduler, and the app.
  • retry_queue.py — durable Copilot-outage queue for one-off scheduled jobs only: a job whose run failed with copilot.CopilotUnavailableError (raised when retries exhaust on 5xx/network or transient stream failures; 4xx and permanent Responses rejections never queue) is persisted to state_dir/pending_runs.jsonl and replayed FIFO by a drain task with backoff (30s doubling to 5 min). The retry is the health probe — no separate health check that could pass while chat still fails — and an item is removed only after its replay fully succeeds, so a crash mid-replay reprocesses instead of losing. Jobs are handed over by _fire before their row is removed (rows must still be removed — a live failing row hot-loops through the reload poll) and replay through run_job with a [catch-up: failed at … during a Copilot outage] prefix, so the close contract and delivery apply unchanged; recurring jobs don't queue (their past next is the self-healing retry signal). A replay failing with a non-outage error is dropped with an important push so a poison item can't wedge the queue behind it. Web messages never queue here: their archived rows marked unavailable are their own durable queue, drained by Companion.replay_outages with this module's backoff (BACKOFF_INITIAL/next_backoff are shared for that reason). Telegram-era message records still in the file are dropped with a log line at load.

The web app

companion.py serves the packaged pwa/ assets and the JSON API in the bot's own process (aiohttp, pwa.host/pwa.port, always on). Chat is home and the only conversation; Now shows wiki/now.md read-only, rendered by pwa/markdown.js (the same renderer as assistant replies, tested by tests/test_markdown.mjs), without LLM calls or actions: vault-relative links render as their text since the app cannot open a page, only http(s):/mailto: links get an href, and the file's own leading # heading becomes the view's title. The shared ConversationArchive is passed in (the app never opens its own) and also stores push subscriptions and seen marks, never authentication sessions.

Instance identity: assistant.name / AGENT_NAME (default Noxide) controls model identity, app labels, installation manifest, app name and fallback text, not the push title. Never hard-code a user's instance name. HTML and worker templates receive safely escaped configuration; a name-derived worker cache suffix makes renames update the offline shell. Technical namespaces and app IDs remain stable across renames.

Theme: every colour in style.css is a token with a light palette on :root and a dark one applied by prefers-color-scheme unless <html data-theme> says otherwise; theme.js is a classic script in the head, after the stylesheet, that applies the stored choice (noxide-theme in localStorage: light/dark, absent means System) before first paint and keeps the theme-color meta on the sidebar surface, and the Preferences dialog's Appearance radios write that key and call window.applyTheme. Lifecycle: sw.js caches a versioned shell bundle, not API responses. Its CACHE version is stamped by the server (shell_revision: a hash of the instance name and every file in _ASSETS), so any change to a shell asset is a new version and installed apps are offered the update; there is nothing to bump by hand (a manual counter was skipped once, 2026-09-16, and a device that had installed the interim version was never offered the fix). A new shell file must be added to _ASSETS and the worker's SHELL list. Updates wait for the app's Reload action (ACTIVATE_UPDATE), preserving drafts and avoiding in-flight mutation requests. Other tabs offer their own reload. Startup/network/proxy failures show an unavailable screen. The shell is visible from the first paint, saying Opening chat…, since it used to stay blank until /api/session answered and a phone's waking VPN can hold that for seconds; and coming back to an open app (visibilitychange) fetches the chat at once instead of at the next poll, floating Updating… over the top of the timeline when that takes longer than UPDATING_DELAY_MS (400ms), until a request asked after the return settles (2026-10-15). tests.browser_pwa_lifecycle exercises this against a disposable server with Playwright.

Access control: there is no application password, login/logout or session-cookie authentication (PWA_PASSWORD was removed; the old session table is dropped on startup) and no user allowlist. Access control is exclusively the deployment's responsibility (Tailscale Serve, restricted tailnet rules, localhost-bound backend; never Funnel/public exposure). Keep Host/Origin checks and CSP as browser protections, not authentication. Preferences offers Appearance, the Model picker (GET /api/models refreshes the catalog through ModelPicker.refresh every time the dialog opens and returns choices with the current and default aliases; POST /api/model {alias} switches the Copilot client for every conversation and job until restart; both answer 409 when no picker was wired), Notifications, Install, Reset context and Clear local drafts; the chat view has no header row of its own, and the Load earlier messages button is rendered at the top of the scrolling timeline, only when an older page exists.

Push previews use the instance name as title and include up to 500 characters of reply/reminder text. Lifecycle pushes (2026-09-19): Companion.notify_lifecycle sends process notices (lifecycle.py's Restarting…/cut-short, __main__'s Started and dropped-reminder) as kind: lifecycle payloads with no thread and no unread count; the worker gives them their own noxide-lifecycle tag (so Started replaces Restarting… on the lock screen and neither replaces an unread reply) and leaves the badge alone. They are opt-in per device — a lifecycle column on subscriptions, set through POST /api/push (absent means keep the stored choice) and read through GET /api/push?endpoint= for the Preferences checkbox — because wud restarts the bot on every merge; an important=True notice (work cut short, a reminder dropped) goes to every device and graceful_shutdown waits up to 15s for it. startup_message compares shell_revision with state_dir/shell_revision and says "Restarted with an app update" when it changed (a first start only writes the baseline). Lifecycle text is never archived: it must not become assistant rows the model sees. A push waits PUSH_GRACE_SECONDS (5s, longer than the client's 2.2s poll) and is dropped for every device when a focused client has acknowledged displaying the space through the message's created timestamp (POST /api/seen, sent by app.js only when the tab is visible, the window focused, the user has given input within the last 3 minutes, the chat view current and the thread scrolled to the end — the input requirement came after a desktop left open on the chat overnight acknowledged a 03:01 reminder and no phone was notified, 2026-09-19); the marker is persisted per space in the seen table because it also drives the app badge: unread_count is the replies newer than the seen mark, returned on /api/messages (the client calls navigator.setAppBadge/clearAppBadge on each poll) and in every push payload as unread (the worker sets the badge from it, so a closed app still counts). A companion started over replies that have no seen mark baselines them as read, so the badge never opens on the whole history. The test button bypasses the grace. Clicking a notification opens the chat: the worker focuses the open app and posts it an OPEN_CHAT message, and app.js switches its own hash (drafts survive, route() runs); only with no open window does it openWindow the #chat URL. There is no presence tracking, no per-device unread state (the seen mark and the badge count are shared) and no cross-device dismissal; a device that displays the reply after the window still gets the push, since it cannot be retracted. drain() awaits delayed pushes so a reply landing just before a restart still notifies. Quiet hours (2026-09-23): with pwa.quiet_hours (HH:MM-HH:MM local, may cross midnight; parsed by quiet_hours.py, validated at startup), deliver still archives a reminder at once but records metadata.push.held_until instead of pushing (the nightly compile's notices had woken the phone at 03:01 on four of nine nights); release_held, run by nudge_loop every minute before the nudge sweep, sends held rows of the last day through _push_unless_seen once their time has passed, so a reminder already read in the app is marked displayed rather than pushed. Only proactive deliveries are held — replies and lifecycle pushes are not — and nudges neither fire inside the window nor count from the row's creation: they count from the push's at, otherwise a reminder released at 07:30 would be nudged at 07:31. Delivery status (2026-09-22): notify_push takes the archived row's message_id (the reply row reply:<user id>, or the delivery's own id) and _push records the outcome on it under metadata.push — devices tried, accepted by their push services, at — or displayed: true when the grace skipped it; acceptance by the provider is the only delivery signal there is. /api/messages carries the metadata and app.js shows a status line under an assistant message only when accepted < devices. The same line shows the run's receipt (metadata.wrote, wiki/ prefix dropped) and the guard's "Nothing was saved" (metadata.guard). nudge_unseen (every NUDGE_POLL_SECONDS from nudge_loop) pushes once more each reminder — a thread the assistant started, routine check-ins excepted — still newer than the seen mark NUDGE_AFTER_SECONDS after its push, marking nudged on the row so it happens once, and only within NUDGE_WINDOW_SECONDS so a device away for a week is not buried on its return.

Messages: accepted web messages are idempotent by client UUID; interruption/outage requires explicit retry, never silent replay of potential side effects. Several web messages may be pending at once: each is its own thread (or, with reply_to, a reply in one) and its own run; threads run in parallel while replies within a thread are serialized in arrival order by the agent's thread lock, so a later reply sees the earlier exchange; a message stays queued until the run holds the lock and running after, and MAX_IN_FLIGHT (16) bounds web runs, queued ones included. The app inserts the row and passes its id to Agent.run, which completes it (reply row, context records, status) atomically; the app's own send closure archives intermediate send_message texts as replies in the thread. A run that fails on CopilotUnavailableError marks the row unavailable and sets Companion.outage; replay_outages (a background task from __main__, 2026-09-22) then retries unavailable rows oldest first with the job queue's backoff — the retry is the health probe — through the same _process as a hand retry: a row that failed in this process calls Agent.resume (the failed turn is still in memory), a row left by a previous process (the event is set at construction when such rows exist) reruns the message with AUTO_RETRY_PREFIX. The loop awaits the run with asyncio.wait, never await task, so cancelling it at shutdown does not cancel a run the drain is waiting for; a row the user retried by hand meanwhile is skipped. Rows interrupted by a restart (marked by the archive on open) are never replayed automatically: they may have written already, so Retry reruns them with an explicit partial-processing warning. GET /api/messages returns a page of threads in the order they started (MESSAGE_PAGE 20, paged by the root's created, each capped at its newest THREAD_MESSAGES 100 messages) — a reply never moves its thread, the list is a timeline of interactions — and the client renders each thread as one box, chat-style (the assistant's messages left, the user's right, no name labels, the time small inside the bubble, day separators between threads), ending on a Reply link; on touch, swiping the box to the left replies too, as in Telegram (pointer events, touch only, since a mouse drag is text selection; 2026-10-11, it was rightward). The box follows the finger to the commit distance, arms (its reply icon turns solid), then resists; a pointercancel — the system taking the gesture over — snaps back without acting. The thread list clips sideways overflow and the icon renders only mid-swipe, because a box pushed past the list's edge gave it a horizontal scrollbar under the finger. On coarse pointers the Reply link and the reply chip's Cancel are finger-sized (44px and 40px), and Cancel sits at the chip's left end, away from Send. Asking for the active thread again starts a new thread; reply mode marks the box and its link, shows a chip above the composer and the send carries reply_to. A notification click opens the reply's thread in reply mode (OPEN_CHAT with the thread, or #chat/<thread> for a fresh window). The run's on_research callback sets an in-memory activity text on the message, returned on /api/messages and shown on its status line ("Searching the web…") until the run ends. Proactive deliveries go through Companion.deliver: archived as an assistant thread root in SPACE, then pushed with that thread, so the notification click opens it in reply mode.

Attachments: POST /api/attachments takes a raw body (images JPEG/PNG/WebP/GIF and, since 2026-09-22, documents PDF/plain text/Markdown/CSV/JSON — _UPLOAD_TYPES; sniffed against the declared type by magic bytes, or for text types by decoding as UTF-8 without NUL bytes; 20 MB cap read from the stream in chunks so the app-wide 64 KB JSON limit does not apply), stores it through VaultTools.save_attachment and returns the vault path; a message then lists up to MAX_ATTACHMENTS such paths, validated against a strict attachments/<date>-<hex>.<ext> pattern and existence, plus an optional names map (stored path → original file name, sanitized to one path component without control characters by _safe_name, keys must be the message's own paths), stored in the row's metadata. _attachment_turn rebuilds the model-facing text and the vision input at run time: images get a stored-path note each (numbered when several) and ride the turn as data URLs; documents get a note with their original name, type and stored path and never their bytes (the model reads them through extract_attachment); the two kinds are numbered separately. Images ride only the live turn, stored history keeps the text so later turns never re-pay image tokens, and a resume does not show them again (its turn already carried them). GET /api/attachment?path= serves any stored attachment with its uploaded type, jailed by the same pattern, for thumbnails and file chips. A thumbnail links there with target="_blank", but in the iOS home-screen app (navigator.standalone) a tap opens it in the #image-viewer dialog instead: the link is inside the manifest scope, so iOS loaded the raw image into the app's own window, which has no back button (2026-10-09); browsers keep the new tab. A document's file chip trapped the app the same way, and there it opens the #document-viewer dialog (2026-10-13): a text file as text, a PDF as one image per page, because WebKit on iOS shows only the first page of a PDF embedded in a page (an <iframe>/<embed> is no fix). GET /api/attachment/pages?path= returns the page sizes, so the lazy page images have their height before they load, and GET /api/attachment/page?path=&page=N (1-based) draws one page as JPEG through extract.render_pdf_page, under the same PDFium lock as extraction (PDFium is not thread-safe), its longer side capped at 2400px so an oversized or malformed page cannot become a gigabyte bitmap; a PDF PDFium cannot open is a 422. Only the dialog's button or Escape closes it, since a tap there is a scroll. The client decodes and re-encodes images on the device (JPEG within 2000px, keeping small accepted originals) because phones hand over HEIC, uploads documents as they are typed by extension, and refuses anything else with a toast; paste, drag-drop and the attach button share one path. The CSP's img-src allows blob: because the composer previews are object URLs (they were silently blocked until 2026-09-22). Voice: POST /api/transcribe takes a raw browser recording and returns text through the Transcriber (409 when unconfigured, 502 on a transcription error); /api/session reports voice so the button hides without a key.

Capture (2026-09-23): POST /api/capture is the one route a non-browser client can use — an iOS Shortcut, so Siri can ask the assistant a question and read the reply aloud. It is enabled by pwa.capture_token (PWA_CAPTURE_TOKEN, 16+ characters, validated at startup) and answers 404 without one. The security middleware exempts this path from the Origin/X-Noxide check and the handler requires Authorization: Bearer <token> instead (_capture_authorized, constant-time compare, 403 otherwise); the token is a stand-in for the same-origin headers a Shortcut cannot send, not access control, which stays with the network, and it opens no other route. The body is {"text", "wait"?} — or, with any content type but JSON, a recording (_capture_input: read through _read_upload, transcribed by the Transcriber like /api/transcribe, 409 without one, 502 on a transcription error, 400 on silence, wait from the query string, and the transcript returned as text beside the reply so the Shortcut can show what was heard; this is how a Spanish or Catalan question bypasses Siri's language). The message is archived with a server-generated id and metadata.via = "shortcut" (the timeline shows a "Shortcut" tag beside the time) and launched exactly like a composer message, then the handler waits — asyncio.wait on the task, never await task, so a client that gives up cannot cancel the run — up to wait seconds (CAPTURE_WAIT_SECONDS 45 by default, capped at CAPTURE_WAIT_MAX 55; the Shortcut owns the number because the Shortcuts app's own request timeout is the constraint) and returns {"id", "status", "reply"} from the row's state: done with the reply rendered by spoken (markdown markers dropped, since Siri reads the asterisks; the archived reply keeps them), working when the run outlasts the wait (it carries on and pushes as any reply), unavailable after a Copilot outage (the row is in the automatic replay queue), failed otherwise. reply is always a sentence a Shortcut can speak. A reply handed back this way is heard, so its id goes into Companion.spoken and _push_unless_seen records it displayed instead of pushing it (the badge still counts it: the seen mark is not advanced, since that would mark older unread replies read too). Not done on purpose: an idempotency key (a Shortcut re-run after a timeout is a second message), replies threaded onto an earlier capture, uploads through the token, a polling endpoint.

Layout notes that took real debugging: the composer textarea carries autocorrect="off" only on devices without a touch-first pointer (touchFirst() in app.js, (pointer: coarse), the same signal that keeps Return for newlines on the phone) and nothing else — Safari on macOS rewrites words in any editable field as they are typed ("treminada" became "terminada", 2026-09-25) where chat apps only underline them, so autocorrect is off there and spellcheck stays at its default; do not add spellcheck="false", the underline is the wanted behaviour. On the phone the attribute is left out, because the keyboard's typo correction is wanted as in every other app: the first fix put it on every device and iOS lost its correction with it (2026-09-27); tests.browser_pwa_lifecycle checks both sides. Composer buttons prevent mousedown focus so the textarea keeps focus and the layout does not shift under the tap. On the phone the Chat/Now navigation sits in the header, so the composer is the bottom edge and carries the home-indicator inset, dropped while the field has focus. iOS keeps the page full height under the keyboard and scrolls the window to reveal the field, which used to take the header off-screen: app.js sizes .shell to visualViewport.height (--shell-height) whenever it is shorter than the window at scale 1 and pins the window at the top, so the header stays and the composer sits right above the keyboard; it rechecks on window focus/resize/pageshow, visibilitychange, focusout and a 2s timer while visible, because a keyboard dismissed while the app is in the background fires no viewport event and the shrunken shell stuck on return (2026-09-17). Rechecking cannot help when iOS leaves the window itself shrunk once the keyboard has gone (a WebKit bug in home-screen apps on iOS 17/18: window height, visual viewport and 100dvh all report the keyboard-reduced height, no event fires, the band below the composer stays until force-quit, 2026-09-19), so app.js also sends the shell through a layout (display none, reflow, back) 300ms after the field blurs and after the app returns — never while the field has focus, since hiding it closes the keyboard, and with the scrollers' positions put back, since a hidden scroller forgets them. Both that rule and the composer's dropped inset read a focused field as a raised keyboard, so on the phone the two must stay together: iOS raises the keyboard only for a tap, so the app focuses the composer itself only off touch devices (focusComposer: a notification opening a thread, a finished transcription), and it blurs the field when the app goes to the background, since iOS can bring it back focused with no keyboard. A focused field with no keyboard is what left the band below the composer, or the composer flush on the home indicator, on screen (2026-10-15). The composer's auto-grow (fit) restores the thread's scroll position in the same step, because measuring shrinks the field to one line and the thread's clamp otherwise showed as content jumping up. The thread follows its end until the reader scrolls up, and again once they scroll back: stickToEnd in app.js is an intent set only from the thread's scroll events (and from openThread, the one place the app moves the reader itself), never a measurement taken when something changes, and every render, box resize and content resize (a ResizeObserver on the thread's children, re-targeted per render) re-pins while it holds. It was a gap measurement per render, and a thumbnail, which has no reserved height, landed after the render had pinned the end and pushed the end 160px away; the next message then read the reader as scrolled up and nothing pinned again until they scrolled by hand (2026-09-19).

Web push is optional and VAPID-based with restricted provider endpoints and no redirects. Shell-only service-worker caching and same-origin/Host checks are intentional; deployment provides access control. Keep deployment snippets in docs/deployment.md; use tests.preview_companion for a disposable fake-agent UI preview.

Tool plumbing

Tools are plain OpenAI function schemas assembled in Agent._all_tools() from VaultTools.tool_schemas(), Scheduler.tool_schemas(), SkillLibrary.tool_schemas() (when wired), agent-owned history tools (get_history, search_history), and callback-backed tools (send_message, research, extract_attachment, fan_out) added only when the corresponding callback was injected. History tools receive the current conversation's history explicitly and are not available to workers. Dispatch is by name in Agent._dispatch_tool. To add a tool: add its schema and its dispatch branch, keeping the return value a string (error strings like [tool error: ...] go back to the model). Vault file tools have two dispatch layers: VaultTools.dispatch and the file-tools allowlist in Agent._dispatch_tool_unlocked — a tool present in the first but missing from the second is advertised to the model yet answers [unknown tool: ...] (how move_file first shipped broken; the agent-level test is what catches it).

Conventions the code relies on

  • Vault file reads return the sentinel string "[file not found: ...]" instead of raising; callers check startswith("[file not found"). edit_file mirrors this with "[edit error: ...]" for a missing or ambiguous match, and create_file/rewrite_file/move_file with "[create error: ...]"/"[rewrite error: ...]"/"[move error: ...]" for an existing file (or destination) or a stale version token — all leave the file untouched so the model can re-read and retry.
  • Every tool that returns content caps it and says so in the returned string (read_file 100k chars, search 200 matches, extract_attachment 20k, research summary 6k). A new content tool should do the same — an uncapped one can displace the whole conversation.
  • system/schedule.md rows need all six columns (five-column rows from before next still parse, with next empty); interior blanks are real columns, so the parser must not collapse them (that bug silently dropped hand-written jobs). Unparseable rows inside the table are logged at WARNING rather than skipped in silence, and _read_table hands them back so _write_entries can re-emit them verbatim — every mutation rewrites the whole table, so a lossy read once truncated a live schedule to the single row being added. Never reintroduce a write that takes only the parsed entries.
  • wiki/now.md duplicates state owned by other wiki pages, so it is the thing ingest most easily leaves stale. prompts/wiki.md makes reading it a mandatory ingest step rather than a conditional one, and states the routine-completion recipe (the case that regressed) in full under ### wiki/routines.md — a local recipe that omits now.md overrides the general ingest list in practice.
  • run_job injects a fire-time state snapshot into the run's live turn: the current content of every vault page the job prompt names (_extract_vault_paths — slash-containing .md paths only, capped at 5 files × 5k chars). This backs the schedule prompt's check-state-before-delivering rule with state the model cannot fail to see — a follow-up job once asked about an interview whose outcome was already recorded in the very page its prompt named. Snapshots ride only the live turn (stored history keeps the bare prompt, the same mechanism as images), or the jobs history would re-pay every old snapshot on every job run.
  • Scheduled runs are tagged [scheduled run] by run_job and close with a JSON object (_JOB_CLOSE_SCHEMA: {"silent": bool, "message": string|null}) per the contract in prompts/schedule.md — which also forbids restating the contract in per-job prompts, because such copies drift (a rewritten "responde [silent]" is how a misplaced sentinel once reached the user verbatim). run_job parses the close tolerantly; when it doesn't parse, a [silent] anywhere in the reply stands down, and anything else is delivered raw as the safety net so a reminder is never lost — except a capped run, which delivers its closing summary as is (the job-close contract does not apply to it), or, when that summary is empty, the sentinel MAX_ITERATIONS_REPLY, a protocol value for callers delivered as a plain one-sentence notice naming the job's prompt (a catch-up compile once delivered the sentinel verbatim, 2026-09-22; it hit the cap chasing check_vault findings one edit and one re-check at a time, which is why the compile procedure now batches the fixes into one turn). Job runs also send the schema as response_format, gated on the /models capability flag — verified (2026-07-29) to be accepted but not enforced by Copilot for every model the bot can use, so the tolerant parse is the mechanism and the API enforcement is a free upgrade if it ever materializes.
  • Images are sent to the model as a multimodal message only on the turn they arrive; stored history keeps the text-only version to avoid re-paying image tokens. The model only ever sees a stored attachment's path — never the bytes, except through extract_attachment and the live image turn.
  • The schedule.md table is parsed/rewritten line-by-line by hand — keep the exact header/separator format defined in schedule.py.
  • Replies carry no process notes. prompts/base.md (Chat discipline) says every word sent to the user arrives verbatim, that right after a tool result the reply starts at once, and quotes the two English notes that did, above the real Spanish reply (2026-09-29, 2026-10-02): both were a short final turn right after a tool result, with almost no output beyond the visible text, so the model's reasoning came out as text. The fix is prompt-only on purpose: a detector cannot tell a leaked note from English the user asked for (an answer for an English application form), and a language scan of the whole archive caught only one of the two, since "Guardado ✅" carries no language signal. Do not add a reply filter without new evidence. The empty-write guard's live note (_GUARD_NOTE) asks for the user's language like the cap note, since an English note right before the final turn is the same shape as the leaks.
  • Skill lookups return the sentinel "[skill not found: <slug>]", mirroring the vault's "[file not found: ...]" convention; a skill file lacking a **Use when:** line is excluded from the prompt menu and logged at WARNING.

History

Telegram was the original and, until 2026-09-21, the primary interface; the web app started as an optional companion. When the user moved to the app entirely, Telegram support was removed rather than kept dormant, together with everything that only existed to reconcile two transports: chat ids and the pinned home chat alias, WEB_CHAT_ID, per-chat archive spaces and their one-time migrations, the Telegram message batcher, the /model inline picker (now the Preferences dropdown), the /clear command (now Reset context), the user allowlist, the message half of the outage retry queue (web messages were never queued there), Telegram delivery bookkeeping (delivery, source, telegram_outputs) and the python-telegram-bot dependency. Do not add a transport abstraction back for a hypothetical second client; the design is one conversation, addressed by threads. What the app still lacks compared with Telegram (burst merging, one-tap voice notes, guaranteed delivery) is tracked in docs/ideas/telegram-parity.md; non-image uploads, delivery status and automatic outage replay were restored on 2026-09-22.

CI / deployment

.github/workflows/ci.yml runs ruff check and pytest on every pull request and push to main. .github/workflows/publish-image.yml builds assistant/Dockerfile (multi-arch) and pushes ghcr.io/acroca/noxide on pushes to main (latest) and v*.*.* tags. Action versions are pinned to commit SHAs — keep it that way.