PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (docs): Introduce Open Spec
Rostislav Dugin8c4ee9fa3b26
diff --git a/.agents/skills/.openspec-target b/.agents/skills/.openspec-targetnew file mode 100644index 00000000..2695308a--- /dev/null+++ b/.agents/skills/.openspec-target@@ -0,0 +1 @@+codexdiff --git a/.agents/skills/openspec-apply-change/SKILL.md b/.agents/skills/openspec-apply-change/SKILL.mdnew file mode 100644index 00000000..13947191--- /dev/null+++ b/.agents/skills/openspec-apply-change/SKILL.md@@ -0,0 +1,188 @@+---+name: openspec-apply-change+description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Implement tasks from an OpenSpec change.++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++**Input**: Optionally specify a change name (e.g., `$openspec-apply-change (Codex) or /openspec-apply-change (other agents) add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.++**Steps**++1. **Select the change**++ If a name is provided, use it. Otherwise:+ - Infer from conversation context if the user mentioned a change+ - Auto-select if only one active change exists+ - If ambiguous, run `openspec list --json` to get available changes and ask the user to select one++ Always announce: "Using change: <name>" and how to override (e.g., `$openspec-apply-change (Codex) or /openspec-apply-change (other agents) <other>`).++2. **Check status to understand the schema**+ ```bash+ openspec status --change "<name>" --json+ ```+ Parse the JSON to understand:+ - `schemaName`: The workflow being used (e.g., "spec-driven")+ - `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints+ - Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)++3. **Get apply instructions**++ ```bash+ openspec instructions apply --change "<name>" --json+ ```++ This returns:+ - `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)+ - Progress (total, complete, remaining)+ - Task list with status+ - Dynamic instruction based on current state+ - Optional `context`: current required project instruction input from the selected root+ - Optional `operationGuidance`: current advisory guidance for apply++ **Handle states:**+ - If `state: "blocked"` (missing artifacts): show message, suggest using `$openspec-continue-change (Codex) or /openspec-continue-change (other agents)` (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)+ - If `state: "all_done"`: congratulate, suggest archive+ - Otherwise: proceed to implementation++ Treat `context` as a required prompt-level input. Read and consider it, and+ apply relevant project facts, conventions, and constraints while implementing.+ Treat `operationGuidance` as optional additive advice. Read and consider every+ entry, and follow entries that are applicable and compatible with the built-in+ workflow.++ Keep both fields separate from CLI-returned state, missing artifacts, tasks,+ progress, `contextFiles`, and the built-in `instruction`. They are not+ evidence of task completion, do not replace the built-in instruction, and do+ not permit bypassing a blocked state. If context conflicts with the built-in+ instruction, an explicit user choice, or a CLI-controlled value, report the+ conflict and preserve the controlling value. If guidance is inapplicable or+ conflicts with those controlling inputs, do not follow it and explain why.+ These are prompt-level behavior contracts, not enforceable checks.++4. **Read context files**++ Read every file path listed under `contextFiles` from the apply instructions output.+ The files depend on the schema being used:+ - **spec-driven**: proposal, specs, design, tasks+ - Other schemas: follow the contextFiles from CLI output++ Do not copy `context` or `operationGuidance` verbatim into implementation+ files or planning artifacts unless the user separately asks for that content.++5. **Show current progress**++ Display:+ - Schema being used+ - Progress: "N/M tasks complete"+ - Remaining tasks overview+ - Dynamic instruction from CLI++6. **Implement tasks (loop until done or blocked)**++ For each pending task:+ - Show which task is being worked on+ - Make the code changes required+ - Keep changes minimal and focused+ - Mark task complete in the tasks file: `- [ ]` → `- [x]`+ - Continue to next task++ **Pause if:**+ - Task is unclear → ask for clarification+ - Implementation reveals a design issue → suggest updating artifacts+ - A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently+ - Error or blocker encountered → report and wait for guidance+ - User interrupts++7. **On completion or pause, show status**++ Display:+ - Tasks completed this session+ - Overall progress: "N/M tasks complete"+ - If all done: suggest archive+ - If paused: explain why and wait for guidance++**Output During Implementation**++```+## Implementing: <change-name> (schema: <schema-name>)++Working on task 3/7: <task description>+[...implementation happening...]+✓ Task complete++Working on task 4/7: <task description>+[...implementation happening...]+✓ Task complete+```++**Output On Completion**++```+## Implementation Complete++**Change:** <change-name>+**Schema:** <schema-name>+**Progress:** 7/7 tasks complete ✓++### Completed This Session+- [x] Task 1+- [x] Task 2+...++All tasks complete! You can archive this change with `$openspec-archive-change (Codex) or /openspec-archive-change (other agents)`.+```++**Output On Pause (Issue Encountered)**++```+## Implementation Paused++**Change:** <change-name>+**Schema:** <schema-name>+**Progress:** 4/7 tasks complete++### Issue Encountered+<description of the issue>++**Options:**+1. <option 1>+2. <option 2>+3. Other approach++What would you like to do?+```++**Guardrails**+- Keep going through tasks until done or blocked+- Always read context files before starting (from the apply instructions output)+- If task is ambiguous, pause and ask before implementing+- If implementation reveals issues, pause and suggest artifact updates+- Keep code changes minimal and scoped to each task+- Update task checkbox immediately after completing each task+- Pause on errors, blockers, or unclear requirements - don't guess+- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior+- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred+- Use contextFiles from CLI output, don't assume specific file names+- Do not use context or operation guidance as proof that a task is complete+- Apply relevant project context; report conflicts with controlling workflow inputs+- Consider every guidance entry; explain any inapplicable or conflicting advice+- Do not copy runtime context or operation guidance into implementation files or planning artifacts+- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria++**Fluid Workflow Integration**++This skill supports the "actions on a change" model:++- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions+- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidlydiff --git a/.agents/skills/openspec-archive-change/SKILL.md b/.agents/skills/openspec-archive-change/SKILL.mdnew file mode 100644index 00000000..3432b85d--- /dev/null+++ b/.agents/skills/openspec-archive-change/SKILL.md@@ -0,0 +1,182 @@+---+name: openspec-archive-change+description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Archive a completed change in the experimental workflow.++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.++**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.++**Steps**++1. **Select the change**++ If a name is provided, use it. Otherwise:+ - Infer from conversation context if the user mentioned a change+ - Auto-select if only one active change exists+ - If ambiguous, run `openspec list --json` to get available changes and ask the user to select one++ When prompting, show only active changes (not already archived).+ Include the schema used for each change if available.++ Always announce: "Using change: <name>" and how to override (e.g., `$openspec-archive-change (Codex) or /openspec-archive-change (other agents) <other>`).++ **Load current archive inputs before the existing archive checks:**++ After resolving the selected change and planning root, run:+ ```bash+ openspec instructions archive --change "<name>" --json+ ```+ Keep the same selected-root flags on this command. This lookup is advisory and+ optional: it only supplies extra prompt inputs, so it must never block archiving.+ If it exits non-zero or returns invalid JSON — for example on an older CLI that+ does not support this command yet — continue the archive workflow with no+ context and no operation guidance. Do not report an error and do not stop.++ A successful response may omit both optional fields. Treat `context` as a+ required prompt-level input: read and consider it, and apply relevant project+ facts, conventions, and constraints. Treat `operationGuidance` as optional+ additive advice: read and consider every entry, and follow entries that are+ applicable and compatible with the built-in archive workflow.++ Keep both fields separate from built-in steps, explicit user choices, resolved+ paths, CLI checks, and command contracts. If context conflicts with one of those+ controlling inputs, report the conflict and preserve the controlling value. If+ guidance is inapplicable or conflicts with a controlling input, do not follow it+ and explain why. Do not infer replacement paths, skipped prompts, or flags from+ either field, and do not copy their text verbatim into specs, change artifacts,+ or archive summaries unless the user separately asks for it. These are+ prompt-level behavior contracts, not enforceable checks.++2. **Check artifact completion status**++ Run `openspec status --change "<name>" --json` to check artifact completion.++ Parse the JSON to understand:+ - `schemaName`: The workflow being used+ - `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context+ - `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)++ **If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):+ - Display warning listing incomplete artifacts+ - Ask the user to confirm they want to proceed+ - Proceed if user confirms++3. **Check task completion status**++ Read the tasks file (typically `tasks.md`) to check for incomplete tasks.++ Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).++ **If incomplete tasks found:**+ - Display warning showing count of incomplete tasks+ - Ask the user to confirm they want to proceed+ - Proceed if user confirms++ **If no tasks file exists:** Proceed without task-related warning.++4. **Assess delta spec sync state**++ Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only+ delta-spec source. If the `specs` entry is missing or+ `existingOutputPaths` is empty, proceed without a sync prompt and do not infer+ delta specs from other artifacts.++ **If delta specs exist:**+ - Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)+ - Determine what changes would be applied (adds, modifications, removals, renames)+ - Show a combined summary before prompting++ **Prompt options:**+ - If changes needed: "Sync now (recommended)", "Archive without syncing"+ - If already synced: "Archive now", "Sync anyway", "Cancel"++ Route on the answer:+ - "Cancel" — stop, do not archive+ - "Archive without syncing" or "Archive now" — proceed to archive+ - "Sync now" or "Sync anyway" — sync, then verify (below)+ - Anything else — ask again rather than archiving++ Before a selected sync writes any main spec, run+ `openspec instructions specs --change "<name>" --json` once with the same+ selected-root flags. Require a zero exit status and valid artifact-instruction+ JSON. If the lookup fails or returns invalid JSON, report the error and stop+ before writing any main spec or moving the change. A valid response with omitted+ `rules` is the no-rules case. Apply returned `rules` only to the content and+ form of main specs produced by this merge; do not use them as archive guidance,+ change CLI behavior, or copy the rule text into any output file.++ Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.++ Then re-run the comparison from the top of this step against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:+ - ADDED requirements present+ - MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact+ - REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty; a spec the sync deliberately kept and reported is also a match+ - RENAMED requirements present under the new name and absent under the old one++ If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.++5. **Perform the archive**++ Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:+ ```bash+ mkdir -p "<planningHome.changesDir>/archive"+ ```++ Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).++ **Check if target already exists:**+ - If yes: Fail with error, suggest renaming existing archive or using different date+ - If no: Move `changeRoot` to the archive directory++ ```bash+ mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"+ ```++6. **Display summary**++ Show archive completion summary including:+ - Change name+ - Schema that was used+ - Archive location+ - Whether specs were synced (if applicable)+ - Note about any warnings (incomplete artifacts/tasks)++**Output On Success**++```markdown+## Archive Complete++**Change:** <change-name>+**Schema:** <schema-name>+**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/+**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">++<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>+```++**Guardrails**+- Announce the selected change; prompt for selection when it is ambiguous+- Use artifact graph (openspec status --json) for completion checking+- Don't block archive on warnings - just inform and confirm+- Preserve .openspec.yaml when moving to archive (it moves with the directory)+- Show clear summary of what happened+- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)+- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`+- If delta specs exist, always run the sync assessment and show the combined summary before prompting+- Apply relevant runtime context and report conflicts; operation guidance remains advisory+- Consider every guidance entry and explain any inapplicable or conflicting advice+- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged+- Artifact rules constrain only the specs being written and are never operation guidance+- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output filesdiff --git a/.agents/skills/openspec-explore/SKILL.md b/.agents/skills/openspec-explore/SKILL.mdnew file mode 100644index 00000000..d01c3255--- /dev/null+++ b/.agents/skills/openspec-explore/SKILL.md@@ -0,0 +1,311 @@+---+name: openspec-explore+description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.++**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. For a new change, scaffold it first as described below.++**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++---++## The Stance++- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script+- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.+- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking+- **Adaptive** - Follow interesting threads, pivot when new information emerges+- **Patient** - Don't rush to conclusions, let the shape of the problem emerge+- **Grounded** - Explore the actual codebase when relevant, don't just theorize++---++## What You Might Do++Depending on what the user brings, you might:++**Explore the problem space**+- Ask clarifying questions that emerge from what they said+- Challenge assumptions+- Reframe the problem+- Find analogies++**Investigate the codebase**+- Map existing architecture relevant to the discussion+- Find integration points+- Identify patterns already in use+- Surface hidden complexity++**Compare options**+- Brainstorm multiple approaches+- Build comparison tables+- Sketch tradeoffs+- Recommend a path (if asked)++**Visualize**+```++------------------------------------------++| Use ASCII diagrams liberally |++------------------------------------------++| |+| [State A] -------> [State B] |+| | |+| v |+| [State C] |+| |+| System diagrams, state machines, |+| data flows, architecture sketches, |+| dependency graphs, comparison tables |+| |++------------------------------------------++```++**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.+Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.++**Surface risks and unknowns**+- Identify what could go wrong+- Find gaps in understanding+- Suggest spikes or investigations++---++## OpenSpec Awareness++You have full context of the OpenSpec system. Use it naturally, don't force it.++### Check for context++At the start, quickly check what exists:+```bash+openspec list --json+```++This tells you:+- If there are active changes+- Their names, schemas, and status+- What the user might be working on++Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:+- `context`: project background - tech stack, conventions, constraints+- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact++Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.++### When no change exists++Think freely. When insights crystallize, you might offer:++- "This feels solid enough to start a change. Want me to create a proposal?"+- Or keep exploring - no pressure to formalize++If the user asks you to capture the exploration as a new change, transition seamlessly into the requested capture:++1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.+2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.+3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists.+4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.++Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status.++### When a change exists++If the user mentions a change or you detect one is relevant:++1. **Resolve and read existing artifacts for context**+ - Run `openspec status --change "<name>" --json`.+ - Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.+ - Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.++2. **Reference them naturally in conversation**+ - "Your design mentions using Redis, but we just realized SQLite fits better..."+ - "The proposal scopes this to premium users, but we're now thinking everyone..."++3. **Offer to capture when decisions are made**++ `<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.++ | Insight Type | Where to Capture |+ |----------------------------|-------------------------------------|+ | New requirement discovered | `specs/<capability-path>/spec.md` |+ | Requirement changed | `specs/<capability-path>/spec.md` |+ | Design decision made | `design.md` |+ | Scope changed | `proposal.md` |+ | New work identified | `tasks.md` |+ | Assumption invalidated | Relevant artifact |++ Example offers:+ - "That's a design decision. Capture it in design.md?"+ - "This is a new requirement. Add it to specs?"+ - "This changes scope. Update the proposal?"++4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.++---++## What You Don't Have To Do++- Follow a script+- Ask the same questions every time+- Produce a specific artifact+- Reach a conclusion+- Stay on topic if a tangent is valuable+- Be brief (this is thinking time)++---++## Handling Different Entry Points++**User brings a vague idea:**+```+User: I'm thinking about adding real-time collaboration++You: Real-time collab is a big space. Let me think about this...++ COLLABORATION SPECTRUM+ ============================================++ Awareness Coordination Sync+ | | |+ v v v+ +--------+ +--------+ +--------++ |Presence| |Cursors | | CRDT |+ | "3 | | Multi | |Conflict|+ |online" | | select | | free |+ +--------+ +--------+ +--------++ | | |+ trivial moderate complex++ Where's your head at?+```++**User brings a specific problem:**+```+User: The auth system is a mess++You: [reads codebase]++ +---------------------------------------------++ | CURRENT AUTH FLOW |+ +---------------------------------------------++ |+ +-------------+-------------++ v v v+ +---------+ +---------+ +---------++ | Google | | GitHub | | Email |+ | OAuth | | OAuth | | Magic |+ +----+----+ +----+----+ +----+----++ | | |+ +-------------+-------------++ v+ +-----------++ | Session |+ +-----+-----++ |+ v+ +-----------++ | Perms |+ +-----------+++ I see three tangles. Which one's burning?+```++**User is stuck mid-implementation:**+```+User: $openspec-explore (Codex) or /openspec-explore (other agents) add-auth-system+ The OAuth integration is more complex than expected++You: [reads change artifacts]++ You're on task 4: "Implement OAuth flow"++ Let me trace what's involved...++ [draws diagram, explores options, suggests paths]++ Want to update the design to reflect this?+ Or add a spike task to investigate?+```++**User wants to compare options:**+```+User: Should we use Postgres or SQLite?++You: Generic answer is boring. What's the context?++User: A CLI tool that tracks local dev environments++You: That changes everything.++ +-------------------------------------------------++ | CLI TOOL DATA STORAGE |+ +-------------------------------------------------+++ Key constraints:+ - No daemon running+ - Must work offline+ - Single user++ SQLite Postgres+ Deployment embedded needs server+ Offline yes no+ Single file yes no++ SQLite. Not even close.++ Unless... is there a sync component?+```++---++## Ending Discovery++There's no required ending. Discovery might:++- **Flow into a proposal**: "Ready to start? I can create a change proposal."+- **Result in artifact updates**: "Updated design.md with these decisions"+- **Just provide clarity**: User has what they need, moves on+- **Continue later**: "We can pick this up anytime"++When it feels like things are crystallizing, you might summarize:++```+## What We Figured Out++**The problem**: [crystallized understanding]++**The approach**: [if one emerged]++**Open questions**: [if any remain]++**Next steps** (if ready):+- Create a change proposal+- Keep exploring: just keep talking+```++But this summary is optional. Sometimes the thinking IS the value.++---++## Guardrails++- **Don't implement** - Never write code or implement features. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not.+- **Don't fake understanding** - If something is unclear, dig deeper+- **Don't rush** - Discovery is thinking time, not task time+- **Don't force structure** - Let patterns emerge naturally+- **Don't auto-capture** - Offer to save insights, don't just do it. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write.+- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.+- **Do visualize** - A good diagram is worth many paragraphs+- **Do explore the codebase** - Ground discussions in reality+- **Do question assumptions** - Including the user's and your owndiff --git a/.agents/skills/openspec-propose/SKILL.md b/.agents/skills/openspec-propose/SKILL.mdnew file mode 100644index 00000000..48f162cc--- /dev/null+++ b/.agents/skills/openspec-propose/SKILL.md@@ -0,0 +1,149 @@+---+name: openspec-propose+description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Propose a new change - create the change and generate all artifacts in one step.++**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.++I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:+- proposal.md (what & why)+- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)+- design.md (how)+- tasks.md (implementation steps)++`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.++When the user is ready to implement, they must start the apply workflow explicitly.++---++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.++**Steps**++1. **Understand the request and clarify material ambiguity**++ If no clear input is provided, ask the user (open-ended, no preset options):+ > "What change do you want to work on? Describe what you want to build or fix."++ From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).++ **IMPORTANT**: Do NOT proceed without understanding what the user wants to build.++ If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.++2. **Determine the workflow schema**++ Use the configured default schema unless the user explicitly requests a different workflow.++ **Use a different schema only if the user:**+ - Explicitly requests a specific schema by name → use `--schema <schema-name>`+ - Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context reports only `no_openspec_root`, run `openspec schemas --json` from the current working directory instead. Do not use this fallback for invalid or unavailable stores.++ Otherwise, omit `--schema` to preserve the configured default.++3. **Create the change directory**++ Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.++ Using the configured default:+ ```bash+ openspec new change "<name>"+ ```++ Using an explicitly requested schema:+ ```bash+ openspec new change "<name>" --schema "<schema-name>"+ ```+ This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.++4. **Get the artifact build order**+ ```bash+ openspec status --change "<name>" --json+ ```+ Parse the JSON to get:+ - `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)+ - `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)+ - `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.++5. **Create every artifact in the required set**++ Use a todo list to track progress through the artifacts.++ Loop through artifacts in dependency order (artifacts with no pending dependencies first):++ a. **For each artifact that is `ready` (dependencies satisfied)**:+ - Get instructions:+ ```bash+ openspec instructions <artifact-id> --change "<name>" --json+ ```+ - The instructions JSON includes:+ - `context`: Project background (constraints for you - do NOT include in output)+ - `rules`: Artifact-specific rules (constraints for you - do NOT include in output)+ - `template`: The structure to use for your output file+ - `instruction`: Schema-specific guidance for this artifact type+ - `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact+ - `resolvedOutputPath`: Resolved path or pattern to write the artifact+ - `dependencies`: Completed artifacts to read for context+ - Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)+ - If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`+ - Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path+ - Apply `context` and `rules` as constraints - but do NOT copy them into the file+ - Show brief progress: "Created <artifact-id>"++ b. **Continue until every artifact in the required set exists (not just `apply.requires`)**+ - After creating each artifact, re-run `openspec status --change "<name>" --json`+ - The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone+ - `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on+ - An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one+ - Create every artifact in the required set that is missing, then re-check - creating one can unblock others+ - Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it+ - Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway+ - Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped++ c. **If an artifact requires user input** (unclear context):+ - Ask the user to clarify+ - Then continue with creation++6. **Show final status**+ ```bash+ openspec status --change "<name>"+ ```++**Output**++After completing all artifacts, summarize:+- Change name and location+- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why+- What's ready: "All artifacts needed for implementation are ready."+- Prompt: "The artifacts are ready for review. When you are ready, run `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)` or ask me to apply this change."++**Artifact Creation Guidelines**++- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names+- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly+- The schema defines what each artifact should contain - follow it+- Read dependency artifacts for context before creating new ones+- Use `template` as the structure for your output file - fill in its sections+- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file+ - Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact+ - These guide what you write, but should never appear in the output++**Guardrails**+- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow+- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`+- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)+- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them+- If a change with that name already exists, ask if user wants to continue it or create a new one+- Verify each artifact file exists after writing before proceeding to nextdiff --git a/.agents/skills/openspec-sync-specs/SKILL.md b/.agents/skills/openspec-sync-specs/SKILL.mdnew file mode 100644index 00000000..b6e5281b--- /dev/null+++ b/.agents/skills/openspec-sync-specs/SKILL.md@@ -0,0 +1,262 @@+---+name: openspec-sync-specs+description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Sync delta specs from a change to main specs.++This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.++**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.++**Steps**++1. **Select the change**++ If a name is provided, use it. Otherwise:+ - Infer from conversation context if the user mentioned a change+ - Auto-select if only one active change exists+ - If ambiguous, run `openspec list --json` to get available changes and ask the user to select one++ When prompting, show changes that have delta specs (under `specs/` directory).++ Always announce: "Using change: <name>" and how to override (e.g., `$openspec-sync-specs (Codex) or /openspec-sync-specs (other agents) <other>`).++2. **Resolve change context**++ Run:+ ```bash+ openspec status --change "<name>" --json+ ```++ The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.++3. **Find delta specs**++ Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the+ only source of delta spec paths. If the `specs` entry is missing or+ `existingOutputPaths` is empty, report that there are no delta specs to sync,+ do not infer them from other artifacts, and stop without requesting artifact+ instructions or writing a main spec.++ Sync every path in `existingOutputPaths` unless the caller narrowed the set.+ A caller narrows it by naming an explicit list of complete entries from+ `existingOutputPaths` — copy those absolute values verbatim. Archive does+ this inline, and a user can too (for example, by selecting the entry ending+ in `/specs/billing/invoices/spec.md`).+ Then sync only the named paths and leave the remaining delta specs untouched:+ bulk archive excludes a delta whose implementation it could not find, and+ syncing it anyway would write a main spec the caller deliberately withheld.+ Carry that narrowed selection through step 4; never widen it back to the full+ list. If a named path is not in `existingOutputPaths`, do not sync it —+ report it and stop, rather than dropping it silently. If the named list is+ empty, report that there is nothing to sync and stop without writing a main+ spec.++ Each delta spec file contains sections like:+ - `## ADDED Requirements` - New requirements to add+ - `## MODIFIED Requirements` - Changes to existing requirements+ - `## REMOVED Requirements` - Requirements to remove+ - `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)++ If no delta specs found, inform user and stop.++4. **For each delta spec, apply changes to main specs**++ Before the first main-spec write, obtain one current specs-rule snapshot:+ - If archive invoked this workflow inline and supplied a valid snapshot from+ `openspec instructions specs --change "<name>" --json`, reuse it and do not+ fetch the same instructions again.+ - Otherwise run that command once now with the same selected-root flags.+ - If the direct lookup exits non-zero or returns invalid artifact-instruction+ JSON, report the error and stop before writing any main spec. Do not treat the+ failure as an absent rule set.+ - A valid response with omitted `rules` means no artifact rules are configured+ and the existing semantic merge continues.++ Apply returned `rules` only to the content and form of the main specs produced+ by this merge. Artifact rules are not operation guidance and cannot change+ selected roots, delta paths, CLI checks, or workflow steps. Use their text as+ constraints without copying it verbatim into a main spec or summary.++ For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):++ a. **Read the delta spec** to understand the intended changes++ b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)++ c. **Apply changes intelligently**:++ **ADDED Requirements:**+ - If requirement doesn't exist in main spec → add it+ - If requirement already exists → update it to match (treat as implicit MODIFIED)++ **MODIFIED Requirements:**+ - Find the requirement in main spec+ - Apply the changes - this can be:+ - Adding new scenarios the main spec does not have yet+ - Modifying existing scenarios+ - Changing the requirement description+ - Preserve scenarios/content not mentioned in the delta++ **REMOVED Requirements:**+ - Remove the entire requirement block from main spec+ - Retiring the capability. Delete the whole `spec.md` - and the directory once+ nothing else is left in it - only when ALL of these hold:+ 1. removing the requirements *this run* left no requirement blocks;+ 2. the rest of the spec is well-formed (it still has a `## Purpose`);+ 3. the main spec was not already empty before this sync - if you removed+ nothing, change nothing;+ 4. every other nonblank line in the whole file is accounted for as the+ title, Purpose, Requirements header, or a canonical requirement's+ statement, scenarios, or fenced examples;+ 5. the change's `.openspec.yaml` declares `retire_capabilities: true`;+ 6. the `spec.md` resolves inside the real specs root (do not follow a+ capability-directory symlink to delete an external file).+ If removing the selected requirements would leave no requirement blocks and+ any retirement condition is not satisfied, do not modify the main spec. Stop+ the sync for that capability, report the blocking condition, and tell the user+ how to resolve it. Never write or leave an empty `## Requirements` section.+ When only the marker is missing, say that too - it is the one thing the user+ can add to make the retirement go through.+ - Deleting the file also deletes its `## Purpose`; any other section blocks+ retirement. Name Purpose when you report the retirement. Include a pasteable+ `git checkout` only when the spec lived in the caller's checkout;+ otherwise give checkout-scoped recovery guidance.++ **RENAMED Requirements:**+ - Find the FROM requirement, rename to TO++ **`## Purpose` in the delta:**+ - The main spec already has one and it is authoritative - leave it alone+ (this is what `openspec archive` does; it warns and moves on)++ d. **Create new main spec** if capability doesn't exist yet:+ - Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`+ - Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one+ (this is what `openspec archive` does); only write a brief TBD placeholder when it does not+ - Add Requirements section with the ADDED requirements+ - Follow the **Main Spec Format Reference** below++5. **Validate updated main specs**++ Run `openspec validate --specs` with the same selected-root flags used earlier.+ If validation fails, report the problems and do not claim the sync succeeded.++6. **Show summary**++ After applying all changes, summarize:+ - Which capabilities were updated+ - What changes were made (requirements added/modified/removed/renamed)+ - Any new main spec left with a TBD Purpose placeholder, so it gets written+ now rather than lingering+ - Any capability retired, naming the deleted `spec.md`, its Purpose, and+ either a pasteable `git checkout` or checkout-scoped recovery guidance++**Delta Spec Format Reference**++```markdown+## Purpose++Only on a delta that introduces a brand-new capability. Seeds the new main spec.++## ADDED Requirements++### Requirement: New Feature+The system SHALL do something new.++#### Scenario: Basic case+- **WHEN** user does X+- **THEN** system does Y++## MODIFIED Requirements++### Requirement: Existing Feature+The system SHALL keep doing the existing thing, now also handling A.++#### Scenario: Scenario the main spec already has+- **WHEN** user does X+- **THEN** system does Y++#### Scenario: New scenario to add+- **WHEN** user does A+- **THEN** system does B++## REMOVED Requirements++### Requirement: Deprecated Feature++## RENAMED Requirements++- FROM: `### Requirement: Old Name`+- TO: `### Requirement: New Name`+```++**Main Spec Format Reference**++Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:++```markdown+# <capability> Specification++## Purpose+Short description of what this capability does and why it exists.++## Requirements++### Requirement: New Feature+The system SHALL do something new.++#### Scenario: Basic case+- **WHEN** user does X+- **THEN** system does Y+```++**Key Principle: Intelligent Merging**++Unlike programmatic merging, you merge rather than overwrite:+- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.+- Keep anything the delta does not mention, in the main spec's existing order+- Use your judgment to merge changes sensibly++**Output On Success**++```markdown+## Specs Synced: <change-name>++Updated main specs:++**<capability-1>**:+- Added requirement: "New Feature"+- Modified requirement: "Existing Feature" (added 1 scenario)++**<capability-2>**:+- Created new spec file+- Added requirement: "Another Feature"++Main specs are now updated. The change remains active - archive when implementation is complete.+```++**Guardrails**+- Read both delta and main specs before making changes+- Preserve existing content not mentioned in delta+- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers+- If something is unclear, ask for clarification+- Show what you're changing as you go+- The operation should be idempotent - running twice should give same result+- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts+- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list+- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline+- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response+- Artifact rules constrain only the specs being written and are never copied into output filesdiff --git a/.agents/skills/openspec-update-change/SKILL.md b/.agents/skills/openspec-update-change/SKILL.mdnew file mode 100644index 00000000..d2bf0fbe--- /dev/null+++ b/.agents/skills/openspec-update-change/SKILL.md@@ -0,0 +1,91 @@+---+name: openspec-update-change+description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Never edits code.+allowed-tools: Bash(openspec:*)+license: MIT+compatibility: Requires openspec CLI.+metadata:+ author: openspec+ version: "1.0"+ generatedBy: "1.11.0"+---++Revise a change's existing planning artifacts and keep them coherent. Never edit code.++**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.++**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.++`$openspec-continue-change (Codex) or /openspec-continue-change (other agents)` is an optional workflow and may not be installed. Before suggesting it anywhere below, verify that it is available. If it is unavailable, `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to create it.++**Steps**++1. **Select the change**++ If a name is provided, use it. Otherwise:+ - Infer from conversation context if the user mentioned a change+ - Auto-select if only one active change exists+ - If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one++ When prompting, present the top 3-4 most recently modified changes as options, showing:+ - Change name+ - Schema (from `schema` field if present, otherwise "spec-driven")+ - Status (e.g., "0/5 tasks", "complete", "no tasks")+ - How recently it was modified (from `lastModified` field)++ Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.++ Always announce: "Using change: <name>" and how to override (e.g., `$openspec-update-change (Codex) or /openspec-update-change (other agents) <other>`).++2. **Get the change's artifacts**+ ```bash+ openspec status --change "<name>" --json+ ```+ Parse the JSON to understand current state. The response includes:+ - `schemaName`: The workflow schema being used (e.g., "spec-driven")+ - `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")+ - `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.+ - `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.++ The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.++ The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.++3. **Understand the request**+ - If the user asked for a specific revision ("the design now uses X"), that is the starting edit.+ - If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.++4. **Read and reconcile**+ - Read the artifact(s) the request touches and the change's other existing artifacts.+ - Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.+ - Note everything that is now inconsistent, missing, or contradictory.+ - Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `$openspec-continue-change (Codex) or /openspec-continue-change (other agents)` to create them.+ - If the change is already coherent, say so and make no edits.++5. **Confirm and apply, one artifact at a time**+ - Show each proposed revision and why. Write only after the user confirms.+ - If the user rejects a revision, do not write it - leave that artifact unchanged.+ - When a substantial rewrite is needed, get that artifact's rules and template first:+ ```bash+ openspec instructions "<artifact-id>" --change "<name>" --json+ ```++6. **Point to the next step (guidance only - NEVER act on it)**+ - Artifacts still missing -> suggest `$openspec-continue-change (Codex) or /openspec-continue-change (other agents)` to create them.+ - Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)` to carry the delta into code.+ - Everything done and implemented -> suggest `$openspec-archive-change (Codex) or /openspec-archive-change (other agents)`.++**Output**++After each invocation, show:+- Which artifacts were revised (and which proposed revisions were rejected)+- Anything deferred to `$openspec-continue-change (Codex) or /openspec-continue-change (other agents)` (not-yet-created artifacts or files)+- Where the change stands and the recommended next command++**Guardrails**+- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `$openspec-apply-change (Codex) or /openspec-apply-change (other agents)`.+- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.+- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.+- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `$openspec-continue-change (Codex) or /openspec-continue-change (other agents)`'s job.+- Confirm every edit with the user before writing.+- If the request changes the change's *intent* rather than refining it, first verify whether the optional `$openspec-new-change (Codex) or /openspec-new-change (other agents)` workflow is available. If it is, recommend starting fresh with `$openspec-new-change (Codex) or /openspec-new-change (other agents)` (the "Update vs. Start Fresh" heuristic). If it is unavailable, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead.diff --git a/.claude/agents/claude-md-reviewer.md b/.claude/agents/claude-md-reviewer.mdindex 1eadbee3..670d11b0 100644--- a/.claude/agents/claude-md-reviewer.md+++ b/.claude/agents/claude-md-reviewer.md@@ -1,10 +1,10 @@---name: claude-md-reviewer-description: Audits a plan or a working-tree diff against the repo's CLAUDE.md standards. Invoke after producing an implementation plan and again after finishing an implementation.+description: Audits a plan or a working-tree diff against the repo's AGENTS.md standards. Invoke after producing an implementation plan and again after finishing an implementation.tools: Read, Grep, Glob, Bash----You audit work against the Databasus `CLAUDE.md` standards. You report violations; you never fix them. You have no `Write` or `Edit` tool — the calling agent applies every fix.+You audit work against the Databasus `AGENTS.md` standards. You report violations; you never fix them. You have no `Write` or `Edit` tool — the calling agent applies every fix.Your caller tells you the mode: **plan** or **implementation**. If the mode is absent, infer it: a plan file path means plan mode, otherwise implementation mode.@@ -18,16 +18,16 @@ Your caller tells you the mode: **plan** or **implementation**. If the mode is aEvery file is governed by **two** documents at once, and you audit it against both. Neither replaces the other: the root doc carries the project-wide philosophy, and the module doc carries the stack-specific rules on top of it.-1. **Always** read `CLAUDE.md` at the repo root. It governs every file in every module, with no exceptions.+1. **Always** read `AGENTS.md` at the repo root. It governs every file in every module, with no exceptions.2. **Also** read the module doc for each area the change touches:| Touched path | Module doc || --- | --- |- | `backend/**` | `backend/CLAUDE.md` |- | `agent/**` | `agent/verification/CLAUDE.md` |- | `frontend/**` | `frontend/CLAUDE.md` |+ | `backend/**` | `backend/AGENTS.md` |+ | `agent/**` | `agent/verification/AGENTS.md` |+ | `frontend/**` | `frontend/AGENTS.md` |-A change spanning several modules is audited against the root doc plus *every* module doc it touches. A change under `backend/` is audited against the root doc **and** `backend/CLAUDE.md` — never the module doc alone, and never the root doc alone.+A change spanning several modules is audited against the root doc plus *every* module doc it touches. A change under `backend/` is audited against the root doc **and** `backend/AGENTS.md` — never the module doc alone, and never the root doc alone.Skip only the module docs that govern nothing in scope. Never skip the root doc.@@ -37,7 +37,7 @@ Audit against the root doc and the module doc together. Run the root-level passThese are the rules that get violated most. They are not the whole of the docs — the docs you read in step 2 are authoritative, and this list is a prompt for where to look first.-### From the root `CLAUDE.md` — applies to every changed file+### From the root `AGENTS.md` — applies to every changed file**Naming.** Names state intent, not mechanism. No `data`, `handle`, `process`, `tmp`, `helper`, `manager`. No type-suffix noise (`nameStr`, `agentList`, `tokenObj`). Booleans and predicate methods take `is` / `can` / `has` / `should` — `IsAborted(id)`, not `AbortedContains(id)`. State that holds the entity being acted on names the entity — `deletingAgentId`, not `deletingId`. Getters take a `Get` prefix and name the entity — `GetRunningVerificationIDs()`, not `Active()`; this is house style and deliberately departs from vanilla Go. A getter returning a bool stays a predicate (`Is...`/`Has...`). A name that hides a second effect is a lie — a function that records *and* cancels is `recordAndCancelAborts`, or it is two functions. Tests use domain nouns, never `got` / `want` / `expected`.@@ -45,7 +45,7 @@ These are the rules that get violated most. They are not the whole of the docs**Backward compatibility.** Never preserved unless the user asked for it. Flag every deprecation shim, alias, and fallback for the old shape.-**Language.** English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages — including user-facing fallback copy.+**Language.** English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages — including user-facing fallback copy. The one exception under `frontend/src/` is the interface dictionaries (`frontend/src/shared/i18n/locales/<locale>.ts`), whose values are in the target language; their keys, identifiers and comments stay English.**Types and signatures.** No generic type names (`Manager`, `Provisioner`, `Handler`). No package stutter (`container.ContainerManager`) — `revive` fails CI on it; put the noun on the variable instead. Roughly four or more positional parameters, or two adjacent same-typed parameters, become a named struct.@@ -53,11 +53,11 @@ These are the rules that get violated most. They are not the whole of the docs### From the module docs — applies on top of the root pass-**`backend/CLAUDE.md`.** Dependency injection through `SetupDependencies()`; never inject another feature's repository. Controller tests preferred over unit tests; `features/tests/` is reserved for backup→restore cycle tests; clean up test data. Logging: values in the message, IDs and errors as key-value pairs, scope IDs via `logger.With(...)`; never log secrets, tokens, or credentials — redact at the logger layer, not at call sites. File organization, spacing between logical statements, time handling, and modern Go (`slices`, `context` helpers, `omitzero` over `omitempty`, `new(val)`).+**`backend/AGENTS.md`.** Dependency injection through `SetupDependencies()`; never inject another feature's repository. Controller tests preferred over unit tests; `features/tests/` is reserved for backup→restore cycle tests; clean up test data. Logging: values in the message, IDs and errors as key-value pairs, scope IDs via `logger.With(...)`; never log secrets, tokens, or credentials — redact at the logger layer, not at call sites. File organization, spacing between logical statements, time handling, and modern Go (`slices`, `context` helpers, `omitzero` over `omitempty`, `new(val)`).-**`agent/verification/CLAUDE.md`.** The same spacing, file organization, background-service, testing, time-handling, logging and modern-Go rules as the backend doc, in their agent-specific form. Read it rather than assuming it matches the backend doc.+**`agent/verification/AGENTS.md`.** The same spacing, file organization, background-service, testing, time-handling, logging and modern-Go rules as the backend doc, in their agent-specific form. Read it rather than assuming it matches the backend doc.-**`frontend/CLAUDE.md`.** Feature-Sliced Design: import direction, correct slice placement, no cross-imports between same-layer slices. React component structure order, vertical spacing, UI kit and icons, forms and progressive disclosure, user-facing copy.+**`frontend/AGENTS.md`.** Feature-Sliced Design: import direction, correct slice placement, no cross-imports between same-layer slices. React component structure order, vertical spacing, UI kit and icons, forms and progressive disclosure, user-facing copy.## Step 4 — Lint (implementation mode only)@@ -81,7 +81,7 @@ CHANGES REQUIREDOn the line below the verdict, name the docs you audited against, so the caller can see the root doc was not skipped:```-Audited against: CLAUDE.md, backend/CLAUDE.md+Audited against: AGENTS.md, backend/AGENTS.md```On `CHANGES REQUIRED`, list findings beneath that, most severe first, one per line. Every finding names the doc the rule comes from:@@ -93,8 +93,8 @@ On `CHANGES REQUIRED`, list findings beneath that, most severe first, one per liFor example:```-backend/internal/features/system/agent/service.go:42 — [CLAUDE.md] getters take a Get prefix and name the entity — rename Active() to GetRunningVerificationIDs()-backend/internal/features/system/agent/di.go:17 — [backend/CLAUDE.md] never inject another feature's repository — depend on the audit log service, not AuditLogRepository+backend/internal/features/system/agent/service.go:42 — [AGENTS.md] getters take a Get prefix and name the entity — rename Active() to GetRunningVerificationIDs()+backend/internal/features/system/agent/di.go:17 — [backend/AGENTS.md] never inject another feature's repository — depend on the audit log service, not AuditLogRepository```In plan mode a finding cites the plan's section instead of a line number.diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..125d434d--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,165 @@+# Databasus — Agent Rules and Guidelines++This document contains project-wide coding standards and best practices for Databasus.+This is NOT a strict set of rules — it is a set of recommendations to help write better, more consistent code.++Per-folder rules live next to the code they govern:++- [`backend/AGENTS.md`](backend/AGENTS.md) — Go + Gin + GORM + PostgreSQL backend (controllers, migrations, CRUD, DI, testing, logging)+- [`agent/verification/AGENTS.md`](agent/verification/AGENTS.md) — Go verification agent CLI (self-update + capacity heartbeat; restore logic deferred)+- [`frontend/AGENTS.md`](frontend/AGENTS.md) — React 19 + TypeScript + Vite + Ant Design + Tailwind+- [`website/AGENTS.md`](website/AGENTS.md) — Next.js marketing site and its 6-language translation rules+- [`assets/readme/AGENTS.md`](assets/readme/AGENTS.md) — translated copies of the root `README.md`++This root file holds the engineering philosophy that applies everywhere.++---++## Development environment++Work happens inside the repo's [Dev Container](.devcontainer/devcontainer.json). The container ships Go, Node.js + pnpm, Docker-in-Docker, linters and matching VS Code extensions, so the toolchain is identical for every contributor. Ports `4005` (backend) and `5173` (Vite) are forwarded automatically. Don't install or rely on host-level SDKs — run `make`, `pnpm` and `docker` commands from inside the container.++Running the backend suite host-native is supported on Fedora via `make test-fedora`, which shims the Debian soname the bundled `assets/tools` clients expect. Any other host distro is on its own — the container stays the reference environment. Also project sometimes is run in different worktrees, in this case it is needed to copy .env.example -> .env, `make swagger` and `pnpm install` to run tests++---++## Language in code++**English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages.** No other language inside `backend/` or `agent/` at all, and none inside `frontend/src/` outside the interface dictionaries named below — not even for user-facing fallback copy or error messages.++Translated end-user content is allowed in four places and nowhere else: the website page copies (`website/app/[lang]/*/content/<locale>.tsx`), the README translations (`assets/readme/README.<locale>.md`), the six language-switcher labels in the root `README.md`, and the frontend interface dictionaries (`frontend/src/shared/i18n/locales/<locale>.ts`). Even there, file names (locale codes aside), identifiers, dictionary keys and commit messages stay English.++The dictionaries are the only target-language text anywhere under `frontend/`, `index.html` included. Every other file there stays English, fallback copy and error messages included: a component renders a translation by looking up a key, never by holding the translated string itself.++---++## Engineering philosophy++**Think like a skeptical senior engineer and code reviewer. Don't just do what was asked — also think about what should have been asked. Catch real issues, not theoretical ones.**++### Task tiers (scale your response to the task)++- **Trivial** (typos, formatting, single-field adds): apply directly. Steps 5 only.+- **Standard** (CRUD, typical features): steps 1, 5.+- **Complex** (architecture, security, performance-critical): all steps.+- **Unclear** (ambiguous requirements): steps 1 and 4 are mandatory.++### Steps for non-trivial tasks++1. **Restate the objective**, list explicit + inferred assumptions, flag shaky ones.+2. **Propose solutions** — for complex tasks, 2–3 approaches including a simpler baseline; recommend one with tradeoffs (complexity, maintainability, performance, extensibility).+3. **Identify risks** — edge cases, security/privacy, performance, operational concerns (deployment, observability, rollback). Before finalizing, ask "what could go wrong?" and patch.+4. **Handle ambiguity** — pick a reasonable default, label it, note what changes under alternative assumptions.+5. **Deliver quality** — correct, testable, maintainable code with minimal tests/validation. Prefer controller tests over unit tests.+6. **Fix root causes, not symptoms** — ask "why did this happen?" and address the underlying issue.++### After each run: suggest refactorings++Reread the diff with fresh eyes and **list** (don't silently apply) refactor suggestions: unclear names, duplication, dead code, deep nesting, misplaced responsibilities, leaky abstractions. Keep suggestions concrete (file + lines), behavior-preserving, and scoped to the current change. If the diff is already clean, say so in one line.++### Mandatory compliance review++Every non-trivial change is audited twice by the [`claude-md-reviewer`](.claude/agents/claude-md-reviewer.md) subagent — against this document **and** the module doc for each area it touches (`backend/AGENTS.md`, `agent/verification/AGENTS.md`, `frontend/AGENTS.md`, `website/AGENTS.md`, `assets/readme/AGENTS.md`). The module docs add stack-specific rules on top of this one; they never replace it, so a change under `backend/` answers to both.++1. **After planning, before writing code** — it checks the proposed names, file placement, and any planned backward-compat shims while they're still cheap to change.+2. **After implementing, before finishing the turn** — it checks the working-tree diff and runs the linter for each directory the diff touches.++The reviewer is read-only: it reports findings, you apply the fixes. Resolve every `CHANGES REQUIRED` finding before moving on. Hooks in [`.claude/settings.json`](.claude/settings.json) prompt for both checkpoints, but the obligation is this rule, not the hook — honour it if hooks are disabled.++### Naming++Name variables and functions for **intent**, not mechanism. Naming is the biggest readability lever — avoid generic placeholders (`data`, `handle`, `process`, `tmp`, `helper`, `manager`), type-suffix noise (`nameStr`, `agentList`, `tokenObj`), and mechanism-flavored names (`tickNow`, `hbResp`, `dataObj`).++Booleans take an `is` / `can` / `has` / `should` prefix (`isAllowed`, `canAccess`, `hasItems`, `shouldRetry`) — never bare nouns/verbs like `allowed` or `touches`.++State that holds "the entity currently being X-ed" must include the entity: `createdAgent`, not `created`; `listedAgents`, not `listed`; `deletingAgentId`, not `deletingId`. Pair related state explicitly: `revealedToken` + `revealedTokenAgentName`, not `tokenAgentName`. Loop variables get the domain word — `for _, agent := range listedAgents` (Go) — single letters only inside trivial one-line lambdas (`.map((a) => a.id)`).++Test-mechanism names (`got`, `want`, `expected`) are not acceptable — use the domain noun: `persistedAgent`, `firstRotation`, `secondRotation`. Match domain language across the wire — if the API says `agent`, don't rename to `worker` or `node` in client code.++Idiomatic short names stay where the convention is well-established: Go receivers (`s *AgentService`, `r *AgentRepository`, `ctx *gin.Context`) and JS/TS error catches (`} catch (e) {`). When no good name exists, the abstraction is wrong — extract or rename it, don't reach for `helper` / `tmp` / `manager`.++Examples:++```go+// bad+var hbResp HeartbeatResponse+var got *Agent+for _, a := range listed { ... }++// good+var heartbeatResponse HeartbeatResponse+var persistedAgent *Agent+for _, agent := range listedAgents { ... }+```++```ts+// bad+const [tickNow, setTickNow] = useState(Date.now());+const [deletingId, setDeletingId] = useState<string | null>(null);+const [tokenAgentName, setTokenAgentName] = useState('');++// good+const [currentTimeMs, setCurrentTimeMs] = useState(Date.now());+const [deletingAgentId, setDeletingAgentId] = useState<string | null>(null);+const [revealedTokenAgentName, setRevealedTokenAgentName] = useState('');+```++### Functions, methods and types++The intent rule applies to callables and types too — this is where it's violated most:++- **A name that needs a "what" comment is a naming bug.** Doc comments are for *why*, ordering, and hidden constraints — never to restate behavior. If you wrote `// Foo does X` above `func Foo`, rename `Foo` until that comment is redundant, then delete it. Keep only the sentence a name *cannot* carry (e.g. "must be called before the container exists").+- **Predicate methods read as a question**, same as boolean vars: `IsAborted(id)`, not `AbortedContains(id)`; `HasCapacity()`, not `CapacityCheck()`.+- **The name states everything the unit does.** A function that records *and* cancels is `recordAndCancelAborts` — or it's two functions. A name that hides a second effect is a lie.+- **Getters take a `Get` prefix and name the entity.** `GetRunningVerificationIDs()`, not `Active()`, `RunningVerificationIDs()`, or `DiskUsageBytes()`. This is a deliberate house style: prefer the explicit `Get` *even though vanilla Go idiom omits it* — it keeps accessors visually distinct from actions and matches the backend (`GetAuditLogService`, `GetGlobalAuditLogs`). Constructors stay `New...`; a getter that returns a bool is still a predicate, so it stays `Is/Has...`, not `Get...`.+- **Long positional parameter lists become a struct.** ~4+ params, or two same-typed params adjacent → a named parameter/DTO struct (the input counterpart to the result type, e.g. `spawnPlan` → `SpawnSpec`). Kills call-site ordering bugs and the comment explaining argument order.+- **Type names: avoid generic *and* avoid package stutter.** Not `Manager` / `Provisioner` / `Handler` (generic), not `container.ContainerManager` (stutters — `revive` fails CI). If the only honest name stutters, put the noun on the *variable*, not the type: keep the type `container.Manager`, name the variable `containerManager`. If no precise type name exists, the abstraction is wrong — split it.++```go+// bad — comment restates the name; name hides the second effect; predicate isn't a question+// applyAborts records the abort set and cancels each registered job.+func (h *Heartbeater) applyAborts(ids []uuid.UUID) { ... }+func (h *Heartbeater) AbortedContains(id uuid.UUID) bool { ... }++// good — the names carry it; no comment needed+func (h *Heartbeater) recordAndCancelAborts(ids []uuid.UUID) { ... }+func (h *Heartbeater) IsAborted(id uuid.UUID) bool { ... }+```++### Linting and formatting++After each change run linting and formatting depending on folder you are working it.+- backend and agent has `make lint` commands+- frontend has `pnpm lint` and `pnpm format` commands++### Comments are a last resort++The default is **no comment**. Before writing one, reach for a clearer name or a smaller function first — self-explanatory code beats commented code every time. A comment is justified only when it carries something the code cannot: a *why* (business rule, hidden cross-system constraint, non-obvious algorithm or optimisation, ADR reference). Never write a comment that restates *what* the code does or narrates the obvious — if a `// Foo does X` comment sits above the code, that's a naming bug: rename until the comment is redundant, then delete it. This applies everywhere, tests included — a well-named test needs no header comment explaining what it checks.++### No issue numbers in production code++Fixing an issue does not put its number in the code. Production files, comments and error messages state the constraint itself — an issue number is a pointer to a discussion the reader has to leave the code to follow, and it rots the moment the tracker moves.++The one exception is a test written specifically to pin that issue's behaviour: there the number belongs next to the test, because it says *why this case exists* and where the reproduction came from.++### No "how it was" comments, no unrequested backward compatibility++Don't write comments that explain previous behavior ("used to be X", "was renamed from Y", "kept for legacy callers"). Code shows the current state; history lives in git.++Don't preserve backward compatibility unless the user asks for it. No deprecation shims, no aliases, no fallbacks for the old shape. When planning a change that would break existing callers, schemas, configs, or APIs, call out the break explicitly in the plan. If the user approves it, delete the old code outright — do not leave a transition layer behind.++### Security++Databasus handles sensitive data, so security is a layered defence. CodeQL, CodeRabbit, Codex Security, Trivy, Dependabot, gitleaks and semgrep all run on every PR. When working in the repo:++- Don't disable or weaken security checks to make a build pass. For genuine false positives, suppress explicitly with a documented reason (e.g. `.trivyignore`) and explain why in the PR.+- Pin every new GitHub Action to a full commit SHA with a `# vX.Y.Z` tag comment. No floating tags like `@v4` or `@main`.+- Workflows default to top-level `permissions: contents: read`; elevate per-job only when justified.+- Keep Dockerfiles free of secrets, floating base-image tags and unjustified root. If root-at-start is required (PUID/PGID remap, volume chown, initdb), drop privileges with `gosu` before `exec`-ing the app.+- Never log secrets, tokens or credentials. Redact at the logger layer, not at call sites.++The README's `🛡️ Security & reliability engineering` section is the public-facing version of these practices — keep both consistent if substance changes. That section, like the rest of `README.md`, exists in 6 languages: a substantive edit lands in the English file and in all five `assets/readme/README.<locale>.md` copies.++## Commiting++Never put Co-Authoring in commit message until it is requested directly\ No newline at end of filediff --git a/CLAUDE.md b/CLAUDE.mdindex 1fcf6c51..1c6b8c7d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,163 +1,5 @@-# Databasus — Agent Rules and Guidelines+# Databasus-This document contains project-wide coding standards and best practices for Databasus.-This is NOT a strict set of rules — it is a set of recommendations to help write better, more consistent code.+The agent rules for this repository live in [`AGENTS.md`](AGENTS.md).-Per-folder rules live next to the code they govern:--- [`backend/CLAUDE.md`](backend/CLAUDE.md) — Go + Gin + GORM + PostgreSQL backend (controllers, migrations, CRUD, DI, testing, logging)-- [`agent/verification/CLAUDE.md`](agent/verification/CLAUDE.md) — Go verification agent CLI (self-update + capacity heartbeat; restore logic deferred)-- [`frontend/CLAUDE.md`](frontend/CLAUDE.md) — React 19 + TypeScript + Vite + Ant Design + Tailwind-- [`website/CLAUDE.md`](website/CLAUDE.md) — Next.js marketing site and its 6-language translation rules-- [`assets/readme/CLAUDE.md`](assets/readme/CLAUDE.md) — translated copies of the root `README.md`--This root file holds the engineering philosophy that applies everywhere.-------## Development environment--Work happens inside the repo's [Dev Container](.devcontainer/devcontainer.json). The container ships Go, Node.js + pnpm, Docker-in-Docker, linters and matching VS Code extensions, so the toolchain is identical for every contributor. Ports `4005` (backend) and `5173` (Vite) are forwarded automatically. Don't install or rely on host-level SDKs — run `make`, `pnpm` and `docker` commands from inside the container.--Running the backend suite host-native is supported on Fedora via `make test-fedora`, which shims the Debian soname the bundled `assets/tools` clients expect. Any other host distro is on its own — the container stays the reference environment. Also project sometimes is run in different worktrees, in this case it is needed to copy .env.example -> .env, `make swagger` and `pnpm install` to run tests-------## Language in code--**English only in code, comments, identifiers, log messages, API strings, test assertions, and commit messages.** No other language inside `backend/`, `agent/`, or `frontend/src/` — even for user-facing fallback copy or error messages.--Translated end-user content is allowed in three places and nowhere else: the website page copies (`website/app/[lang]/*/content/<locale>.tsx`), the README translations (`assets/readme/README.<locale>.md`), and the six language-switcher labels in the root `README.md`. Even there, file names, identifiers and commit messages stay English.-------## Engineering philosophy--**Think like a skeptical senior engineer and code reviewer. Don't just do what was asked — also think about what should have been asked. Catch real issues, not theoretical ones.**--### Task tiers (scale your response to the task)--- **Trivial** (typos, formatting, single-field adds): apply directly. Steps 5 only.-- **Standard** (CRUD, typical features): steps 1, 5.-- **Complex** (architecture, security, performance-critical): all steps.-- **Unclear** (ambiguous requirements): steps 1 and 4 are mandatory.--### Steps for non-trivial tasks--1. **Restate the objective**, list explicit + inferred assumptions, flag shaky ones.-2. **Propose solutions** — for complex tasks, 2–3 approaches including a simpler baseline; recommend one with tradeoffs (complexity, maintainability, performance, extensibility).-3. **Identify risks** — edge cases, security/privacy, performance, operational concerns (deployment, observability, rollback). Before finalizing, ask "what could go wrong?" and patch.-4. **Handle ambiguity** — pick a reasonable default, label it, note what changes under alternative assumptions.-5. **Deliver quality** — correct, testable, maintainable code with minimal tests/validation. Prefer controller tests over unit tests.-6. **Fix root causes, not symptoms** — ask "why did this happen?" and address the underlying issue.--### After each run: suggest refactorings--Reread the diff with fresh eyes and **list** (don't silently apply) refactor suggestions: unclear names, duplication, dead code, deep nesting, misplaced responsibilities, leaky abstractions. Keep suggestions concrete (file + lines), behavior-preserving, and scoped to the current change. If the diff is already clean, say so in one line.--### Mandatory compliance review--Every non-trivial change is audited twice by the [`claude-md-reviewer`](.claude/agents/claude-md-reviewer.md) subagent — against this document **and** the module doc for each area it touches (`backend/CLAUDE.md`, `agent/verification/CLAUDE.md`, `frontend/CLAUDE.md`, `website/CLAUDE.md`, `assets/readme/CLAUDE.md`). The module docs add stack-specific rules on top of this one; they never replace it, so a change under `backend/` answers to both.--1. **After planning, before writing code** — it checks the proposed names, file placement, and any planned backward-compat shims while they're still cheap to change.-2. **After implementing, before finishing the turn** — it checks the working-tree diff and runs the linter for each directory the diff touches.--The reviewer is read-only: it reports findings, you apply the fixes. Resolve every `CHANGES REQUIRED` finding before moving on. Hooks in [`.claude/settings.json`](.claude/settings.json) prompt for both checkpoints, but the obligation is this rule, not the hook — honour it if hooks are disabled.--### Naming--Name variables and functions for **intent**, not mechanism. Naming is the biggest readability lever — avoid generic placeholders (`data`, `handle`, `process`, `tmp`, `helper`, `manager`), type-suffix noise (`nameStr`, `agentList`, `tokenObj`), and mechanism-flavored names (`tickNow`, `hbResp`, `dataObj`).--Booleans take an `is` / `can` / `has` / `should` prefix (`isAllowed`, `canAccess`, `hasItems`, `shouldRetry`) — never bare nouns/verbs like `allowed` or `touches`.--State that holds "the entity currently being X-ed" must include the entity: `createdAgent`, not `created`; `listedAgents`, not `listed`; `deletingAgentId`, not `deletingId`. Pair related state explicitly: `revealedToken` + `revealedTokenAgentName`, not `tokenAgentName`. Loop variables get the domain word — `for _, agent := range listedAgents` (Go) — single letters only inside trivial one-line lambdas (`.map((a) => a.id)`).--Test-mechanism names (`got`, `want`, `expected`) are not acceptable — use the domain noun: `persistedAgent`, `firstRotation`, `secondRotation`. Match domain language across the wire — if the API says `agent`, don't rename to `worker` or `node` in client code.--Idiomatic short names stay where the convention is well-established: Go receivers (`s *AgentService`, `r *AgentRepository`, `ctx *gin.Context`) and JS/TS error catches (`} catch (e) {`). When no good name exists, the abstraction is wrong — extract or rename it, don't reach for `helper` / `tmp` / `manager`.--Examples:--```go-// bad-var hbResp HeartbeatResponse-var got *Agent-for _, a := range listed { ... }--// good-var heartbeatResponse HeartbeatResponse-var persistedAgent *Agent-for _, agent := range listedAgents { ... }-```--```ts-// bad-const [tickNow, setTickNow] = useState(Date.now());-const [deletingId, setDeletingId] = useState<string | null>(null);-const [tokenAgentName, setTokenAgentName] = useState('');--// good-const [currentTimeMs, setCurrentTimeMs] = useState(Date.now());-const [deletingAgentId, setDeletingAgentId] = useState<string | null>(null);-const [revealedTokenAgentName, setRevealedTokenAgentName] = useState('');-```--### Functions, methods and types--The intent rule applies to callables and types too — this is where it's violated most:--- **A name that needs a "what" comment is a naming bug.** Doc comments are for *why*, ordering, and hidden constraints — never to restate behavior. If you wrote `// Foo does X` above `func Foo`, rename `Foo` until that comment is redundant, then delete it. Keep only the sentence a name *cannot* carry (e.g. "must be called before the container exists").-- **Predicate methods read as a question**, same as boolean vars: `IsAborted(id)`, not `AbortedContains(id)`; `HasCapacity()`, not `CapacityCheck()`.-- **The name states everything the unit does.** A function that records *and* cancels is `recordAndCancelAborts` — or it's two functions. A name that hides a second effect is a lie.-- **Getters take a `Get` prefix and name the entity.** `GetRunningVerificationIDs()`, not `Active()`, `RunningVerificationIDs()`, or `DiskUsageBytes()`. This is a deliberate house style: prefer the explicit `Get` *even though vanilla Go idiom omits it* — it keeps accessors visually distinct from actions and matches the backend (`GetAuditLogService`, `GetGlobalAuditLogs`). Constructors stay `New...`; a getter that returns a bool is still a predicate, so it stays `Is/Has...`, not `Get...`.-- **Long positional parameter lists become a struct.** ~4+ params, or two same-typed params adjacent → a named parameter/DTO struct (the input counterpart to the result type, e.g. `spawnPlan` → `SpawnSpec`). Kills call-site ordering bugs and the comment explaining argument order.-- **Type names: avoid generic *and* avoid package stutter.** Not `Manager` / `Provisioner` / `Handler` (generic), not `container.ContainerManager` (stutters — `revive` fails CI). If the only honest name stutters, put the noun on the *variable*, not the type: keep the type `container.Manager`, name the variable `containerManager`. If no precise type name exists, the abstraction is wrong — split it.--```go-// bad — comment restates the name; name hides the second effect; predicate isn't a question-// applyAborts records the abort set and cancels each registered job.-func (h *Heartbeater) applyAborts(ids []uuid.UUID) { ... }-func (h *Heartbeater) AbortedContains(id uuid.UUID) bool { ... }--// good — the names carry it; no comment needed-func (h *Heartbeater) recordAndCancelAborts(ids []uuid.UUID) { ... }-func (h *Heartbeater) IsAborted(id uuid.UUID) bool { ... }-```--### Linting and formatting--After each change run linting and formatting depending on folder you are working it.-- backend and agent has `make lint` commands-- frontend has `pnpm lint` and `pnpm format` commands--### Comments are a last resort--The default is **no comment**. Before writing one, reach for a clearer name or a smaller function first — self-explanatory code beats commented code every time. A comment is justified only when it carries something the code cannot: a *why* (business rule, hidden cross-system constraint, non-obvious algorithm or optimisation, ADR reference). Never write a comment that restates *what* the code does or narrates the obvious — if a `// Foo does X` comment sits above the code, that's a naming bug: rename until the comment is redundant, then delete it. This applies everywhere, tests included — a well-named test needs no header comment explaining what it checks.--### No issue numbers in production code--Fixing an issue does not put its number in the code. Production files, comments and error messages state the constraint itself — an issue number is a pointer to a discussion the reader has to leave the code to follow, and it rots the moment the tracker moves.--The one exception is a test written specifically to pin that issue's behaviour: there the number belongs next to the test, because it says *why this case exists* and where the reproduction came from.--### No "how it was" comments, no unrequested backward compatibility--Don't write comments that explain previous behavior ("used to be X", "was renamed from Y", "kept for legacy callers"). Code shows the current state; history lives in git.--Don't preserve backward compatibility unless the user asks for it. No deprecation shims, no aliases, no fallbacks for the old shape. When planning a change that would break existing callers, schemas, configs, or APIs, call out the break explicitly in the plan. If the user approves it, delete the old code outright — do not leave a transition layer behind.--### Security--Databasus handles sensitive data, so security is a layered defence. CodeQL, CodeRabbit, Codex Security, Trivy, Dependabot, gitleaks and semgrep all run on every PR. When working in the repo:--- Don't disable or weaken security checks to make a build pass. For genuine false positives, suppress explicitly with a documented reason (e.g. `.trivyignore`) and explain why in the PR.-- Pin every new GitHub Action to a full commit SHA with a `# vX.Y.Z` tag comment. No floating tags like `@v4` or `@main`.-- Workflows default to top-level `permissions: contents: read`; elevate per-job only when justified.-- Keep Dockerfiles free of secrets, floating base-image tags and unjustified root. If root-at-start is required (PUID/PGID remap, volume chown, initdb), drop privileges with `gosu` before `exec`-ing the app.-- Never log secrets, tokens or credentials. Redact at the logger layer, not at call sites.--The README's `🛡️ Security & reliability engineering` section is the public-facing version of these practices — keep both consistent if substance changes. That section, like the rest of `README.md`, exists in 6 languages: a substantive edit lands in the English file and in all five `assets/readme/README.<locale>.md` copies.--## Commiting--Never put Co-Authoring in commit message until it is requested directly\ No newline at end of file+Per-folder rules sit next to the code they govern, each in that folder's own `AGENTS.md`.diff --git a/adr/AGENTS.md b/adr/AGENTS.mdnew file mode 100644index 00000000..47b34bf0--- /dev/null+++ b/adr/AGENTS.md@@ -0,0 +1,49 @@+# Writing ADRs++ADRs live here, numbered `NNNN-slug.md`. Start from [`0000-adr-template.md`](0000-adr-template.md)+and drop every section you don't need.++## What an ADR is for++Record **why** a decision was made, so nobody re-litigates it in six months.++Write one only if all three hold:++1. It's expensive to reverse.+2. A future reader would look at the code and ask "why on earth like this?"+3. There was a real alternative and we picked against it for a reason.++Obvious decisions don't get an ADR.++## Write the substance, not the details++The code is the source of truth for *how*. The ADR is the source of truth for *why*. Never restate+the code in prose.++Keep out:++- Env-var names, config keys, flags, defaults, limits+- Function, package and type names, call chains, file layout+- Anything you'd have to update after a rename++Keep in:++- The problem and the constraint that forced the decision+- What we decided, in plain words+- Alternatives we rejected, and why they lost+- Consequences we're knowingly accepting++Rule of thumb: if a sentence would go stale after a refactor, it belongs in the code, not here.++## Style++- One page. If it's longer, you're explaining the implementation.+- Plain language. A new engineer should get it without opening the repo.+- Present tense, stated as fact: "We export logs over OTLP", not "It was decided that...".+- English only.+- Name the decision in the title, not the technology: "Export logs over OTLP" beats "OpenTelemetry".++## Keeping them honest++An ADR is a snapshot of a decision, not living documentation. When a decision is replaced, don't+edit history: write a new ADR and mark the old one `Superseded by ADR-NNNN`.diff --git a/adr/CLAUDE.md b/adr/CLAUDE.mdindex 47b34bf0..188fe0c6 100644--- a/adr/CLAUDE.md+++ b/adr/CLAUDE.md@@ -1,49 +1,3 @@# Writing ADRs-ADRs live here, numbered `NNNN-slug.md`. Start from [`0000-adr-template.md`](0000-adr-template.md)-and drop every section you don't need.--## What an ADR is for--Record **why** a decision was made, so nobody re-litigates it in six months.--Write one only if all three hold:--1. It's expensive to reverse.-2. A future reader would look at the code and ask "why on earth like this?"-3. There was a real alternative and we picked against it for a reason.--Obvious decisions don't get an ADR.--## Write the substance, not the details--The code is the source of truth for *how*. The ADR is the source of truth for *why*. Never restate-the code in prose.--Keep out:--- Env-var names, config keys, flags, defaults, limits-- Function, package and type names, call chains, file layout-- Anything you'd have to update after a rename--Keep in:--- The problem and the constraint that forced the decision-- What we decided, in plain words-- Alternatives we rejected, and why they lost-- Consequences we're knowingly accepting--Rule of thumb: if a sentence would go stale after a refactor, it belongs in the code, not here.--## Style--- One page. If it's longer, you're explaining the implementation.-- Plain language. A new engineer should get it without opening the repo.-- Present tense, stated as fact: "We export logs over OTLP", not "It was decided that...".-- English only.-- Name the decision in the title, not the technology: "Export logs over OTLP" beats "OpenTelemetry".--## Keeping them honest--An ADR is a snapshot of a decision, not living documentation. When a decision is replaced, don't-edit history: write a new ADR and mark the old one `Superseded by ADR-NNNN`.+See [`AGENTS.md`](AGENTS.md).diff --git a/agent/verification/AGENTS.md b/agent/verification/AGENTS.mdnew file mode 100644index 00000000..7d5a134b--- /dev/null+++ b/agent/verification/AGENTS.md@@ -0,0 +1,289 @@+# Verification agent guidelines (Go CLI)++Coding standards for the Databasus verification agent — a Go CLI worker that runs on a cloud-managed Linux VM, reports its capacity to the backend over HTTP, and (once the restore phase lands) claims and verifies backups. It has no Gin HTTP server and owns no database schema. The long-running goroutine in this phase is the **capacity heartbeat loop**; the claim/report runner arrives with the restore phase. There is no Windows daemon — the agent runs in the foreground under systemd or as a container.++For project-wide engineering philosophy, naming, and lint/format commands, see the root `AGENTS.md`. For the backend (Gin/GORM/Swagger) ruleset, see `backend/AGENTS.md`.++---++## Table of Contents++- [Spacing between logical statements](#spacing-between-logical-statements)+- [Comments](#comments)+- [File organization](#file-organization)+- [Background services](#background-services)+- [Testing](#testing)+- [Time handling](#time-handling)+- [Logging](#logging)+- [Modern Go](#modern-go)++---++## Spacing between logical statements++Add blank lines between logical blocks so the flow is visible at a glance:++- before the final `return`+- after variable declarations, before they're used+- between error handling and subsequent logic+- between distinct logical operations++Bad:++```go+func encodeMessages(messages []Message) (string, error) {+ if len(messages) > 0 {+ messagesBytes, err := json.Marshal(messages)+ if err != nil {+ return "", err+ }+ return string(messagesBytes), nil+ }+ return "", nil+}+```++Good:++```go+func encodeMessages(messages []Message) (string, error) {+ if len(messages) > 0 {+ messagesBytes, err := json.Marshal(messages)+ if err != nil {+ return "", err+ }++ return string(messagesBytes), nil+ }++ return "", nil+}+```++---++## Comments++- **No obvious comments** — don't restate what the code already shows.+- **Explain *why*, not *what*** — code shows what happens; comments explain business rules, hidden constraints, or non-obvious optimizations.+- **Prefer refactoring over commenting** — better names or smaller functions usually beat a comment.+- **Complex algorithms deserve comments** — formulas, business rules, non-obvious optimizations.+- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.++Bad (each comment restates the function name):++```go+// Send heartbeat+sendHeartbeat(request)++// CreateValidLogItems creates valid log items for testing+func CreateValidLogItems(count int, uniqueID string) []LogItemRequestDTO {+```++---++## File organization++One responsibility per file. Don't dump a whole package into one file — split+by role so a reader can find a type by its filename. Conventional names within+a feature package:++- `doc.go` — package doc comment, once the package spans more than one file+- `<feature>.go` — the core type and its methods (the orchestrator/executor)+- `dto.go` — request/response and cross-package data + interface seams+- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)+- `enums.go` — typed-constant groups (`type Status string` + its values)+- `constants.go` — package-level constants that aren't an enum+- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)++Only create a file when there is real content for it — an empty `enums.go` or+`constants.go` is noise, not structure. Test files mirror the source split:+`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →+`diskexhaustion_test.go`.++---++## Background services++The agent ships at least one long-running goroutine (the capacity `Heartbeater`; also `BackgroundUpgrader`). Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**++```go+type Heartbeater struct {+ // ...+ hasRun atomic.Bool+}++func (h *Heartbeater) Run(ctx context.Context) {+ if h.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", h))+ }++ ticker := time.NewTicker(heartbeatInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ h.beat(ctx, logger)+ }+ }+}+```++`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed.++---++## Testing++**Always run tests after writing them and verify they pass.**++### Naming++- `Test_WhatWeDo_WhatWeExpect`+- `Test_WhatWeDo_WhichConditions_WhatWeExpect`++Examples: `Test_DeriveCapacity_WhenConcurrentJobsExceedCPU_ReturnsError`, `Test_ValidateTransport_WhenHttpAndNotTTYWithoutFlag_FailsFast`, `Test_Heartbeat_WhenCalled_SendsFlatEnvelopeWithBearerAndAgentPath`, `Test_BackgroundUpgrader_WhenRunCalledTwice_Panics`.++### Where tests live++- **Unit / package tests**: alongside the code, named `*_test.go` (e.g. `internal/features/heartbeat/heartbeat_test.go`).+- **End-to-end tests**: under `agent/verification/e2e/`. Run via `make e2e` / `make e2e-clean`.++The agent has no HTTP API of its own, so there are no controller tests — test exported functions of the packages, the CLI commands, and the HTTP-client/IO logic directly.++### Refactor tests as you touch them++When editing existing tests, look for repetitive setup that should become a helper, oversized tests that should be split, and similar patterns across files that should be consolidated. Helpers live in a `testing.go` file inside the package.++### Clean up test data++If a test creates files, processes, or external state, clean it up via `t.Cleanup(...)` or `defer`. Skip cleanup only when the test uses an isolated tempdir the OS reclaims, or when it explicitly validates a failure path where cleanup isn't possible.++---++## Time handling++Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.++---++## Logging++We use `log/slog`. Three rules.++### 1. Scope IDs early via `logger.With(...)`++Attach `agent_id`, `verification_id`, `upgrade_target`, etc. as soon as you know them so every downstream line carries them automatically. For background services, also scope `job_id` (fresh UUID per execution) and `job_name` (stable snake_case const) in `Run()`.++```go+const jobName = "verification_heartbeat"++func (h *Heartbeater) Run(ctx context.Context) {+ logger := h.log.With("job_id", uuid.New(), "job_name", jobName)++ logger.Info("heartbeat loop started")+ // every subsequent log carries job_id + job_name+}+```++### 2. Values in message, IDs and errors as kv pairs++Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.++```go+// good+logger.Info(fmt.Sprintf("heartbeat ok: last_seen_at=%s", seenAt))+logger.Info("agent registered", "agent_id", agentID)+logger.Error("heartbeat failed", "error", err)++// bad — ID buried in the message string, error formatted instead of attached+logger.Info(fmt.Sprintf("agent registered %s", agentID))+logger.Error(fmt.Sprintf("heartbeat failed: %v", err))+```++### 3. Style and level++- All keys `snake_case` (`agent_id`, `verification_id`) — never camelCase.+- Messages start lowercase, no trailing period.+- **Debug**: routine ops, function entry, query result counts.+- **Info**: significant state changes, completed actions (`"agent started"`, `"heartbeat loop stopped"`).+- **Warn**: degraded but recoverable (`"heartbeat failed, will retry next tick"`, `"upgrade skipped: same version"`).+- **Error**: failures that need attention (`"auto-update failed"`, `"failed to re-exec after upgrade"`).++### What never goes into logs++- **Passwords, tokens, API keys, full `Authorization` headers** — centralize redaction; don't redact ad-hoc at call sites (config logging masks the token via `maskSensitive`).+- **Full request / response bodies** — log only the fields you actually need.++---++## Modern Go++Prefer modern stdlib idioms over manual equivalents.++### `slices` package — avoid manual loops++```go+slices.Contains(items, x)+slices.Index(items, x) // returns index or -1+slices.IndexFunc(items, func(item T) bool { return item.ID == id })+slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })+slices.Sort(items)+slices.Max(items) / slices.Min(items)+slices.Reverse(items) // in-place+slices.Compact(items) // remove consecutive duplicates+slices.Clone(s)+slices.Clip(s)+```++### Quick wins++- `any` instead of `interface{}`.+- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.+- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.+- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.+- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.+- `slog.DiscardHandler` for a no-op logger in tests.++### `context` helpers++```go+stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation+ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause+ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause+```++### `omitzero` instead of `omitempty` for non-nullable types++`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:++```go+// good+type Config struct {+ Timeout time.Duration `json:"timeout,omitzero"`+ CreatedAt time.Time `json:"createdAt,omitzero"`+}++// bad+type Config struct {+ Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!+ CreatedAt time.Time `json:"createdAt,omitempty"`+}+```++### `new(val)` for pointer literals (Go 1.26+)++`new()` accepts expressions, eliminating the temp-variable pattern:++```go+// good+cfg := Config{Timeout: new(30), Debug: new(true)}++// bad+timeout := 30+debug := true+cfg := Config{Timeout: &timeout, Debug: &debug}+```diff --git a/agent/verification/CLAUDE.md b/agent/verification/CLAUDE.mdindex 96bb464f..470f9327 100644--- a/agent/verification/CLAUDE.md+++ b/agent/verification/CLAUDE.md@@ -1,289 +1,3 @@-# Verification agent guidelines (Go CLI)+# Verification agent-Coding standards for the Databasus verification agent — a Go CLI worker that runs on a cloud-managed Linux VM, reports its capacity to the backend over HTTP, and (once the restore phase lands) claims and verifies backups. It has no Gin HTTP server and owns no database schema. The long-running goroutine in this phase is the **capacity heartbeat loop**; the claim/report runner arrives with the restore phase. There is no Windows daemon — the agent runs in the foreground under systemd or as a container.--For project-wide engineering philosophy, naming, and lint/format commands, see the root `CLAUDE.md`. For the backend (Gin/GORM/Swagger) ruleset, see `backend/CLAUDE.md`.-------## Table of Contents--- [Spacing between logical statements](#spacing-between-logical-statements)-- [Comments](#comments)-- [File organization](#file-organization)-- [Background services](#background-services)-- [Testing](#testing)-- [Time handling](#time-handling)-- [Logging](#logging)-- [Modern Go](#modern-go)-------## Spacing between logical statements--Add blank lines between logical blocks so the flow is visible at a glance:--- before the final `return`-- after variable declarations, before they're used-- between error handling and subsequent logic-- between distinct logical operations--Bad:--```go-func encodeMessages(messages []Message) (string, error) {- if len(messages) > 0 {- messagesBytes, err := json.Marshal(messages)- if err != nil {- return "", err- }- return string(messagesBytes), nil- }- return "", nil-}-```--Good:--```go-func encodeMessages(messages []Message) (string, error) {- if len(messages) > 0 {- messagesBytes, err := json.Marshal(messages)- if err != nil {- return "", err- }-- return string(messagesBytes), nil- }-- return "", nil-}-```-------## Comments--- **No obvious comments** — don't restate what the code already shows.-- **Explain *why*, not *what*** — code shows what happens; comments explain business rules, hidden constraints, or non-obvious optimizations.-- **Prefer refactoring over commenting** — better names or smaller functions usually beat a comment.-- **Complex algorithms deserve comments** — formulas, business rules, non-obvious optimizations.-- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.--Bad (each comment restates the function name):--```go-// Send heartbeat-sendHeartbeat(request)--// CreateValidLogItems creates valid log items for testing-func CreateValidLogItems(count int, uniqueID string) []LogItemRequestDTO {-```-------## File organization--One responsibility per file. Don't dump a whole package into one file — split-by role so a reader can find a type by its filename. Conventional names within-a feature package:--- `doc.go` — package doc comment, once the package spans more than one file-- `<feature>.go` — the core type and its methods (the orchestrator/executor)-- `dto.go` — request/response and cross-package data + interface seams-- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)-- `enums.go` — typed-constant groups (`type Status string` + its values)-- `constants.go` — package-level constants that aren't an enum-- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)--Only create a file when there is real content for it — an empty `enums.go` or-`constants.go` is noise, not structure. Test files mirror the source split:-`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →-`diskexhaustion_test.go`.-------## Background services--The agent ships at least one long-running goroutine (the capacity `Heartbeater`; also `BackgroundUpgrader`). Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**--```go-type Heartbeater struct {- // ...- hasRun atomic.Bool-}--func (h *Heartbeater) Run(ctx context.Context) {- if h.hasRun.Swap(true) {- panic(fmt.Sprintf("%T.Run() called multiple times", h))- }-- ticker := time.NewTicker(heartbeatInterval)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- h.beat(ctx, logger)- }- }-}-```--`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed.-------## Testing--**Always run tests after writing them and verify they pass.**--### Naming--- `Test_WhatWeDo_WhatWeExpect`-- `Test_WhatWeDo_WhichConditions_WhatWeExpect`--Examples: `Test_DeriveCapacity_WhenConcurrentJobsExceedCPU_ReturnsError`, `Test_ValidateTransport_WhenHttpAndNotTTYWithoutFlag_FailsFast`, `Test_Heartbeat_WhenCalled_SendsFlatEnvelopeWithBearerAndAgentPath`, `Test_BackgroundUpgrader_WhenRunCalledTwice_Panics`.--### Where tests live--- **Unit / package tests**: alongside the code, named `*_test.go` (e.g. `internal/features/heartbeat/heartbeat_test.go`).-- **End-to-end tests**: under `agent/verification/e2e/`. Run via `make e2e` / `make e2e-clean`.--The agent has no HTTP API of its own, so there are no controller tests — test exported functions of the packages, the CLI commands, and the HTTP-client/IO logic directly.--### Refactor tests as you touch them--When editing existing tests, look for repetitive setup that should become a helper, oversized tests that should be split, and similar patterns across files that should be consolidated. Helpers live in a `testing.go` file inside the package.--### Clean up test data--If a test creates files, processes, or external state, clean it up via `t.Cleanup(...)` or `defer`. Skip cleanup only when the test uses an isolated tempdir the OS reclaims, or when it explicitly validates a failure path where cleanup isn't possible.-------## Time handling--Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.-------## Logging--We use `log/slog`. Three rules.--### 1. Scope IDs early via `logger.With(...)`--Attach `agent_id`, `verification_id`, `upgrade_target`, etc. as soon as you know them so every downstream line carries them automatically. For background services, also scope `job_id` (fresh UUID per execution) and `job_name` (stable snake_case const) in `Run()`.--```go-const jobName = "verification_heartbeat"--func (h *Heartbeater) Run(ctx context.Context) {- logger := h.log.With("job_id", uuid.New(), "job_name", jobName)-- logger.Info("heartbeat loop started")- // every subsequent log carries job_id + job_name-}-```--### 2. Values in message, IDs and errors as kv pairs--Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.--```go-// good-logger.Info(fmt.Sprintf("heartbeat ok: last_seen_at=%s", seenAt))-logger.Info("agent registered", "agent_id", agentID)-logger.Error("heartbeat failed", "error", err)--// bad — ID buried in the message string, error formatted instead of attached-logger.Info(fmt.Sprintf("agent registered %s", agentID))-logger.Error(fmt.Sprintf("heartbeat failed: %v", err))-```--### 3. Style and level--- All keys `snake_case` (`agent_id`, `verification_id`) — never camelCase.-- Messages start lowercase, no trailing period.-- **Debug**: routine ops, function entry, query result counts.-- **Info**: significant state changes, completed actions (`"agent started"`, `"heartbeat loop stopped"`).-- **Warn**: degraded but recoverable (`"heartbeat failed, will retry next tick"`, `"upgrade skipped: same version"`).-- **Error**: failures that need attention (`"auto-update failed"`, `"failed to re-exec after upgrade"`).--### What never goes into logs--- **Passwords, tokens, API keys, full `Authorization` headers** — centralize redaction; don't redact ad-hoc at call sites (config logging masks the token via `maskSensitive`).-- **Full request / response bodies** — log only the fields you actually need.-------## Modern Go--Prefer modern stdlib idioms over manual equivalents.--### `slices` package — avoid manual loops--```go-slices.Contains(items, x)-slices.Index(items, x) // returns index or -1-slices.IndexFunc(items, func(item T) bool { return item.ID == id })-slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })-slices.Sort(items)-slices.Max(items) / slices.Min(items)-slices.Reverse(items) // in-place-slices.Compact(items) // remove consecutive duplicates-slices.Clone(s)-slices.Clip(s)-```--### Quick wins--- `any` instead of `interface{}`.-- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.-- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.-- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.-- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.-- `slog.DiscardHandler` for a no-op logger in tests.--### `context` helpers--```go-stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation-ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause-ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause-```--### `omitzero` instead of `omitempty` for non-nullable types--`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:--```go-// good-type Config struct {- Timeout time.Duration `json:"timeout,omitzero"`- CreatedAt time.Time `json:"createdAt,omitzero"`-}--// bad-type Config struct {- Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!- CreatedAt time.Time `json:"createdAt,omitempty"`-}-```--### `new(val)` for pointer literals (Go 1.26+)--`new()` accepts expressions, eliminating the temp-variable pattern:--```go-// good-cfg := Config{Timeout: new(30), Debug: new(true)}--// bad-timeout := 30-debug := true-cfg := Config{Timeout: &timeout, Debug: &debug}-```+See [`AGENTS.md`](AGENTS.md), and the repository-wide rules in [`../../AGENTS.md`](../../AGENTS.md).diff --git a/assets/readme/AGENTS.md b/assets/readme/AGENTS.mdnew file mode 100644index 00000000..938f2477--- /dev/null+++ b/assets/readme/AGENTS.md@@ -0,0 +1,76 @@+# README translations — Agent Rules++Translated copies of the root `README.md`, one file per locale:+`README.ru.md`, `README.es.md`, `README.pt.md`, `README.zh.md`, `README.fr.md`.+English stays at the repo root; only the translations live here.++## Sync rule (critical)++**Any change to `/README.md` must be applied to all 5 copies here** — structure,+headings, links, code blocks, badges. A translation that lags behind the English+file is worse than no translation: readers act on install commands.++The `## 🛡️ Security & reliability engineering` section is the sharpest case. The+root `AGENTS.md` requires it to stay consistent with the project's actual+security practices, so a change there now lands in 6 files.++## Structure++Each file mirrors the English README exactly: same sections in the same order,+same heading levels, same emoji in headings, same bullet structure, same+horizontal rules, same HTML blocks. The `### 📦 Installation` teaser inside+Features duplicates the real `## 📦 Installation` in English too — keep the+duplication.++## Byte-identical to English++Code blocks (commands, YAML, comments inside them), shields.io badge URLs and+their alt texts, inline code, image `alt`/`width` attributes, product and tool+names, version numbers, ports, and English UI labels quoted in the text+(`"New Database"` in the Usage steps — the interface is English, so the docs+quote it verbatim).++## Paths++These files sit one directory deeper than the English README:++- images: `../logo.svg`, `../dashboard-dark.svg`, `../dashboard.svg`, `../healthchecks.svg`+- repo files: `../../LICENSE`, `../../deploy/helm/README.md`+- the English README: `../../README.md`++## Website links++Links to `databasus.com` carry the locale prefix and a trailing slash:+`https://databasus.com/<locale>/storages/`, `https://databasus.com/<locale>/faq/#backup-databasus`.+The fragment ids (`#backup-databasus`, `#oss-programs`) are identical in every+locale — never translate them. `https://databasus.com/contribute` has no+translation on the site and stays unprefixed.++## In-page anchors++Unlike the website, anchors here are **not** identical across locales: GitHub+derives them from the heading text, so translated headings produce translated+anchors. Nothing outside these files links into their sections, so each file's+mini-TOC and in-body links simply point at its own slugs. Rule of thumb for the+slug: lowercase, punctuation dropped, emoji dropped but the space around it+becomes a hyphen, remaining spaces become hyphens, Cyrillic and CJK preserved.+`## ✨ Features` gives `#-features`; `## 🛡️ Security & reliability engineering`+gives `#️-security--reliability-engineering` (the variation selector survives).++## Language++Translation content is in the target language; the six language-switcher labels+(`English`, `Русский`, `Español`, `Português`, `中文`, `Français`) appear in the+root `README.md` as well. Everything else in this directory stays English,+including commit messages and this document; file names carry only the locale+code. The root `AGENTS.md` holds the full list of places translated content is+allowed.++## Translation quality++The rules in [`website/AGENTS.md`](../../website/AGENTS.md) under "Translation+quality" apply here in full: edited copy rather than word-for-word, no calques,+no bureaucratese, no marketing filler, per-locale conventions (ru «е» not «ё»;+es usted with «copia de seguridad» as the canonical term; pt-BR; zh 你 with+full-width punctuation and CJK↔Latin spacing; fr vous with a space before %).+The proofread website pages of each locale are the tone reference.diff --git a/assets/readme/CLAUDE.md b/assets/readme/CLAUDE.mdindex c8350d14..fda11853 100644--- a/assets/readme/CLAUDE.md+++ b/assets/readme/CLAUDE.md@@ -1,74 +1,3 @@-# README translations — Agent Rules+# README translations-Translated copies of the root `README.md`, one file per locale:-`README.ru.md`, `README.es.md`, `README.pt.md`, `README.zh.md`, `README.fr.md`.-English stays at the repo root; only the translations live here.--## Sync rule (critical)--**Any change to `/README.md` must be applied to all 5 copies here** — structure,-headings, links, code blocks, badges. A translation that lags behind the English-file is worse than no translation: readers act on install commands.--The `## 🛡️ Security & reliability engineering` section is the sharpest case. The-root `CLAUDE.md` requires it to stay consistent with the project's actual-security practices, so a change there now lands in 6 files.--## Structure--Each file mirrors the English README exactly: same sections in the same order,-same heading levels, same emoji in headings, same bullet structure, same-horizontal rules, same HTML blocks. The `### 📦 Installation` teaser inside-Features duplicates the real `## 📦 Installation` in English too — keep the-duplication.--## Byte-identical to English--Code blocks (commands, YAML, comments inside them), shields.io badge URLs and-their alt texts, inline code, image `alt`/`width` attributes, product and tool-names, version numbers, ports, and English UI labels quoted in the text-(`"New Database"` in the Usage steps — the interface is English, so the docs-quote it verbatim).--## Paths--These files sit one directory deeper than the English README:--- images: `../logo.svg`, `../dashboard-dark.svg`, `../dashboard.svg`, `../healthchecks.svg`-- repo files: `../../LICENSE`, `../../deploy/helm/README.md`-- the English README: `../../README.md`--## Website links--Links to `databasus.com` carry the locale prefix and a trailing slash:-`https://databasus.com/<locale>/storages/`, `https://databasus.com/<locale>/faq/#backup-databasus`.-The fragment ids (`#backup-databasus`, `#oss-programs`) are identical in every-locale — never translate them. `https://databasus.com/contribute` has no-translation on the site and stays unprefixed.--## In-page anchors--Unlike the website, anchors here are **not** identical across locales: GitHub-derives them from the heading text, so translated headings produce translated-anchors. Nothing outside these files links into their sections, so each file's-mini-TOC and in-body links simply point at its own slugs. Rule of thumb for the-slug: lowercase, punctuation dropped, emoji dropped but the space around it-becomes a hyphen, remaining spaces become hyphens, Cyrillic and CJK preserved.-`## ✨ Features` gives `#-features`; `## 🛡️ Security & reliability engineering`-gives `#️-security--reliability-engineering` (the variation selector survives).--## Language--Translation content is in the target language; the six language-switcher labels-(`English`, `Русский`, `Español`, `Português`, `中文`, `Français`) appear in the-root `README.md` as well. Everything else in the repo stays English, including-file names, commit messages and this document.--## Translation quality--The rules in [`website/CLAUDE.md`](../../website/CLAUDE.md) under "Translation-quality" apply here in full: edited copy rather than word-for-word, no calques,-no bureaucratese, no marketing filler, per-locale conventions (ru «е» not «ё»;-es usted with «copia de seguridad» as the canonical term; pt-BR; zh 你 with-full-width punctuation and CJK↔Latin spacing; fr vous with a space before %).-The proofread website pages of each locale are the tone reference.+See [`AGENTS.md`](AGENTS.md), and the repository-wide rules in [`../../AGENTS.md`](../../AGENTS.md).diff --git a/backend/AGENTS.md b/backend/AGENTS.mdnew file mode 100644index 00000000..a293b579--- /dev/null+++ b/backend/AGENTS.md@@ -0,0 +1,687 @@+# Backend guidelines (Go + Gin + GORM)++Coding standards for the Databasus backend (Go + Gin + GORM + PostgreSQL).+For project-wide engineering philosophy, naming, and lint/format commands, see the root `AGENTS.md`.++---++## Table of Contents++- [Spacing between logical statements](#spacing-between-logical-statements)+- [Comments](#comments)+- [File organization](#file-organization)+- [Controllers](#controllers)+- [Dependency injection (DI)](#dependency-injection-di)+- [Background services](#background-services)+- [Migrations](#migrations)+- [Testing](#testing)+- [Time handling](#time-handling)+- [Logging](#logging)+- [CRUD examples](#crud-examples)+- [Modern Go](#modern-go)++---++## Spacing between logical statements++Add blank lines between logical blocks so the flow is visible at a glance:++- before the final `return`+- after variable declarations, before they're used+- between error handling and subsequent logic+- between distinct logical operations++Bad:++```go+func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {+ var task models.Task+ result := storage.GetDb().Where("id = ?", id).First(&task)+ if result.Error != nil {+ if errors.Is(result.Error, gorm.ErrRecordNotFound) {+ return nil, errors.New("task not found")+ }+ return nil, result.Error+ }+ return &task, nil+}+```++Good:++```go+func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {+ var task models.Task++ result := storage.GetDb().Where("id = ?", id).First(&task)+ if result.Error != nil {+ if errors.Is(result.Error, gorm.ErrRecordNotFound) {+ return nil, errors.New("task not found")+ }++ return nil, result.Error+ }++ return &task, nil+}+```++---++## Comments++**Comment only in the rare, genuinely non-obvious case.** The default is no comment. A+comment must earn its place by carrying something the code itself cannot — never by+restating, narrating, or labelling what is already visible.++- **Almost never comment.** If you're about to write one, first try a clearer name or a+ smaller function. Self-explanatory code with no comment beats commented code.+- **A comment may only explain *why*** — a business rule, a hidden cross-system constraint,+ a non-obvious algorithm or optimisation, an ADR reference. Never *what* the code does.+- **Don't narrate the obvious.** No "first failing check", no "the detected platform", no+ "re-open the connection", no step-by-step play-by-play. If the reader can see it, delete it.+- **A name that needs a "what" comment is a naming bug** — rename until the comment is+ redundant, then delete it.+- **Swagger comments are mandatory** for every HTTP endpoint.+- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.++Bad (comments restate the code / narrate the obvious):++```go+// Create test project+project := CreateTestProject(projectName, user, router)++// CreateValidLogItems creates valid log items for testing+func CreateValidLogItems(count int, uniqueID string) []logs_receiving.LogItemRequestDTO {++// the first failing check, plus the detected platform+type ConnectionDiagnostics struct {+```++---++## File organization++One responsibility per file. Don't dump a whole package into one file — split+by role so a reader can find a type by its filename. Conventional names within+a feature package:++- `doc.go` — package doc comment, once the package spans more than one file+- `<feature>.go` — the core type and its methods (the orchestrator/executor)+- `dto.go` — request/response and cross-package data + interface seams+- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)+- `enums.go` — typed-constant groups (`type Status string` + its values)+- `constants.go` — package-level constants that aren't an enum+- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)++Only create a file when there is real content for it — an empty `enums.go` or+`constants.go` is noise, not structure. Test files mirror the source split:+`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →+`diskexhaustion_test.go`. The CRUD layout — `controller.go`, `service.go`,+`repository.go`, `model.go`, `dto.go`, `di.go` — is the same principle applied+to a Gin/GORM feature.++---++## Controllers++- One controller per feature, combining all routes for that feature.+- Method names express **what we do** (`GetAvailableTasks`), not the suffix `Handler`.+- All routes use Gin and take `*gin.Context`.+- Every route is documented with Swagger annotations — see [CRUD examples → controller.go](#controllergo) for the canonical annotation format.++```go+type AuditLogController struct {+ auditLogService *AuditLogService+}++func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {+ auditRoutes := router.Group("/audit-logs")++ auditRoutes.GET("/global", c.GetGlobalAuditLogs)+ auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)+}+```++---++## Dependency injection (DI)++For DI files (controllers, services, repositories, use cases — not plain data structs), use **implicit positional field declaration**. Adding a new dependency must force every callsite to update; named-field syntax silently accepts a missing field as zero.++```go+// good — positional, fails to compile if a field is added or reordered+var orderController = &OrderController{+ orderService,+ bot_users.GetBotUserService(),+ bots.GetBotService(),+ users.GetUserService(),+}++// bad — named fields, silently accept new fields with zero values+var orderController = &OrderController{+ orderService: orderService,+ botUserService: bot_users.GetBotUserService(),+ botService: bots.GetBotService(),+ userService: users.GetUserService(),+}+```++Apply this anywhere you see the `var fooController = &FooController{...}` + `GetFooController()` getter shape.++### `SetupDependencies()` pattern++`SetupDependencies()` runs cross-feature wiring (e.g. registering audit-log writers on user services) and **must be idempotent** — tests call it many times. Use `sync.OnceFunc`:++```go+var SetupDependencies = sync.OnceFunc(func() {+ users_services.GetUserService().SetAuditLogWriter(auditLogService)+ users_services.GetSettingsService().SetAuditLogWriter(auditLogService)+})+```++`sync.OnceFunc` (Go 1.21+) is concise and thread-safe — don't reinvent it with `sync.Once` + `atomic.Bool`.++### Never inject another feature's repository++A feature's repositories are its **private implementation detail**. When feature A needs data that lives under feature B, extend B's *service* with a public method and inject **that service** — not B's repository.++The seam must live at the service layer so authorization, logging, and invariants stay auditable in one place, and so schema changes don't ripple across features. A feature injecting its **own** repository is unchanged.++```go+// good — cross-feature data access goes through the owning service+var backupController = &BackupController{+ backupService,+ databases.GetDatabaseService(), // service, not repository+}++// bad — reaches into another feature's private layer+var backupController = &BackupController{+ backupService,+ databases.GetDatabaseRepository(), // bypasses authz / logging / invariants+}+```++---++## Background services++A background service runs an infinite loop in a goroutine. Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**++```go+type BackgroundService struct {+ // ...+ hasRun atomic.Bool+}++func (s *BackgroundService) Run(ctx context.Context) {+ if s.hasRun.Swap(true) {+ panic(fmt.Sprintf("%T.Run() called multiple times", s))+ }++ ticker := time.NewTicker(1 * time.Minute)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ s.doWork()+ }+ }+}+```++`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed. Applies to schedulers, registries, worker nodes, and cleanup services.++---++## Migrations++- PostgreSQL only.+- Primary UUID keys → `gen_random_uuid()`.+- Time columns → `TIMESTAMPTZ` (timestamp with zone), never `TIMESTAMP`.+- Tables, constraints, and indexes go in **separate** declarations (table first, then each constraint / index on its own statement).+- Format SQL: align column types, put each constraint clause on its own line.++```sql+CREATE TABLE marketplace_info (+ bot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ title TEXT NOT NULL,+ description TEXT NOT NULL,+ short_description TEXT NOT NULL,+ tutorial_url TEXT,+ info_order BIGINT NOT NULL DEFAULT 0,+ is_published BOOLEAN NOT NULL DEFAULT FALSE+);++ALTER TABLE marketplace_info_images+ ADD CONSTRAINT fk_marketplace_info_images_bot_id+ FOREIGN KEY (bot_id)+ REFERENCES marketplace_info (bot_id);+```++For migrations stub generation use Makefile and only then fill manually.++---++## Testing++**Always run tests after writing them and verify they pass.**++### Naming++- `Test_WhatWeDo_WhatWeExpect`+- `Test_WhatWeDo_WhichConditions_WhatWeExpect`++Examples: `Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated`, `Test_DeleteApiKey_WhenUserIsProjectMember_ReturnsForbidden`, `Test_GetProjectAuditLogs_WithDifferentUserRoles_EnforcesPermissionsCorrectly`, `Test_ProjectLifecycleE2E_CompletesSuccessfully`.++This convention applies to `t.Run` subtest names too. When a per-version orchestrator runs former+top-level test functions as subtests (see ADR-0013), name each subtest the full former function+name verbatim — `t.Run("Test_CreateReadOnlyUser_UserCanReadButNotWrite", ...)`, not an abbreviation.+Reserve non-`Test_` subtest names for grouping labels only: the engine-version group (`"PostgreSQL 16"`)+and per-case variants (`"CPU=4 directory"`).++### Prefer controller tests over unit tests++- Test through HTTP endpoints whenever possible — that's the contract real callers see.+- Avoid testing repositories or services in isolation; cover them via the API.+- Use unit tests only for complex model logic with no API surface.+- File names: `controller_test.go` or `service_test.go` — never `integration_test.go`.++### `features/tests/` is for backup → restore cycle tests only++The `internal/features/tests/` package is reserved for **end-to-end tests that exercise a full backup → restore cycle** against a real database container (today: `tests/logical/`; physical restore tests land here once the restore path ships). These tests cross multiple feature packages and have no single "owner" file, so they live in this shared package.++**Everything else** — controller tests, service tests, executor / backuper tests, slot-lifecycle tests, helpers — lives next to its source per the source-split rule (`backup_slot.go` → `backup_slot_test.go`, `full.go` → `full_test.go`). Shared per-package test fixtures go in that package's `testing.go`.++### Shared testing utilities++Each feature creates a `testing.go` (or `testing/testing.go`) with router builders, model creation helpers, and request helpers used by other features' tests. Build creation helpers via the API (`POST /...`) — not direct DB inserts — so the helpers double as a sanity check on the create endpoint.++### Refactor tests as you touch them++When editing existing tests, look for: repetitive setup that should become a helper, oversized tests that should be split, inline test data that should reuse a helper, and similar patterns across files that should be consolidated.++### Clean up test data++If the feature has a DELETE endpoint or cleanup method, **use it** in the test (`defer` or `t.Cleanup`). Prefer API cleanup over direct DB delete. Skip cleanup only when the test runs in an auto-rollback transaction, the cleanup endpoint doesn't exist yet, or the test explicitly validates a failure path where cleanup isn't possible.++### Canonical controller test++```go+func Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated(t *testing.T) {+ router := CreateApiKeyTestRouter(GetProjectController(), GetMembershipController())+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ project, _ := projects_testing.CreateTestProjectViaAPI("Test Project", owner, router)++ request := CreateApiKeyRequestDTO{Name: "Test API Key"}+ var response ApiKey+ test_utils.MakePostRequestAndUnmarshal(t, router,+ "/api/v1/projects/api-keys/"+project.ID.String(),+ "Bearer "+owner.Token, request, http.StatusOK, &response)++ assert.Equal(t, "Test API Key", response.Name)+ assert.NotEmpty(t, response.Token)+}+```++The same shape extends to:+- **Permission-failure tests** — assert `http.StatusForbidden` plus the error message body.+- **Cross-tenant isolation tests** — create a second user/project, attempt to access the first via the second's endpoint, assert `http.StatusBadRequest`.+- **E2E lifecycle tests** — chain create → mutate → transfer → verify, all via API.++---++## Time handling++Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.++---++## Logging++We use `log/slog`. Three rules.++### 1. Scope IDs early via `logger.With(...)`++Attach `database_id`, `backup_id`, `verification_id`, etc. as soon as you know them so every downstream line carries them automatically.++```go+func (s *BackupService) CreateBackup(logger *slog.Logger, databaseID uuid.UUID) {+ logger = logger.With("database_id", databaseID)++ logger.Debug("creating backup")+ // every subsequent log automatically carries database_id+}+```++For background services, also scope `task_name` per subtask in `Run()`. Inside loops, scope further with the loop's identifying ID.++### 2. Values in message, IDs and errors as kv pairs++Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.++```go+// good+logger.Info(fmt.Sprintf("subscription renewed: %s -> %s, %d GB", oldStatus, newStatus, sub.StorageGB))+logger.Info("deleted old backup", "backup_id", backup.ID)+logger.Error("failed to save subscription", "error", err)++// bad — ID buried in the message string, error formatted instead of attached+logger.Info(fmt.Sprintf("deleted old backup %s", backup.ID))+logger.Error(fmt.Sprintf("failed to save subscription: %v", err))+```++### 3. Style and level++- All keys `snake_case` (`database_id`, `total_size_mb`) — never camelCase.+- Messages start lowercase, no trailing period.+- **Debug**: routine ops, function entry, query result counts.+- **Info**: significant state changes, completed actions.+- **Warn**: degraded but recoverable.+- **Error**: failures that need attention.++### Required contextual fields++Every log line must carry enough to reconstruct one entity's history:++- **`request_id`** — auto-generated per HTTP request by `middleware.AssignRequestID()`, echoed back as `X-Request-Id`, and carried in the request's `context.Context`. The fan-out handler attaches it to any record logged through a `...Context` method, so on the request path use `logger.InfoContext(ctx, ...)` / `ErrorContext` and pass `ctx.Request.Context()` from the controller into the service. Never set `request_id` by hand.+- **`user_id`, `database_id`, `backup_id`, `verification_id`, etc.** — attach via `logger.With(...)` at the boundary where the entity becomes known so downstream logs inherit it.+- **Background jobs / schedulers** (no HTTP request, no `request_id`): pass these inline on every log call:+ - **`job_id`** — fresh UUID per execution; the correlation ID for one run.+ - **`job_name`** — stable snake_case identifier of which job this is (e.g. `"backup_retention_cleanup"`, `"audit_log_cleanup"`). Define it as a `const` next to the service — never the struct's type name (renames break log queries). Lets you query "all runs of job X" or "all errors from job Y" across history.++```go+const jobName = "backup_retention_cleanup"++func (c *BackupCleaner) Run(ctx context.Context) {+ jobID := uuid.New()+ logger := c.logger.With("job_id", jobID, "job_name", jobName)++ logger.Info("job started")+ // ...+}+```++### What never goes into logs++- **Passwords, tokens, API keys, full `Authorization` / `Cookie` headers** — centralize redaction at the logger config; don't redact ad-hoc at call sites.+- **PII (email, phone)** — mask before logging (`r***@example.com`, `+7***1234`).+- **Full request / response bodies** — log only the fields you actually need, never whole payloads.++---++## CRUD examples++A complete feature has these files. The controller carries the canonical Swagger annotation format — that's the part to memorize.++### controller.go++```go+package audit_logs++type AuditLogController struct {+ auditLogService *AuditLogService+}++func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {+ auditRoutes := router.Group("/audit-logs")++ auditRoutes.GET("/global", c.GetGlobalAuditLogs)+ auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)+}++// GetGlobalAuditLogs+// @Summary Get global audit logs (ADMIN only)+// @Description Retrieve all audit logs across the system+// @Tags audit-logs+// @Accept json+// @Produce json+// @Security BearerAuth+// @Param limit query int false "Limit number of results" default(100)+// @Param offset query int false "Offset for pagination" default(0)+// @Param beforeDate query string false "Filter logs created before this date (RFC3339 format)" format(date-time)+// @Success 200 {object} GetAuditLogsResponse+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Router /audit-logs/global [get]+func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {+ user, isOk := ctx.MustGet("user").(*user_models.User)+ if !isOk {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})+ return+ }++ request := &GetAuditLogsRequest{}+ if err := ctx.ShouldBindQuery(request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})+ return+ }++ response, err := c.auditLogService.GetGlobalAuditLogs(ctx.Request.Context(), user, request)+ if err != nil {+ if err.Error() == "only administrators can view global audit logs" {+ ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})+ return+ }+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})+ return+ }++ ctx.JSON(http.StatusOK, response)+}+```++### di.go++```go+var auditLogRepository = &AuditLogRepository{}+var auditLogService = &AuditLogService{+ auditLogRepository,+ logger.GetLogger(),+ logger.GetAuditLogger(),+}+var auditLogController = &AuditLogController{auditLogService}++func GetAuditLogService() *AuditLogService { return auditLogService }+func GetAuditLogController() *AuditLogController { return auditLogController }++var SetupDependencies = sync.OnceFunc(func() {+ users_services.GetUserService().SetAuditLogWriter(auditLogService)+ users_services.GetSettingsService().SetAuditLogWriter(auditLogService)+})+```++### dto.go++```go+type GetAuditLogsRequest struct {+ Limit int `form:"limit" json:"limit"`+ Offset int `form:"offset" json:"offset"`+ BeforeDate *time.Time `form:"beforeDate" json:"beforeDate"`+}++type GetAuditLogsResponse struct {+ AuditLogs []*AuditLog `json:"auditLogs"`+ Total int64 `json:"total"`+ Limit int `json:"limit"`+ Offset int `json:"offset"`+}+```++### model.go++```go+type AuditLog struct {+ ID uuid.UUID `json:"id" gorm:"column:id"`+ UserID *uuid.UUID `json:"userId" gorm:"column:user_id"`+ ProjectID *uuid.UUID `json:"projectId" gorm:"column:project_id"`+ Message string `json:"message" gorm:"column:message"`+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+}++func (AuditLog) TableName() string { return "audit_logs" }+```++### repository.go++```go+type AuditLogRepository struct{}++func (r *AuditLogRepository) Create(auditLog *AuditLog) error {+ if auditLog.ID == uuid.Nil {+ auditLog.ID = uuid.New()+ }++ return storage.GetDb().Create(auditLog).Error+}++func (r *AuditLogRepository) GetGlobal(+ ctx context.Context,+ limit, offset int,+ beforeDate *time.Time,+) ([]*AuditLog, error) {+ var auditLogs []*AuditLog++ query := storage.GetDb().WithContext(ctx).Order("created_at DESC")+ if beforeDate != nil {+ query = query.Where("created_at < ?", *beforeDate)+ }++ err := query.Limit(limit).Offset(offset).Find(&auditLogs).Error++ return auditLogs, err+}+```++### service.go++```go+type AuditLogService struct {+ auditLogRepository *AuditLogRepository+ logger *slog.Logger+ auditLogger *slog.Logger+}++func (s *AuditLogService) WriteAuditLog(ctx context.Context, entry audit_logs_models.AuditEntry) {+ auditLog := &AuditLog{+ UserID: entry.UserID,+ ProjectID: entry.ProjectID,+ Message: entry.Message,+ CreatedAt: time.Now().UTC(),+ }++ s.auditLogger.InfoContext(ctx, entry.Message, "user_id", entry.UserID, "project_id", entry.ProjectID)++ if err := s.auditLogRepository.Create(auditLog); err != nil {+ s.logger.ErrorContext(ctx, "failed to create audit log", "error", err)+ }+}++func (s *AuditLogService) GetGlobalAuditLogs(+ ctx context.Context,+ user *user_models.User,+ request *GetAuditLogsRequest,+) (*GetAuditLogsResponse, error) {+ if user.Role != user_enums.UserRoleAdmin {+ return nil, errors.New("only administrators can view global audit logs")+ }++ limit := request.Limit+ if limit <= 0 || limit > 1000 {+ limit = 100+ }++ offset := max(request.Offset, 0)++ auditLogs, err := s.auditLogRepository.GetGlobal(ctx, limit, offset, request.BeforeDate)+ if err != nil {+ return nil, err+ }++ total, err := s.auditLogRepository.CountGlobal(ctx, request.BeforeDate)+ if err != nil {+ return nil, err+ }++ return &GetAuditLogsResponse{+ AuditLogs: auditLogs,+ Total: total,+ Limit: limit,+ Offset: offset,+ }, nil+}+```++For `controller_test.go`, see [Testing → Canonical controller test](#canonical-controller-test) above.++---++## Modern Go++Prefer modern stdlib idioms over manual equivalents.++### `slices` package — avoid manual loops++```go+slices.Contains(items, x)+slices.Index(items, x) // returns index or -1+slices.IndexFunc(items, func(item T) bool { return item.ID == id })+slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })+slices.Sort(items) // ordered types+slices.Max(items) / slices.Min(items)+slices.Reverse(items) // in-place+slices.Compact(items) // remove consecutive duplicates+slices.Clone(s) // shallow copy+slices.Clip(s) // trim unused capacity+```++### Quick wins++- `any` instead of `interface{}`.+- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.+- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.+- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.+- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.++### `context` helpers++```go+stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation+ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause+ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause+```++### `omitzero` instead of `omitempty` for non-nullable types++`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:++```go+// good+type Config struct {+ Timeout time.Duration `json:"timeout,omitzero"`+ CreatedAt time.Time `json:"createdAt,omitzero"`+}++// bad+type Config struct {+ Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!+ CreatedAt time.Time `json:"createdAt,omitempty"`+}+```++### `new(val)` for pointer literals (Go 1.26+)++`new()` accepts expressions, eliminating the temp-variable pattern:++```go+// good+cfg := Config{Timeout: new(30), Debug: new(true)}++// bad+timeout := 30+debug := true+cfg := Config{Timeout: &timeout, Debug: &debug}+```diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex e2433303..e8602361 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1,687 +1,3 @@-# Backend guidelines (Go + Gin + GORM)+# Backend-Coding standards for the Databasus backend (Go + Gin + GORM + PostgreSQL).-For project-wide engineering philosophy, naming, and lint/format commands, see the root `CLAUDE.md`.-------## Table of Contents--- [Spacing between logical statements](#spacing-between-logical-statements)-- [Comments](#comments)-- [File organization](#file-organization)-- [Controllers](#controllers)-- [Dependency injection (DI)](#dependency-injection-di)-- [Background services](#background-services)-- [Migrations](#migrations)-- [Testing](#testing)-- [Time handling](#time-handling)-- [Logging](#logging)-- [CRUD examples](#crud-examples)-- [Modern Go](#modern-go)-------## Spacing between logical statements--Add blank lines between logical blocks so the flow is visible at a glance:--- before the final `return`-- after variable declarations, before they're used-- between error handling and subsequent logic-- between distinct logical operations--Bad:--```go-func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {- var task models.Task- result := storage.GetDb().Where("id = ?", id).First(&task)- if result.Error != nil {- if errors.Is(result.Error, gorm.ErrRecordNotFound) {- return nil, errors.New("task not found")- }- return nil, result.Error- }- return &task, nil-}-```--Good:--```go-func (r *Repository) FindById(id uuid.UUID) (*models.Task, error) {- var task models.Task-- result := storage.GetDb().Where("id = ?", id).First(&task)- if result.Error != nil {- if errors.Is(result.Error, gorm.ErrRecordNotFound) {- return nil, errors.New("task not found")- }-- return nil, result.Error- }-- return &task, nil-}-```-------## Comments--**Comment only in the rare, genuinely non-obvious case.** The default is no comment. A-comment must earn its place by carrying something the code itself cannot — never by-restating, narrating, or labelling what is already visible.--- **Almost never comment.** If you're about to write one, first try a clearer name or a- smaller function. Self-explanatory code with no comment beats commented code.-- **A comment may only explain *why*** — a business rule, a hidden cross-system constraint,- a non-obvious algorithm or optimisation, an ADR reference. Never *what* the code does.-- **Don't narrate the obvious.** No "first failing check", no "the detected platform", no- "re-open the connection", no step-by-step play-by-play. If the reader can see it, delete it.-- **A name that needs a "what" comment is a naming bug** — rename until the comment is- redundant, then delete it.-- **Swagger comments are mandatory** for every HTTP endpoint.-- **No "Summary" / "Conclusion" sections in `.md` files** unless explicitly requested.--Bad (comments restate the code / narrate the obvious):--```go-// Create test project-project := CreateTestProject(projectName, user, router)--// CreateValidLogItems creates valid log items for testing-func CreateValidLogItems(count int, uniqueID string) []logs_receiving.LogItemRequestDTO {--// the first failing check, plus the detected platform-type ConnectionDiagnostics struct {-```-------## File organization--One responsibility per file. Don't dump a whole package into one file — split-by role so a reader can find a type by its filename. Conventional names within-a feature package:--- `doc.go` — package doc comment, once the package spans more than one file-- `<feature>.go` — the core type and its methods (the orchestrator/executor)-- `dto.go` — request/response and cross-package data + interface seams-- `errors.go` — sentinel errors (`var Err... = errors.New(...)`)-- `enums.go` — typed-constant groups (`type Status string` + its values)-- `constants.go` — package-level constants that aren't an enum-- background loops, reapers, and pools get their own file (`reaper.go`, `pool.go`)--Only create a file when there is real content for it — an empty `enums.go` or-`constants.go` is noise, not structure. Test files mirror the source split:-`restorer.go` → `restorer_test.go`, `diskexhaustion.go` →-`diskexhaustion_test.go`. The CRUD layout — `controller.go`, `service.go`,-`repository.go`, `model.go`, `dto.go`, `di.go` — is the same principle applied-to a Gin/GORM feature.-------## Controllers--- One controller per feature, combining all routes for that feature.-- Method names express **what we do** (`GetAvailableTasks`), not the suffix `Handler`.-- All routes use Gin and take `*gin.Context`.-- Every route is documented with Swagger annotations — see [CRUD examples → controller.go](#controllergo) for the canonical annotation format.--```go-type AuditLogController struct {- auditLogService *AuditLogService-}--func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {- auditRoutes := router.Group("/audit-logs")-- auditRoutes.GET("/global", c.GetGlobalAuditLogs)- auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)-}-```-------## Dependency injection (DI)--For DI files (controllers, services, repositories, use cases — not plain data structs), use **implicit positional field declaration**. Adding a new dependency must force every callsite to update; named-field syntax silently accepts a missing field as zero.--```go-// good — positional, fails to compile if a field is added or reordered-var orderController = &OrderController{- orderService,- bot_users.GetBotUserService(),- bots.GetBotService(),- users.GetUserService(),-}--// bad — named fields, silently accept new fields with zero values-var orderController = &OrderController{- orderService: orderService,- botUserService: bot_users.GetBotUserService(),- botService: bots.GetBotService(),- userService: users.GetUserService(),-}-```--Apply this anywhere you see the `var fooController = &FooController{...}` + `GetFooController()` getter shape.--### `SetupDependencies()` pattern--`SetupDependencies()` runs cross-feature wiring (e.g. registering audit-log writers on user services) and **must be idempotent** — tests call it many times. Use `sync.OnceFunc`:--```go-var SetupDependencies = sync.OnceFunc(func() {- users_services.GetUserService().SetAuditLogWriter(auditLogService)- users_services.GetSettingsService().SetAuditLogWriter(auditLogService)-})-```--`sync.OnceFunc` (Go 1.21+) is concise and thread-safe — don't reinvent it with `sync.Once` + `atomic.Bool`.--### Never inject another feature's repository--A feature's repositories are its **private implementation detail**. When feature A needs data that lives under feature B, extend B's *service* with a public method and inject **that service** — not B's repository.--The seam must live at the service layer so authorization, logging, and invariants stay auditable in one place, and so schema changes don't ripple across features. A feature injecting its **own** repository is unchanged.--```go-// good — cross-feature data access goes through the owning service-var backupController = &BackupController{- backupService,- databases.GetDatabaseService(), // service, not repository-}--// bad — reaches into another feature's private layer-var backupController = &BackupController{- backupService,- databases.GetDatabaseRepository(), // bypasses authz / logging / invariants-}-```-------## Background services--A background service runs an infinite loop in a goroutine. Calling `Run()` twice on the same instance is always a bug — duplicate goroutines leak resources and corrupt state. **Always panic; never just log a warning.**--```go-type BackgroundService struct {- // ...- hasRun atomic.Bool-}--func (s *BackgroundService) Run(ctx context.Context) {- if s.hasRun.Swap(true) {- panic(fmt.Sprintf("%T.Run() called multiple times", s))- }-- ticker := time.NewTicker(1 * time.Minute)- defer ticker.Stop()-- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- s.doWork()- }- }-}-```--`atomic.Bool.Swap(true)` does the check-and-set atomically — no `sync.Once` needed. Applies to schedulers, registries, worker nodes, and cleanup services.-------## Migrations--- PostgreSQL only.-- Primary UUID keys → `gen_random_uuid()`.-- Time columns → `TIMESTAMPTZ` (timestamp with zone), never `TIMESTAMP`.-- Tables, constraints, and indexes go in **separate** declarations (table first, then each constraint / index on its own statement).-- Format SQL: align column types, put each constraint clause on its own line.--```sql-CREATE TABLE marketplace_info (- bot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- title TEXT NOT NULL,- description TEXT NOT NULL,- short_description TEXT NOT NULL,- tutorial_url TEXT,- info_order BIGINT NOT NULL DEFAULT 0,- is_published BOOLEAN NOT NULL DEFAULT FALSE-);--ALTER TABLE marketplace_info_images- ADD CONSTRAINT fk_marketplace_info_images_bot_id- FOREIGN KEY (bot_id)- REFERENCES marketplace_info (bot_id);-```--For migrations stub generation use Makefile and only then fill manually.-------## Testing--**Always run tests after writing them and verify they pass.**--### Naming--- `Test_WhatWeDo_WhatWeExpect`-- `Test_WhatWeDo_WhichConditions_WhatWeExpect`--Examples: `Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated`, `Test_DeleteApiKey_WhenUserIsProjectMember_ReturnsForbidden`, `Test_GetProjectAuditLogs_WithDifferentUserRoles_EnforcesPermissionsCorrectly`, `Test_ProjectLifecycleE2E_CompletesSuccessfully`.--This convention applies to `t.Run` subtest names too. When a per-version orchestrator runs former-top-level test functions as subtests (see ADR-0013), name each subtest the full former function-name verbatim — `t.Run("Test_CreateReadOnlyUser_UserCanReadButNotWrite", ...)`, not an abbreviation.-Reserve non-`Test_` subtest names for grouping labels only: the engine-version group (`"PostgreSQL 16"`)-and per-case variants (`"CPU=4 directory"`).--### Prefer controller tests over unit tests--- Test through HTTP endpoints whenever possible — that's the contract real callers see.-- Avoid testing repositories or services in isolation; cover them via the API.-- Use unit tests only for complex model logic with no API surface.-- File names: `controller_test.go` or `service_test.go` — never `integration_test.go`.--### `features/tests/` is for backup → restore cycle tests only--The `internal/features/tests/` package is reserved for **end-to-end tests that exercise a full backup → restore cycle** against a real database container (today: `tests/logical/`; physical restore tests land here once the restore path ships). These tests cross multiple feature packages and have no single "owner" file, so they live in this shared package.--**Everything else** — controller tests, service tests, executor / backuper tests, slot-lifecycle tests, helpers — lives next to its source per the source-split rule (`backup_slot.go` → `backup_slot_test.go`, `full.go` → `full_test.go`). Shared per-package test fixtures go in that package's `testing.go`.--### Shared testing utilities--Each feature creates a `testing.go` (or `testing/testing.go`) with router builders, model creation helpers, and request helpers used by other features' tests. Build creation helpers via the API (`POST /...`) — not direct DB inserts — so the helpers double as a sanity check on the create endpoint.--### Refactor tests as you touch them--When editing existing tests, look for: repetitive setup that should become a helper, oversized tests that should be split, inline test data that should reuse a helper, and similar patterns across files that should be consolidated.--### Clean up test data--If the feature has a DELETE endpoint or cleanup method, **use it** in the test (`defer` or `t.Cleanup`). Prefer API cleanup over direct DB delete. Skip cleanup only when the test runs in an auto-rollback transaction, the cleanup endpoint doesn't exist yet, or the test explicitly validates a failure path where cleanup isn't possible.--### Canonical controller test--```go-func Test_CreateApiKey_WhenUserIsProjectOwner_ApiKeyCreated(t *testing.T) {- router := CreateApiKeyTestRouter(GetProjectController(), GetMembershipController())- owner := users_testing.CreateTestUser(users_enums.UserRoleMember)- project, _ := projects_testing.CreateTestProjectViaAPI("Test Project", owner, router)-- request := CreateApiKeyRequestDTO{Name: "Test API Key"}- var response ApiKey- test_utils.MakePostRequestAndUnmarshal(t, router,- "/api/v1/projects/api-keys/"+project.ID.String(),- "Bearer "+owner.Token, request, http.StatusOK, &response)-- assert.Equal(t, "Test API Key", response.Name)- assert.NotEmpty(t, response.Token)-}-```--The same shape extends to:-- **Permission-failure tests** — assert `http.StatusForbidden` plus the error message body.-- **Cross-tenant isolation tests** — create a second user/project, attempt to access the first via the second's endpoint, assert `http.StatusBadRequest`.-- **E2E lifecycle tests** — chain create → mutate → transfer → verify, all via API.-------## Time handling--Always use `time.Now().UTC()` instead of `time.Now()` to keep timezones consistent across the application.-------## Logging--We use `log/slog`. Three rules.--### 1. Scope IDs early via `logger.With(...)`--Attach `database_id`, `backup_id`, `verification_id`, etc. as soon as you know them so every downstream line carries them automatically.--```go-func (s *BackupService) CreateBackup(logger *slog.Logger, databaseID uuid.UUID) {- logger = logger.With("database_id", databaseID)-- logger.Debug("creating backup")- // every subsequent log automatically carries database_id-}-```--For background services, also scope `task_name` per subtask in `Run()`. Inside loops, scope further with the loop's identifying ID.--### 2. Values in message, IDs and errors as kv pairs--Sizes, counts, and status transitions go into the message via `fmt.Sprintf`. IDs and errors stay as structured kv pairs so they're searchable in log aggregation tools.--```go-// good-logger.Info(fmt.Sprintf("subscription renewed: %s -> %s, %d GB", oldStatus, newStatus, sub.StorageGB))-logger.Info("deleted old backup", "backup_id", backup.ID)-logger.Error("failed to save subscription", "error", err)--// bad — ID buried in the message string, error formatted instead of attached-logger.Info(fmt.Sprintf("deleted old backup %s", backup.ID))-logger.Error(fmt.Sprintf("failed to save subscription: %v", err))-```--### 3. Style and level--- All keys `snake_case` (`database_id`, `total_size_mb`) — never camelCase.-- Messages start lowercase, no trailing period.-- **Debug**: routine ops, function entry, query result counts.-- **Info**: significant state changes, completed actions.-- **Warn**: degraded but recoverable.-- **Error**: failures that need attention.--### Required contextual fields--Every log line must carry enough to reconstruct one entity's history:--- **`request_id`** — auto-generated per HTTP request by `middleware.AssignRequestID()`, echoed back as `X-Request-Id`, and carried in the request's `context.Context`. The fan-out handler attaches it to any record logged through a `...Context` method, so on the request path use `logger.InfoContext(ctx, ...)` / `ErrorContext` and pass `ctx.Request.Context()` from the controller into the service. Never set `request_id` by hand.-- **`user_id`, `database_id`, `backup_id`, `verification_id`, etc.** — attach via `logger.With(...)` at the boundary where the entity becomes known so downstream logs inherit it.-- **Background jobs / schedulers** (no HTTP request, no `request_id`): pass these inline on every log call:- - **`job_id`** — fresh UUID per execution; the correlation ID for one run.- - **`job_name`** — stable snake_case identifier of which job this is (e.g. `"backup_retention_cleanup"`, `"audit_log_cleanup"`). Define it as a `const` next to the service — never the struct's type name (renames break log queries). Lets you query "all runs of job X" or "all errors from job Y" across history.--```go-const jobName = "backup_retention_cleanup"--func (c *BackupCleaner) Run(ctx context.Context) {- jobID := uuid.New()- logger := c.logger.With("job_id", jobID, "job_name", jobName)-- logger.Info("job started")- // ...-}-```--### What never goes into logs--- **Passwords, tokens, API keys, full `Authorization` / `Cookie` headers** — centralize redaction at the logger config; don't redact ad-hoc at call sites.-- **PII (email, phone)** — mask before logging (`r***@example.com`, `+7***1234`).-- **Full request / response bodies** — log only the fields you actually need, never whole payloads.-------## CRUD examples--A complete feature has these files. The controller carries the canonical Swagger annotation format — that's the part to memorize.--### controller.go--```go-package audit_logs--type AuditLogController struct {- auditLogService *AuditLogService-}--func (c *AuditLogController) RegisterRoutes(router *gin.RouterGroup) {- auditRoutes := router.Group("/audit-logs")-- auditRoutes.GET("/global", c.GetGlobalAuditLogs)- auditRoutes.GET("/users/:userId", c.GetUserAuditLogs)-}--// GetGlobalAuditLogs-// @Summary Get global audit logs (ADMIN only)-// @Description Retrieve all audit logs across the system-// @Tags audit-logs-// @Accept json-// @Produce json-// @Security BearerAuth-// @Param limit query int false "Limit number of results" default(100)-// @Param offset query int false "Offset for pagination" default(0)-// @Param beforeDate query string false "Filter logs created before this date (RFC3339 format)" format(date-time)-// @Success 200 {object} GetAuditLogsResponse-// @Failure 401 {object} map[string]string-// @Failure 403 {object} map[string]string-// @Router /audit-logs/global [get]-func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {- user, isOk := ctx.MustGet("user").(*user_models.User)- if !isOk {- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user type in context"})- return- }-- request := &GetAuditLogsRequest{}- if err := ctx.ShouldBindQuery(request); err != nil {- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})- return- }-- response, err := c.auditLogService.GetGlobalAuditLogs(ctx.Request.Context(), user, request)- if err != nil {- if err.Error() == "only administrators can view global audit logs" {- ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})- return- }- ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve audit logs"})- return- }-- ctx.JSON(http.StatusOK, response)-}-```--### di.go--```go-var auditLogRepository = &AuditLogRepository{}-var auditLogService = &AuditLogService{- auditLogRepository,- logger.GetLogger(),- logger.GetAuditLogger(),-}-var auditLogController = &AuditLogController{auditLogService}--func GetAuditLogService() *AuditLogService { return auditLogService }-func GetAuditLogController() *AuditLogController { return auditLogController }--var SetupDependencies = sync.OnceFunc(func() {- users_services.GetUserService().SetAuditLogWriter(auditLogService)- users_services.GetSettingsService().SetAuditLogWriter(auditLogService)-})-```--### dto.go--```go-type GetAuditLogsRequest struct {- Limit int `form:"limit" json:"limit"`- Offset int `form:"offset" json:"offset"`- BeforeDate *time.Time `form:"beforeDate" json:"beforeDate"`-}--type GetAuditLogsResponse struct {- AuditLogs []*AuditLog `json:"auditLogs"`- Total int64 `json:"total"`- Limit int `json:"limit"`- Offset int `json:"offset"`-}-```--### model.go--```go-type AuditLog struct {- ID uuid.UUID `json:"id" gorm:"column:id"`- UserID *uuid.UUID `json:"userId" gorm:"column:user_id"`- ProjectID *uuid.UUID `json:"projectId" gorm:"column:project_id"`- Message string `json:"message" gorm:"column:message"`- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`-}--func (AuditLog) TableName() string { return "audit_logs" }-```--### repository.go--```go-type AuditLogRepository struct{}--func (r *AuditLogRepository) Create(auditLog *AuditLog) error {- if auditLog.ID == uuid.Nil {- auditLog.ID = uuid.New()- }-- return storage.GetDb().Create(auditLog).Error-}--func (r *AuditLogRepository) GetGlobal(- ctx context.Context,- limit, offset int,- beforeDate *time.Time,-) ([]*AuditLog, error) {- var auditLogs []*AuditLog-- query := storage.GetDb().WithContext(ctx).Order("created_at DESC")- if beforeDate != nil {- query = query.Where("created_at < ?", *beforeDate)- }-- err := query.Limit(limit).Offset(offset).Find(&auditLogs).Error-- return auditLogs, err-}-```--### service.go--```go-type AuditLogService struct {- auditLogRepository *AuditLogRepository- logger *slog.Logger- auditLogger *slog.Logger-}--func (s *AuditLogService) WriteAuditLog(ctx context.Context, entry audit_logs_models.AuditEntry) {- auditLog := &AuditLog{- UserID: entry.UserID,- ProjectID: entry.ProjectID,- Message: entry.Message,- CreatedAt: time.Now().UTC(),- }-- s.auditLogger.InfoContext(ctx, entry.Message, "user_id", entry.UserID, "project_id", entry.ProjectID)-- if err := s.auditLogRepository.Create(auditLog); err != nil {- s.logger.ErrorContext(ctx, "failed to create audit log", "error", err)- }-}--func (s *AuditLogService) GetGlobalAuditLogs(- ctx context.Context,- user *user_models.User,- request *GetAuditLogsRequest,-) (*GetAuditLogsResponse, error) {- if user.Role != user_enums.UserRoleAdmin {- return nil, errors.New("only administrators can view global audit logs")- }-- limit := request.Limit- if limit <= 0 || limit > 1000 {- limit = 100- }-- offset := max(request.Offset, 0)-- auditLogs, err := s.auditLogRepository.GetGlobal(ctx, limit, offset, request.BeforeDate)- if err != nil {- return nil, err- }-- total, err := s.auditLogRepository.CountGlobal(ctx, request.BeforeDate)- if err != nil {- return nil, err- }-- return &GetAuditLogsResponse{- AuditLogs: auditLogs,- Total: total,- Limit: limit,- Offset: offset,- }, nil-}-```--For `controller_test.go`, see [Testing → Canonical controller test](#canonical-controller-test) above.-------## Modern Go--Prefer modern stdlib idioms over manual equivalents.--### `slices` package — avoid manual loops--```go-slices.Contains(items, x)-slices.Index(items, x) // returns index or -1-slices.IndexFunc(items, func(item T) bool { return item.ID == id })-slices.SortFunc(items, func(a, b T) int { return cmp.Compare(a.X, b.X) })-slices.Sort(items) // ordered types-slices.Max(items) / slices.Min(items)-slices.Reverse(items) // in-place-slices.Compact(items) // remove consecutive duplicates-slices.Clone(s) // shallow copy-slices.Clip(s) // trim unused capacity-```--### Quick wins--- `any` instead of `interface{}`.-- `for i := range len(items)` instead of `for i := 0; i < len(items); i++`.-- `sync.OnceFunc(fn)` / `sync.OnceValue(fn)` instead of `sync.Once` + wrapper.-- `t.Context()` in tests instead of `context.WithCancel(context.Background())` + `defer cancel()` — auto-cancels at test end.-- `wg.Go(fn)` instead of `wg.Add(1)` + `go func() { defer wg.Done(); fn() }()`.--### `context` helpers--```go-stop := context.AfterFunc(ctx, cleanup) // run cleanup on cancellation-ctx, cancel := context.WithTimeoutCause(parent, d, ErrTimeout) // timeout with cause-ctx, cancel := context.WithDeadlineCause(parent, deadline, ErrDeadline) // deadline with cause-```--### `omitzero` instead of `omitempty` for non-nullable types--`omitempty` is broken for `time.Duration`, `time.Time`, structs, slices, and maps — it doesn't omit a zero value. Use `omitzero`:--```go-// good-type Config struct {- Timeout time.Duration `json:"timeout,omitzero"`- CreatedAt time.Time `json:"createdAt,omitzero"`-}--// bad-type Config struct {- Timeout time.Duration `json:"timeout,omitempty"` // broken for Duration!- CreatedAt time.Time `json:"createdAt,omitempty"`-}-```--### `new(val)` for pointer literals (Go 1.26+)--`new()` accepts expressions, eliminating the temp-variable pattern:--```go-// good-cfg := Config{Timeout: new(30), Debug: new(true)}--// bad-timeout := 30-debug := true-cfg := Config{Timeout: &timeout, Debug: &debug}-```+See [`AGENTS.md`](AGENTS.md), and the repository-wide rules in [`../AGENTS.md`](../AGENTS.md).diff --git a/frontend/AGENTS.md b/frontend/AGENTS.mdnew file mode 100644index 00000000..48bc2cd2--- /dev/null+++ b/frontend/AGENTS.md@@ -0,0 +1,217 @@+# Frontend guidelines (React + TypeScript)++This document contains coding standards for the Databasus frontend (React 19 + TypeScript + Vite + Ant Design + TailwindCSS).+For project-wide engineering philosophy, see the root `AGENTS.md`.++---++## Table of Contents++- [UI kit and icons](#ui-kit-and-icons)+- [React component structure](#react-component-structure)+- [Vertical spacing](#vertical-spacing)+- [Clipboard operations](#clipboard-operations)+- [Forms](#forms)+- [User-facing copy](#user-facing-copy)+- [FSD (Feature-Sliced Design)](#fsd-feature-sliced-design)+- [Refactoring](#refactoring)++---++## UI kit and icons++- **AntD 5 only** for components. Don't pull in Mantine, MUI, Chakra, shadcn, or Radix directly. Use AntD primitives (`Button`, `Input`, `Modal`, `Form`, `Table`, `Menu`, `Tabs`, etc.) plus Tailwind utility classes for layout and spacing.+- **`@ant-design/icons` only** for icons. Don't add `lucide-react`, `@heroicons/react`, `react-icons`, or FontAwesome.++---++## React component structure++Write React components with the following structure:++```typescript+interface Props {+ someValue: SomeValue;+}++const someHelperFunction = () => {+ ...+}++export const ReactComponent = ({ someValue }: Props): JSX.Element => {+ // First put states+ const [someState, setSomeState] = useState<...>(...)++ // Then place functions+ const loadSomeData = async () => {+ ...+ }++ // Then hooks+ useEffect(() => {+ loadSomeData();+ });++ // Then calculated values+ const calculatedValue = someValue.calculate();++ return <div> ... </div>+}+```++### Structure order++1. **Props interface** — Define component props+2. **Helper functions** (outside component) — Pure utility functions+3. **Component declaration**+ - **States** — `useState` declarations+ - **Plain functions** — Event handlers, async operations, in-component formatters. Anything that does _not_ call a React hook.+ - **Hooks** — `useRef` + ref mutation, `useCallback`, `useMemo`, `useEffect`. A function wrapped in `useCallback` is a hook — it lives here, not in the functions section.+ - **Calculated values** — Derived data computed inline (e.g. an AntD `columns` array).+ - **Return** — JSX markup++**All hooks (including every `useEffect`) come below every plain function definition.** If a `useEffect` reads a handler, the handler must be defined above it — don't reorder by putting handlers below the effects.++---++## Vertical spacing++- Structure function bodies with vertical rhythm. Put a blank line between logically distinct steps (setup / main work / return, independent branches, before and after a guard). Do not leave blank lines at the start or end of a body, never stack two in a row. Do not insert blanks inside a tight expression, a single statement split across lines, or a short (≤ 5-line) function. If blank lines alone aren't enough to navigate a body, extract — don't add comments.++---++## Clipboard operations++Always use `ClipboardHelper` (`shared/lib/ClipboardHelper.ts`) for clipboard operations — never call `navigator.clipboard` directly.++- **Copy:** `ClipboardHelper.copyToClipboard(text)` — uses `navigator.clipboard` with `execCommand('copy')` fallback for non-secure contexts (HTTP).+- **Paste:** Check `ClipboardHelper.isClipboardApiAvailable()` first. If available, use `ClipboardHelper.readFromClipboard()`. If not, show `ClipboardPasteModalComponent` (`shared/ui`) which lets the user paste manually via a text input modal.++---++## Forms++### Progressive disclosure++- Submit buttons (`Save`, `Update password`, etc.) render **only when the form is dirty**.+- Dependent fields (e.g. `Confirm password`) render **only after the field they depend on has a value**.++---++## User-facing copy++Use a plain hyphen `-` in any string the user will see — labels, descriptions, notifications, modal bodies, error messages. Reserve em dashes (`—`) and en dashes (`–`) for markdown docs and code comments only.++---++## FSD (Feature-Sliced Design)++The project follows FSD v2.1. Layers in use: `app/`, `pages/`, `widgets/`, `features/`, `entity/`, `shared/`.++### Import direction++`app → pages → widgets → features → entity → shared`++A module may only import from layers strictly **below** it. Cross-imports between slices on the **same** layer are forbidden.++Paths below are written from `src/` for readability. Real imports are relative; the project has no path alias.++```text+✅ Allowed+ a widget imports features/backups, entity/backups, shared/ui+ a feature imports entity/databases, shared/api+ an entity imports shared/lib++❌ Violations+ an entity imports features/databases (upward: entity sits below features)+ a feature imports pages/AuthPageComponent (upward: pages sits above features)+ features/users imports features/backups (same layer: cross-slice import)+ shared/lib imports entity/users (upward: shared is the bottom layer)+```++### Where new code goes++- Used in only one page → keep it in that `pages/` slice.+- Reusable infrastructure, **no business logic** → `shared/` (UI kit, utils, API client, route constants, auth tokens, CRUD helpers).+- User interaction reused in 2+ pages → `features/`.+- Domain model reused in 2+ pages/features → `entity/`.+- App-wide providers, router, theme → `app/`.++**When in doubt — keep it in `pages/`.** Extract only when a second real consumer appears.++### Quick placement table++| Scenario | Single use | Reused in 2+ places |+| ------------------------ | ------------------------------------- | ------------------------------------- |+| Profile form | `pages/profile/ui/ProfileForm.tsx` | `features/profile-form/` |+| Database card | `pages/databases/ui/DatabaseCard.tsx` | `entity/database/ui/DatabaseCard.tsx` |+| Data fetching for backup | `pages/backup/api/fetch-backup.ts` | `entity/backup/api/` |+| Auth token / session | `shared/auth/` (always) | `shared/auth/` (always) |+| Login form | `pages/login/ui/LoginForm.tsx` | `features/auth/` |+| CRUD helpers | `shared/api/` (always) | `shared/api/` (always) |+| Date formatting util | — | `shared/lib/format-date.ts` |+| Modal content | `pages/[page]/ui/SomeModal.tsx` | — |++### MUST rules++1. **Downward-only imports.** No upward imports, no same-layer cross-imports.+2. **Public API via `index.ts`.** External consumers import only from a slice's `index.ts`, never its internal files.+ ```text+ ✅ features/users+ ❌ features/users/ui/AuthNavbarComponent+ ```+3. **Domain-based file names.** Name files by the domain they represent, not their technical role.+ ```text+ // ❌ model/types.ts, model/utils.ts, lib/helpers.ts+ // ✅ model/user.ts, model/backup.ts, api/fetch-database.ts+ ```+4. **No business logic in `shared/`.** Shared holds only infrastructure. Domain calculations live in `entity/` or higher.+5. **One type per file in `model/` / DTOs.** Each `interface`, `class`, or `enum` that represents a domain entity, DTO, request body, or response shape gets its own file in `model/` (or `models/`), named after the type. Don't co-locate sibling types like `Foo` + `FooStatus` + `FooResponse` in a single `Foo.ts` — split them. Re-export each from the slice `index.ts` so consumers still import from the slice's public API.+ ```text+ // ❌ model/RestoreVerification.ts — enums + table-stat + main interface all in one file+ // ✅ model/RestoreVerification.ts — interface RestoreVerification+ // ✅ model/RestoreVerificationTableStat.ts — interface RestoreVerificationTableStat+ // ✅ model/VerificationStatus.ts — enum VerificationStatus+ // ✅ model/VerificationTrigger.ts — enum VerificationTrigger+ ```+ Tiny shape-only helper types tightly coupled to a parent type (a literal-union alias, a `Pick<>`) may stay in the parent's file. Splitting applies to anything with its own identity — anything you'd reasonably import on its own elsewhere.++### Segments inside a slice++- `ui/` — components, styles+- `model/` — state, types, domain logic, validation+- `api/` — backend calls, request functions, API-specific types+- `lib/` — internal helpers for this slice only+- `config/` — slice-level config / feature flags++`app/` and `shared/` have **segments only, no slices**. Segments within them may import from each other.++### AVOID++- Creating an entity prematurely (single consumer → keep it in the page).+- Putting CRUD inside `entity/` — CRUD is infrastructure, goes to `shared/api/`.+- Creating a `user` entity just for auth tokens/DTOs — those belong in `shared/auth/` or `shared/api/`.+- Extracting single-use code "for future reuse."+- God slices (`user-management/` covering auth + profile + password) — split by focused responsibility.+- Importing UI segments of one entity from another entity. Entity UI may be imported only from features/widgets/pages.+- Abusing the `@x` cross-import pattern — it is a last resort, not a tool.++### Cross-imports between same-layer slices++When two slices on the same layer need to share code, try **in order**:++1. **Merge** — if they always change together, they are one slice.+2. **Extract shared logic down to `entity/`** — keep UI in the features/widgets.+3. **Compose in a higher layer (IoC)** — the parent page/widget imports both and wires them together via props/slots.+4. **`@x` notation** — explicit, documented cross-import between entities only. Last resort.++---++## Refactoring++When applying changes, **do not forget to refactor old code**. You can shortify, make more readable, improve code quality, etc. Common logic can be extracted to functions, constants, files, etc.++**After each large change with more than ~50-100 lines of code:**++- Run `pnpm format` (from `frontend/` root folder)+- Run `pnpm lint` to verify the changediff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.mdindex 38e8eb07..119a748d 100644--- a/frontend/CLAUDE.md+++ b/frontend/CLAUDE.md@@ -1,219 +1,3 @@-# Frontend guidelines (React + TypeScript)+# Frontend-This document contains coding standards for the Databasus frontend (React 19 + TypeScript + Vite + Ant Design + TailwindCSS).-For project-wide engineering philosophy, see the root `CLAUDE.md`.-------## Table of Contents--- [UI kit and icons](#ui-kit-and-icons)-- [React component structure](#react-component-structure)-- [Vertical spacing](#vertical-spacing)-- [Clipboard operations](#clipboard-operations)-- [Forms](#forms)-- [User-facing copy](#user-facing-copy)-- [FSD (Feature-Sliced Design)](#fsd-feature-sliced-design)-- [Refactoring](#refactoring)-------## UI kit and icons--- **AntD 5 only** for components. Don't pull in Mantine, MUI, Chakra, shadcn, or Radix directly. Use AntD primitives (`Button`, `Input`, `Modal`, `Form`, `Table`, `Menu`, `Tabs`, etc.) plus Tailwind utility classes for layout and spacing.-- **`@ant-design/icons` only** for icons. Don't add `lucide-react`, `@heroicons/react`, `react-icons`, or FontAwesome.-------## React component structure--Write React components with the following structure:--```typescript-interface Props {- someValue: SomeValue;-}--const someHelperFunction = () => {- ...-}--export const ReactComponent = ({ someValue }: Props): JSX.Element => {- // First put states- const [someState, setSomeState] = useState<...>(...)-- // Then place functions- const loadSomeData = async () => {- ...- }-- // Then hooks- useEffect(() => {- loadSomeData();- });-- // Then calculated values- const calculatedValue = someValue.calculate();-- return <div> ... </div>-}-```--### Structure order--1. **Props interface** — Define component props-2. **Helper functions** (outside component) — Pure utility functions-3. **Component declaration**- - **States** — `useState` declarations- - **Plain functions** — Event handlers, async operations, in-component formatters. Anything that does _not_ call a React hook.- - **Hooks** — `useRef` + ref mutation, `useCallback`, `useMemo`, `useEffect`. A function wrapped in `useCallback` is a hook — it lives here, not in the functions section.- - **Calculated values** — Derived data computed inline (e.g. an AntD `columns` array).- - **Return** — JSX markup--**All hooks (including every `useEffect`) come below every plain function definition.** If a `useEffect` reads a handler, the handler must be defined above it — don't reorder by putting handlers below the effects.-------## Vertical spacing--- Structure function bodies with vertical rhythm. Put a blank line between logically distinct steps (setup / main work / return, independent branches, before and after a guard). Do not leave blank lines at the start or end of a body, never stack two in a row. Do not insert blanks inside a tight expression, a single statement split across lines, or a short (≤ 5-line) function. If blank lines alone aren't enough to navigate a body, extract — don't add comments.-------## Clipboard operations--Always use `ClipboardHelper` (`shared/lib/ClipboardHelper.ts`) for clipboard operations — never call `navigator.clipboard` directly.--- **Copy:** `ClipboardHelper.copyToClipboard(text)` — uses `navigator.clipboard` with `execCommand('copy')` fallback for non-secure contexts (HTTP).-- **Paste:** Check `ClipboardHelper.isClipboardApiAvailable()` first. If available, use `ClipboardHelper.readFromClipboard()`. If not, show `ClipboardPasteModalComponent` (`shared/ui`) which lets the user paste manually via a text input modal.-------## Forms--### Progressive disclosure--- Submit buttons (`Save`, `Update password`, etc.) render **only when the form is dirty**.-- Dependent fields (e.g. `Confirm password`) render **only after the field they depend on has a value**.-------## User-facing copy--Use a plain hyphen `-` in any string the user will see — labels, descriptions, notifications, modal bodies, error messages. Reserve em dashes (`—`) and en dashes (`–`) for markdown docs and code comments only.-------## FSD (Feature-Sliced Design)--The project follows FSD v2.1. Layers in use: `app/`, `pages/`, `widgets/`, `features/`, `entities/`, `shared/`.--### Import direction--`app → pages → widgets → features → entities → shared`--A module may only import from layers strictly **below** it. Cross-imports between slices on the **same** layer are forbidden.--```tsx-// ✅ Allowed-import { useUser } from '@/entities/user';-import { LoginForm } from '@/features/auth';-// ❌ Violations-import { loginUser } from '@/features/auth';-// inside entities/-import { likePost } from '@/features/like-post';-// inside another feature-import { ProfilePage } from '@/pages/profile';-import { Button } from '@/shared/ui/Button';--// inside a feature-```--### Where new code goes--- Used in only one page → keep it in that `pages/` slice.-- Reusable infrastructure, **no business logic** → `shared/` (UI kit, utils, API client, route constants, auth tokens, CRUD helpers).-- User interaction reused in 2+ pages → `features/`.-- Domain model reused in 2+ pages/features → `entities/`.-- App-wide providers, router, theme → `app/`.--**When in doubt — keep it in `pages/`.** Extract only when a second real consumer appears.--### Quick placement table--| Scenario | Single use | Reused in 2+ places |-| ------------------------ | ------------------------------------- | --------------------------------------- |-| Profile form | `pages/profile/ui/ProfileForm.tsx` | `features/profile-form/` |-| Database card | `pages/databases/ui/DatabaseCard.tsx` | `entities/database/ui/DatabaseCard.tsx` |-| Data fetching for backup | `pages/backup/api/fetch-backup.ts` | `entities/backup/api/` |-| Auth token / session | `shared/auth/` (always) | `shared/auth/` (always) |-| Login form | `pages/login/ui/LoginForm.tsx` | `features/auth/` |-| CRUD helpers | `shared/api/` (always) | `shared/api/` (always) |-| Date formatting util | — | `shared/lib/format-date.ts` |-| Modal content | `pages/[page]/ui/SomeModal.tsx` | — |--### MUST rules--1. **Downward-only imports.** No upward imports, no same-layer cross-imports.-2. **Public API via `index.ts`.** External consumers import only from a slice's `index.ts`, never its internal files.- ```tsx- // ✅- import { LoginForm } from '@/features/auth'- // ❌- import { LoginForm } from '@/features/auth/ui/LoginForm'- ```-3. **Domain-based file names.** Name files by the domain they represent, not their technical role.- ```text- // ❌ model/types.ts, model/utils.ts, lib/helpers.ts- // ✅ model/user.ts, model/backup.ts, api/fetch-database.ts- ```-4. **No business logic in `shared/`.** Shared holds only infrastructure. Domain calculations live in `entities/` or higher.-5. **One type per file in `model/` / DTOs.** Each `interface`, `class`, or `enum` that represents a domain entity, DTO, request body, or response shape gets its own file in `model/` (or `models/`), named after the type. Don't co-locate sibling types like `Foo` + `FooStatus` + `FooResponse` in a single `Foo.ts` — split them. Re-export each from the slice `index.ts` so consumers still import from the slice's public API.- ```text- // ❌ model/RestoreVerification.ts — enums + table-stat + main interface all in one file- // ✅ model/RestoreVerification.ts — interface RestoreVerification- // ✅ model/RestoreVerificationTableStat.ts — interface RestoreVerificationTableStat- // ✅ model/VerificationStatus.ts — enum VerificationStatus- // ✅ model/VerificationTrigger.ts — enum VerificationTrigger- ```- Tiny shape-only helper types tightly coupled to a parent type (a literal-union alias, a `Pick<>`) may stay in the parent's file. Splitting applies to anything with its own identity — anything you'd reasonably import on its own elsewhere.--### Segments inside a slice--- `ui/` — components, styles-- `model/` — state, types, domain logic, validation-- `api/` — backend calls, request functions, API-specific types-- `lib/` — internal helpers for this slice only-- `config/` — slice-level config / feature flags--`app/` and `shared/` have **segments only, no slices**. Segments within them may import from each other.--### AVOID--- Creating an entity prematurely (single consumer → keep it in the page).-- Putting CRUD inside `entities/` — CRUD is infrastructure, goes to `shared/api/`.-- Creating a `user` entity just for auth tokens/DTOs — those belong in `shared/auth/` or `shared/api/`.-- Extracting single-use code "for future reuse."-- God slices (`user-management/` covering auth + profile + password) — split by focused responsibility.-- Importing UI segments of one entity from another entity. Entity UI may be imported only from features/widgets/pages.-- Abusing the `@x` cross-import pattern — it is a last resort, not a tool.--### Cross-imports between same-layer slices--When two slices on the same layer need to share code, try **in order**:--1. **Merge** — if they always change together, they are one slice.-2. **Extract shared logic down to `entities/`** — keep UI in the features/widgets.-3. **Compose in a higher layer (IoC)** — the parent page/widget imports both and wires them together via props/slots.-4. **`@x` notation** — explicit, documented cross-import between entities only. Last resort.-------## Refactoring--When applying changes, **do not forget to refactor old code**. You can shortify, make more readable, improve code quality, etc. Common logic can be extracted to functions, constants, files, etc.--**After each large change with more than ~50-100 lines of code:**--- Run `pnpm format` (from `frontend/` root folder)-- Run `pnpm lint` to verify the change+See [`AGENTS.md`](AGENTS.md), and the repository-wide rules in [`../AGENTS.md`](../AGENTS.md).diff --git a/openspec/config.yaml b/openspec/config.yamlnew file mode 100644index 00000000..d73f2370--- /dev/null+++ b/openspec/config.yaml@@ -0,0 +1,56 @@+schema: spec-driven++context: |+ Databasus - PostgreSQL/MySQL/MariaDB/MongoDB backup and restore platform,+ self-hosted, Docker-deployed.++ Stack: Go + Gin + GORM + PostgreSQL (backend/), Go CLI (agent/verification/),+ React 19 + TypeScript + Vite + Ant Design 5 + Tailwind (frontend/),+ Next.js 16 static export (website/).++ Per-folder rules live in backend/AGENTS.md, agent/verification/AGENTS.md,+ frontend/AGENTS.md, website/AGENTS.md; the root AGENTS.md holds the+ engineering philosophy. A change under a folder answers to both.++ Conventions that shape planning:+ - English only in code, comments, identifiers, API strings and commit+ messages. AGENTS.md enumerates every place translated end-user content+ is allowed; a change that needs another one amends that rule explicitly+ and with the user's approval, rather than assuming it.+ - No unrequested backward compatibility. A change that breaks callers,+ schemas, configs or APIs states the break; approved breaks delete the+ old code rather than leaving a shim.+ - No issue numbers in production code. The exception is a test pinning a+ specific issue's behavior.+ - Names state intent. Getters take Get, predicates read as questions,+ booleans take is/can/has/should.+ - Work happens inside the repo Dev Container. Commands are make (backend,+ agent) and pnpm (frontend).+ - Every non-trivial change is audited by the claude-md-reviewer subagent+ twice: after planning and after implementation.++rules:+ proposal:+ - Name the module AGENTS.md files the change answers to.+ - Include an explicit out-of-scope list; scope creep is the main failure mode here.+ - Mark anything that breaks existing callers, schemas, configs or APIs as BREAKING, and say what gets deleted rather than kept as a shim.+ specs:+ - State behavior a user or a downstream system can observe. No Go types, React components, file paths or library names.+ - Security-relevant behavior gets its own requirement, not a footnote.+ design:+ - For each decision, name the alternatives rejected and why. A decision with no alternatives listed is a description, not a decision.+ - Ground claims about current state in file:line references.+ - Say which module AGENTS.md rules the approach is constrained by.+ tasks:+ - Each task's verification is a real command from this repo (make lint, make test, make test-fedora, pnpm lint, pnpm test, pnpm build) or an observable behavior, never "should work".+ - Order by dependency, smallest slice first when the work is repetitive.++operations:+ apply:+ guidance:+ - Run the linter for every directory the diff touches before finishing.+ - Run claude-md-reviewer after planning and again before finishing the turn; resolve every CHANGES REQUIRED finding.+ - Never commit or push without explicit approval. No AI attribution trailers in commit messages.+ archive:+ guidance:+ - Confirm the module AGENTS.md files were updated if the change introduced a convention.diff --git a/website/AGENTS.md b/website/AGENTS.mdnew file mode 100644index 00000000..9bad0e79--- /dev/null+++ b/website/AGENTS.md@@ -0,0 +1,65 @@+# Website — Agent Rules++Next.js 16 App Router, static export (`output: "export"`, `trailingSlash: true`), deployed to GitHub Pages. The site is translated into 5 locales (`ru`, `es`, `pt`, `zh`, `fr`) by full per-language page copies, not dictionaries.++## Structure++- `app/(en)/` — the English site (root layout with `lang="en"`). URLs are unchanged by the route group. `not-found.tsx` and `error.tsx` live here; the `[lang]` tree deliberately has none (GitHub Pages serves the single `out/404.html`).+- `app/[lang]/` — translated pages. Root layout renders `<html lang>` per locale, `generateStaticParams()` returns the 5 locales, `dynamicParams = false`.+- `app/components/SiteDocument.tsx` — the shared document skeleton (head preloads, analytics script, body). Both root layouts are thin wrappers over it; never duplicate head markup in a layout.+- `app/i18n.ts` — single source of truth: `LOCALES`, hreflang codes, OG locales, `TRANSLATED_PATHS`, `getLocalizedUrl()` (absolute, for metadata), `getLocalizedHref()` (relative, for in-page links), `getLanguageAlternates()`, `splitLocaleFromPathname()`. Never hand-build a localized URL, absolute or relative.++## Translated page convention++Every translated page follows one shape, no exceptions:++```+app/[lang]/<path>/page.tsx — thin dispatcher+app/[lang]/<path>/content/ru.tsx — full page copy per locale+app/[lang]/<path>/content/es.tsx+...+```++Each `content/<locale>.tsx` exports **both** `metadata` (fully translated, `canonical` via `getLocalizedUrl`, `languages` via `getLanguageAlternates`, `openGraph.locale` from `OG_LOCALES`) and the default page component. The dispatcher imports all five and picks by `params.lang` in `generateMetadata` and in render. A translator (human or agent) owns exactly one `content/<locale>.tsx` per page and touches nothing shared.++`generateStaticParams` lives only in `app/[lang]/layout.tsx` — do not add it to pages.++## Sync rule (critical)++**If you change a page in `app/(en)/` that is listed in `TRANSLATED_PATHS`, you must apply the same change to all 5 copies in `app/[lang]/<path>/content/`.** That includes structure, links, and metadata. Check before finishing:++1. The section/element hierarchy matches the English page.+2. Internal links carry the `/{lang}/` prefix — except links to untranslated pages (`/sponsorship`, `/privacy`, `/terms-of-use`, `/contribute/*`), which stay unprefixed.+3. Heading `id` anchors are identical to English in every locale (cross-links like `/faq#oss-programs` depend on them).+4. Technical strings (install commands, configs, file names, code blocks) are byte-identical to English.+5. Adding a page to the translated core or adding a locale starts in `app/i18n.ts` (`TRANSLATED_PATHS` / `LOCALES`); sitemap and hreflang follow from it automatically.++## Translation rules++- Titles and `<h1>` target the highest-volume search phrasing of the locale, not a literal translation. Canonical head-forms: ru «резервное копирование PostgreSQL», es «copia de seguridad de PostgreSQL», pt «backup PostgreSQL», fr «sauvegarde PostgreSQL», zh «PostgreSQL 备份». Check what query the English page targets (title/keywords) and pick the frequent equivalent.+- Synonyms go in body text, canonical query forms in h1/h2 (ru «бекап», «дамп»; es «respaldo»; pt «cópia de segurança»; fr «backup»; zh «数据库备份»). Don't force synonyms into subheadings.+- Portuguese is Brazilian (pt-BR): usuário, equipe, seção, arquivo, gerund progressives («está rodando», never «está a correr»), proclisis («se conecta»). Chinese is Simplified.+- `keywords` get a plain translation, nothing more (search engines ignore them).+- URL form everywhere (canonical, hreflang, sitemap) is **with** trailing slash — Next normalizes rendered metadata URLs to that form under `trailingSlash: true`, and internal consistency of the cluster is what matters. `getLocalizedUrl` produces it; never hand-build URLs.++## Translation quality++Translations are edited copy in the target language, not word-for-word renderings. The Russian pages were proofread by the owner — treat their current text as the tone reference before writing or editing any locale.++- **No calques.** If a sentence keeps English word order or literally renders an English construction, rewrite it («Результат отправляется обратно — включая X» → «Результат приходит вам: X»; "user experience with X" → just describe working with X). Read the sentence aloud in the target language; if it sounds translated, it is.+- **No bureaucratese or pompous filler.** Cut inflated verbs («обеспечивает возможность» → «умеет», «дает») and closing self-praise sentences ("This adoption level reflects strong community trust…"). End on the last concrete fact.+- **No repeats.** Don't restate a list or repeat the same verb in adjacent sentences ("supports X, Y, Z… X, Y, Z are also supported").+- **Everyday tech anglicisms are fine in body text** when they are what practitioners actually say (ru: бекап, дамп, стриминг, продакшен, комплаенс, «из коробки», «соло-разработчик») — don't swap them for stiff formal equivalents. The formal canonical query form still owns `title`/`h1`/`h2` (see above). Exception by owner's choice: «рабочие пространства», not «воркспейсы».+- **Follow locale conventions.** Russian: «е», never «ё»; numerals like «2-х минут», «3-х попыток», «17-й версии»; «—» stays where Russian grammar wants it. Spanish: usted; canonical «copia de seguridad» in headings, «respaldo» as a body synonym; no bare English «backup» in prose. French: vous; a space before % («99 %»); a plain ASCII space (not ` `) before `: ; ! ?`. Chinese: 你, never 您 (titles included); full-width punctuation in prose(,。:); a space at every CJK↔Latin boundary. Number formatting per locale: en `1,800,000`, fr `1 800 000`, es/pt `1.800.000`, zh `180 万` (万-format for millions in prose).+- **Product stats stay in sync.** Docker pulls, GitHub stars and similar figures must match across all 6 languages *and* every duplicated block on a page (visible FAQ + its JSON-LD copy). Changing a number means changing it everywhere; competitors' figures are separate and only change when their reality does.+- **Some labels stay English everywhere** by design: the hero badges ("GitHub stars" / "Docker pulls"), brand-name nav items (Slack, Google Drive, "Databasus vs X"), and product UI option names quoted in docs ("After backup", "Scheduled verification", "Hourly") — the interface is English, so the docs quote it verbatim.++## Language exception++The repo-wide "English only" rule has exactly one carve-out here: rendered content and metadata of `content/<locale>.tsx` files are in the target language. Identifiers, comments, file names (locale codes aside), commit messages, and everything else stay English.++## Verification++- `npm run build` — static export must succeed; `out/index.html` and `out/404.html` must exist.+- `npm run lint` (`next lint` was removed in Next 16).+- Completeness: for every `TRANSLATED_PATHS` × locale pair, `out/{lang}/{path}/index.html` exists with the right `<html lang=`, hreflang links, and a translated `<title>`.diff --git a/website/CLAUDE.md b/website/CLAUDE.mdindex 9bad0e79..9049ca51 100644--- a/website/CLAUDE.md+++ b/website/CLAUDE.md@@ -1,65 +1,3 @@-# Website — Agent Rules+# Website-Next.js 16 App Router, static export (`output: "export"`, `trailingSlash: true`), deployed to GitHub Pages. The site is translated into 5 locales (`ru`, `es`, `pt`, `zh`, `fr`) by full per-language page copies, not dictionaries.--## Structure--- `app/(en)/` — the English site (root layout with `lang="en"`). URLs are unchanged by the route group. `not-found.tsx` and `error.tsx` live here; the `[lang]` tree deliberately has none (GitHub Pages serves the single `out/404.html`).-- `app/[lang]/` — translated pages. Root layout renders `<html lang>` per locale, `generateStaticParams()` returns the 5 locales, `dynamicParams = false`.-- `app/components/SiteDocument.tsx` — the shared document skeleton (head preloads, analytics script, body). Both root layouts are thin wrappers over it; never duplicate head markup in a layout.-- `app/i18n.ts` — single source of truth: `LOCALES`, hreflang codes, OG locales, `TRANSLATED_PATHS`, `getLocalizedUrl()` (absolute, for metadata), `getLocalizedHref()` (relative, for in-page links), `getLanguageAlternates()`, `splitLocaleFromPathname()`. Never hand-build a localized URL, absolute or relative.--## Translated page convention--Every translated page follows one shape, no exceptions:--```-app/[lang]/<path>/page.tsx — thin dispatcher-app/[lang]/<path>/content/ru.tsx — full page copy per locale-app/[lang]/<path>/content/es.tsx-...-```--Each `content/<locale>.tsx` exports **both** `metadata` (fully translated, `canonical` via `getLocalizedUrl`, `languages` via `getLanguageAlternates`, `openGraph.locale` from `OG_LOCALES`) and the default page component. The dispatcher imports all five and picks by `params.lang` in `generateMetadata` and in render. A translator (human or agent) owns exactly one `content/<locale>.tsx` per page and touches nothing shared.--`generateStaticParams` lives only in `app/[lang]/layout.tsx` — do not add it to pages.--## Sync rule (critical)--**If you change a page in `app/(en)/` that is listed in `TRANSLATED_PATHS`, you must apply the same change to all 5 copies in `app/[lang]/<path>/content/`.** That includes structure, links, and metadata. Check before finishing:--1. The section/element hierarchy matches the English page.-2. Internal links carry the `/{lang}/` prefix — except links to untranslated pages (`/sponsorship`, `/privacy`, `/terms-of-use`, `/contribute/*`), which stay unprefixed.-3. Heading `id` anchors are identical to English in every locale (cross-links like `/faq#oss-programs` depend on them).-4. Technical strings (install commands, configs, file names, code blocks) are byte-identical to English.-5. Adding a page to the translated core or adding a locale starts in `app/i18n.ts` (`TRANSLATED_PATHS` / `LOCALES`); sitemap and hreflang follow from it automatically.--## Translation rules--- Titles and `<h1>` target the highest-volume search phrasing of the locale, not a literal translation. Canonical head-forms: ru «резервное копирование PostgreSQL», es «copia de seguridad de PostgreSQL», pt «backup PostgreSQL», fr «sauvegarde PostgreSQL», zh «PostgreSQL 备份». Check what query the English page targets (title/keywords) and pick the frequent equivalent.-- Synonyms go in body text, canonical query forms in h1/h2 (ru «бекап», «дамп»; es «respaldo»; pt «cópia de segurança»; fr «backup»; zh «数据库备份»). Don't force synonyms into subheadings.-- Portuguese is Brazilian (pt-BR): usuário, equipe, seção, arquivo, gerund progressives («está rodando», never «está a correr»), proclisis («se conecta»). Chinese is Simplified.-- `keywords` get a plain translation, nothing more (search engines ignore them).-- URL form everywhere (canonical, hreflang, sitemap) is **with** trailing slash — Next normalizes rendered metadata URLs to that form under `trailingSlash: true`, and internal consistency of the cluster is what matters. `getLocalizedUrl` produces it; never hand-build URLs.--## Translation quality--Translations are edited copy in the target language, not word-for-word renderings. The Russian pages were proofread by the owner — treat their current text as the tone reference before writing or editing any locale.--- **No calques.** If a sentence keeps English word order or literally renders an English construction, rewrite it («Результат отправляется обратно — включая X» → «Результат приходит вам: X»; "user experience with X" → just describe working with X). Read the sentence aloud in the target language; if it sounds translated, it is.-- **No bureaucratese or pompous filler.** Cut inflated verbs («обеспечивает возможность» → «умеет», «дает») and closing self-praise sentences ("This adoption level reflects strong community trust…"). End on the last concrete fact.-- **No repeats.** Don't restate a list or repeat the same verb in adjacent sentences ("supports X, Y, Z… X, Y, Z are also supported").-- **Everyday tech anglicisms are fine in body text** when they are what practitioners actually say (ru: бекап, дамп, стриминг, продакшен, комплаенс, «из коробки», «соло-разработчик») — don't swap them for stiff formal equivalents. The formal canonical query form still owns `title`/`h1`/`h2` (see above). Exception by owner's choice: «рабочие пространства», not «воркспейсы».-- **Follow locale conventions.** Russian: «е», never «ё»; numerals like «2-х минут», «3-х попыток», «17-й версии»; «—» stays where Russian grammar wants it. Spanish: usted; canonical «copia de seguridad» in headings, «respaldo» as a body synonym; no bare English «backup» in prose. French: vous; a space before % («99 %»); a plain ASCII space (not ` `) before `: ; ! ?`. Chinese: 你, never 您 (titles included); full-width punctuation in prose(,。:); a space at every CJK↔Latin boundary. Number formatting per locale: en `1,800,000`, fr `1 800 000`, es/pt `1.800.000`, zh `180 万` (万-format for millions in prose).-- **Product stats stay in sync.** Docker pulls, GitHub stars and similar figures must match across all 6 languages *and* every duplicated block on a page (visible FAQ + its JSON-LD copy). Changing a number means changing it everywhere; competitors' figures are separate and only change when their reality does.-- **Some labels stay English everywhere** by design: the hero badges ("GitHub stars" / "Docker pulls"), brand-name nav items (Slack, Google Drive, "Databasus vs X"), and product UI option names quoted in docs ("After backup", "Scheduled verification", "Hourly") — the interface is English, so the docs quote it verbatim.--## Language exception--The repo-wide "English only" rule has exactly one carve-out here: rendered content and metadata of `content/<locale>.tsx` files are in the target language. Identifiers, comments, file names (locale codes aside), commit messages, and everything else stay English.--## Verification--- `npm run build` — static export must succeed; `out/index.html` and `out/404.html` must exist.-- `npm run lint` (`next lint` was removed in Next 16).-- Completeness: for every `TRANSLATED_PATHS` × locale pair, `out/{lang}/{path}/index.html` exists with the right `<html lang=`, hreflang links, and a translated `<title>`.+See [`AGENTS.md`](AGENTS.md), and the repository-wide rules in [`../AGENTS.md`](../AGENTS.md).