clarify

Ask the user a question when you need clarification, feedback, or a decision before proceeding. Supports two modes:

1. **Multiple choice** — provide up to 4 choices. The user picks one or types their own answer via a 5th 'Other' option.
2. **Open-ended** — omit choices entirely. The user types a free-form response.

Use this tool when:
- The task is ambiguous and you need the user to choose an approach
- You want post-task feedback ('How did that work out?')
- You want to offer to save a skill or update memory
- A decision has meaningful trade-offs the user should weigh in on

Do NOT use this tool for simple yes/no confirmation of dangerous commands (the terminal tool handles that). Prefer making a reasonable default choice yourself when the decision is low-stakes.

The question to present to the user.

Choices:
Up to 4 answer choices. Omit this parameter entirely to ask an open-ended question. When provided, the UI automatically appends an 'Other (type your answer)' option.

cronjob

Manage scheduled cron jobs with a single compressed tool.

Use action='create' to schedule a new job from a prompt or one or more skills.
Use action='list' to inspect jobs.
Use action='update', 'pause', 'resume', 'remove', or 'run' to manage an existing job.

To stop a job the user no longer wants: first action='list' to find the job_id, then action='remove' with that job_id. Never guess job IDs — always list first.

Jobs run in a fresh session with no current-chat context, so prompts must be self-contained.
If skills are provided on create, the future cron run loads those skills in order, then follows the prompt as the task instruction.
On update, passing skills=[] clears attached skills.

NOTE: The agent's final response is auto-delivered to the target. Put the primary
user-facing content in the final response. Cron jobs run autonomously with no user
present — they cannot ask questions or request clarification.

Important safety rule: cron-run sessions should not recursively schedule more cron jobs.

One of: create, list, update, pause, resume, remove, run

Required for update/pause/resume/remove/run

For create: the full self-contained prompt. If skills are also provided, this becomes the task instruction paired with those skills.

For create/update: '30m', 'every 2h', '0 9 * * *', or ISO timestamp

Optional human-friendly name

Optional repeat count. Omit for defaults (once for one-shot, forever for recurring).

Omit this parameter to auto-deliver back to the current chat and topic (recommended). Auto-detection preserves thread/topic context. Only set explicitly when the user asks to deliver somewhere OTHER than the current conversation. Values: 'origin' (same as omitting), 'local' (no delivery, save only), or platform:chat_id:thread_id for a specific destination. Examples: 'telegram:-1001234567890:17585', 'discord:#engineering', 'sms:+15551234567'. WARNING: 'platform:chat_id' without :thread_id loses topic targeting.

Optional ordered list of skill names to load before executing the cron prompt. On update, pass an empty array to clear attached skills.

Optional per-job model override. If provider is omitted, the current main provider is pinned at creation time so the job stays stable.

Provider name (e.g. 'openrouter', 'anthropic', or 'custom:<name>' for a provider defined in custom_providers config — always include the ':<name>' suffix, never pass the bare 'custom'). Omit to use and pin the current provider.

Model name (e.g. 'anthropic/claude-sonnet-4', 'claude-sonnet-4')

Optional path to a script that runs each tick. In the default mode its stdout is injected into the agent's prompt as context (data-collection / change-detection pattern). With no_agent=True, the script IS the job and its stdout is delivered verbatim (classic watchdog pattern). Relative paths resolve under ~/.hermes/scripts/. ``.sh``/``.bash`` extensions run via bash, everything else via Python. On update, pass empty string to clear.

Default: False (LLM-driven job — the agent runs the prompt each tick). Set True to skip the LLM entirely: the scheduler just runs ``script`` on schedule and delivers its stdout verbatim. No tokens, no agent loop, no model override honoured.

REQUIREMENTS when True: ``script`` MUST be set (``prompt`` and ``skills`` are ignored).

DELIVERY SEMANTICS when True: (a) non-empty stdout is sent verbatim as the message; (b) EMPTY stdout means SILENT — nothing is sent to the user and they won't see anything happened, so design your script to stay quiet when there's nothing to report (the watchdog pattern); (c) non-zero exit / timeout sends an error alert so a broken watchdog can't fail silently.

WHEN TO USE True: recurring script-only pings where the script itself produces the exact message text (memory/disk/GPU watchdogs, threshold alerts, heartbeats, CI notifications, API pollers with a fixed output shape). WHEN TO USE False (default): anything that needs reasoning — summarize a feed, draft a daily briefing, pick interesting items, rephrase data for a human, follow conditional logic based on content.

Optional job ID or list of job IDs whose most recent completed output is injected into the prompt as context before each run. Use this to chain cron jobs: job A collects data, job B processes it. Each entry must be a valid job ID (from cronjob action='list'). Note: injects the most recent completed output — does not wait for upstream jobs running in the same tick. On update, pass an empty array to clear.

Optional list of toolset names to restrict the job's agent to (e.g. ["web", "terminal", "file", "delegation"]). When set, only tools from these toolsets are loaded, significantly reducing input token overhead. When omitted, all default tools are loaded. Infer from the job's prompt — e.g. use "web" if it calls web_search, "terminal" if it runs scripts, "file" if it reads files, "delegation" if it calls delegate_task. On update, pass an empty array to clear.

Optional absolute path to run the job from. When set, AGENTS.md / CLAUDE.md / .cursorrules from that directory are injected into the system prompt, and the terminal/file/code_exec tools use it as their working directory — useful for running a job inside a specific project repo. Must be an absolute path that exists. When unset (default), preserves the original behaviour: no project context files, tools use the scheduler's cwd. On update, pass an empty string to clear. Jobs with workdir run sequentially (not parallel) to keep per-job directories isolated.

Spawn one or more subagents to work on tasks in isolated contexts. Each subagent gets its own conversation, terminal session, and toolset. Only the final summary is returned -- intermediate tool results never enter your context window.

TWO MODES (one of 'goal' or 'tasks' is required):
1. Single task: provide 'goal' (+ optional context, toolsets)
2. Batch (parallel): provide 'tasks' array with up to delegation.max_concurrent_children items (default 3, configurable via config.yaml, no hard ceiling). All run concurrently and results are returned together. Nested delegation requires role='orchestrator' and delegation.max_spawn_depth >= 2.

WHEN TO USE delegate_task:
- Reasoning-heavy subtasks (debugging, code review, research synthesis)
- Tasks that would flood your context with intermediate data
- Parallel independent workstreams (research A and B simultaneously)

WHEN NOT TO USE (use these instead):
- Mechanical multi-step work with no reasoning needed -> use execute_code
- Single tool call -> just call the tool directly
- Tasks needing user interaction -> subagents cannot use clarify
- Durable long-running work that must outlive the current turn -> use cronjob (action='create') or terminal(background=True, notify_on_complete=True) instead. delegate_task runs SYNCHRONOUSLY inside the parent turn: if the parent is interrupted (user sends a new message, /stop, /new) the child is cancelled with status='interrupted' and its work is discarded. Children cannot continue in the background.

IMPORTANT:
- Subagents have NO memory of your conversation. Pass all relevant info (file paths, error messages, constraints) via the 'context' field.
- If the user is writing in a non-English language, or asked for output in a specific language / tone / style, say so in 'context' (e.g. "respond in Chinese", "return output in Japanese"). Otherwise subagents default to English and their summaries will contaminate your final reply with the wrong language.
- Subagent summaries are SELF-REPORTS, not verified facts. A subagent that claims "uploaded successfully" or "file written" may be wrong. For operations with external side-effects (HTTP POST/PUT, remote writes, file creation at shared paths, publishing), require the subagent to return a verifiable handle (URL, ID, absolute path, HTTP status) and verify it yourself — fetch the URL, stat the file, read back the content — before telling the user the operation succeeded.
- Leaf subagents (role='leaf', the default) CANNOT call: delegate_task, clarify, memory, send_message, execute_code.
- Orchestrator subagents (role='orchestrator') retain delegate_task so they can spawn their own workers, but still cannot use clarify, memory, send_message, or execute_code. Orchestrators are bounded by delegation.max_spawn_depth (default 2) and can be disabled globally via delegation.orchestrator_enabled=false.
- Each subagent gets its own terminal session (separate working directory and state).
- Results are always returned as an array, one entry per task.

What the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history.

Background information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs.

Toolsets to enable for this subagent. Default: inherits your enabled toolsets. Available toolsets: 'browser', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'vision', 'web', 'yuanbao'. Common patterns: ['terminal', 'file'] for code work, ['web'] for research, ['browser'] for web interaction, ['terminal', 'file', 'web'] for full-stack tasks.

Task goal

Task-specific context

Toolsets for this specific task. Available: 'browser', 'cronjob', 'discord', 'discord_admin', 'feishu_doc', 'feishu_drive', 'file', 'homeassistant', 'image_gen', 'kanban', 'search', 'session_search', 'skills', 'spotify', 'terminal', 'todo', 'tts', 'video', 'vision', 'web', 'yuanbao'. Use 'web' for network access, 'terminal' for shell, 'browser' for web interaction.

Per-task ACP command override (e.g. 'claude'). Overrides the top-level acp_command for this task only.

Per-task ACP args override.

Per-task role override. See top-level 'role' for semantics.

Batch mode: tasks to run in parallel (limit configurable via delegation.max_concurrent_children, default 3). Each gets its own subagent with isolated context and terminal session. When provided, top-level goal/context/toolsets are ignored.

Role of the child agent. 'leaf' (default) = focused worker, cannot delegate further. 'orchestrator' = can use delegate_task to spawn its own workers. Requires delegation.max_spawn_depth >= 2 in config; ignored (treated as 'leaf') when the child would exceed max_spawn_depth or when delegation.orchestrator_enabled=false.

Override ACP command for child agents (e.g. 'claude', 'copilot'). When set, children use ACP subprocess transport instead of inheriting the parent's transport. Enables spawning Claude Code (claude --acp --stdio) or other ACP-capable agents from any parent, including Discord/Telegram/CLI.

Arguments for the ACP command (default: ['--acp', '--stdio']). Only used when acp_command is set. Example: ['--acp', '--stdio', '--model', 'claude-opus-4-6']

Run a Python script that can call Hermes tools programmatically. Use this when you need 3+ tool calls with processing logic between them, need to filter/reduce large tool outputs before they enter your context, need conditional branching (if X then Y else Z), or need to loop (fetch N pages, process N files, retry on failure).

Use normal tool calls instead when: single tool call with no processing, you need to see the full result and apply complex reasoning, or the task requires interactive user input.

Available via `from hermes_tools import ...`:

  read_file(path: str, offset: int = 1, limit: int = 500) -> dict
    Lines are 1-indexed. Returns {"content": "...", "total_lines": N}
  write_file(path: str, content: str) -> dict
    Always overwrites the entire file.
  search_files(pattern: str, target="content", path=".", file_glob=None, limit=50) -> dict
    target: "content" (search inside files) or "files" (find files by name). Returns {"matches": [...]}
  patch(path: str, old_string: str, new_string: str, replace_all: bool = False) -> dict
    Replaces old_string with new_string in the file.
  terminal(command: str, timeout=None, workdir=None) -> dict
    Foreground only (no background/pty). Returns {"output": "...", "exit_code": N}

