feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)

M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes.

M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open.

Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018.

Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
This commit is contained in:
schihei committed 2026-11-26 13:30:32 +01:00
1 parent 26b493e7e5
commit 64078e2f04
80 files changed
+4090 -325

No files matched your search

@@ -0,0 +1,3 @@
Please accurately translate the following text into {target_lang}. You must **retain the exact same number of delimiters in the translation. Strictly do not omit, escape, or translate these symbols, and pay close attention to their placement**.
{source_text}
@@ -0,0 +1,10 @@
### Task
Translate the user-facing text within the following {format_type} data into {target_lang}.
### Strict Rules
1. **Structure Preservation:** You MUST preserve the original {format_type} data structure, nesting, hierarchy, and indentation exactly as they are.
2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.
3. **Strict Non-Translation:** NEVER translate or alter code tags, keys, properties, object names, or variable placeholders. Leave them exactly in their original English/code form.
### Source Data
{source_text}
@@ -0,0 +1,106 @@
import Foundation
import SprachmittlerOllama
import SprachmittlerText
import Testing
@testable import SprachmittlerEngines
@Suite("Hy-MT3 adapter and registry")
struct HyMT3AdapterTests {
private let adapter = HyMT3Adapter()
@Test func matchesEveryHyMT3TagAndRejectsOtherFamilies() {
#expect(adapter.supports(model: HyMT3ModelPreset.defaultModel))
#expect(adapter.supports(model: HyMT3ModelPreset.fastModel))
#expect(adapter.supports(model: "hf.co/tencent/Hy-MT3-30B-A3B-GGUF:Q4_K_M"))
#expect(!adapter.supports(model: "llama3.1:8b"))
let registry = AdapterRegistry(adapters: [adapter])
#expect(registry.adapter(for: HyMT3ModelPreset.defaultModel)?.identifier == "hy-mt3")
#expect(registry.adapter(for: "llama3.1:8b") == nil)
#expect(throws: AdapterError.noAdapter(model: "llama3.1:8b")) {
try registry.makeRequest(
AdapterRequest(
text: "Hello.",
target: HyMT3Languages.german,
model: "llama3.1:8b",
keepAlive: "30m"
)
)
}
}
@Test func requestHasOneUserMessageAndPublisherSampling() {
let request = adapter.makeRequest(
AdapterRequest(
text: "Hello.",
target: HyMT3Languages.german,
model: "test-model",
keepAlive: "5m"
)
)
#expect(request.model == "test-model")
#expect(request.stream)
#expect(request.keepAlive == "5m")
#expect(request.messages.count == 1)
#expect(request.messages.first?.role == "user")
#expect(request.messages.first?.content == HyMT3Prompt.defaultTranslation(
target: HyMT3Languages.german,
source: "Hello."
))
#expect(request.options.temperature == 0.7)
#expect(request.options.topP == 0.6)
#expect(request.options.topK == 20)
#expect(request.options.repeatPenalty == 1.05)
#expect(request.options.numPredict == 4096)
#expect(request.options.numCtx == 8192)
}
@Test func encodingUsesOnlyTheDocumentedOptionNames() throws {
let request = adapter.makeRequest(
AdapterRequest(
text: "Hello.",
target: HyMT3Languages.german,
model: "test-model",
keepAlive: "30m"
)
)
let data = try JSONEncoder().encode(request)
let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
let options = try #require(object["options"] as? [String: Any])
#expect(Set(options.keys) == ["temperature", "top_p", "top_k", "repeat_penalty", "num_predict", "num_ctx"])
#expect(object["keep_alive"] as? String == "30m")
#expect((object["messages"] as? [[String: Any]])?.first?["role"] as? String == "user")
#expect(object["think"] == nil)
#expect(object["system"] == nil)
}
@Test func warmUpAndUnloadUseFixedText() {
let warmUp = adapter.warmUpRequest(model: "test-model", keepAlive: "30m")
#expect(warmUp.messages.first?.content == "Hello.")
#expect(warmUp.options.numPredict == 8)
let unload = adapter.unloadRequest(model: "test-model")
#expect(unload.messages.first?.content == "Hello.")
#expect(unload.keepAlive == "0")
}
@Test func samplingMergeOnlyOverridesKnownKeys() {
let merged = SamplingOptions.publisherDefault.merging(
SamplingOverrides(temperature: 0.2, numPredict: 2048)
)
#expect(merged.temperature == 0.2)
#expect(merged.numPredict == 2048)
#expect(merged.topP == 0.6)
#expect(merged.numCtx == 8192)
#expect(merged.chatOptions() == ChatOptions(
temperature: 0.2,
topP: 0.6,
topK: 20,
repeatPenalty: 1.05,
numPredict: 2048,
numCtx: 8192
))
}
}
@@ -1,93 +0,0 @@
import Foundation
import SprachmittlerOllama
import Testing
@testable import SprachmittlerEngines
@Suite("Hy-MT3 request factory")
struct HyMT3RequestFactoryTests {
@Test func warmUpUsesFixedTextAndEightTokens() throws {
let request = HyMT3RequestFactory().warmUpRequest()
let message = try #require(request.messages.first)
#expect(request.messages.count == 1)
#expect(message.role == "user")
#expect(message.content == "Hello.")
#expect(request.options.numPredict == 8)
#expect(request.options.numCtx == 8192)
#expect(request.keepAlive == "30m")
#expect(request.stream)
#expect(request.model == HyMT3ModelPreset.defaultModel)
}
@Test func unloadUsesKeepAliveZero() {
let request = HyMT3RequestFactory().unloadRequest()
#expect(request.keepAlive == "0")
#expect(request.messages.map(\.content) == ["Hello."])
}
@Test func translationPromptIsByteExact() throws {
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
let request = factory.translationRequest(text: "Hello.", target: HyMT3Languages.german)
let message = try #require(request.messages.first)
#expect(request.messages.count == 1)
#expect(
message.content
== "Translate the following text into German. "
+ "Note that you should **only output the translated result without any additional explanation**:"
+ "\n\nHello."
)
#expect(request.model == "test-model")
#expect(request.keepAlive == "5m")
#expect(request.options.numPredict == 4096)
#expect(request.options.numCtx == 8192)
#expect(request.options.temperature == 0.7)
#expect(request.options.topP == 0.6)
#expect(request.options.topK == 20)
#expect(request.options.repeatPenalty == 1.05)
}
@Test func promptMatchesTheGoldenFixture() throws {
let base = try #require(Bundle.module.resourceURL)
let url = base.appendingPathComponent("Fixtures/default-prompt.txt")
let template = try String(contentsOf: url, encoding: .utf8)
.trimmingCharacters(in: .newlines)
let expected = template
.replacingOccurrences(of: "{target_lang}", with: "German")
.replacingOccurrences(of: "{source_text}", with: "Hello.")
#expect(
HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
== expected
)
}
@Test func promptPrefixIsStableForTheSameTarget() {
let factory = HyMT3RequestFactory()
let first = factory.translationRequest(text: "One.", target: HyMT3Languages.german)
let second = factory.translationRequest(text: "Two.", target: HyMT3Languages.german)
let firstContent = first.messages[0].content
let secondContent = second.messages[0].content
let suffix = "\n\n"
let firstPrefix = firstContent.components(separatedBy: suffix)[0]
let secondPrefix = secondContent.components(separatedBy: suffix)[0]
#expect(firstPrefix == secondPrefix)
#expect(firstContent.hasSuffix("One."))
#expect(secondContent.hasSuffix("Two."))
}
@Test func resolvesOnlyTheProvisionalCommonLanguages() {
#expect(HyMT3Languages.resolve("de") == HyMT3Languages.german)
#expect(HyMT3Languages.resolve("EN") == HyMT3Languages.english)
#expect(HyMT3Languages.resolve("zh-Hant")?.modelName == "Traditional Chinese")
#expect(HyMT3Languages.resolve("xx") == nil)
#expect(HyMT3Languages.all.count == 16)
}
@Test func optionsMatchTheDocumentedPublisherValues() {
#expect(HyMT3Options.translation.temperature == 0.7)
#expect(HyMT3Options.translation.topP == 0.6)
#expect(HyMT3Options.translation.topK == 20)
#expect(HyMT3Options.translation.repeatPenalty == 1.05)
#expect(HyMT3Options.translation.numPredict == 4096)
#expect(HyMT3Options.translation.numCtx == 8192)
#expect(HyMT3Options.warmUp.numPredict == 8)
}
}
@@ -0,0 +1,67 @@
import Testing
@testable import SprachmittlerEngines
@Suite("Hy-MT3 language catalogue")
struct LanguageCatalogueTests {
@Test func containsAll102Languages() {
#expect(HyMT3Languages.count == 102)
#expect(Set(HyMT3Languages.all.map(\.code)).count == 102)
}
@Test func exactModelNamesForVariants() {
#expect(HyMT3Languages.resolve("zh")?.modelName == "Chinese")
#expect(HyMT3Languages.resolve("zh-Hant")?.modelName == "Traditional Chinese")
#expect(HyMT3Languages.resolve("pt")?.modelName == "Portuguese")
#expect(HyMT3Languages.resolve("nb")?.modelName == "Norwegian")
#expect(HyMT3Languages.resolve("nn")?.modelName == "Norwegian Nynorsk")
#expect(HyMT3Languages.resolve("kk")?.modelName == "Arabic Kazakh")
#expect(HyMT3Languages.resolve("kk-Cyrl")?.modelName == "Cyrillic Kazakh")
#expect(HyMT3Languages.resolve("mn")?.modelName == "Traditional Mongolian")
#expect(HyMT3Languages.resolve("mn-Cyrl")?.modelName == "Cyrillic Mongolian")
#expect(HyMT3Languages.resolve("ku")?.modelName == "Kurdish")
#expect(HyMT3Languages.resolve("ckb")?.modelName == "Central Kurdish")
}
@Test func variantsCollapseToCanonicalCodes() {
#expect(HyMT3Languages.resolve("zh-Hans")?.code == "zh")
#expect(HyMT3Languages.resolve("zh-CN")?.code == "zh")
#expect(HyMT3Languages.resolve("zh-TW")?.code == "zh-Hant")
#expect(HyMT3Languages.resolve("pt-BR")?.code == "pt")
#expect(HyMT3Languages.resolve("pt-PT")?.code == "pt")
#expect(HyMT3Languages.resolve("no")?.code == "nb")
#expect(HyMT3Languages.resolve("fil")?.code == "tl")
#expect(HyMT3Languages.resolve("iw")?.code == "he")
#expect(HyMT3Languages.resolve("in")?.code == "id")
#expect(HyMT3Languages.resolve("kk-KZ")?.code == "kk-Cyrl")
#expect(HyMT3Languages.resolve("de-AT")?.code == "de")
}
@Test func unknownCodesAreNeverGuessed() {
#expect(HyMT3Languages.resolve("xx") == nil)
#expect(HyMT3Languages.resolve("xx-YY") == nil)
#expect(HyMT3Languages.resolve("") == nil)
}
@Test func rightToLeftLanguagesAreMarked() {
let codes = Set(HyMT3Languages.rightToLeft.map(\.code))
#expect(codes.isSuperset(of: ["ar", "he", "fa", "ur", "ps", "sd", "ug", "ckb", "yi", "kk"]))
#expect(!codes.contains("de"))
}
@Test func displayNamesNeverEnterThePrompt() {
let german = HyMT3Languages.german
#expect(german.modelName == "German")
#expect(!german.displayName.isEmpty)
#expect(!german.localizedDisplayName.isEmpty)
#expect(
HyMT3Prompt.defaultTranslation(target: german, source: "x")
.contains("into German.")
)
}
@Test func commonTargetsAreTheDocumentedFifteen() {
#expect(HyMT3Languages.common.map(\.code) == [
"en", "de", "fr", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "ar", "tr", "ru", "uk",
])
}
}
@@ -0,0 +1,129 @@
import SprachmittlerText
import Testing
@testable import SprachmittlerEngines
@Suite("Output validation")
struct OutputValidatorTests {
private let validator = OutputValidator()
private let scanner = ProtectedTokenScanner()
@Test func cleanOutputHasNoWarnings() {
let source = "Open https://example.com and write to a@example.com."
let translation = "Öffne https://example.com und schreibe an a@example.com."
let result = validator.validate(
source: source,
translation: translation,
doneReason: "stop",
tokens: scanner.scan(source)
)
#expect(result == .clean)
#expect(!result.blocksReplacement)
}
@Test func missingURLIsAWarning() {
let source = "Open https://example.com now."
let result = validator.validate(
source: source,
translation: "Öffne jetzt.",
doneReason: "stop",
tokens: scanner.scan(source)
)
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
#expect(result.blocksReplacement)
}
@Test func preambleIsDetectedAndKept() {
let translation = "Here is the translation:\n\nThe text."
let result = validator.validate(
source: "The text.",
translation: translation,
doneReason: "stop",
tokens: []
)
#expect(result.warnings.contains(.preambleDetected(firstLine: "Here is the translation:")))
#expect(result.blocksReplacement)
}
@Test func aColonWithoutABlankLineIsNotAPreamble() {
let result = validator.validate(
source: "Note:\nThe text.",
translation: "Note:\nThe text.",
doneReason: "stop",
tokens: []
)
#expect(!result.warnings.contains {
if case .preambleDetected = $0 {
true
} else {
false
}
})
}
@Test func lengthReasonIsTruncated() {
let result = validator.validate(
source: "x",
translation: "x",
doneReason: "length",
tokens: []
)
#expect(result.warnings.contains(.truncated))
#expect(result.blocksReplacement)
}
@Test func emptyOutputIsBlocking() {
let result = validator.validate(
source: "x",
translation: " ",
doneReason: "stop",
tokens: []
)
#expect(result.warnings == [.emptyOutput])
#expect(result.blocksReplacement)
}
@Test func repetitionLoopIsDetected() {
let line = "This line repeats exactly."
let translation = Array(repeating: line, count: 7).joined(separator: "\n")
let result = validator.validate(
source: "x",
translation: translation,
doneReason: "stop",
tokens: []
)
#expect(result.warnings.contains(.repetitionLoop))
#expect(result.blocksReplacement)
}
@Test func numericMismatchIsNonBlocking() {
let result = validator.validate(
source: "It costs 1.5 EUR in 2026.",
translation: "Es kostet 1,5 EUR.",
doneReason: "stop",
tokens: []
)
#expect(result.warnings.contains(.numericMismatch))
#expect(!result.blocksReplacement)
}
@Test func localeNumbersMatchSemantically() {
let result = validator.validate(
source: "It costs 1.5 EUR.",
translation: "Es kostet 1,5 EUR.",
doneReason: "stop",
tokens: []
)
#expect(!result.warnings.contains(.numericMismatch))
}
@Test func duplicateTokenCountMustMatch() {
let source = "https://example.com and https://example.com"
let result = validator.validate(
source: source,
translation: "https://example.com",
doneReason: "stop",
tokens: scanner.scan(source)
)
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
}
}
@@ -0,0 +1,70 @@
import Foundation
import Testing
@testable import SprachmittlerEngines
@Suite("Documented prompts")
struct PromptGoldenTests {
private func fixture(_ name: String) throws -> String {
let base = try #require(Bundle.module.resourceURL)
let url = base.appendingPathComponent("Fixtures/\(name)")
var text = try String(contentsOf: url, encoding: .utf8)
// Fixtures have one final line terminator; the production prompt has none. Remove exactly
// that one terminator so an accidental extra newline still fails the comparison.
if text.hasSuffix("\n") {
text.removeLast()
}
return text
}
@Test func defaultPromptMatchesTheGoldenFile() throws {
let expected = try fixture("default-prompt.txt")
.replacingOccurrences(of: "{target_lang}", with: "German")
.replacingOccurrences(of: "{source_text}", with: "Hello.")
#expect(HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.") == expected)
}
@Test func delimitersPromptMatchesTheGoldenFile() throws {
let expected = try fixture("delimiters-prompt.txt")
.replacingOccurrences(of: "{target_lang}", with: "German")
.replacingOccurrences(of: "{source_text}", with: "Use {{limit}}.")
#expect(
HyMT3Prompt.delimiters(target: HyMT3Languages.german, source: "Use {{limit}}.")
== expected
)
}
@Test func structuredData1MatchesTheGoldenFile() throws {
let expected = try fixture("structured-data-1-prompt.txt")
.replacingOccurrences(of: "{format_type}", with: "JSON")
.replacingOccurrences(of: "{target_lang}", with: "German")
.replacingOccurrences(of: "{source_text}", with: #"{"name":"value"}"#)
#expect(
HyMT3Prompt.structuredData1(
format: .json,
target: HyMT3Languages.german,
source: #"{"name":"value"}"#
) == expected
)
}
@Test func prefixIsStableForTheSameTarget() {
let first = HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "One.")
let second = HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Two.")
let prefix = "Translate the following text into German. Note that you should "
+ "**only output the translated result without any additional explanation**:\n\n"
#expect(first.hasPrefix(prefix))
#expect(second.hasPrefix(prefix))
#expect(first != second)
}
@Test func variantsResolveToDocumentedTemplates() {
#expect(
HyMT3Prompt.text(for: .structuredData1(format: .markdown), target: HyMT3Languages.german, source: "x")
.contains("### Task")
)
#expect(
HyMT3Prompt.text(for: .delimiters, target: HyMT3Languages.german, source: "x")
.contains("retain the exact same number of delimiters")
)
}
}
@@ -0,0 +1,61 @@
import SprachmittlerText
import Testing
@testable import SprachmittlerEngines
@Suite("Prompt policy")
struct PromptPolicyTests {
private let policy = PromptPolicy()
private let token = ProtectedToken(kind: .url, value: "https://example.com")
@Test func v1StartsWithDefaultForEveryContentClass() {
for content in ContentClass.allCases {
#expect(policy.initialPrompt(for: content) == .defaultTranslation)
}
}
@Test func structuredContentUsesStructuredData1AfterALostToken() {
#expect(policy.retryPrompt(for: .json, lostToken: token) == .structuredData1(format: .json))
#expect(policy.retryPrompt(for: .html, lostToken: token) == .structuredData1(format: .html))
#expect(policy.retryPrompt(for: .markdown, lostToken: token) == .structuredData1(format: .markdown))
}
@Test func plainAndDelimitedTextUseDelimitersAfterALostToken() {
#expect(policy.retryPrompt(for: .plain, lostToken: token) == .delimiters)
#expect(policy.retryPrompt(for: .delimited, lostToken: token) == .delimiters)
#expect(policy.retryPrompt(for: .code, lostToken: token) == .delimiters)
}
}
@Suite("Repetition and numbers")
struct RepetitionAndNumberTests {
@Test func detectsARepeatedLine() {
let text = Array(repeating: "This is a repeated line.", count: 6).joined(separator: "\n")
#expect(RepetitionDetector.detectsLoop(in: text))
}
@Test func doesNotFlagOrdinaryText() {
#expect(!RepetitionDetector.detectsLoop(in: "This is an ordinary translation with no loop."))
}
@Test func detectsARepeatedWindow() {
let window = String(repeating: "a", count: 64)
#expect(RepetitionDetector.detectsLoop(in: String(repeating: window, count: 8)))
}
@Test func incrementalDetectorFiresWhileStreaming() {
var detector = RepetitionDetector()
var fired = false
for _ in 0 ..< 6 {
fired = detector.append("This is a repeated line.\n")
}
#expect(fired)
}
@Test func numericNormalisationTreatsLocaleSeparatorsAsEqual() {
#expect(NumericTokenNormalizer.normalize("1.5") == "1.5")
#expect(NumericTokenNormalizer.normalize("1,5") == "1.5")
#expect(NumericTokenNormalizer.normalize("1 000") == "1000")
#expect(NumericTokenNormalizer.normalize("1,234.56") == "1234.56")
#expect(NumericTokenNormalizer.normalize("1.234,56") == "1234.56")
}
}