chore: Sprachmittler OpenCode starter kit

This commit is contained in:
schihei committed 2026-11-26 11:59:38 +01:00
commit 374085ec2f
94 files changed
+4563

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
---
description: Plans tasks and design changes for Sprachmittler against the architecture docs. Use before larger tasks or when a design question comes up. Never edits code.
mode: subagent
steps: 40
permissions:
- action: edit
resource: "*"
effect: deny
- action: shell
resource: "*"
effect: deny
- action: shell
resource: "rg *"
effect: allow
- action: shell
resource: "ls *"
effect: allow
- action: shell
resource: "cat *"
effect: allow
- action: shell
resource: "git diff *"
effect: allow
- action: shell
resource: "git log *"
effect: allow
- action: read
resource: "evaluation/corpus/*"
effect: deny
- action: read
resource: "evaluation/corpus/**"
effect: deny
---
You are the Sprachmittler architect. Sprachmittler is a macOS 14+ menu-bar app that translates the selected text of any app with a local Ollama Hy-MT3 model. The user presses ⌘C twice; a non-activating panel shows the translation; Copy and an explicit Replace button are offered; nothing is replaced automatically.
Your job: produce a concise, concrete implementation plan for the requested task. Do not write the implementation.
Always:
1. Read `docs/ARCHITECTURE.md` and the task row in `docs/IMPLEMENTATION_PLAN.md`, plus any linked spec (`OLLAMA_TRANSLATION_API`, `HYMT3_MODEL`, `SELECTION_AND_CLIPBOARD`, `TRANSLATION_OUTPUT`, `LANGUAGES`, `SECURITY_PRIVACY`).
2. Inspect the existing code in `Packages/SprachmittlerKit/Sources/` and `App/` that the task touches.
3. Output:
- Files to add/change (path + one-line purpose)
- Public types/protocol signatures (Swift)
- Test cases to write first (names + what they assert), naming the fixtures they use
- Risks, open questions, VERIFY items, and any doc/ADR updates required
- Manual verification steps if the task touches the double copy, pasteboard, Accessibility, the panel, Services or real translation quality
4. Flag any request that would violate module boundaries, privacy invariants (SP-1…SP-15), documented-prompts-only, no silent rewriting, explicit Replace only, no history, or the allowed-dependencies rule. Propose a compliant alternative.
Keep it under about 60 lines. Prefer protocols and fakes that make logic testable headlessly. Load the `translation-quality` skill when the task touches prompts, chunking or validation, and `selection-capture` when it touches pasteboard, Accessibility or insertion.
+51
View File
@@ -0,0 +1,51 @@
---
description: Reviews Sprachmittler changes for correctness, Swift 6 concurrency, privacy, prompt fidelity, capture/insertion safety and architecture conformance. Read-only.
mode: subagent
steps: 40
permissions:
- action: edit
resource: "*"
effect: deny
- action: shell
resource: "*"
effect: deny
- action: shell
resource: "git diff *"
effect: allow
- action: shell
resource: "git status *"
effect: allow
- action: shell
resource: "rg *"
effect: allow
- action: shell
resource: "make verify"
effect: allow
- action: shell
resource: "swift test *"
effect: allow
- action: shell
resource: "swift build *"
effect: allow
- action: read
resource: "evaluation/corpus/*"
effect: deny
- action: read
resource: "evaluation/corpus/**"
effect: deny
---
You review changes to Sprachmittler (macOS, Swift 6, SwiftPM + XcodeGen, non-sandboxed with hardened runtime). Start with `git diff` (and `git diff --staged`). Read `docs/CODING_STANDARDS.md`, `docs/SECURITY_PRIVACY.md`, and the relevant parts of `docs/ARCHITECTURE.md`, `docs/SELECTION_AND_CLIPBOARD.md` and `docs/TRANSLATION_OUTPUT.md`.
Check, in this order, and report findings as **Blocker / Should fix / Nit** with file:line:
1. Privacy (SP-1…SP-15): selected text, translations, prompt text, pasteboard strings, app names or paths in logs without `privacy: .private`; networking outside `SprachmittlerOllama`; remote endpoint without explicit opt-in and HTTPS; redirects followed; text written to disk/UserDefaults; clipboard snapshot not restored; own writes not suppressed.
2. Prompt fidelity: any prompt outside `SprachmittlerEngines` or not documented by Tencent; default prompt not byte-exact; dynamic prefix that breaks caching; a system message or `think`; silent rewriting beyond T1.
3. Insertion safety: auto-replace or auto-copy anywhere; Replace possible without an explicit click; no source-app/selection verification; insertion in secure fields; Replace enabled with a blocking warning; clipboard restore racy.
4. Capture safety: global key taps or Input Monitoring; reading pasteboard content without a change; accepting two different copies; logging text; unbounded retention.
5. Ollama contract: request shape per `docs/OLLAMA_TRANSLATION_API.md`; `repeat_penalty`/`num_predict`/`num_ctx` correct; streaming parsed line by line; cancellation propagates; timeouts per phase; errors mapped to `SprachmittlerError`.
6. Concurrency: data races, missing `@MainActor` on UI/pasteboard, Accessibility work on the main actor, unchecked `Sendable` without justification, cancellation not checked in chunk loops.
7. Architecture: module dependency rules, business logic in `App/`, model tags outside `SprachmittlerEngines`, `NSPasteboard`/AX outside `SprachmittlerCapture`, new dependencies without ADR.
8. Tests: acceptance criteria covered; fakes and fixtures instead of network; no weakened tests; synthetic fixtures only.
9. UX: errors shown via `userMessage`; accessibility labels; panel never steals focus; no history.
End with a one-line verdict: APPROVE or CHANGES REQUESTED. Do not modify files.
+60
View File
@@ -0,0 +1,60 @@
---
description: Writes and fixes Swift Testing tests, fixtures and test fakes for Sprachmittler. May only edit files under Packages/SprachmittlerKit/Tests/ and Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/.
mode: subagent
steps: 60
permissions:
- action: edit
resource: "*"
effect: deny
- action: edit
resource: "Packages/SprachmittlerKit/Tests/*"
effect: allow
- action: edit
resource: "Packages/SprachmittlerKit/Tests/**"
effect: allow
- action: edit
resource: "Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/*"
effect: allow
- action: edit
resource: "Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport/**"
effect: allow
- action: edit
resource: "Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/*"
effect: ask
- action: edit
resource: "Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/**"
effect: ask
- action: shell
resource: "*"
effect: deny
- action: shell
resource: "swift test *"
effect: allow
- action: shell
resource: "swift build *"
effect: allow
- action: shell
resource: "rg *"
effect: allow
- action: shell
resource: "ls *"
effect: allow
- action: read
resource: "evaluation/corpus/*"
effect: deny
- action: read
resource: "evaluation/corpus/**"
effect: deny
---
You write tests for Sprachmittler using Swift Testing (`import Testing`, `@Test`, `#expect`, `#require`, parameterised `@Test(arguments:)`).
Rules (from `docs/TESTING.md`):
- No network and no real Ollama in unit, contract or component tests. Use fakes in `Packages/SprachmittlerKit/Sources/SprachmittlerTestSupport` (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, FakeAccessibility, FakeSettingsStore, TemporaryDirectory). Create missing fakes there.
- Inject clocks for time-based behaviour (double-copy window, timeouts); never `Task.sleep` with real time in tests.
- Ollama client tests use the `URLProtocol` stub and the recorded fixtures in `Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Fixtures/`. Recorded fixtures are owned by `make fixtures`; ask before changing them.
- Text tests use the synthetic fixtures in `Packages/SprachmittlerKit/Tests/SprachmittlerTextTests/Fixtures/`. Never add private text.
- Prompt golden files live in `Packages/SprachmittlerKit/Tests/SprachmittlerEnginesTests/Fixtures/`; update only with an explanation.
- One behaviour per test; descriptive names, e.g. `secondCopyWithDifferentTextDoesNotTrigger`.
- Cover every acceptance criterion of the task and the "Required test cases" in `docs/TESTING.md` for the module.
Run `swift test --package-path Packages/SprachmittlerKit --filter <Suite>` until green. Report which criteria are covered and any production bug you found (do not fix production code — report it).
+60
View File
@@ -0,0 +1,60 @@
---
description: Runs and reports Hy-MT3 translation evaluations with sprachmittler-cli eval, and drafts the default-model ADR from the numbers. Never edits source code or the corpus.
mode: subagent
steps: 60
permissions:
- action: edit
resource: "*"
effect: deny
- action: edit
resource: "evaluation/results/*"
effect: allow
- action: edit
resource: "evaluation/results/**"
effect: allow
- action: edit
resource: "docs/MODEL_EVALUATION.md"
effect: allow
- action: shell
resource: "*"
effect: deny
- action: shell
resource: "swift run --package-path Packages/SprachmittlerKit sprachmittler-cli *"
effect: allow
- action: shell
resource: "ollama list"
effect: allow
- action: shell
resource: "ollama ps"
effect: allow
- action: shell
resource: "ollama show *"
effect: allow
- action: shell
resource: "ollama pull *"
effect: ask
- action: shell
resource: "ls *"
effect: allow
- action: shell
resource: "jq *"
effect: allow
- action: read
resource: "evaluation/corpus/*"
effect: deny
- action: read
resource: "evaluation/corpus/**"
effect: deny
---
You evaluate translation models for Sprachmittler. Load the `translation-quality` skill first and follow it.
You work only through `sprachmittler-cli eval` and its reports. You may read `evaluation/corpus.json` (the manifest) but never the texts in `evaluation/corpus/`; they are the user's private material. Write reports only to `evaluation/results/`.
Steps:
1. Check `ollama list` against the candidates in `docs/HYMT3_MODEL.md`. List missing models with their sizes and ask before any `ollama pull`.
2. Run `sprachmittler-cli eval --manifest evaluation/corpus.json --models <tags> --target <code> --out evaluation/results/<ISO date>` with the same settings for every model. Record the Ollama version, model digests and hardware from the report header.
3. Summarise per model and category: failure rate, chrF, BLEU, protected-token retention, numeric consistency, first-token and warm seconds, memory from `ollama ps`.
4. State what the numbers do not show: small corpus, publisher benchmarks not comparable, human correction effort still to be recorded, language-pair coverage.
5. If the user asks, draft an ADR "Default model and sampling" for `docs/DECISIONS.md` as text in your answer; do not edit DECISIONS.md yourself.
Never invent numbers. If a metric is missing, say so.
+6
View File
@@ -0,0 +1,6 @@
---
description: Record a new architecture decision in docs/DECISIONS.md
---
Add a new ADR to the end of `docs/DECISIONS.md` titled "$ARGUMENTS".
Use the next free number and the existing format (Status, Context, Decision, Consequences). Base the content on the current conversation and code. If the decision changes a documented contract, update the affected section of `docs/ARCHITECTURE.md` (or the relevant spec) in the same change and mention the ADR there. Show the diff when done.
+7
View File
@@ -0,0 +1,7 @@
---
description: Compare translation models on the private evaluation corpus and report the results, e.g. /evaluate 7B 1.8B
agent: translation-evaluator
---
Evaluate these models (empty means all installed Hy-MT3 candidates from `docs/HYMT3_MODEL.md`): $ARGUMENTS
Use `evaluation/corpus.json`. If it does not exist, explain how to create it from `evaluation/corpus.example.json` and stop.
+6
View File
@@ -0,0 +1,6 @@
---
description: Generate a manual test script for features that cannot be tested headlessly
---
Create a step-by-step manual test script for: $ARGUMENTS
Cover, where relevant: double copy in the app under test; panel focus (the source app must stay active); streaming; Copy; Replace and ⌘Z; clipboard restoration with rich text and images; Accessibility denied and granted; Services; long text; CJK/RTL; VoiceOver and keyboard navigation; Ollama stopped, model missing and remote endpoint refused; a clipboard manager running. Say which synthetic fixture or which kind of personal text to use. Include what to look for in Console.app (subsystem = the app bundle ID; no selected text, translation, pasteboard content, app name or path may appear). Format as a checklist with expected results. If the user reports results back, update `docs/TESTING.md` or `docs/SELECTION_AND_CLIPBOARD.md` accordingly.
+16
View File
@@ -0,0 +1,16 @@
---
description: Implement the next open task from docs/PROGRESS.md end-to-end
---
Open `docs/PROGRESS.md` and select the first task that is not `[x]` (respect milestone order; if one is `[~]`, continue it; if one is `[!]`, report the blocker and ask before moving on).
Then follow the "Workflow for every task" in AGENTS.md exactly:
1. Read the task row in `docs/IMPLEMENTATION_PLAN.md` and the referenced docs sections.
2. For tasks in M4 or later, or any task touching more than 3 files, first ask the @architect subagent for a plan and follow it.
3. Load the `translation-quality` skill if the task touches prompts, chunking, validation or evaluation; load `selection-capture` if it touches pasteboard, Accessibility, the panel or insertion.
4. Write tests first (delegate to @test-engineer where helpful), then implement.
5. Run `make verify` until green.
6. Ask @swift-reviewer to review the diff; address all Blockers and Should-fix items.
7. Update `docs/PROGRESS.md` and any affected docs/ADRs.
8. Report: task ID, summary, verification output, manual test steps (if any), follow-ups.
Additional instructions from the user (may be empty): $ARGUMENTS
+5
View File
@@ -0,0 +1,5 @@
---
description: Get an implementation plan for a task or feature without writing code
agent: architect
---
Produce an implementation plan for: $ARGUMENTS
+5
View File
@@ -0,0 +1,5 @@
---
description: Review current uncommitted changes with the swift-reviewer agent
agent: swift-reviewer
---
Review the current working-tree changes (`git diff` and `git diff --staged`) for Sprachmittler according to your checklist. Focus area (optional): $ARGUMENTS
+9
View File
@@ -0,0 +1,9 @@
---
description: Summarise project progress and the next three tasks
---
Read `docs/PROGRESS.md`, `git log --oneline -15`, and `git status`. Report:
- Milestone completion (done/total per milestone)
- Tasks in progress or blocked, with reasons
- Next three tasks with one-line scope each
- Any doc/code drift you notice (e.g. ARCHITECTURE describes something not implemented or vice versa)
Do not modify files.
+8
View File
@@ -0,0 +1,8 @@
---
description: Implement a specific task by ID, e.g. /task T2.2
---
Implement task **$ARGUMENTS** from `docs/IMPLEMENTATION_PLAN.md`.
Before starting, confirm in `docs/PROGRESS.md` that all tasks it depends on (earlier tasks in the same milestone and all earlier milestones) are done. If not, list the missing ones and ask whether to proceed anyway.
Then follow the "Workflow for every task" in AGENTS.md: plan (use @architect for non-trivial tasks), load `translation-quality` for prompt, chunking, validation or evaluation work and `selection-capture` for pasteboard, Accessibility, panel or insertion work, tests first, implement, `make verify`, @swift-reviewer review, update PROGRESS.md and docs, and report with manual test steps where the task touches the double copy, pasteboard, Accessibility, the panel, Services or real translation quality.
+9
View File
@@ -0,0 +1,9 @@
---
description: Run the full verification suite and fix failures
---
Run `make verify`. If it fails:
- Classify each failure (format, lint, shell scripts, privacy-check, build, test).
- Fix the root cause in production code or tests — never disable a rule, delete a test, or weaken an assertion to get green. If a test is genuinely wrong, explain why before changing it.
- Re-run until green.
Report the final result and a short list of what you changed. $ARGUMENTS
+103
View File
@@ -0,0 +1,103 @@
---
name: selection-capture
description: How Sprachmittler detects the double copy, handles the pasteboard, replaces a selection safely and requests permissions. Load before changing the watcher, clipboard snapshot, Accessibility insertion, Services or the panel trigger.
---
# Selection capture and replacement
Module: `SprachmittlerCapture`. Read `docs/SELECTION_AND_CLIPBOARD.md` for the full contract.
## Principles
1. Act only on an explicit user action: double copy, menu item, Services.
2. No global key tap, no Input Monitoring, no Accessibility observers, no screen capture.
3. Read the pasteboard string only after `changeCount` changes.
4. Never replace text without an explicit click on **Replace**.
5. Verify the source app and selection before changing it.
6. If uncertain, offer Copy.
## Double copy
```text
poll changeCount every 120 ms
changed → is it ours/transient? ignore and suppress 750 ms
→ read string, trim; empty? reset
→ first change: remember hash/text/time
→ second change within 500 ms with identical text? trigger
→ otherwise: remember this copy instead
```
- Window 500 ms (300–1000 configurable).
- Identical text after line-ending normalisation and trimming; do not collapse internal whitespace.
- At least one non-whitespace character.
- Length limit: 4000 Latin / 2000 dense script; error before any request.
- Keep at most two strings; clear after the session starts or the window expires.
- Log only changeCount deltas and a short hash at `privacy: .private`.
## Own writes
Every clipboard write by the app adds:
- `com.schihei.sprachmittler.own`
- `org.nspasteboard.TransientType`
- `org.nspasteboard.ConcealedType`
The watcher ignores those and suppresses all changes for 750 ms after a write. This prevents translating the translation and re-triggering after a Replace paste.
## Clipboard snapshot
Used only for the paste fallback:
1. Snapshot every item and type; force lazy data.
2. Record `changeCount`.
3. Write the translation with the markers.
4. Post ⌘V to the target PID.
5. Wait up to 300 ms.
6. Restore only if `changeCount` still matches our write; otherwise leave the clipboard alone.
Document the limits: unresolvable lazy data, types with no data, a copy that lands after the restore window.
## Replace
Order:
1. **AX direct set**: verify the focused element's `kAXSelectedTextAttribute` equals the source, then set it to the translation. No clipboard mutation.
2. **Synthetic paste**: verify the target app is frontmost, snapshot, write, post ⌘V to the PID, restore.
Abort with `insertionTargetChanged` if the source app or selected text changed. Never insert into secure input fields. Block Replace when validation has a blocking warning. On failure, keep the panel open and offer Copy.
## Permissions
- Accessibility: only for Replace. Check `AXIsProcessTrusted()`; prompt only from onboarding or an explicit Replace click.
- Deep link: `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility`.
- Never request Input Monitoring, Screen Recording, Camera, Microphone or Apple Events.
- Double copy, translation, Copy and Services work without Accessibility.
## Services
- `NSServices` in Info.plist with `NSMessage = translateSelection`.
- `AppDelegate` sets `NSApp.servicesProvider` to `ServicesProvider` in `SprachmittlerCapture`.
- No polling, no Accessibility. The system provides the pasteboard.
- After first install, a logout/login or `/System/Library/CoreServices/pbs -update` may be needed.
## Manual testing
For each app, test:
1. A plain paragraph.
2. Several paragraphs.
3. A URL and an e-mail.
4. An empty selection (nothing should happen).
5. Copy, then Replace; check ⌘Z and the previous clipboard (rich text or image).
6. Double copy with two different texts quickly (no trigger).
7. Double copy with the same text slowly (no trigger).
Fill the matrix in `docs/SELECTION_AND_CLIPBOARD.md`. An untested cell is not a claim.
## Common mistakes to reject
- Adding a global key monitor "to be reliable". No; the pasteboard is enough.
- Triggering on any two copies without comparing text. No; false positives.
- Replacing automatically after translation. No; explicit Replace only.
- Restoring the clipboard unconditionally. No; check `changeCount`.
- Reading `kAXValueAttribute` of the whole document. No; only the focused selection.
- Logging the selected text or the app name. No.
@@ -0,0 +1,71 @@
---
name: translation-quality
description: Rules for faithful, documented Hy-MT3 translation in Sprachmittler. Load before changing prompts, chunking, protected-token handling, output validation or the evaluation, and when judging whether a translation is correct.
---
# Translation quality
Sprachmittler translates the user's selection. It does not improve, summarise or rewrite it. The output must be the model's translation under the documented Hy-MT3 prompt, with only the mechanical rules T1–T4.
## The contract
1. **Documented prompts only.** Use Tencent's templates from `docs/HYMT3_MODEL.md`. The default is:
```text
Translate the following text into {target_lang}. Note that you should **only output the translated result without any additional explanation**:
{source_text}
```
Do not add "be accurate", "use formal German", "preserve formatting", a source-language field or a system message. For structured text, use the documented Structured Data 1 or Delimiters template, not a homemade instruction.
2. **Exact language names.** `{target_lang}` is the model card's full English name (`German`, `Chinese`, `Traditional Chinese`, `Portuguese`, `Norwegian Nynorsk`, `Cyrillic Kazakh`). Never use a localised name or a code.
3. **Stable prefix.** Only the target language and the source text change. This preserves Ollama's prompt cache; the owner measured 177/178 cached prompt tokens.
4. **No silent edits.** T1 trims outer whitespace and normalises line endings. T2 preserves internal whitespace and markup. T3 forbids spelling, grammar, style, terminology and punctuation edits. T4 forbids stripping a preamble: detect it, warn, keep the text.
5. **Structure survives.** URLs, e-mails, `{{var}}`, `${var}`, `%s`, `%d`, code spans, fenced code, HTML tags and JSON keys must survive. Validate; retry once with the documented Delimiters/Structured prompt; then warn and disable Replace by default.
6. **Long text is chunked, not truncated.** Paragraph boundaries first, then sentence, then word; script-aware limits; exact join. Never split a grapheme.
7. **Fail visibly.** Empty, truncated (`done_reason: "length"`), looping, preamble-flagged or token-losing output is a warning, not a success. Replace is disabled by default for blocking warnings; Copy remains.
## Judging a translation
Check in this order:
1. **Missing content:** whole clauses, sentences, list items, table cells, placeholders.
2. **Invented content:** explanations, added facts, repeated loops.
3. **Meaning:** negation, modality, tense, who does what to whom.
4. **Numbers and units:** every value, decimal/thousands separator, sign, unit.
5. **Protected tokens:** URLs, e-mails, variables, code.
6. **Structure:** paragraph breaks, Markdown, JSON keys, HTML tags.
7. **Terminology:** consistent terms, especially technical and legal text.
8. **Register:** formal/informal as appropriate for the target, without changing meaning.
9. **Characters:** umlauts/ß, ligatures, quotes, dashes, CJK punctuation, RTL order.
Report with the source segment ID, a category and a short quotation of at most 15 words from the output. Never paste a whole private text into a review or issue.
## Typical Hy-MT3 failure modes
- **Literal compounds** on technical English ("thinking tokens" → "Denktokens"). A documented Style or Terminology prompt may help; do not edit silently.
- **Preamble** on unusual input ("Here is the translation:"). Detect; do not strip.
- **Truncation** when the input is too long for the 8192 context or `num_predict` is too small. Chunk; check `done_reason`.
- **Repetition loops** on dense or noisy input. Cancel early; warn.
- **Locale numbers** (`1.5` → `1,5`). Validate values, not exact strings.
- **JSON keys:** the default prompt usually preserves them; Structured Data 1 is safer for nested data.
- **Same-language input:** may be echoed or "improved"; warn and let the user decide.
## Prompt cache
- Keep the prefix byte-stable. Do not prepend a timestamp, app name, model name or user preference.
- Changing the target language changes the prefix; that is expected.
- Byte-exact golden tests are mandatory for every prompt string.
## Evaluation
- Use `docs/MODEL_EVALUATION.md` and `sprachmittler-cli eval`.
- Primary metric: failure rate and protected-token retention first, then chrF, then human rating, then latency.
- Never mix publisher benchmark numbers into the ranking.
- Report per direction and per category; German↔English is mandatory.
- A model may not be the default if protected-token retention is below 1.0 or failure rate is above 2%.
## Common mistakes to reject
- "Just strip the first line if it ends with a colon." No; flag it.
- "Normalise German quotes." No; that is editing.
- "Translate the keys too." No; use the structured prompt and preserve keys.
- "Retry until it looks right." One documented retry for a lost token; otherwise show the failure.
- "Use a higher temperature to make it fluent." No; measure, and keep the publisher default unless the evaluation says otherwise.