Limits: 5-minute timeout, 50KB stdout cap, max 50 tool calls per script. terminal() is foreground-only (no background or pty).

Scripts run in the session's working directory with the active venv's python, so project deps (pandas, etc.) and relative paths work like in terminal().

Print your final result to stdout. Use Python stdlib (json, re, math, csv, datetime, collections, etc.) for processing between tool calls.

Also available (no import needed — built into hermes_tools):
  json_parse(text: str) — json.loads with strict=False; use for terminal() output with control chars
  shell_quote(s: str) — shlex.quote(); use when interpolating dynamic strings into shell commands
  retry(fn, max_attempts=3, delay=2) — retry with exponential backoff for transient failures

Python code to execute. Import tools with `from hermes_tools import terminal, ...` and print your final result to stdout.

memory

Save durable information to persistent memory that survives across sessions. Memory is injected into future turns, so keep it compact and focused on facts that will still matter later.

WHEN TO SAVE (do this proactively, don't wait to be asked):
- User corrects you or says 'remember this' / 'don't do that again'
- User shares a preference, habit, or personal detail (name, role, timezone, coding style)
- You discover something about the environment (OS, installed tools, project structure)
- You learn a convention, API quirk, or workflow specific to this user's setup
- You identify a stable fact that will be useful again in future sessions

PRIORITY: User preferences and corrections > environment facts > procedural knowledge. The most valuable memory prevents the user from having to repeat themselves.

Do NOT save task progress, session outcomes, completed-work logs, or temporary TODO state to memory; use session_search to recall those from past transcripts.
If you've discovered a new way to do something, solved a problem that could be necessary later, save it as a skill with the skill tool.

TWO TARGETS:
- 'user': who the user is -- name, role, preferences, communication style, pet peeves
- 'memory': your notes -- environment facts, project conventions, tool quirks, lessons learned

ACTIONS: add (new entry), replace (update existing -- old_text identifies it), remove (delete -- old_text identifies it).

SKIP: trivial/obvious info, things easily re-discovered, raw data dumps, and temporary task state.

The action to perform.

Which memory store: 'memory' for personal notes, 'user' for user profile.

The entry content. Required for 'add' and 'replace'.

Short unique substring identifying the entry to replace or remove.

patch

Targeted find-and-replace edits in files. Use this instead of sed/awk in terminal. Uses fuzzy matching (9 strategies) so minor whitespace/indentation differences won't break it. Returns a unified diff. Auto-runs syntax checks after editing.

Replace mode (default): find a unique string and replace it.
Patch mode: apply V4A multi-file patches for bulk changes.

Edit mode: 'replace' for targeted find-and-replace, 'patch' for V4A multi-file patches

File path to edit (required for 'replace' mode)

Text to find in the file (required for 'replace' mode). Must be unique in the file unless replace_all=true. Include enough surrounding context to ensure uniqueness.

Replacement text (required for 'replace' mode). Can be empty string to delete the matched text.

Replace all occurrences instead of requiring a unique match (default: false)

V4A format patch content (required for 'patch' mode). Format:
*** Begin Patch
*** Update File: path/to/file
@@ context hint @@
 context line
-removed line
+added line
*** End Patch

process

Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (send raw stdin data without newline), 'submit' (send data + Enter, for answering prompts), 'close' (close stdin/send EOF).

list poll log wait kill write submit close

Action to perform on background processes

Process session ID (from terminal background output). Required for all actions except 'list'.

Text to send to process stdin (for 'write' and 'submit' actions)

Max seconds to block for 'wait' action. Returns partial output on timeout.

Line offset for 'log' action (default: last 200 lines)

Max lines to return for 'log' action

Read a text file with line numbers and pagination. Use this instead of cat/head/tail in terminal. Output format: 'LINE_NUM|CONTENT'. Suggests similar filenames if not found. Use offset and limit for large files. Reads exceeding ~100K characters are rejected; use offset and limit to read specific sections of large files. NOTE: Cannot read images or binary files — use vision_analyze for images.

Path to the file to read (absolute, relative, or ~/path)

Line number to start reading from (1-indexed, default: 1)

Maximum number of lines to read (default: 500, max: 2000)

Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents.

Content search (target='content'): Regex search inside files. Output modes: full matches with line numbers, file paths only, or match counts.

File search (target='files'): Find files by glob pattern (e.g., '*.py', '*config*'). Also use this instead of ls — results sorted by modification time.

Regex pattern for content search, or glob pattern (e.g., '*.py') for file search

'content' searches inside file contents, 'files' searches for files by name

Directory or file to search in (default: current working directory)

Filter files by pattern in grep mode (e.g., '*.py' to only search Python files)

Maximum number of results to return (default: 50)

Skip first N results for pagination (default: 0)

Output format for grep mode: 'content' shows matching lines with line numbers, 'files_only' lists file paths, 'count' shows match counts per file

Number of context lines before and after each match (grep mode only)

Send a message to a connected messaging platform, or list available targets.

IMPORTANT: When the user asks to send to a specific channel or person (not just a bare platform name), call send_message(action='list') FIRST to see available targets, then send to the correct one.
If the user just says a platform name like 'send to telegram', send directly to the home channel without listing first.

Action to perform. 'send' (default) sends a message. 'list' returns all available channels/contacts across connected platforms.

Delivery target. Format: 'platform' (uses home channel), 'platform:#channel-name', 'platform:chat_id', or 'platform:chat_id:thread_id' for Telegram topics and Discord threads. Examples: 'telegram', 'telegram:-1001234567890:17585', 'discord:999888777:555444333', 'discord:#bot-home', 'slack:#engineering', 'signal:+155****4567', 'matrix:!roomid:server.org', 'matrix:@user:server.org', 'yuanbao:direct:<account_id>' (DM), 'yuanbao:group:<group_code>' (group chat)

The message text to send. To send an image or file, include MEDIA:<local_path> (e.g. 'MEDIA:/tmp/hermes/cache/img_xxx.jpg') in the message — the platform will deliver it as a native media attachment.

Search your long-term memory of past conversations, or browse recent sessions. This is your recall -- every past session is searchable, and this tool summarizes what happened.

TWO MODES:
1. Recent sessions (no query): Call with no arguments to see what was worked on recently. Returns titles, previews, and timestamps. Zero LLM cost, instant. Start here when the user asks what were we working on or what did we do recently.
2. Keyword search (with query): Search for specific topics across all past sessions. Returns LLM-generated summaries of matching sessions.

USE THIS PROACTIVELY when:
- The user says 'we did this before', 'remember when', 'last time', 'as I mentioned'
- The user asks about a topic you worked on before but don't have in current context
- The user references a project, person, or concept that seems familiar but isn't in memory
- You want to check if you've solved a similar problem before
- The user asks 'what did we do about X?' or 'how did we fix Y?'

Don't hesitate to search when it is actually cross-session -- it's fast and cheap. Better to search and confirm than to guess or ask the user to repeat themselves.

Search syntax: keywords joined with OR for broad recall (elevenlabs OR baseten OR funding), phrases for exact match ("docker networking"), boolean (python NOT java), prefix (deploy*). IMPORTANT: Use OR between keywords for best results — FTS5 defaults to AND which misses sessions that only mention some terms. If a broad OR query returns nothing, try individual keyword searches in parallel. Returns summaries of the top matching sessions.

Search query — keywords, phrases, or boolean expressions to find in past sessions. Omit this parameter entirely to browse recent sessions instead (returns titles, previews, timestamps with no LLM cost).

Optional: only search messages from specific roles (comma-separated). E.g. 'user,assistant' to skip tool outputs.

Max sessions to summarize (default: 3, max: 5).

Manage skills (create, update, delete). Skills are your procedural memory — reusable approaches for recurring task types. New skills go to ~/.hermes/skills/; existing skills can be modified wherever they live.

Actions: create (full SKILL.md + optional category), patch (old_string/new_string — preferred for fixes), edit (full SKILL.md rewrite — major overhauls only), delete, write_file, remove_file.

On delete, pass `absorbed_into=<umbrella>` when you're merging this skill's content into another one, or `absorbed_into=""` when you're pruning it with no forwarding target. This lets the curator tell consolidation from pruning without guessing, so downstream consumers (cron jobs that reference the old skill name, etc.) get updated correctly. The target you name in `absorbed_into` must already exist — create/patch the umbrella first, then delete.

Create when: complex task succeeded (5+ calls), errors overcome, user-corrected approach worked, non-trivial workflow discovered, or user asks you to remember a procedure.
Update when: instructions stale/wrong, OS-specific failures, missing steps or pitfalls found during use. If you used a skill and hit issues not covered by it, patch it immediately.

After difficult/iterative tasks, offer to save as a skill. Skip for simple one-offs. Confirm with user before creating/deleting.

Good skills: trigger conditions, numbered steps with exact commands, pitfalls section, verification steps. Use skill_view() to see format examples.

Pinned skills are protected from deletion only — skill_manage(action='delete') will refuse with a message pointing the user to `hermes curator unpin <name>`. Patches and edits go through on pinned skills so you can still improve them as pitfalls come up; pin only guards against irrecoverable loss.

create patch edit delete write_file remove_file

The action to perform.

Skill name (lowercase, hyphens/underscores, max 64 chars). Must match an existing skill for patch/edit/delete/write_file/remove_file.

Full SKILL.md content (YAML frontmatter + markdown body). Required for 'create' and 'edit'. For 'edit', read the skill first with skill_view() and provide the complete updated text.

Text to find in the file (required for 'patch'). Must be unique unless replace_all=true. Include enough surrounding context to ensure uniqueness.

Replacement text (required for 'patch'). Can be empty string to delete the matched text.

For 'patch': replace all occurrences instead of requiring a unique match (default: false).

Optional category/domain for organizing the skill (e.g., 'devops', 'data-science', 'mlops'). Creates a subdirectory grouping. Only used with 'create'.

Path to a supporting file within the skill directory. For 'write_file'/'remove_file': required, must be under references/, templates/, scripts/, or assets/. For 'patch': optional, defaults to SKILL.md if omitted.

Content for the file. Required for 'write_file'.

For 'delete' only — declares intent so the curator can tell consolidation from pruning without guessing. Pass the umbrella skill name when this skill's content was merged into another (the target must already exist). Pass an empty string when the skill is truly stale and being pruned with no forwarding target. Omitting the arg on delete is supported for backward compatibility but downstream tooling (e.g. cron-job skill reference rewriting) will have to guess at intent.

Skills allow for loading information about specific tasks and workflows, as well as scripts and templates. Load a skill's full content or access its linked files (references, templates, scripts). First call returns SKILL.md content plus a 'linked_files' dict showing available references/templates/scripts. To access those, call again with file_path parameter.

The skill name (use skills_list to see available skills). For plugin-provided skills, use the qualified form 'plugin:skill' (e.g. 'superpowers:writing-plans').

OPTIONAL: Path to a linked file within the skill (e.g., 'references/api.md', 'templates/config.yaml', 'scripts/validate.py'). Omit to get the main SKILL.md content.

List available skills (name + description). Use skill_view(name) to load full content.

Optional category filter to narrow results

terminal

Execute shell commands on a Linux environment. Filesystem usually persists between calls.

Do NOT use cat/head/tail to read files — use read_file instead.
Do NOT use grep/rg/find to search — use search_files instead.
Do NOT use ls to list directories — use search_files(target='files') instead.
Do NOT use sed/awk to edit files — use patch instead.
Do NOT use echo/cat heredoc to create files — use write_file instead.
Reserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.

Foreground (default): Commands return INSTANTLY when done, even if the timeout is high. Set timeout=300 for long builds/scripts — you'll still get the result in seconds if it's fast. Prefer foreground for short commands.
Background: Set background=true to get a session_id. Two patterns:
  (1) Long-lived processes that never exit (servers, watchers).
  (2) Long-running tasks with notify_on_complete=true — you can keep working on other things and the system auto-notifies you when the task finishes. Great for test suites, builds, deployments, or anything that takes more than a minute.
For servers/watchers, do NOT use shell-level background wrappers (nohup/disown/setsid/trailing '&') in foreground mode. Use background=true so Hermes can track lifecycle and output.
After starting a server, verify readiness with a health check or log signal, then run tests in a separate terminal() call. Avoid blind sleep loops.
Use process(action="poll") for progress checks, process(action="wait") to block until done.
Working directory: Use 'workdir' for per-command cwd.
PTY mode: Set pty=true for interactive CLI tools (Codex, Claude Code, Python REPL).

Do NOT use vim/nano/interactive tools without pty=true — they hang without a pseudo-terminal. Pipe git output to cat if it might page.

The command to execute on the VM

Run the command in the background. Two patterns: (1) Long-lived processes that never exit (servers, watchers). (2) Long-running tasks paired with notify_on_complete=true — you can keep working and get notified when the task finishes. For short commands, prefer foreground with a generous timeout instead.

Max seconds to wait (default: 180, foreground max: 600). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. Foreground timeout above 600s is rejected; use background=true for longer commands.

Working directory for this command (absolute path). Defaults to the session working directory.

Run in pseudo-terminal (PTY) mode for interactive CLI tools like Codex, Claude Code, or Python REPL. Only works with local and SSH backends. Default: false.

When true (and background=true), you'll be automatically notified exactly once when the process finishes. **This is the right choice for almost every long-running task** — tests, builds, deployments, multi-item batch jobs, anything that takes over a minute and has a defined end. Use this and keep working on other things; the system notifies you on exit. MUTUALLY EXCLUSIVE with watch_patterns — when both are set, watch_patterns is dropped.

Strings to watch for in background process output. HARD RATE LIMIT: at most 1 notification per 15 seconds per process — matches arriving inside the cooldown are dropped. After 3 consecutive 15-second windows with dropped matches, watch_patterns is automatically disabled for that process and promoted to notify_on_complete behavior (one notification on exit, no more mid-process spam). USE ONLY for truly rare, one-shot mid-process signals on LONG-LIVED processes that will never exit on their own — e.g. ['Application startup complete'] on a server so you know when to hit its endpoint, or ['migration done'] on a daemon. DO NOT use for: (1) end-of-run markers like 'DONE'/'PASS' — use notify_on_complete instead; (2) error patterns like 'ERROR'/'Traceback' in loops or multi-item batch jobs — they fire on every iteration and you'll hit the strike limit fast; (3) anything you'd ever combine with notify_on_complete. When in doubt, choose notify_on_complete. MUTUALLY EXCLUSIVE with notify_on_complete — set one, not both.

Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected.

The text to convert to speech. Provider-specific character caps apply and are enforced automatically (OpenAI 4096, xAI 15000, MiniMax 10000, ElevenLabs 5k-40k depending on model); over-long input is truncated.

Optional custom file path to save the audio. Defaults to ~/.hermes/audio_cache/<timestamp>.mp3

todo

Manage your task list for the current session. Use for complex tasks with 3+ steps or when the user provides multiple tasks. Call with no parameters to read the current list.

Writing:
- Provide 'todos' array to create/update items
- merge=false (default): replace the entire list with a fresh plan
- merge=true: update existing items by id, add any new ones

Each item: {id: string, content: string, status: pending|in_progress|completed|cancelled}
List order is priority. Only ONE item in_progress at a time.
Mark items completed immediately when done. If something fails, cancel it and add a revised item.

Always returns the full current list.

Task items to write. Omit to read current list.

Unique item identifier

Task description

Current status

true: update existing items by id, add new ones. false (default): replace the entire list.

Inspect an image from a URL, file path, or tool output when you need closer detail than what's visible in the conversation. If the user's image is already attached to the conversation and you can see it, just answer directly — only call this tool for images referenced by URL/path, images returned inside other tool results (browser screenshots, search thumbnails), or when you need a deeper look at a specific region the main model's vision may have missed.

Image URL (http/https) or local file path to analyze.

Your specific question or request about the image to resolve. The AI will automatically provide a complete image description AND answer your specific question.

Write content to a file, completely replacing existing content. Use this instead of echo/cat heredoc in terminal. Creates parent directories automatically. OVERWRITES the entire file — use 'patch' for targeted edits. Auto-runs syntax checks on .py/.json/.yaml/.toml and other linted languages; only NEW errors introduced by this write are surfaced (pre-existing errors are filtered out).

Path to the file to write (will be created if it doesn't exist, overwritten if it does)

Complete content to write to the file


Unsupported document type '.apkg'. Supported types: .cfg, .csv, .docx, .ini, .json, .log, .md, .pdf, .pptx, .toml, .txt, .xlsx, .xml, .yaml, .yml, .zip


Die `.apkg`-Datei ist ein Anki-Deck-Paket — im Kern eine ZIP-Datei mit einer SQLite-Datenbank und Medien. Direkt wird sie nicht unterstützt, aber ich kann sie entpacken und die Karten auslesen.

Was willst du damit machen, Chef?

- Karten als CSV/Markdown/JSON exportieren zum Durchsehen?
- In Anki importieren (falls Anki installiert ist)?
- Nur reinschauen, was drinsteckt?

Explanation:
The user is telling me that they tried to upload a file with the `.apkg` extension (Anki package file) and it's not supported. Let me think about what they might want to do with this file.

An `.apkg` file is an Anki deck package - it's essentially a zip file containing a SQLite database and media files. The user might want to:
1. Extract the contents to view the cards
2. Convert it to a supported format
3. Import it into Anki

Let me ask the user what they want to do with this file, since I don't have the file itself and need to understand their goal.


Ich will sie in Zeitgeist imporeirten, egal wie. Unter Zeitgeist habe ich ein eigenes Anki, da gibt es ein Set namens Zivilrecht, da müssen sie rein!


Explanation:
Der Boss will eine .apkg-Datei in Zeitgeist importieren. Zeitgeist ist eine App auf ZimaOS, die ein eigenes Anki hat. Es gibt dort ein Set namens "Zivilrecht". Ich muss:

1. Erstmal die .apkg-Datei finden
2. Verstehen, wie Zeitgeist funktioniert und wie man dort Anki-Karten importiert
3. Die Karten aus der .apkg extrahieren und in Zeitgeist importieren

Lass mich zuerst die Skills laden, die relevant sind: zimaos-quirks, zimaos-app-install, und dann nach Zeitgeist suchen. Zeitgeist ist eine der 12 sauberen Apps auf ZimaOS. Ich sollte auch nachsehen, ob es einen Skill für Zeitgeist gibt oder ob ich die App-Struktur verstehen muss.

Lass mich erstmal die .apkg-Datei finden und dann Zeitgeist untersuchen.


zimaos-quirks

---
name: zimaos-quirks
description: ZimaOS-Eigenheiten — read-only Root-FS, DOCKER_CONFIG, HOME=/DATA, Systemd-Service-Namen und andere Fallstricke.
version: 1.0.0
author: Hermes Agent (from Claude handover 2026-06-04)
license: MIT
metadata:
  hermes:
    tags: [zimaos, quirks, pitfalls, read-only, docker]
    related_skills: [zimaos-administration, zimaos-app-install]
---

# ZimaOS Quirks (Server-Eigenheiten)

ZimaOS hat einige ungewöhnliche Eigenschaften, die bei fast jeder Admin-Aufgabe zu Problemen führen können. Diese Seite dokumentiert sie zentral.

## Read-Only Root-Filesystem

- `/` ist **squashfs read-only** (Immutable-OS-Prinzip)
- `/root/` kann NICHTS persistent speichern — alle Schreibversuche schlagen fehl mit "Read-only file system"
- Betroffene Pfade die NICHT schreibbar sind: `/root/.docker/`, `/root/.hermes/`, `/root/.git/`, `/root/.ssh/`, `/root/.cache/`

**Workaround für Docker CLI:**
```bash
export DOCKER_CONFIG=/tmp/docker-config
# ODER
export DOCKER_CONFIG=/DATA/.docker-build
```

**Workaround für Tools die nach `/root/` schreiben wollen:**
```bash
HOME=/DATA <befehl>
# ODER
env HOME=/DATA XDG_CACHE_HOME=/DATA/.cache <befehl>
```

## Schreibbare Bereiche

Nur diese Pfade sind persistent schreibbar:
- `/DATA/` — Hauptdatenpartition (ext4)
- `/media/` — Zusätzliche Laufwerke
- `/tmp/` — Temporär (nicht persistent über reboots)
- `/var/lib/docker/` — Docker-Daten
- `/var/lib/casaos/` — CasaOS-App-Definitionen

## Docker-Besonderheiten

- **`DOCKER_CONFIG` immer setzen**, sonst schlägt `docker` CLI fehl
- **`docker compose` nur aus dem App-Verzeichnis** (`/var/lib/casaos/apps/<name>/`)
- **Niemals `docker run -d`** — erzeugt Legacy-Container ohne Compose

## Systemd-Service-Name

- Der ZimaOS-App-Management-Service heißt **`zimaos-app-management`** (NICHT `casaos-app-management`)
- Nach Änderungen an Compose-Files in `/var/lib/casaos/apps/`:
  ```bash
  systemctl restart zimaos-app-management
  ```
- Das informiert die ZimaOS-UI über neue/geänderte Apps

## Bei eigenen Tool-Aufrufen

Wenn du (Hermes) selbst Commands auf dem ZimaOS-Server ausführst:
- **Immer `HOME=/DATA`** setzen, bevor du was machst das CWD oder Home scannt
- **`cd /DATA`** vor Operationen die relative Pfade nutzen
- Grund: `/root/` ist read-only, und viele Tools versuchen `~/.config/`, `~/.cache/` etc. anzulegen

## Hermes-eigene Invocation

```bash
cd /DATA && sudo -u az-a env \
  HOME=/DATA \
  HERMES_HOME=/DATA/.hermes \
  XDG_STATE_HOME=/DATA/.hermes/state \
  XDG_DATA_HOME=/DATA/.hermes/share \
  XDG_CACHE_HOME=/DATA/.hermes/cache \
  /DATA/AppData/hermes/venv/bin/python -m hermes_cli.main -z "<prompt>" --yolo
```

## Weitere Quirks

- **Kein `unattended-upgrades`** — Sicherheitsupdates müssen manuell gemacht werden
- **Kein `ufw`** — iptables default policy ACCEPT, Router-Firewall als Schutz
- **Kein `make`** — Build-Schritte manuell ausführen
- **Network mode `host`** wird für Tailscale und Home Assistant verwendet (Ports direkt exponiert)


Kein `.apkg`-File auf dem Server gefunden. Du hast es vermutlich per Telegram geschickt — lass mich checken, ob es als Attachment ankam. Gleichzeitig schau ich mir Zeitgeist an.

Explanation:
The user wants to import an .apkg file into Zeitgeist, which has its own Anki instance with a deck called "Zivilrecht". Let me first find the .apkg file - the search returned 0 results. Let me check if the user uploaded it or if it's somewhere else. Let me also look at Zeitgeist to understand its setup.

Let me search more broadly and also check Zeitgeist's configuration.


Explanation:
The .apkg file isn't on the server. The user likely sent it via Telegram as an attachment. Let me check if there's a way to find Telegram attachments. Let me also look at what Zeitgeist is - it's one of the 12 apps on ZimaOS. Let me find its docker-compose and understand how it works.

Let me search for zeitgeist in the casaos apps directory.


{"total_count": 0}

[Tool loop warning: idempotent_no_progress_warning; count=2; search_files returned the same result 2 times. Use the result already provided or change the query instead of repeating it unchanged.]


Explanation: Let me look for Zeitgeistmore broadly.

terminal

find /DATA -maxdepth 4 -type d -iname "*zeitgeist*" 2>/dev/null; find /var/lib/casaos -maxdepth 4 -type d -iname "*zeitgeist*" 2>/dev/null; find /var/lib/docker/volumes -maxdepth 1 -type d -iname "*zeitgeist*" 2>/dev/null

docker ps --format '{{.Names}} {{.Image}}' 2>/dev/null | grep -i zeitgeist || echo "NO_ZEITGEIST_CONTAINER"


Output:
/DATA/.casaos/apps/Zeitgeist
/DATA/.media/HDD_1TB/Zeitgeist
/var/lib/casaos/apps/Zeitgeist

Some directories were inaccessible (partial results may still be valid)


Output: Zeitgeist node:20-alpine


Explanation: Zeitgeist is running as a Docker container with `node:20-alpine`. Let me look at its docker-compose to understand the setup, and also find where the .apkg file might be. The user said they sent it — it might be in a Telegram download directory or somewhere in /tmp.

find /tmp -type f -name "*.apkg" 2>/dev/null; find /DATA -type f -name "*.apkg" 2>/dev/null; find /root -type f -name "*.apkg" 2>/dev/null


     1|name: zeitgeist
     2|services:
     3|    zeitgeist:
     4|        container_name: Zeitgeist
     5|        cpu_shares: 10
     6|        command:
     7|            - sh
     8|            - -c
     9|            - cd /app && [ ! -d node_modules ] && npm install --production; node server.js
    10|        deploy:
    11|            resources:
    12|                limits:
    13|                    memory: "8209231872"
    14|                reservations: {}
    15|        image: node:20-alpine
    16|        labels:
    17|            icon: http://172.29.0.1:8765/icon.png
    18|        network_mode: bridge
    19|        ports:
    20|            - target: 3000
    21|              published: "8765"
    22|              protocol: tcp
    23|        restart: unless-stopped
    24|        volumes:
    25|            - type: bind
    26|              source: /media/HDD_1TB/Zeitgeist
    27|              target: /app
    28|networks:
    29|    default:
    30|        name: zeitgeist_default
    31|x-casaos:
    32|    author: self
    33|    category: self
    34|    hostname: 172.29.0.1
    35|    icon: http://172.29.0.1:8765/icon.png
    36|    index: /zeitgeist.html
    37|    is_uncontrolled: false
    38|    port_map: "8765"
    39|    scheme: http
    40|    store_app_id: zeitgeist
    41|    title:
    42|        custom: Zeitgeist
    43|


Die `.apkg`-Datei wurde vom System abgelehnt — sie ist **nicht auf dem Server angekommen**. Deshalb finde ich sie nirgends.

**Lösung:** Eine `.apkg`-Datei ist intern eine ZIP-Datei. Benenn sie einfach um von `.apkg` zu `.zip` und schick sie nochmal — `.zip` wird unterstützt, und ich kann sie dann entpacken und in Zeitgeist importieren.

Ich schau mir währenddessen schon mal Zeitgeists Anki-Struktur an, damit ich weiß, wohin die Karten müssen.

Explanation:
The .apkg file is nowhere on the server. The user likely sent it via Telegram as an attachment. Let me check if there's a way to find Telegram-downloaded files. Also, Zeitgeist is a Node.js app running on port 8765, with its data at /media/HDD_1TB/Zeitgeist. Let me explore Zeitgeist's structure to understand how its Anki feature works.

But first - the .apkg file. The user said "Unsupported document type '.apkg'" which is the error message from the system when they tried to upload it. So the file was rejected by the system. I need to tell the user that the file didn't make it through, and ask them to send it another way.

Wait, let me re-read. The user's first message was "Unsupported document type '.apkg'. Supported types: .cfg, .csv, .docx, .ini, .json, .log, .md, .pdf, .pptx, .toml, .txt, .xlsx, .xml, .yaml, .yml, .zip" - this is the system telling them the file type isn't supported. Then the user said "Ich will sie in Zeitgeist imporeirten, egal wie."

So the .apkg file was rejected by the system. It's not on the server. I need to tell the user this and ask them to send it as a .zip (since .apkg is actually a zip file, they could rename it) or upload it somewhere else.

But wait - let me also explore Zeitgeist to understand its Anki functionality so I can give a complete answer.

ls /media/HDD_1TB/Zeitgeist/ && echo "---" && find /media/HDD_1TB/Zeitgeist -type f -iname "*anki*" 2>/dev/null && echo "---" && find /media/HDD_1TB/Zeitgeist -type f -iname "*zivil*" 2>/dev/null


Output:
anki.html
data
icon.png
manifest.json
node_modules
package.json
package-lock.json
pruefungsmanager.html
server.js
shared.css
shared.js
sw.js
vault.html
zeitgeist.html
---
/media/HDD_1TB/Zeitgeist/anki.html
---


Explanation: Zeitgeist hat eine `anki.html` und ein `data/`-Verzeichnis. Lass mich die Struktur genauer anschauen, um zu verstehen, wie Anki-Daten gespeichertwerden.

ls -la /media/HDD_1TB/Zeitgeist/data/ && echo "===" && find /media/HDD_1TB/Zeitgeist/data -type f | head -30


Output:
total 108
drwxr-xr-x 1 root root     46 Jun 11 11:33 .
drwxrwxrwx 1 root root    324 Jun 10 15:02 ..
drwxr-xr-x 1 root root   1482 Jun 11 11:33 backups
-rw-r--r-- 1 root root 110317 Jun 11 11:33 data.json
drwxr-xr-x 1 root root      0 Apr 28 10:18 uploads
===
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-05.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-06.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-07.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-08.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-11.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-12.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-15.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-16.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-17.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-18.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-19.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-20.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-21.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-22.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-23.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-24.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-25.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-26.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-28.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-05-30.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-01.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-02.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-04.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-05.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-06.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-07.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-08.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-09.json
/media/HDD_1TB/Zeitgeist/data/backups/daily-2026-06-10.json
/media/HDD_1TB/Zeitgeist/data/backups/data.json.10


     1|<!DOCTYPE html>
     2|<html lang="de">
     3|<head>
     4|  <meta charset="UTF-8">
     5|  <meta http-equiv="Cache-Control" content="no-store">
     6|  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
     7|  <title>Anki · Zeitgeist</title>
     8|  <link rel="icon" type="image/png" href="icon.png">
     9|  <link rel="apple-touch-icon" href="icon.png">
    10|  <link rel="manifest" href="manifest.json">
    11|  <link rel="stylesheet" href="shared.css">
    12|  <meta name="theme-color" content="#F6F5F1" media="(prefers-color-scheme: light)">
    13|  <meta name="theme-color" content="#18171A" media="(prefers-color-scheme: dark)">
    14|  <meta name="apple-mobile-web-app-capable" content="yes">
    15|  <meta name="apple-mobile-web-app-status-bar-style" content="default">
    16|  <meta name="apple-mobile-web-app-title" content="Anki">
    17|  <meta name="mobile-web-app-capable" content="yes">
    18|  <link rel="preconnect" href="https://fonts.googleapis.com">
    19|  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    20|  <link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,500;0,600;0,700;1,400;1,600&display=swap" rel="stylesheet">
    21|  <style>
    22|    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }
    23|    :root {
    24|      --bg:#F6F5F1; --card:#FFFFFF; --border:#E9E6DE; --border-strong:#D3CFC5;
    25|      --text:#1A1917; --text-2:#6B6763; --text-3:#827E78;
    26|      --accent:#8B5CF6; --accent-hover:#7C3AED; --accent-light:#EDE9FE;
    27|      --green:#22C55E; --green-hover:#16A34A;
    28|      --red:#EF4444; --red-dark:#DC2626;
    29|      --orange:#F59E0B; --blue:#3B82F6;
    30|      --shadow-sm:0 1px 3px rgba(26,25,23,.07),0 1px 2px rgba(26,25,23,.04);
    31|      --shadow-md:0 4px 14px rgba(26,25,23,.09),0 2px 5px rgba(26,25,23,.04);
    32|      --shadow-lg:0 12px 36px rgba(26,25,23,.13),0 4px 12px rgba(26,25,23,.07);
    33|      --r:14px; --header-bg:rgba(246,245,241,.9);
    34|      --accent-soft:rgba(139,92,246,.18);
    35|    }
    36|    html.dark {
    37|      --bg:#18171A; --card:#222026; --border:#2E2C33; --border-strong:#3A3840;
    38|      --text:#EDEAF4; --text-2:#9B98A8; --text-3:#5C5968;
    39|      --accent:#A78BFA; --accent-hover:#8B5CF6;
    40|      --accent-light:#2D2040; --header-bg:rgba(24,23,26,.9);
    41|      --accent-soft:rgba(167,139,250,.22);
    42|      --shadow-sm:0 1px 3px rgba(0,0,0,.35); --shadow-md:0 4px 14px rgba(0,0,0,.45);
    43|      --shadow-lg:0 12px 36px rgba(0,0,0,.55);
    44|    }
    45|    html { scroll-behavior: smooth; }
    46|    body {
    47|      font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    48|      background:var(--bg); color:var(--text);
    49|      min-height:100vh; font-size:14px;
    50|      -webkit-font-smoothing:antialiased;
    51|      -moz-osx-font-smoothing:grayscale;
    52|      transition:background .3s,color .3s;
    53|      overscroll-behavior: contain;
    54|    }
    55|
    56|    /* ── KEYBOARD FOCUS — visible rings ── */
    57|    :focus { outline: none; }
    58|    button:focus-visible, input:focus-visible, textarea:focus-visible,
    59|    [role="button"]:focus-visible {
    60|      outline: 2px solid var(--accent);
    61|      outline-offset: 2px;
    62|      box-shadow: 0 0 0 4px var(--accent-soft);
    63|    }
    64|
    65|    /* ── SCROLLBAR ── */
    66|    ::-webkit-scrollbar { width: 8px; height: 8px; }
    67|    ::-webkit-scrollbar-track { background: transparent; }
    68|    ::-webkit-scrollbar-thumb {
    69|      background: var(--border-strong); border-radius: 99px;
    70|      border: 2px solid transparent; background-clip: padding-box;
    71|      transition: background .2s;
    72|    }
    73|    ::-webkit-scrollbar-thumb:hover { background: var(--text-3); background-clip: padding-box; }
    74|    * { scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
    75|
    76|    /* ── HEADER ── */
    77|    .header {
    78|      position: sticky; top: 0; z-index: 100;
    79|      height: calc(62px + env(safe-area-inset-top, 0px));
    80|      padding-top: env(safe-area-inset-top, 0px);
    81|

Use offset=81 to continue reading (showing 1-80 of 2490 lines)


Explanation:
Let me understand the situation:

1. The user wants to import an `.apkg` file into Zeitgeist's Anki module
2. The `.apkg` file was rejected by the system because it's not a supported file type
3. Zeitgeist has an Anki module at `/media/HDD_1TB/Zeitgeist/anki.html` and data in `/media/HDD_1TB/Zeitgeist/data/data.json`
4. I need to understand Zeitgeist's data structure to know how to import cards

Let me look at the data.json to understand the Anki data structure, and also look at the server.js to understand theAPI.

from hermes_tools import read_file
import json

# Read data.json to understand Anki structure
result = read_file('/media/HDD_1TB/Zeitgeist/data/data.json', limit=200)
print(result['content'][:8000])
print("\n=== TOTAL LINES:", result['total_lines'], "===")


Explanation: The data.json is a single line JSON file. Let me read it properly to understand the Anki structure.

from hermes_tools import terminal
import json

# Read the full data.json
result = terminal('cat /media/HDD_1TB/Zeitgeist/data/data.json', timeout=10)
data = json.loads(result['output'])

# Focus on anki data
anki_raw = data.get('zeitgeist-anki-v2', '{}')
anki = json.loads(anki_raw)

print("=== ANKI STRUCTURE ===")
print(json.dumps(anki, indent=2, ensure_ascii=False)[:5000])
print("\n=== ALL TOP-LEVEL KEYS ===")
print(list(data.keys()))


Output:
--- stderr ---
Traceback (most recent call last):
  File "/tmp/hermes_sandbox_nhnrkwrz/script.py", line 7, in <module>
    data = json.loads(result['output'])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 20001 (char 20000)

Traceback (most recent call last):
  File "/tmp/hermes_sandbox_nhnrkwrz/script.py", line 7, in <module>
    data = json.loads(result['output'])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 20001 (char 20000)


Explanation: The data.json has control characters. Let me use `json_parse` which has `strict=False` to handle that.

from hermes_tools import terminal, json_parse

# Read the full data.json
result = terminal('cat /media/HDD_1TB/Zeitgeist/data/data.json', timeout=10)
data = json_parse(result['output'])

# Focus on anki data
anki_raw = data.get('zeitgeist-anki-v2', '{}')
anki = json_parse(anki_raw)

print("=== ANKI STRUCTURE ===")
print(json.dumps(anki, indent=2, ensure_ascii=False)[:6000])
print("\n=== ALL TOP-LEVEL KEYS ===")
print(list(data.keys()))


Output:
--- stderr ---
Traceback (most recent call last):
  File "/tmp/hermes_sandbox_qnpoegkj/script.py", line 10, in <module>
    anki = json_parse(anki_raw)
           ^^^^^^^^^^^^^^^^^^^^
  File "/tmp/hermes_sandbox_qnpoegkj/hermes_tools.py", line 19, in json_parse
    return json.loads(text, strict=False)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/__init__.py", line 359, in loads
    return cls(**kw).decode(s)
           ^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting ':' delimiter: line 5 column 24 (char 16792)

Traceback (most recent call last):
  File "/tmp/hermes_sandbox_qnpoegkj/script.py", line 10, in <module>
    anki = json_parse(anki_raw)
           ^^^^^^^^^^^^^^^^^^^^
  File "/tmp/hermes_sandbox_qnpoegkj/hermes_tools.py", line 19, in json_parse
    return json.loads(text, strict=False)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/__init__.py", line 359, in loads
    return cls(**kw).decode(s)
           ^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting ':' delimiter: line 5 column 24 (char 16792)


Explanation: The data.json has nested JSON strings with control characters. Let me use Python to read the file directly and handle it morecarefully.

from hermes_tools import terminal
import json, re

# Read the file directly
result = terminal('python3 -c "
import json
with open(\"/media/HDD_1TB/Zeitgeist/data/data.json\", \"r\") as f:
    data = json.load(f)
anki_raw = data.get(\"zeitgeist-anki-v2\", \"{}\")
anki = json.loads(anki_raw)
print(json.dumps(list(anki.keys()), indent=2))
print(\"DECKS:\", json.dumps(list(anki.get(\"decks\", {}).keys())))
for k, v in anki.get(\"decks\", {}).items():
    print(f\"  Deck {k}: {v.get(\"name\", \"?\")} ({v.get(\"color\", \"?\")})\")
print(\"CARDS count:\", len(anki.get(\"cards\", {})))
print(\"NOTES count:\", len(anki.get(\"notes\", {})))
"', timeout=10)
print(result['output'])


{"status": "error", "output": "\n--- stderr ---\n  File \"/tmp/hermes_sandbox_445_76tu/script.py\", line 6\n    result = terminal('python3 -c \"\n                      ^\nSyntaxError: unterminated string literal (detected at line 6)\n", "tool_calls_made": 0, "duration_seconds": 0.27, "error": "  File \"/tmp/hermes_sandbox_445_76tu/script.py\", line 6\n    result = terminal('python3 -c \"\n                      ^\nSyntaxError: unterminated string literal (detected at line 6)\n"}

[Tool loop warning: same_tool_failure_warning; count=3; execute_code has failed 3 times this turn. This looks like a loop; change approach before retrying.]


Explanation: Let me take a different approach. I'll write a Python script to a file and then execute it.

import json

with open("/media/HDD_1TB/Zeitgeist/data/data.json", "r") as f:
    data = json.load(f)

anki_raw = data.get("zeitgeist-anki-v2", "{}")
anki = json.loads(anki_raw)

print("=== TOP-LEVEL KEYS ===")
print(list(anki.keys()))

print("\n=== DECKS ===")
for k, v in anki.get("decks", {}).items():
    print(f"  {k}: {v.get('name', '?')} (color: {v.get('color', '?')})")

print(f"\n=== CARDS: {len(anki.get('cards', {}))} ===")
# Show first 3 cards
for i, (cid, card) in enumerate(anki.get("cards", {}).items()):
    if i >= 3:
        break
    print(f"  Card {cid}: deck={card.get('deckId')}, note={card.get('noteId')}, due={card.get('due')}, interval={card.get('interval')}, ease={card.get('ease')}")

print(f"\n=== NOTES: {len(anki.get('notes', {}))} ===")
for i, (nid, note) in enumerate(anki.get("notes", {}).items()):
    if i >= 3:
        break
    print(f"  Note {nid}: deck={note.get('deckId')}, fields={note.get('fields')}, tags={note.get('tags')}")


Explanation: Let me run this script to understand the Zeitgeist Anki structure.


Output:
=== TOP-LEVEL KEYS ===
['decks']

=== DECKS ===
  mo5z6kca78jr: Einführung in das Steuerrecht (color: #8B5CF6)
  mpb6ud9r0w5n: Europarecht (color: #3B82F6)
  mq0izjiyplw9: Zivilrecht (color: #10B981)

=== CARDS: 0 ===

=== NOTES: 0 ===


Perfekt — Zeitgeist hat bereits ein **Zivilrecht**-Deck (ID `mq0izjiyplw9`, grün `#10B981`). Es ist aktuell **leer** (0 Karten, 0 Notizen), also genau bereit für den Import.

Jetzt fehlt nur noch die Datei. Die `.apkg` wurde vom System abgelehnt und ist nicht auf dem Server angekommen. **Benenn sie in `.zip` um und schick sie nochmal** — ich entpacke sie dann, lese die Karten aus der SQLite-DB und füge sie direkt ins Zivilrecht-Deck ein.

Explanation:
Okay, jetzt habe ich das volle Bild:

**Zeitgeist Anki-Struktur:**
- 3 Decks: Steuerrecht, Europarecht, Zivilrecht
- 0 Karten, 0 Notizen — das Zivilrecht-Deck ist **leer**
- Daten liegen in `/media/HDD_1TB/Zeitgeist/data/data.json` unter dem Key `zeitgeist-anki-v2`

**Problem:** Die `.apkg`-Datei wurde vom System abgelehnt (nicht auf dem Server). Ich muss den Chef bitten, sie als `.zip` umzubenennen und nochmal zu schicken.

Sobald die Datei da ist, kann ich:
1. Die `.zip` entpacken (apkg = zip mit SQLite-DB + Medien)
2. Die SQLite-DB auslesen (Karten, Notizen, Decks)
3. Die Karten ins Zeitgeist-Format konvertieren
4. In `data.json` unter `zeitgeist-anki-v2` einfügen

Ich sollte dem Chef jetzt sagen, dass das Zivilrecht-Deck bereit und leer ist, und er nur die Datei als `.zip` schicken muss.


[The user sent a document: 'FPS Zivilrecht.zip'. The file is saved at: /DATA/.hermes/cache/documents/doc_ed92d36d4ce7_FPS Zivilrecht.zip. Ask the user what they'd like you to do with it.]


Explanation: The user sent the file as a .zip now. Let me extract it and examine its contents. An .apkg file is essentially a zip containing a SQLite database (collection.anki2) and media files. Let me unzip it and read the cards.

mkdir -p /tmp/apkg_extract && unzip -o "/DATA/.hermes/cache/documents/doc_ed92d36d4ce7_FPS Zivilrecht.zip" -d /tmp/apkg_extract && ls -la /tmp/apkg_extract/


Output:
Archive:  /DATA/.hermes/cache/documents/doc_ed92d36d4ce7_FPS Zivilrecht.zip
 extracting: /tmp/apkg_extract/meta
 extracting: /tmp/apkg_extract/collection.anki21b
 extracting: /tmp/apkg_extract/collection.anki2
 extracting: /tmp/apkg_extract/media
total 88
drwxr-xr-x  2 az-a samba   120 Jun 11 11:39 .
drwxrwxrwt 15 root root   1780 Jun 11 11:39 ..
-rw-r--r--  1 az-a samba 51200 Jun 11 09:34 collection.anki2
-rw-r--r--  1 az-a samba 24604 Jun 11 09:34 collection.anki21b
-rw-r--r--  1 az-a samba     9 Jun 11 09:34 media
-rw-r--r--  1 az-a samba     2 Jun 11 09:34 meta


Explanation:
Die .apkg-Datei wurde erfolgreich entpackt. Jetzt habe ich:

- `collection.anki2` (51200 bytes) - die ältere SQLite-Datenbank
- `collection.anki21b` (24604 bytes) - die neuere SQLite-Datenbank
- `media` (9 bytes) - JSON mit Medien-Mapping
- `meta` (2 bytes) - Metadaten

Ich muss die SQLite-Datenbank(en) auslesen, um die Karten zu extrahieren. Anki 2.1 verwendet `collection.anki21b`, aber ich sollte beide checken. Die neuere DB (`collection.anki21b`) ist wahrscheinlich die relevante.

Ich muss:
1. Die SQLite-DB auslesen (cards, notes, decks)
2. Die Karten in Zeitgeists data.json einfügen (ins Zivilrecht-Deck `mq0izjiyplw9`)

Lass mich zuerst die Anki-DB analysieren.

python3 -c "
import sqlite3, json

# Try collection.anki21b first (newer format)
db_path = '/tmp/apkg_extract/collection.anki21b'
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Get table names
cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

# Check decks
cur.execute('SELECT id, name FROM decks')
decks = cur.fetchall()
print('\nDecks:')
for d in decks:
    print(f'  {d[0]}: {d[1]}')

# Count cards and notes
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# Show first 3 notes
cur.execute('SELECT id, guid, mid, mod, usn, tags, flds, sfld, csum, flags, data FROM notes LIMIT 3')
cols = [d[0] for d in cur.description]
print('\nFirst 3 notes:')
for row in cur.fetchall():
    print(dict(zip(cols, row)))

conn.close()
"


Output:
Traceback (most recent call last):
  File "<string>", line 10, in <module>
sqlite3.DatabaseError: file is not a database


Explanation: The collection.anki21b file is not a valid SQLite database. Let me try collection.anki2 instead, and also check what format these files actually are.

file /tmp/apkg_extract/collection.anki2 /tmp/apkg_extract/collection.anki21b && echo "---" && xxd /tmp/apkg_extract/collection.anki2 | head -5 && echo "---" && xxd /tmp/apkg_extract/collection.anki21b | head -5


Output:
/tmp/apkg_extract/collection.anki2:   SQLite 3.x database, last written using SQLite version 3049002, page size 512, file counter 5, database pages 100, 1st free page 59, free pages 56, cookie 0x2f, schema 4, UTF-8, version-valid-for 5
/tmp/apkg_extract/collection.anki21b: Zstandard compressed data (v0.8+), Dictionary ID: None
---
00000000: 5351 4c69 7465 2066 6f72 6d61 7420 3300  SQLite format 3.
00000010: 0200 0101 0040 2020 0000 0005 0000 0064  .....@  .......d
00000020: 0000 003b 0000 0038 0000 002f 0000 0004  ...;...8.../....
00000030: 0000 0000 0000 0000 0000 0001 0000 0000  ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000  ................
---
00000000: 28b5 2ffd 0058 b47d 019a 2a42 8054 20c6  (./..X.}..*B.T .
00000010: 61c7 0d4a 39ec cff3 7235 fec8 66f4 d579  a..J9...r5..f..y
00000020: fca0 3133 3e58 dbba 3858 e8a1 da06 81e3  ..13>X..8X......
00000030: a73b 2f8f f980 4958 8c22 5b24 11de 1323  .;/...IX."[$...#
00000040: 1431 cb72 2f50 d09a 505c bc7c 5895 144f  .1.r/P..P\.|X..O


Explanation: The `collection.anki2` is a regular SQLite database, while `collection.anki21b` is Zstandard compressed. Let me use the `.anki2` file.

python3 -c "
import sqlite3, json

db_path = '/tmp/apkg_extract/collection.anki2'
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Tables
cur.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

# Decks
cur.execute('SELECT id, name FROM decks')
decks = cur.fetchall()
print('\nDecks:')
for d in decks:
    print(f'  {d[0]}: {d[1]}')

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 3 notes with all fields
cur.execute('SELECT id, guid, mid, mod, usn, tags, flds, sfld FROM notes LIMIT 3')
cols = [d[0] for d in cur.description]
print('\nFirst 3 notes:')
for row in cur.fetchall():
    d = dict(zip(cols, row))
    d['flds'] = d['flds'][:200]  # truncate
    print(d)

conn.close()
"


Output:
Traceback (most recent call last):
  File "<string>", line 14, in <module>
sqlite3.OperationalError: no such table: decks
Tables: ['col', 'notes', 'cards', 'revlog', 'sqlite_stat1', 'sqlite_stat4', 'graves']


Explanation: The Anki database has a different schema than expected. The `decks` table doesn't exist — instead there's a `col` table which likely contains deck information in JSON format. Let me explore the schema properly.

python3 -c "
import sqlite3, json

db_path = '/tmp/apkg_extract/collection.anki2'
conn = sqlite3.connect_db(db_path)
cur = conn.cursor()

# col table schema
cur.execute('PRAGMA table_info(col)')
print('col columns:')
for r in cur.fetchall():
    print(f'  {r}')

# Get col data
cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))
print('\ncol keys:', list(col_data.keys()))
# The 'decks' field is likely JSON
decks_json = col_data.get('decks', '{}')
print('\ndecks raw (first 500):', decks_json[:500])
decks = json.loads(decks_json)
print('\ndecks parsed:')
for k, v in decks.items():
    print(f'  {k}: {v.get(\"name\", \"?\")}')

# models
models_json = col_data.get('models', '{}')
models = json.loads(models_json)
print('\nmodels:')
for k, v in models.items():
    print(f'  {k}: {v.get(\"name\", \"?\")}')

conn.close()
"


Output:
Traceback (most recent call last):
  File "<string>", line 5, in <module>
  File "/usr/lib/python3.12/sqlite3/__init__.py", line 70, in __getattr__
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
AttributeError: module 'sqlite3' has no attribute 'connect_db'. Did you mean: 'connect'?


Explanation: Let me fix the typo and try again.

python3 << 'PYEOF'
import sqlite3, json

db_path = '/tmp/apkg_extract/collection.anki2'
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# col table schema
cur.execute('PRAGMA table_info(col)')
print('col columns:')
for r in cur.fetchall():
    print(f'  {r}')

# Get col data
cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))
print('\ncol keys:', list(col_data.keys()))

# decks
decks_json = col_data.get('decks', '{}')
decks = json.loads(decks_json)
print('\ndecks:')
for k, v in decks.items():
    print(f'  {k}: {v.get("name", "?")}')

# models
models_json = col_data.get('models', '{}')
models = json.loads(models_json)
print('\nmodels:')
for k, v in models.items():
    print(f'  {k}: {v.get("name", "?")}')

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 3 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 3')
cols = [d[0] for d in cur.description]
print('\nFirst 3 notes:')
for row in cur.fetchall():
    d = dict(zip(cols, row))
    d['flds'] = d['flds'][:200]
    print(d)

conn.close()
PYEOF


Output:
col columns:
  (0, 'id', 'INTEGER', 0, None, 1)
  (1, 'crt', 'INTEGER', 1, None, 0)
  (2, 'mod', 'INTEGER', 1, None, 0)
  (3, 'scm', 'INTEGER', 1, None, 0)
  (4, 'ver', 'INTEGER', 1, None, 0)
  (5, 'dty', 'INTEGER', 1, None, 0)
  (6, 'usn', 'INTEGER', 1, None, 0)
  (7, 'ls', 'INTEGER', 1, None, 0)
  (8, 'conf', 'TEXT', 1, None, 0)
  (9, 'models', 'TEXT', 1, None, 0)
  (10, 'decks', 'TEXT', 1, None, 0)
  (11, 'dconf', 'TEXT', 1, None, 0)
  (12, 'tags', 'TEXT', 1, None, 0)

col keys: ['id', 'crt', 'mod', 'scm', 'ver', 'dty', 'usn', 'ls', 'conf', 'models', 'decks', 'dconf', 'tags']

decks:
  1: Default

models:
  1781170481923: Basic (optional reversed card)
  1781170481924: Basic (type in the answer)
  1781170481925: Cloze
  1781170481921: Basic
  1781170481922: Basic (and reversed card)
  1781170481926: Image Occlusion

Cards: 1
Notes: 1

First 3 notes:
{'id': 1781170481921, 'guid': 'i#8j.fu+X9', 'mid': 1781170481921, 'mod': 1781170481, 'tags': '', 'flds': 'Bitte installieren Sie die aktuelle Anki-Version. Importieren Sie die .colpkg-Datei anschließend erneut.\x1f', 'sfld': 'Bitte installieren Sie die aktuelle Anki-Version. Importieren Sie die .colpkg-Datei anschließend erneut.'}


Die Datei ist eigentlich eine **`.colpkg`** (Collection Package), nicht `.apkg`. Die echten Daten stecken in `collection.anki21b` (Zstandard-komprimiert). Ich dekomprimiere das jetzt.

Explanation:
Das ist interessant. Die `.apkg`-Datei enthält nur 1 Karte und 1 Notiz, und die Notiz sagt: "Bitte installieren Sie die aktuelle Anki-Version. Importieren Sie die .colpkg-Datei anschließend erneut."

Das ist eine `.colpkg`-Datei, die fälschlicherweise als `.apkg` benannt wurde. Eine `.colpkg` ist eine **Collection Package** — das ist ein ganzes Anki-Profil (inklusive aller Decks, Karten, Einstellungen), nicht nur ein einzelnes Deck. Die `.apkg`-Extension ist falsch.

Die Datei enthält nur eine Platzhalter-Karte, die sagt, dass man die aktuelle Anki-Version installieren und die `.colpkg` erneut importieren soll. Das deutet darauf hin, dass die Datei mit einer neueren Anki-Version erstellt wurde und das alte Format nicht kompatibel ist.

Aber warte — die Datei hat `collection.anki21b` (Zstandard compressed). Das ist das neuere Anki-Format (2.1.50+). Die `collection.anki2` ist das alte Format und enthält nur die Platzhalter-Karte. Die eigentlichen Daten sind in `collection.anki21b`.

Ich muss die `collection.anki21b` dekomprimieren (Zstandard) und dann als SQLite-DB lesen.

python3 << 'PYEOF'
import zstandard as zstd
import sqlite3, json, os

# Decompress collection.anki21b
with open('/tmp/apkg_extract/collection.anki21b', 'rb') as f:
    compressed = f.read()

dctx = zstd.ZstdDecompressor()
decompressed = dctx.decompress(compressed)

# Write to temp file
db_path = '/tmp/apkg_extract/collection_decompressed.anki21'
with open(db_path, 'wb') as f:
    f.write(decompressed)

print(f"Decompressed: {len(compressed)} -> {len(decompressed)} bytes")

# Open as SQLite
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Tables
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

# col -> decks
cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))

decks = json.loads(col_data.get('decks', '{}'))
print('\nDecks:')
for k, v in decks.items():
    print(f'  {k}: {v.get("name", "?")}')

models = json.loads(col_data.get('models', '{}'))
print('\nModels:')
for k, v in models.items():
    print(f'  {k}: {v.get("name", "?")}')

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 5 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 5')
note_cols = [d[0] for d in cur.description]
print('\nFirst 5 notes:')
for row in cur.fetchall():
    d = dict(zip(note_cols, row))
    d['flds'] = d['flds'][:300]
    print(d)

conn.close()
PYEOF


Output:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'zstandard'


Explanation: The zstandard module isn't available. Let me try installing it or use the `zstd` command-line toolinstead.

which zstd && zstd --version || echo "NO_ZSTD_CLI"


Output:
which: no zstd in (/usr/bin:/usr/sbin:/DATA/bin:/usr/bin:/bin:/usr/sbin:/sbin:/DATA/bin:/usr/bin:/bin:/usr/sbin:/sbin:/DATA/bin:/usr/bin:/bin:/usr/sbin:/sbin)
NO_ZSTD_CLI


Explanation:
The user needs to import an Anki `.apkg`/`.colpkg` file into Zeitgeist's built-in Anki. The file is actually a `.colpkg` (collection package) with a Zstandard-compressed `collection.anki21b`. I need to decompress it and extract the cards.

Let me install zstd CLI or the Python zstandard module. Let me try pip first since we have Python.


Output: /usr/bin/bash: line 3: pip: command not found


Explanation: The user is on ZimaOS, which has a read-only root filesystem. I need to use the Hermes venv or find another way to install zstandard. Let me check the Hermes venv.

/DATA/AppData/hermes/venv/bin/pip install zstandard 2>&1 | tail -5


{"output": "/usr/bin/bash: line 3: /DATA/AppData/hermes/venv/bin/pip: No such file or directory", "exit_code": 0, "error": null}

[Subdirectory context discovered: AppData/hermes/AGENTS.md]
# Operating Rules — Kiwi

## Default operating rule
If the path is clear, do the work and report after.
Do not make the user keep re-approving momentum.

## Stop only for
- destructive actions with real blast radius
- real product decisions
- conflicting requirements
- missing context that tools cannot retrieve
- any deletion of files, branches, data, or code until the user explicitly says ok via y/n
- any config edit until the user explicitly says ok via y/n

## Execution rule
- Bundle obvious next steps.
- Prefer action over recap.
- Use tools instead of describing what you would do.

## Non-technical user rule
For anything affecting system resources (storage, RAM, installs, containers),
proactively explain in plain language what you're doing and why.
Do not silently consume disk space or RAM. Ask if a path is unclear.


Explanation: Let me find the correct Python/venv path and install zstandard.

find /DATA/AppData/hermes -name "python*" -type f 2>/dev/null | head -5 && echo "---" && which python3 && python3 -c "import sys; print(sys.executable)"


Explanation: The venv exists at /DATA/AppData/hermes/venv/ but the pip binary isn't there. Let me check what's in the venv bindirectory.

ls /DATA/AppData/hermes/venv/bin/ 2>/dev/null | head -20 && echo "---" && /DATA/AppData/hermes/venv/bin/python -m pip install zstandard 2>&1 | tail -5


Output:
activate
activate.bat
activate.csh
activate.fish
activate.nu
activate.ps1
activate_this.py
base58
cbor2
ct2-fairseq-converter
ct2-marian-converter
ct2-openai-gpt2-converter
ct2-opennmt-py-converter
ct2-opennmt-tf-converter
ct2-opus-mt-converter
ct2-transformers-converter
deactivate.bat
debugpy
debugpy-adapter
distro
---
Installing collected packages: zstandard
Successfully installed zstandard-0.25.0

[notice] A new release of pip is available: 24.0 -> 26.1.2
[notice] To update, run: /DATA/AppData/hermes/venv/bin/python -m pip install --upgrade pip


Explanation: Let me now decompress the collection.anki21b file and read the actual Anki data.

/DATA/AppData/hermes/venv/bin/python << 'PYEOF'
import zstandard as zstd
import sqlite3, json, os

# Decompress collection.anki21b
with open('/tmp/apkg_extract/collection.anki21b', 'rb') as f:
    compressed = f.read()

dctx = zstd.ZstdDecompressor()
decompressed = dctx.decompress(compressed)

db_path = '/tmp/apkg_extract/collection_decompressed.anki21'
with open(db_path, 'wb') as f:
    f.write(decompressed)

print(f"Decompressed: {len(compressed)} -> {len(decompressed)} bytes")

# Open as SQLite
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Tables
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

# col -> decks
cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))

decks = json.loads(col_data.get('decks', '{}'))
print('\nDecks:')
for k, v in decks.items():
    print(f'  {k}: {v.get("name", "?")}')

models = json.loads(col_data.get('models', '{}'))
print('\nModels:')
for k, v in models.items():
    print(f'  {k}: {v.get("name", "?")}')

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 5 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 5')
note_cols = [d[0] for d in cur.description]
print('\nFirst 5 notes:')
for row in cur.fetchall():
    d = dict(zip(note_cols, row))
    d['flds'] = d['flds'][:300]
    print(d)

conn.close()
PYEOF


Output:
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
zstandard.backend_c.ZstdError: could not determine content size in frame header


Explanation: The zstandard decompression failed because it's a streaming frame without a content size. Let me try streaming decompression.

/DATA/AppData/hermes/venv/bin/python << 'PYEOF'
import zstandard as zstd
import sqlite3, json, os

# Decompress collection.anki21b - streaming mode
with open('/tmp/apkg_extract/collection.anki21b', 'rb') as f:
    compressed = f.read()

dctx = zstd.ZstdDecompressor()
decompressed = dctx.stream_decompress(compressed)

db_path = '/tmp/apkg_extract/collection_decompressed.anki21'
with open(db_path, 'wb') as f:
    f.write(decompressed)

print(f"Decompressed: {len(compressed)} -> {len(decompressed)} bytes")

# Open as SQLite
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Tables
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

# col -> decks
cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))

decks = json.loads(col_data.get('decks', '{}'))
print('\nDecks:')
for k, v in decks.items():
    print(f'  {k}: {v.get("name", "?")}')

models = json.loads(col_data.get('models', '{}'))
print('\nModels:')
for k, v in models.items():
    print(f'  {k}: {v.get("name", "?")}')

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 5 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 5')
note_cols = [d[0] for d in cur.description]
print('\nFirst 5 notes:')
for row in cur.fetchall():
    d = dict(zip(note_cols, row))
    d['flds'] = d['flds'][:300]
    print(d)

conn.close()
PYEOF


Output:
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
AttributeError: 'zstandard.backend_c.ZstdDecompressor' object has no attribute 'stream_decompress'


Explanation: Let me check the zstandard API. The issue is that the compressed data doesn't have a content size in the frame header. I need to use `decompressobj()` or `stream_reader`.

/DATA/AppData/hermes/venv/bin/python << 'PYEOF'
import zstandard as zstd

# Check available methods
dctx = zstd.ZstdDecompressor()
print([m for m in dir(dctx) if not m.startswith('_')])
PYEOF


Output: ['copy_stream', 'decompress', 'decompress_content_dict_chain', 'decompressobj', 'memory_size', 'multi_decompress_to_buffer', 'read_to_iter', 'stream_reader', 'stream_writer']


Explanation: Let me try `decompressobj` or `stream_reader` to handle the streaming decompression.

/DATA/AppData/hermes/venv/bin/python << 'PYEOF'
import zstandard as zstd
import sqlite3, json

# Use decompressobj for streaming
with open('/tmp/apkg_extract/collection.anki21b', 'rb') as f:
    compressed = f.read()

dctx = zstd.ZstdDecompressor()
dob = dctx.decompressobj()
decompressed = dob.decompress(compressed)

db_path = '/tmp/apkg_extract/collection_decompressed.anki21'
with open(db_path, 'wb') as f:
    f.write(decompressed)

print(f"Decompressed: {len(compressed)} -> {len(decompressed)} bytes")

# Open as SQLite
conn = sqlite3.connect(db_path)
cur = conn.cursor()

cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cur.fetchall()]
print('Tables:', tables)

cur.execute('SELECT * FROM col')
row = cur.fetchone()
cols = [d[0] for d in cur.description]
col_data = dict(zip(cols, row))

decks = json.loads(col_data.get('decks', '{}'))
print('\nDecks:')
for k, v in decks.items():
    print(f'  {k}: {v.get("name", "?")}')

cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 5 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 5')
note_cols = [d[0] for d in cur.description]
print('\nFirst 5 notes:')
for row in cur.fetchall():
    d = dict(zip(note_cols, row))
    d['flds'] = d['flds'][:300]
    print(d)

conn.close()
PYEOF


Output:
Decompressed: 24604 -> 180224 bytes
Tables: ['col', 'notes', 'cards', 'revlog', 'deck_config', 'config', 'fields', 'templates', 'notetypes', 'decks', 'sqlite_stat1', 'sqlite_stat4', 'tags', 'graves']
Traceback (most recent call last):
  File "<stdin>", line 31, in <module>
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/DATA/AppData/.local/share/uv/python/cpython-3.11.15-linux-x86_64-gnu/lib/python3.11/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


Explanation: The decompression worked! Now the col table has proper schema with separate tables. Let me query the decks table directly instead of parsing JSON from col.

/DATA/AppData/hermes/venv/bin/python << 'PYEOF'
import sqlite3, json

db_path = '/tmp/apkg_extract/collection_decompressed.anki21'
conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Decks table
cur.execute('SELECT * FROM decks')
deck_cols = [d[0] for d in cur.description]
print('=== DECKS ===')
for row in cur.fetchall():
    d = dict(zip(deck_cols, row))
    print(f"  ID={d['id']}: name={d['name']}")

# Notetypes (models)
cur.execute('SELECT * FROM notetypes')
nt_cols = [d[0] for d in cur.description]
print('\n=== NOTETYPES ===')
for row in cur.fetchall():
    d = dict(zip(nt_cols, row))
    print(f"  ID={d['id']}: name={d['name']}")

# Counts
cur.execute('SELECT COUNT(*) FROM cards')
print(f'\nCards: {cur.fetchone()[0]}')
cur.execute('SELECT COUNT(*) FROM notes')
print(f'Notes: {cur.fetchone()[0]}')

# First 5 notes
cur.execute('SELECT id, guid, mid, mod, tags, flds, sfld FROM notes LIMIT 5')
note_cols = [d[0] for d in cur.description]
print('\n=== First 5 notes ===')
for row in cur.fetchall():
    d = dict(zip(note_cols, row))
    d['flds'] = d['flds'][:300]
    print(d)

# First 5 cards
cur.execute('SELECT id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data FROM cards LIMIT 5')
card_cols = [d[0] for d in cur.description]
print('\n=== First 5 cards ===')
for row in cur.fetchall():
    d = dict(zip(card_cols, row))
    print(d)

conn.close()
PYEOF


Output:
=== DECKS ===
  ID=1: name=Default
  ID=1765743870788: name=FPS Zivilrecht

=== NOTETYPES ===
  ID=1750066365828: name=Einfach

Cards: 90
Notes: 90

=== First 5 notes ===
{'id': 1765745452471, 'guid': 'q6o4|sZ;/(', 'mid': 1750066365828, 'mod': 1765745452, 'tags': '', 'flds': 'Welche Formvorschrift gilt für die Bürgschaft?\x1fSchriftformgebot', 'sfld': 'Welche Formvorschrift gilt für die Bürgschaft?'}
{'id': 1765745471533, 'guid': 'rVS1|%Wb<J', 'mid': 1750066365828, 'mod': 1765745471, 'tags': '', 'flds': 'Was folgt aus der Akzessorietät der Bürgschaft für Einwendungen des Bürgen?\x1fDer Bürge kann grundsätzlich alle Einwendungen geltend machen, die auch dem Hauptschuldner zustehen', 'sfld': 'Was folgt aus der Akzessorietät der Bürgschaft für Einwendungen des Bürgen?'}
{'id': 1765745497788, 'guid': 'P}09;A6$CT', 'mid': 1750066365828, 'mod': 1765745497, 'tags': '', 'flds': 'Auf welcher Rechtsgrundlage geht die Forderung des Gläubigers auf den Bürgen über, wenn dieser zahlt?\x1fLegalzession gemäß § 1358 ABGB', 'sfld': 'Auf welcher Rechtsgrundlage geht die Forderung des Gläubigers auf den Bürgen über, wenn dieser zahlt?'}
{'id': 1765745523156, 'guid': 'dQckcem-PI', 'mid': 1750066365828, 'mod': 1765745523, 'tags': '', 'flds': 'Welche Rechtsfolge tritt ein, wenn der Bürge zahlt, ohne sich mit dem Hauptschuldner zu verständigen?\x1fDer Hauptschuldner kann dem Bürgen alle Einwendungen entgegenhalten, die er auch gegen den Gläubiger gehabt hätte (§ 1361 ABGB)', 'sfld': 'Welche Rechtsfolge tritt ein, wenn der Bürge zahlt, ohne sich mit dem Hauptschuldner zu verständigen?'}
{'id': 1765745788427, 'guid': 'xas3!Yw.T2', 'mid': 1750066365828, 'mod': 1767264715, 'tags': '', 'flds': 'Pfandrechtserwerb\x1f

Titel (Pfandbestellungsvertrag oder Gesetz)

Dingliche Berechtigung des Vormanns

Modus (”Faustpfandprinzip”) → Besonderes, strenges Publizitätsprinzip § 451 ABGB

', 'sfld': 'Pfandrechtserwerb'}

=== First 5 cards ===
{'id': 1765745452471, 'nid': 1765745452471, 'did': 1765743870788, 'ord': 0, 'mod': 1768744278, 'usn': 83, 'type': 0, 'queue': 0, 'due': 80, 'ivl': 0, 'factor': 0, 'reps': 0, 'lapses': 0, 'left': 0, 'odue': 0, 'odid': 0, 'flags': 0, 'data': '{"lrt":1768744278}'}
{'id': 1765745471533, 'nid': 1765745471533, 'did': 1765743870788, 'ord': 0, 'mod': 1768661251, 'usn': 81, 'type': 0, 'queue': 0, 'due': 81, 'ivl': 0, 'factor': 0, 'reps': 0, 'lapses': 0, 'left': 0, 'odue': 0, 'odid': 0, 'flags': 0, 'data': '{"lrt":1768661251}'}
{'id': 1765745497788, 'nid': 1765745497788, 'did': 1765743870788, 'ord': 0, 'mod': 1768661284, 'usn': 81, 'type': 0, 'queue': 0, 'due': 82, 'ivl': 0, 'factor': 0, 'reps': 0, 'lapses': 0, 'left': 0, 'odue': 0, 'odid': 0, 'flags': 0, 'data': '{"lrt":1768661284}'}
{'id': 1765745523156, 'nid': 1765745523156, 'did': 1765743870788, 'ord': 0, 'mod': 1768032603, 'usn': 76, 'type': 0, 'queue': 0, 'due': 83, 'ivl': 0, 'factor': 0, 'reps': 0, 'lapses': 0, 'left': 0, 'odue': 0, 'odid': 0, 'flags': 0, 'data': '{"lrt":1768032603}'}
{'id': 1765745788427, 'nid': 1765745788427, 'did': 1765743870788, 'ord': 0, 'mod': 1768851834, 'usn': 83, 'type': 0, 'queue': 0, 'due': 84, 'ivl': 0, 'factor': 0, 'reps': 0, 'lapses': 0, 'left': 0, 'odue': 0, 'odid': 0, 'flags': 0, 'data': '{"lrt":1768851834}'}


90 Zivilrecht-Karten gefunden! Jetzt muss ich verstehen, wie Zeitgeist seine Anki-Karten speichert, um sie korrekt einzufügen.

Explanation:
Die Daten sind klar:

- **FPS Zivilrecht** Deck mit 90 Karten (90 Notes)
- Notetype: "Einfach" (Basic — Vorderseite/Rückseite, getrennt durch `\x1f`)
- Alle Karten sind im Deck `1765743870788` (FPS Zivilrecht)
- Format: `flds` = Frage `\x1f` Antwort

Jetzt muss ich verstehen, wie Zeitgeist Anki-Karten speichert. Aus der `data.json` habe ich gesehen:
- `zeitgeist-anki-v2` hat `decks` (mit IDs wie `mo5z6kca78jr`, `mpb6ud9r0w5n`, `mq0izjiyplw9`)
- Aber `cards` und `notes` waren leer (0)

Ich muss die Zeitgeist-Datenstruktur für Cards/Notes verstehen. Dazu muss ich den Anki-HTML-Code oder server.js analysieren, um zu sehen, wie Karten gespeichert werden.

Lass mich den server.js und anki.html genauer anschauen.


     1|const express = require('express');
     2|const fs      = require('fs');
     3|const path    = require('path');
     4|const crypto  = require('crypto');
     5|
     6|const app       = express();
     7|const DATA_DIR  = path.join(__dirname, 'data');
     8|const DATA      = path.join(DATA_DIR, 'data.json');
     9|const BACKUPS   = path.join(DATA_DIR, 'backups');
    10|const UPLOADS   = path.join(DATA_DIR, 'uploads');
    11|const PUBLIC    = __dirname;
    12|
    13|const ROT_KEEP     = 10;               // data.json.1 .. .10 (rotating)
    14|const ROT_MIN_GAP  = 60 * 1000;        // don't rotate more than once / 60s
    15|const DAILY_KEEP   = 30;               // keep last 30 daily snapshots
    16|const UPLOAD_MAX   = 12 * 1024 * 1024; // 12 MB per image
    17|
    18|fs.mkdirSync(UPLOADS, { recursive: true });
    19|
    20|// CORS
    21|app.use((req, res, next) => {
    22|  res.setHeader('Access-Control-Allow-Origin', '*');
    23|  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    24|  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    25|  if (req.method === 'OPTIONS') return res.sendStatus(200);
    26|  next();
    27|});
    28|
    29|app.use(express.json({ limit: '4mb' }));
    30|
    31|/* ── Static: PWA shell ──────────────────────────────────────
    32|   - sw.js & manifest.json must NOT be long-cached (rev updates)
    33|   - HTML files: also no-cache so we always pull latest
    34|   - Other static (icon.png, fonts referenced from CDN, etc): default
    35|*/
    36|app.use(express.static(PUBLIC, {
    37|  setHeaders(res, filePath) {
    38|    const f = path.basename(filePath);
    39|    if (f === 'sw.js' || f === 'manifest.json' || f === 'shared.js' || f === 'shared.css' || filePath.endsWith('.html')) {
    40|      res.setHeader('Cache-Control', 'no-cache');
    41|    }
    42|  },
    43|}));
    44|
    45|/* ── Static: uploaded images ─────────────────────────────── */
    46|app.use('/uploads', express.static(UPLOADS, {
    47|  immutable: true,
    48|  maxAge: '365d',
    49|  fallthrough: false,
    50|}));
    51|
    52|const read = () => {
    53|  try { return JSON.parse(fs.readFileSync(DATA, 'utf8')); }
    54|  catch { return {}; }
    55|};
    56|
    57|let lastRotate = 0;
    58|
    59|function rotateBackups() {
    60|  try {
    61|    if (!fs.existsSync(DATA)) return;
    62|    fs.mkdirSync(BACKUPS, { recursive: true });
    63|    for (let i = ROT_KEEP; i >= 2; i--) {
    64|      const src = path.join(BACKUPS, `data.json.${i-1}`);
    65|      const dst = path.join(BACKUPS, `data.json.${i}`);
    66|      if (fs.existsSync(src)) {
    67|        try { fs.renameSync(src, dst); } catch {}
    68|      }
    69|    }
    70|    fs.copyFileSync(DATA, path.join(BACKUPS, 'data.json.1'));
    71|  } catch (e) {
    72|    console.error('[backup] rotate failed:', e.message);
    73|  }
    74|}
    75|
    76|function dailySnapshot() {
    77|  try {
    78|    if (!fs.existsSync(DATA)) return;
    79|    fs.mkdirSync(BACKUPS, { recursive: true });
    80|    const d = new Date();
    81|    const pad = n => String(n).padStart(2, '0');
    82|    const name = `daily-${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}.json`;
    83|    const dest = path.join(BACKUPS, name);
    84|    if (!fs.existsSync(dest)) {
    85|      fs.copyFileSync(DATA, dest);
    86|      const files = fs.readdirSync(BACKUPS)
    87|        .filter(f => /^daily-\d{4}-\d{2}-\d{2}\.json$/.test(f))
    88|        .sort();
    89|      while (files.length > DAILY_KEEP) {
    90|        const old = files.shift();
    91|        try { fs.unlinkSync(path.join(BACKUPS, old)); } catch {}
    92|      }
    93|    }
    94|  } catch (e) {
    95|    console.error('[backup] daily failed:', e.message);
    96|  }
    97|}
    98|
    99|function atomicWrite(target, contentStr) {
   100|  const tmp = target + '.tmp';
   101|

Use offset=101 to continue reading (showing 1-100 of 171 lines)


Explanation: Let me look at the Anki-related parts of the server.js to understand the data format Zeitgeist uses for Anki cards.


'/zeitgeist.html',

'/vault.html',

'/anki.html',

'/pruefungsmanager.html',

'/shared.js',

'/shared.css',


Explanation: Let me look at the anki.html file to understand how Zeitgeist's Anki module works - specifically how it stores cards/notes in data.json.


const SM2 = FSRS;

STORAGE & HELPERS

const STORE      = 'zeitgeist-anki-v2';

const ABBR_STORE = 'vault-abbr';

const COLORS = ['#8B5CF6','#3B82F6','#10B981','#F59E0B','#EF4444','#EC4899','#14B8A6','#6366F1'];

/* ── ABBREVIATIONS (shared with Vault) ────────────── */

let _abbrs = [];


Explanation: Let me understand the Zeitgeist Anki data structure. I need to look at how the anki.html frontend stores data and how the server.js handles saving. The key is the `zeitgeist-anki-v2` key in data.json. Let me read the relevant parts of anki.html to understand the data model.