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

+23 -7
View File
@@ -6,19 +6,35 @@ import SprachmittlerCore
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler")
private var environment: AppEnvironment?
func applicationDidFinishLaunching(_ notification: Notification) {
loggers.logger(.session).notice("Sprachmittler launched")
// Build AppEnvironment here (composition root): settings, Ollama services, session,
// double-copy watcher and panel controller. Start the watcher only after explicit consent.
//
// The Services provider is wired here once SprachmittlerCapture.ServicesProvider exists:
// NSApp.servicesProvider = servicesProvider
// NSUpdateDynamicServices()
let environment = AppEnvironment()
self.environment = environment
environment.start { [weak self] captured in
self?.handle(captured)
}
NSApp.servicesProvider = environment.servicesProvider
NSUpdateDynamicServices()
}
func applicationWillTerminate(_ notification: Notification) {
// Cancel in-flight translations, stop the pasteboard watcher and close the panel.
environment?.stop()
environment = nil
}
/// Menu-bar action: translate the current clipboard text.
func captureClipboardText() {
environment?.captureClipboardText()
}
private func handle(_ captured: CapturedText) {
// The M4 session will replace this log-only sink. Log counts and source only.
loggers.logger(.capture).notice(
"Captured \(captured.text.count) characters from \(captured.source.rawValue, privacy: .public)"
)
}
}
+77
View File
@@ -0,0 +1,77 @@
import Foundation
import SprachmittlerCapture
import SprachmittlerCore
/// The app composition root for capture. It owns the watcher, pasteboard and Services provider.
@MainActor
final class AppEnvironment {
let pasteboard: SystemPasteboard
let watcher: PasteboardWatcher
private var onCapture: ((CapturedText) -> Void)?
/// The most recent capture, kept in memory only for the M4 panel.
private(set) var lastCaptured: CapturedText?
/// The most recent capture rejection, for the M4 panel and diagnostics.
private(set) var lastCaptureFailure: CaptureValidation?
/// The Services provider, created lazily so it can capture `self` weakly.
lazy var servicesProvider = ServicesProvider { [weak self] captured in
Task { @MainActor in
self?.deliver(captured)
}
}
/// Creates the capture stack.
init() {
let pasteboard = SystemPasteboard()
self.pasteboard = pasteboard
watcher = PasteboardWatcher(pasteboard: pasteboard)
}
/// Starts the watcher and delivers every capture to `onCapture`.
func start(onCapture: @escaping (CapturedText) -> Void) {
self.onCapture = onCapture
watcher.start { [weak self] event in
self?.handle(event)
}
}
/// Stops the watcher and releases the in-memory text.
func stop() {
watcher.stop()
lastCaptured = nil
}
/// Reads the clipboard once for the menu-bar item.
func captureClipboardText() {
guard !pasteboard.containsOwnWriteMarkers(),
let text = pasteboard.string(),
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
return
}
deliver(CapturedText(text: text, capturedAt: Date(), source: .menu))
}
private func handle(_ event: PasteboardWatcherEvent) {
switch event {
case let .captured(captured):
deliver(captured)
case .textTooLong, .noText, .ignoredOwnWrite:
break
}
}
private func deliver(_ captured: CapturedText) {
switch CapturePolicy.validate(captured.text) {
case .valid:
lastCaptureFailure = nil
case let failure:
lastCaptureFailure = failure
return
}
lastCaptured = captured
onCapture?(captured)
}
}
+9 -9
View File
@@ -8,17 +8,17 @@ struct SprachmittlerApp: App {
var body: some Scene {
MenuBarExtra("Sprachmittler", systemImage: "translate") {
// Replaced by MenuBar/StatusMenu.swift.
Button("Translate Clipboard Text") {}
.disabled(true)
Divider()
Button("Set up Sprachmittler…") {}
.disabled(true)
SettingsLink {
Text("Settings…")
Button(String(localized: "Translate Clipboard Text")) {
(NSApp.delegate as? AppDelegate)?.captureClipboardText()
}
Divider()
Button("Quit Sprachmittler") {
Button(String(localized: "Set up Sprachmittler…")) {}
.disabled(true)
SettingsLink {
Text(String(localized: "Settings…"))
}
Divider()
Button(String(localized: "Quit Sprachmittler")) {
NSApplication.shared.terminate(nil)
}
.keyboardShortcut("q")
+7 -3
View File
@@ -50,7 +50,7 @@ let package = Package(
// Fakes shared by tests (FakePasteboard, FakeClock, FakeOllamaTransport, FakeTextInserter, …).
.target(
name: "SprachmittlerTestSupport",
dependencies: ["SprachmittlerCore", "SprachmittlerOllama"],
dependencies: ["SprachmittlerCore", "SprachmittlerCapture", "SprachmittlerOllama"],
swiftSettings: strictSettings
),
@@ -78,12 +78,15 @@ let package = Package(
),
.testTarget(
name: "SprachmittlerEnginesTests",
dependencies: ["SprachmittlerEngines"],
dependencies: ["SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText"],
resources: [.copy("Fixtures")]
),
.testTarget(
name: "SprachmittlerCoreTests",
dependencies: ["SprachmittlerCore", "SprachmittlerOllama", "SprachmittlerTestSupport"]
dependencies: [
"SprachmittlerCore", "SprachmittlerEngines", "SprachmittlerOllama", "SprachmittlerText",
"SprachmittlerTestSupport",
]
),
.testTarget(
name: "SprachmittlerCaptureTests",
@@ -97,6 +100,7 @@ let package = Package(
name: "SprachmittlerCLITests",
dependencies: [
"sprachmittler-cli",
"SprachmittlerCore",
"SprachmittlerEngines",
"SprachmittlerOllama",
"SprachmittlerTestSupport",
@@ -0,0 +1,26 @@
import Foundation
/// One pasteboard item's type-to-data map. The key is the raw pasteboard type.
public struct ClipboardItemData: Sendable, Equatable {
/// The item's data, keyed by pasteboard type.
public let data: [String: Data]
/// Creates an item snapshot.
public init(data: [String: Data]) {
self.data = data
}
}
/// A full pasteboard snapshot used only for the Replace paste fallback.
public struct ClipboardSnapshot: Sendable, Equatable {
/// Every item, in pasteboard order.
public let items: [ClipboardItemData]
/// The `changeCount` when the snapshot was taken.
public let changeCount: Int
/// Creates a snapshot.
public init(items: [ClipboardItemData], changeCount: Int) {
self.items = items
self.changeCount = changeCount
}
}
@@ -0,0 +1,82 @@
import Foundation
/// The double-copy state machine result (`docs/SELECTION_AND_CLIPBOARD.md` §2).
public enum DoubleCopyOutcome: Sendable, Equatable {
/// No trigger.
case none
/// A valid double copy; the value is normalised line endings and trimmed, internal whitespace kept.
case captured(String)
/// The change had no usable text; the state was reset.
case empty
}
/// The pure double-copy state machine. It has no pasteboard or timer dependency.
public struct DoubleCopyDetector: Sendable {
/// Detector configuration.
public struct Configuration: Sendable, Equatable {
/// The two-copy window; 500 ms by default (range 300–1000).
public let window: TimeInterval
/// Creates a configuration.
public init(window: TimeInterval = 0.5) {
self.window = window
}
}
private struct Candidate {
let changeCount: Int
let text: String
let date: Date
}
private let configuration: Configuration
private var candidate: Candidate?
/// Creates a detector.
public init(configuration: Configuration = Configuration()) {
self.configuration = configuration
}
/// Records one changed pasteboard value and returns the outcome.
public mutating func record(changeCount: Int, text: String?, at date: Date) -> DoubleCopyOutcome {
guard let text else {
candidate = nil
return .empty
}
let normalized = text
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard normalized.contains(where: { !$0.isWhitespace }) else {
candidate = nil
return .empty
}
if let candidate {
if candidate.changeCount == changeCount {
return .none
}
let elapsed = date.timeIntervalSince(candidate.date)
if candidate.text == normalized, elapsed >= 0, elapsed <= configuration.window {
self.candidate = nil
return .captured(normalized)
}
}
candidate = Candidate(changeCount: changeCount, text: normalized, date: date)
return .none
}
/// Forgets the remembered copy. Call when the session starts or the window expires.
public mutating func reset() {
candidate = nil
}
/// Clears the remembered copy once the two-copy window has passed, so no text is retained
/// longer than necessary.
public mutating func expire(at date: Date) {
guard let candidate, date.timeIntervalSince(candidate.date) > configuration.window else {
return
}
self.candidate = nil
}
}
@@ -0,0 +1,25 @@
import Foundation
/// The pasteboard operations `SprachmittlerCapture` needs. Tests use a fake; the app uses
/// `SystemPasteboard`. Every member is main-actor isolated because `NSPasteboard` is.
@MainActor
public protocol PasteboardAccessing: AnyObject {
/// The current pasteboard change count.
var changeCount: Int { get }
/// The plain-text string, read only after `changeCount` changed.
func string() -> String?
/// True when the pasteboard contains our own marker or a transient/concealed marker.
func containsOwnWriteMarkers() -> Bool
/// Snapshots every item and type, forcing lazy data.
func snapshot() -> ClipboardSnapshot?
/// Restores a snapshot only when `changeCount` still matches the recorded value.
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
/// Writes `text` with the own/transient/concealed markers and returns the new change count.
@discardableResult
func write(_ text: String) -> Int
}
@@ -0,0 +1,35 @@
import Foundation
/// A source of pasteboard poll ticks. Production uses a 120 ms timer; tests drive it manually.
public protocol PasteboardTicking: Sendable {
/// A stream of ticks. Cancelling the consuming task must terminate the stream.
func ticks() -> AsyncStream<Void>
}
/// The production 120 ms ticker (`docs/SELECTION_AND_CLIPBOARD.md` §2).
public struct TimerPasteboardTicker: PasteboardTicking {
/// The poll interval.
public let interval: Duration
/// Creates a ticker.
public init(interval: Duration = .milliseconds(120)) {
self.interval = interval
}
public func ticks() -> AsyncStream<Void> {
AsyncStream { continuation in
let task = Task {
while !Task.isCancelled {
do {
try await Task.sleep(for: interval)
} catch {
break
}
continuation.yield(())
}
continuation.finish()
}
continuation.onTermination = { _ in task.cancel() }
}
}
}
@@ -0,0 +1,125 @@
import Foundation
import SprachmittlerCore
/// A pasteboard watcher event.
public enum PasteboardWatcherEvent: Sendable, Equatable {
/// A validated double copy.
case captured(CapturedText)
/// The copied text is above the script-aware limit.
case textTooLong(characters: Int, limit: Int)
/// The change had no usable text.
case noText
/// A change was our own write or the marker/suppression window.
case ignoredOwnWrite
}
/// Polls `changeCount`, reads the string only after a change, and emits double copies.
///
/// This type never reads the pasteboard in the background: `poll` first compares `changeCount`
/// and only then reads the string.
@MainActor
public final class PasteboardWatcher {
/// The own-write suppression window.
public static let suppressionWindow: TimeInterval = 0.75
private let pasteboard: any PasteboardAccessing
private let ticker: any PasteboardTicking
private let now: @MainActor () -> Date
private var detector: DoubleCopyDetector
private var lastChangeCount: Int
private var suppressUntil = Date.distantPast
private var task: Task<Void, Never>?
/// True while the poll task is running.
public private(set) var isRunning = false
/// Creates a watcher. The initial change count is recorded without reading any string.
public init(
pasteboard: any PasteboardAccessing,
configuration: DoubleCopyDetector.Configuration = DoubleCopyDetector.Configuration(),
ticker: any PasteboardTicking = TimerPasteboardTicker(),
now: @escaping @MainActor () -> Date = { Date() }
) {
self.pasteboard = pasteboard
detector = DoubleCopyDetector(configuration: configuration)
self.ticker = ticker
self.now = now
lastChangeCount = pasteboard.changeCount
}
/// Starts polling. Calling it twice is a no-op.
public func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void) {
guard task == nil else { return }
lastChangeCount = pasteboard.changeCount
detector.reset()
isRunning = true
let ticker = ticker
task = Task { [weak self] in
for await _ in ticker.ticks() {
guard let self else { break }
if let event = poll(at: now()) {
onEvent(event)
}
}
}
}
/// Stops polling and releases the in-memory copies.
public func stop() {
task?.cancel()
task = nil
isRunning = false
detector.reset()
}
/// Polls once. Public so component tests can avoid real time.
@discardableResult
public func poll(at date: Date) -> PasteboardWatcherEvent? {
let count = pasteboard.changeCount
guard count != lastChangeCount else {
detector.expire(at: date)
return nil
}
lastChangeCount = count
if date < suppressUntil {
return .ignoredOwnWrite
}
if pasteboard.containsOwnWriteMarkers() {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
return .ignoredOwnWrite
}
guard let string = pasteboard.string() else {
detector.reset()
return .noText
}
switch detector.record(changeCount: count, text: string, at: date) {
case .none:
return nil
case .empty:
return .noText
case let .captured(text):
let limit = CaptureLimits.characters(for: text)
guard text.count <= limit else {
detector.reset()
return .textTooLong(characters: text.count, limit: limit)
}
detector.reset()
return .captured(CapturedText(text: text, capturedAt: date, source: .doubleCopy))
}
}
/// Marks a clipboard write by this app so the watcher suppresses it and the next changes.
public func noteOwnWrite(at date: Date) {
suppressUntil = date.addingTimeInterval(Self.suppressionWindow)
detector.reset()
}
/// Clears the remembered copy without stopping the watcher.
public func clear() {
detector.reset()
}
}
@@ -0,0 +1,41 @@
import AppKit
import Foundation
import SprachmittlerCore
/// The Services entry point (`docs/SELECTION_AND_CLIPBOARD.md` §6).
///
/// The system supplies the pasteboard, so this path needs no Accessibility permission and no
/// polling. `AppDelegate` installs this object as `NSApp.servicesProvider`.
///
/// `@unchecked Sendable` is safe: the only stored value is an immutable `@Sendable` closure, and
/// AppKit invokes the selector on the main thread.
public final class ServicesProvider: NSObject, @unchecked Sendable {
/// The captured-text handler. The app hops to the main actor itself.
public typealias Handler = @Sendable (CapturedText) -> Void
private let handler: Handler
/// Creates a provider.
public init(handler: @escaping Handler) {
self.handler = handler
super.init()
}
/// The `NSMessage = translateSelection` selector from Info.plist.
@objc
@MainActor
public func translateSelection(
_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
guard !SystemPasteboard.containsOwnWriteMarkers(in: pasteboard),
let text = pasteboard.string(forType: .string),
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
error.pointee = "No text was selected." as NSString
return
}
handler(CapturedText(text: text, capturedAt: Date(), source: .services))
}
}
@@ -0,0 +1,78 @@
import AppKit
import Foundation
/// The production pasteboard adapter. This is the only type that touches `NSPasteboard.general`.
@MainActor
public final class SystemPasteboard: PasteboardAccessing {
private nonisolated static let ownType = NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
private nonisolated static let transientType = NSPasteboard.PasteboardType("org.nspasteboard.TransientType")
private nonisolated static let concealedType = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
private let pasteboard: NSPasteboard
/// Creates an adapter for the general pasteboard.
public init(pasteboard: NSPasteboard = .general) {
self.pasteboard = pasteboard
}
public var changeCount: Int {
pasteboard.changeCount
}
public func string() -> String? {
pasteboard.string(forType: .string)
}
public func containsOwnWriteMarkers() -> Bool {
Self.containsOwnWriteMarkers(in: pasteboard)
}
/// True when a pasteboard carries our own or a transient/concealed marker.
public nonisolated static func containsOwnWriteMarkers(in pasteboard: NSPasteboard) -> Bool {
let types = pasteboard.types ?? []
return types.contains(ownType)
|| types.contains(transientType)
|| types.contains(concealedType)
}
public func snapshot() -> ClipboardSnapshot? {
let items = pasteboard.pasteboardItems ?? []
let snapshots = items.map { item -> ClipboardItemData in
var data: [String: Data] = [:]
for type in item.types {
// `data(forType:)` forces lazy providers now; an unresolved provider is skipped.
if let value = item.data(forType: type) {
data[type.rawValue] = value
}
}
return ClipboardItemData(data: data)
}
return ClipboardSnapshot(items: snapshots, changeCount: pasteboard.changeCount)
}
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
guard pasteboard.changeCount == expected else { return false }
pasteboard.clearContents()
guard !snapshot.items.isEmpty else { return true }
let items = snapshot.items.map { snapshotItem -> NSPasteboardItem in
let item = NSPasteboardItem()
for (type, data) in snapshotItem.data {
item.setData(data, forType: NSPasteboard.PasteboardType(type))
}
return item
}
return pasteboard.writeObjects(items)
}
@discardableResult
public func write(_ text: String) -> Int {
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
let marker = Data()
pasteboard.setData(marker, forType: Self.ownType)
pasteboard.setData(marker, forType: Self.transientType)
pasteboard.setData(marker, forType: Self.concealedType)
return pasteboard.changeCount
}
}
@@ -0,0 +1,9 @@
import SprachmittlerText
/// The capture character limit for a text, based on its script (`docs/TRANSLATION_OUTPUT.md` §3).
public enum CaptureLimits {
/// 4000 characters for Latin/Cyrillic/Greek, 2000 for dense scripts.
public static func characters(for text: String) -> Int {
Chunker().limit(for: text)
}
}
@@ -0,0 +1,25 @@
import SprachmittlerText
/// The result of validating a captured text before any translation request.
public enum CaptureValidation: Sendable, Equatable {
/// The text may be translated.
case valid
/// The text has no non-whitespace character.
case empty
/// The text exceeds the script-aware limit.
case textTooLong(characters: Int, limit: Int)
}
/// Applies the capture rules shared by double copy, the menu and Services.
public enum CapturePolicy {
/// Validates non-emptiness and the 4000/2000 script-aware limit.
public static func validate(_ text: String) -> CaptureValidation {
guard text.contains(where: { !$0.isWhitespace }) else { return .empty }
let limit = CaptureLimits.characters(for: text)
let characters = text.count
guard characters <= limit else {
return .textTooLong(characters: characters, limit: limit)
}
return .valid
}
}
@@ -0,0 +1,10 @@
import SprachmittlerText
/// Capture-side text helpers. Kept in Core so `SprachmittlerCapture` never imports the text
/// module directly (ARCHITECTURE §4).
public enum CaptureText {
/// Double-copy comparison: line endings and outer trimming only.
public static func normalizeForComparison(_ text: String) -> String {
TextNormalization.normalizeForComparison(text)
}
}
@@ -0,0 +1,28 @@
import Foundation
/// Where a captured text came from (`docs/ARCHITECTURE.md` §5).
public enum CaptureSource: String, Sendable, Codable, Equatable {
/// The double-copy gesture.
case doubleCopy
/// The Services menu.
case services
/// The menu-bar item.
case menu
}
/// A non-empty text captured for translation.
public struct CapturedText: Sendable, Equatable {
/// The captured text.
public let text: String
/// When it was captured.
public let capturedAt: Date
/// Where it came from.
public let source: CaptureSource
/// Creates a captured text.
public init(text: String, capturedAt: Date, source: CaptureSource) {
self.text = text
self.capturedAt = capturedAt
self.source = source
}
}
@@ -0,0 +1,40 @@
import Foundation
import SprachmittlerText
/// The target of a Replace action (`docs/SELECTION_AND_CLIPBOARD.md` §4).
public struct InsertionTarget: Sendable, Equatable {
/// The process that owned the selection.
public let pid: pid_t
/// The bundle identifier, when available.
public let bundleID: String?
/// The selected text at capture time, when available.
public let selectedText: String?
/// When the target was captured.
public let capturedAt: Date
/// Creates an insertion target.
public init(pid: pid_t, bundleID: String?, selectedText: String?, capturedAt: Date) {
self.pid = pid
self.bundleID = bundleID
self.selectedText = selectedText
self.capturedAt = capturedAt
}
}
/// How a Replace action succeeded.
public enum InsertionMethod: String, Sendable, Equatable {
/// Accessibility direct replacement.
case accessibility
/// Synthetic paste.
case paste
}
/// The outcome of a Replace action.
public enum InsertionOutcome: Sendable, Equatable {
/// The selection was replaced.
case replaced(using: InsertionMethod)
/// Nothing was inserted; the translation is on the clipboard.
case copiedOnly
/// The insertion failed.
case failed(SprachmittlerError)
}
@@ -0,0 +1,8 @@
import SprachmittlerEngines
/// A BCP-47 language code. Codes are stored as their canonical string form.
public typealias LanguageCode = String
/// The UI-facing name for a target language. The value type lives in `SprachmittlerEngines` because
/// it carries the exact model-card name used by prompts (ADR-014, ADR-017).
public typealias TargetLanguage = SprachmittlerEngines.ModelLanguage
@@ -0,0 +1,322 @@
import Foundation
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
/// Timing for one completed translation (`docs/ARCHITECTURE.md` §5).
public struct TranslationTiming: Sendable, Equatable {
/// Time to the first delta, when one arrived.
public let firstTokenMs: Int?
/// Total time.
public let totalMs: Int
/// Prompt tokens reported by Ollama, summed over attempts.
public let promptTokens: Int?
/// Output tokens reported by Ollama, summed over attempts.
public let outputTokens: Int?
/// Creates a timing value.
public init(firstTokenMs: Int?, totalMs: Int, promptTokens: Int?, outputTokens: Int?) {
self.firstTokenMs = firstTokenMs
self.totalMs = totalMs
self.promptTokens = promptTokens
self.outputTokens = outputTokens
}
}
/// The result of the documented translation pipeline.
public struct PipelineResult: Sendable, Equatable {
/// The translation after T1 only.
public let translation: String
/// Validation warnings and guard findings from the output validator.
public let warnings: [TranslationWarning]
/// The advisory source language, when detection succeeded.
public let sourceLanguage: String?
/// Timing counters.
public let timing: TranslationTiming
/// How many chunks were translated.
public let chunkCount: Int
/// Creates a result.
public init(
translation: String,
warnings: [TranslationWarning],
sourceLanguage: String?,
timing: TranslationTiming,
chunkCount: Int
) {
self.translation = translation
self.warnings = warnings
self.sourceLanguage = sourceLanguage
self.timing = timing
self.chunkCount = chunkCount
}
}
/// Translates text with the documented prompt, chunking and validation.
///
/// This type is shared by the CLI and the M4 session. It never edits the model output beyond T1
/// and it retries only once, only when a protected token was lost.
public struct TranslationPipeline: Sendable {
private let chat: any OllamaChatting
private let registry: AdapterRegistry
private let detector: any LanguageDetecting
private let chunker: Chunker
private let scanner: ProtectedTokenScanner
private let validator: OutputValidator
private let policy: PromptPolicy
private let clock: @Sendable () -> Date
/// Creates a pipeline. Concrete clients come from the composition root.
public init(
chat: any OllamaChatting,
registry: AdapterRegistry,
detector: any LanguageDetecting = NaturalLanguageDetector(),
chunker: Chunker = Chunker(),
scanner: ProtectedTokenScanner = ProtectedTokenScanner(),
validator: OutputValidator = OutputValidator(),
policy: PromptPolicy = PromptPolicy(),
clock: @escaping @Sendable () -> Date = { Date() }
) {
self.chat = chat
self.registry = registry
self.detector = detector
self.chunker = chunker
self.scanner = scanner
self.validator = validator
self.policy = policy
self.clock = clock
}
/// Translates `text` into `target` with `model`.
public func translate(
text: String,
target: ModelLanguage,
model: String,
keepAlive: String
) async throws -> PipelineResult {
let normalized = TextNormalization.normalizeInput(text)
guard !normalized.isEmpty else {
throw SprachmittlerError.emptyText
}
guard registry.adapter(for: model) != nil else {
throw SprachmittlerError.noAdapter(model: model)
}
let started = clock()
let detection = detector.detect(normalized)
let content = ContentClassifier(scanner: scanner).classify(normalized)
let tokens = scanner.scan(normalized)
let chunks = chunker.chunks(for: normalized)
let context = TranslationContext(
content: content,
target: target,
model: model,
keepAlive: keepAlive,
tokens: tokens
)
let accumulator = try await translateAll(chunks, context: context)
let final = TextNormalization.normalizeOutput(accumulator.joined)
let validation = validator.validate(
source: normalized,
translation: final,
doneReason: accumulator.sawLength ? "length" : nil,
tokens: tokens
)
var warnings = accumulator.warnings
warnings.append(contentsOf: validation.warnings)
if let detection, LanguageMatching.isSameLanguage(detection, target: target) {
warnings.append(.sameLanguage(source: detection.code, target: target.code))
}
let elapsed = max(0, Int(clock().timeIntervalSince(started) * 1000))
let firstTokenMs = accumulator.firstTokenAt.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
return PipelineResult(
translation: final,
warnings: deduplicated(warnings),
sourceLanguage: detection?.code,
timing: TranslationTiming(
firstTokenMs: firstTokenMs,
totalMs: elapsed,
promptTokens: accumulator.promptTokens,
outputTokens: accumulator.outputTokens
),
chunkCount: chunks.count
)
}
private struct TranslationContext {
let content: ContentClass
let target: ModelLanguage
let model: String
let keepAlive: String
let tokens: [ProtectedToken]
}
private struct Accumulator {
var firstTokenAt: Date?
var promptTokens: Int?
var outputTokens: Int?
var joined = ""
var warnings: [TranslationWarning] = []
var sawLength = false
}
private func translateAll(_ chunks: [TextChunk], context: TranslationContext) async throws -> Accumulator {
var accumulator = Accumulator()
do {
for chunk in chunks {
try Task.checkCancellation()
let result = try await translateChunk(chunk, context: context)
if accumulator.firstTokenAt == nil {
accumulator.firstTokenAt = result.firstTokenAt
}
accumulator.promptTokens = sum(accumulator.promptTokens, result.promptTokens)
accumulator.outputTokens = sum(accumulator.outputTokens, result.outputTokens)
if result.looped {
accumulator.warnings.append(.repetitionLoop)
}
if result.doneReason == "length" {
accumulator.sawLength = true
}
accumulator.joined += result.text + chunk.separatorAfter
}
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return accumulator
}
private struct ChunkTranslation {
let text: String
let doneReason: String?
let looped: Bool
let firstTokenAt: Date?
let promptTokens: Int?
let outputTokens: Int?
}
private func translateChunk(
_ chunk: TextChunk,
context: TranslationContext
) async throws -> ChunkTranslation {
let chunkTokens = context.tokens.filter { chunk.text.contains($0.value) }
var prompt = policy.initialPrompt(for: context.content)
var retried = false
var response = StreamResult(
text: "",
doneReason: nil,
metrics: .empty,
firstTokenAt: nil,
looped: false
)
var promptTokens: Int?
var outputTokens: Int?
while true {
let request = try registry.makeRequest(
AdapterRequest(
text: chunk.text,
target: context.target,
model: context.model,
keepAlive: context.keepAlive,
prompt: prompt
)
)
let attempt = try await stream(request)
response = attempt
promptTokens = sum(promptTokens, attempt.metrics.promptEvalCount)
outputTokens = sum(outputTokens, attempt.metrics.evalCount)
let translated = TextNormalization.normalizeOutput(attempt.text)
let missing = validator.missingTokens(
source: chunk.text,
translation: translated,
tokens: chunkTokens
)
let retryPrompt = missing.isEmpty
? nil
: policy.retryPrompt(for: context.content, lostToken: missing[0])
if !retried, let retryPrompt {
retried = true
prompt = retryPrompt
continue
}
break
}
return ChunkTranslation(
text: TextNormalization.normalizeOutput(response.text),
doneReason: response.doneReason,
looped: response.looped,
firstTokenAt: response.firstTokenAt,
promptTokens: promptTokens,
outputTokens: outputTokens
)
}
private struct StreamResult {
let text: String
let doneReason: String?
let metrics: ChatMetrics
let firstTokenAt: Date?
let looped: Bool
}
private func stream(_ request: ChatRequest) async throws -> StreamResult {
var text = ""
var doneReason: String?
var metrics = ChatMetrics.empty
var firstTokenAt: Date?
var repetition = RepetitionDetector()
var looped = false
do {
for try await event in chat.chat(request) {
try Task.checkCancellation()
switch event {
case let .delta(delta):
if firstTokenAt == nil {
firstTokenAt = clock()
}
text += delta
if repetition.append(delta) {
looped = true
}
case let .done(reason, doneMetrics):
doneReason = reason
metrics = doneMetrics
}
if looped {
break
}
}
} catch let error as OllamaError {
throw SprachmittlerError(ollama: error)
} catch is CancellationError {
throw SprachmittlerError.cancelled
}
return StreamResult(
text: text,
doneReason: doneReason,
metrics: metrics,
firstTokenAt: firstTokenAt,
looped: looped
)
}
private func sum(_ current: Int?, _ next: Int?) -> Int? {
switch (current, next) {
case let (current?, next?): current + next
case let (current?, nil): current
case let (nil, next?): next
case (nil, nil): nil
}
}
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
var seen = Set<TranslationWarning>()
return warnings.filter { seen.insert($0).inserted }
}
}
@@ -0,0 +1,5 @@
import SprachmittlerEngines
/// Validation warnings are defined in `SprachmittlerEngines`, where validation lives, and
/// re-exported here for the session and UI layers.
public typealias TranslationWarning = SprachmittlerEngines.TranslationWarning
@@ -0,0 +1,52 @@
import SprachmittlerOllama
/// The Hy-MT3 adapter: exact documented prompt, publisher sampling, no system message, no
/// thinking and an explicit 8192-token context (`docs/HYMT3_MODEL.md` §1–§3).
public struct HyMT3Adapter: TranslationAdapter {
/// The stable adapter identifier.
public let identifier = "hy-mt3"
/// The adapter version.
public let version = 1
/// Creates the adapter.
public init() {}
/// Matches every Hy-MT3 tag, including 7B, 1.8B and 30B-A3B conversions.
public func supports(model: String) -> Bool {
HyMT3ModelPreset.isHyMT3(model)
}
/// Builds one documented request. There is exactly one user message and no system message.
public func makeRequest(_ request: AdapterRequest) -> ChatRequest {
let content = HyMT3Prompt.text(for: request.prompt, target: request.target, source: request.text)
return ChatRequest(
model: request.model,
messages: [ChatMessage(content: content)],
stream: true,
keepAlive: request.keepAlive,
options: request.sampling.chatOptions()
)
}
/// A warm-up request with fixed synthetic text and `num_predict: 8` (T1.5).
public func warmUpRequest(model: String, keepAlive: String) -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: keepAlive,
options: HyMT3Options.warmUp
)
}
/// A request that unloads the model after it completes.
public func unloadRequest(model: String) -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: "0",
options: HyMT3Options.warmUp
)
}
}
@@ -1,34 +1,202 @@
/// The provisional common-language table for the M1 CLI. T2.3 replaces this with the complete
/// 102-language catalogue from docs/LANGUAGES.md.
import Foundation
/// The complete Hy-MT3 language catalogue from `docs/LANGUAGES.md`.
///
/// `modelName` is the exact English name from the model card and is the only value that may enter
/// a prompt. BCP-47 variants collapse to the canonical entry; unknown codes return nil.
public enum HyMT3Languages {
/// English.
public static let english = ModelLanguage(code: "en", modelName: "English")
public static let english = lang("en", "English")
/// German.
public static let german = ModelLanguage(code: "de", modelName: "German")
public static let german = lang("de", "German")
/// The common targets exposed by the M1 CLI.
/// All 102 supported languages, in the documentation's order.
public static let all: [ModelLanguage] = [
// Supported since Hy-MT2 (33)
lang("zh", "Chinese", display: "Chinese (Simplified)", dense: true),
english,
lang("fr", "French"),
lang("pt", "Portuguese"),
lang("es", "Spanish"),
lang("ja", "Japanese", dense: true),
lang("tr", "Turkish"),
lang("ru", "Russian"),
lang("ar", "Arabic", rtl: true, dense: true),
lang("ko", "Korean", dense: true),
lang("th", "Thai", dense: true),
lang("it", "Italian"),
german,
ModelLanguage(code: "fr", modelName: "French"),
ModelLanguage(code: "es", modelName: "Spanish"),
ModelLanguage(code: "it", modelName: "Italian"),
ModelLanguage(code: "pt", modelName: "Portuguese"),
ModelLanguage(code: "nl", modelName: "Dutch"),
ModelLanguage(code: "pl", modelName: "Polish"),
ModelLanguage(code: "zh", modelName: "Chinese"),
ModelLanguage(code: "zh-Hant", modelName: "Traditional Chinese"),
ModelLanguage(code: "ja", modelName: "Japanese"),
ModelLanguage(code: "ko", modelName: "Korean"),
ModelLanguage(code: "ar", modelName: "Arabic"),
ModelLanguage(code: "tr", modelName: "Turkish"),
ModelLanguage(code: "ru", modelName: "Russian"),
ModelLanguage(code: "uk", modelName: "Ukrainian"),
lang("vi", "Vietnamese"),
lang("ms", "Malay"),
lang("id", "Indonesian"),
lang("tl", "Filipino"),
lang("hi", "Hindi", dense: true),
lang("zh-Hant", "Traditional Chinese", dense: true),
lang("pl", "Polish"),
lang("cs", "Czech"),
lang("nl", "Dutch"),
lang("km", "Khmer", dense: true),
lang("my", "Burmese", dense: true),
lang("fa", "Persian", rtl: true, dense: true),
lang("gu", "Gujarati", dense: true),
lang("ur", "Urdu", rtl: true, dense: true),
lang("te", "Telugu", dense: true),
lang("mr", "Marathi", dense: true),
lang("he", "Hebrew", rtl: true, dense: true),
lang("bn", "Bengali", dense: true),
lang("ta", "Tamil", dense: true),
lang("uk", "Ukrainian"),
// Chinese minority languages and dialects (5)
lang("bo", "Tibetan", dense: true),
lang("mn", "Traditional Mongolian", dense: true),
lang("yue", "Cantonese", dense: true),
lang("kk", "Arabic Kazakh", rtl: true, dense: true),
lang("ug", "Uyghur", rtl: true, dense: true),
// Newly supported in Hy-MT3 (64)
lang("el", "Greek"),
lang("cy", "Welsh"),
lang("si", "Sinhala", dense: true),
lang("ro", "Romanian"),
lang("ca", "Catalan"),
lang("pa", "Punjabi", dense: true),
lang("hu", "Hungarian"),
lang("gl", "Galician"),
lang("sd", "Sindhi", rtl: true, dense: true),
lang("bg", "Bulgarian"),
lang("eu", "Basque"),
lang("as", "Assamese", dense: true),
lang("sr", "Serbian"),
lang("af", "Afrikaans"),
lang("or", "Odia", dense: true),
lang("hr", "Croatian"),
lang("lb", "Luxembourgish"),
lang("kn", "Kannada", dense: true),
lang("sk", "Slovak"),
lang("mt", "Maltese"),
lang("ml", "Malayalam", dense: true),
lang("sl", "Slovenian"),
lang("eo", "Esperanto"),
lang("sa", "Sanskrit", dense: true),
lang("sq", "Albanian"),
lang("yi", "Yiddish", rtl: true, dense: true),
lang("lo", "Lao", dense: true),
lang("mk", "Macedonian"),
lang("hy", "Armenian"),
lang("jv", "Javanese"),
lang("be", "Belarusian"),
lang("ka", "Georgian"),
lang("su", "Sundanese"),
lang("lt", "Lithuanian"),
lang("az", "Azerbaijani"),
lang("ceb", "Cebuano"),
lang("lv", "Latvian"),
lang("uz", "Uzbek"),
lang("war", "Waray"),
lang("et", "Estonian"),
lang("ky", "Kyrgyz"),
lang("sw", "Swahili"),
lang("fi", "Finnish"),
lang("tk", "Turkmen"),
lang("am", "Amharic", dense: true),
lang("sv", "Swedish"),
lang("tg", "Tajik"),
lang("so", "Somali"),
lang("da", "Danish"),
lang("tt", "Tatar"),
lang("mg", "Malagasy"),
lang("nb", "Norwegian"),
lang("ba", "Bashkir"),
lang("ht", "Haitian Creole"),
lang("nn", "Norwegian Nynorsk"),
lang("ku", "Kurdish"),
lang("kk-Cyrl", "Cyrillic Kazakh"),
lang("is", "Icelandic"),
lang("ckb", "Central Kurdish", rtl: true, dense: true),
lang("mn-Cyrl", "Cyrillic Mongolian"),
lang("ga", "Irish"),
lang("ps", "Pashto", rtl: true, dense: true),
lang("gd", "Scottish Gaelic"),
lang("ne", "Nepali", dense: true),
]
/// Resolves a BCP-47 code case-insensitively; unknown codes return nil (never a guess).
/// The 15 common targets from `docs/LANGUAGES.md` §5, in display order.
public static let common: [ModelLanguage] = [
"en", "de", "fr", "es", "it", "pt", "nl", "pl", "zh", "ja", "ko", "ar", "tr", "ru", "uk",
].compactMap { byCode[$0] }
/// The number of catalogue entries; the model card documents 102.
public static var count: Int {
all.count
}
private static let byCode: [String: ModelLanguage] = Dictionary(
all.map { ($0.code.lowercased(), $0) },
uniquingKeysWith: { first, _ in first }
)
private static let aliases: [String: String] = [
"zh-hans": "zh", "zh-cn": "zh", "zh-sg": "zh",
"zh-tw": "zh-Hant", "zh-hk": "zh-Hant", "zh-tr": "zh-Hant",
"pt-br": "pt", "pt-pt": "pt",
"no": "nb", "fil": "tl", "iw": "he", "in": "id",
"kk-kz": "kk-Cyrl",
]
/// Resolves a BCP-47 code case-insensitively. Variants collapse to the canonical entry;
/// unknown codes return nil and are never guessed (`docs/LANGUAGES.md` §4).
public static func resolve(_ code: String) -> ModelLanguage? {
let normalized = code.lowercased()
return all.first { $0.code.lowercased() == normalized }
let normalized = code
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "_", with: "-")
.lowercased()
guard !normalized.isEmpty else { return nil }
if let exact = byCode[normalized] {
return exact
}
if let alias = aliases[normalized], let language = byCode[alias.lowercased()] {
return language
}
if normalized.hasPrefix("zh-hant") {
return byCode["zh-hant"]
}
if normalized.hasPrefix("zh") {
return byCode["zh"]
}
if normalized.hasPrefix("kk-cyrl") {
return byCode["kk-cyrl"]
}
if normalized.hasPrefix("mn-cyrl") {
return byCode["mn-cyrl"]
}
if let separator = normalized.firstIndex(of: "-") {
let base = String(normalized[..<separator])
return byCode[base]
}
return nil
}
/// All right-to-left languages.
public static var rightToLeft: [ModelLanguage] {
all.filter(\.isRTL)
}
private static func lang(
_ code: String,
_ modelName: String,
display: String? = nil,
rtl: Bool = false,
dense: Bool = false
) -> ModelLanguage {
ModelLanguage(
code: code,
modelName: modelName,
displayName: display,
isRTL: rtl,
usesDenseScript: dense
)
}
}
@@ -9,4 +9,9 @@ public enum HyMT3ModelPreset {
public static let defaultKeepAlive = "30m"
/// The only text used for warm-up. Never user text.
public static let warmUpText = "Hello."
/// True for any Hy-MT3 conversion tag. The registry uses this through `HyMT3Adapter`.
public static func isHyMT3(_ model: String) -> Bool {
model.lowercased().contains("hy-mt3")
}
}
@@ -1,25 +1,10 @@
import SprachmittlerOllama
/// The documented Hy-MT3 sampling values from docs/HYMT3_MODEL.md §2.
/// Documented Hy-MT3 option sets (`docs/HYMT3_MODEL.md` §2).
public enum HyMT3Options {
/// Translation defaults: temperature 0.7, top_p 0.6, top_k 20, repeat_penalty 1.05,
/// num_predict 4096, num_ctx 8192.
public static let translation = ChatOptions(
temperature: 0.7,
topP: 0.6,
topK: 20,
repeatPenalty: 1.05,
numPredict: 4096,
numCtx: 8192
)
/// Warm-up uses the same model settings but only 8 output tokens.
public static let warmUp = ChatOptions(
temperature: 0.7,
topP: 0.6,
topK: 20,
repeatPenalty: 1.05,
numPredict: 8,
numCtx: 8192
)
/// Warm-up uses the publisher sampling but only 8 output tokens. The publisher values come
/// from `SamplingOptions`, so there is one source of truth.
public static let warmUp = SamplingOptions.publisherDefault
.merging(SamplingOverrides(numPredict: 8))
.chatOptions()
}
@@ -1,6 +1,9 @@
/// The documented Hy-MT3 prompt templates. v1 uses the Default Translation template.
/// The documented Hy-MT3 prompt templates (`docs/HYMT3_MODEL.md` §3–§4).
///
/// These are the only prompt strings in the app. The Default template is canonical for v1; the
/// Delimiters and Structured Data 1 templates are the only documented fallbacks (ADR-012).
public enum HyMT3Prompt {
/// The byte-exact Default Translation prompt from docs/HYMT3_MODEL.md §3.
/// The byte-exact Default Translation prompt from `docs/HYMT3_MODEL.md` §3.
///
/// The prefix depends only on the target language; the source text is appended last so the
/// Ollama prompt cache stays valid.
@@ -9,4 +12,50 @@ public enum HyMT3Prompt {
+ "Note that you should **only output the translated result without any additional explanation**:"
return prefix + "\n\n" + source
}
/// The byte-exact Delimiters prompt, the single documented fallback for a lost token.
public static func delimiters(target: ModelLanguage, source: String) -> String {
let instruction = "Please accurately translate the following text into \(target.modelName). "
+ "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**."
return instruction + "\n\n" + source
}
/// The byte-exact Structured Data 1 prompt for JSON, HTML or Markdown.
public static func structuredData1(
format: StructuredFormat,
target: ModelLanguage,
source: String
) -> String {
let type = format.rawValue
let preservation = "1. **Structure Preservation:** You MUST preserve the original \(type) data "
+ "structure, nesting, hierarchy, and indentation exactly as they are."
let nonTranslation = "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."
return [
"### Task",
"Translate the user-facing text within the following \(type) data into \(target.modelName).",
"",
"### Strict Rules",
preservation,
"2. **Selective Translation:** Translate ONLY the visible, user-facing text content/values.",
nonTranslation,
"",
"### Source Data",
source,
].joined(separator: "\n")
}
/// Builds the prompt for a variant.
public static func text(for variant: PromptVariant, target: ModelLanguage, source: String) -> String {
switch variant {
case .defaultTranslation:
defaultTranslation(target: target, source: source)
case .delimiters:
delimiters(target: target, source: source)
case let .structuredData1(format):
structuredData1(format: format, target: target, source: source)
}
}
}
@@ -1,52 +0,0 @@
import SprachmittlerOllama
/// Builds the documented Hy-MT3 requests. T2.1/T2.2 replace this with the adapter protocol;
/// until then this is the only place the translation request shape is assembled.
public struct HyMT3RequestFactory: Sendable {
/// The model tag.
public let model: String
/// The Ollama `keep_alive` value.
public let keepAlive: String
/// Creates a factory.
public init(
model: String = HyMT3ModelPreset.defaultModel,
keepAlive: String = HyMT3ModelPreset.defaultKeepAlive
) {
self.model = model
self.keepAlive = keepAlive
}
/// A translation request with the documented prompt and sampling.
public func translationRequest(text: String, target: ModelLanguage) -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3Prompt.defaultTranslation(target: target, source: text))],
stream: true,
keepAlive: keepAlive,
options: HyMT3Options.translation
)
}
/// A warm-up request with fixed synthetic text and `num_predict: 8`.
public func warmUpRequest() -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: keepAlive,
options: HyMT3Options.warmUp
)
}
/// A request that unloads the model after it completes.
public func unloadRequest() -> ChatRequest {
ChatRequest(
model: model,
messages: [ChatMessage(content: HyMT3ModelPreset.warmUpText)],
stream: true,
keepAlive: "0",
options: HyMT3Options.warmUp
)
}
}
@@ -0,0 +1,21 @@
import SprachmittlerText
/// Family-neutral same-language check used by the pipeline. The canonical-code mapping stays in
/// Engines, next to the catalogue that defines it.
public enum LanguageMatching {
/// True when detection is confident and every alternative resolves to the target language.
public static func isSameLanguage(_ detection: LanguageDetection, target: ModelLanguage) -> Bool {
guard detection.confidence >= 0.5, !detection.alternatives.isEmpty else { return false }
let targetCode = HyMT3Languages.resolve(target.code)?.code ?? target.code
var agreed = false
for code in detection.alternatives {
guard let language = HyMT3Languages.resolve(code),
language.code.caseInsensitiveCompare(targetCode) == .orderedSame
else {
return false
}
agreed = true
}
return agreed
}
}
@@ -1,13 +1,48 @@
import Foundation
/// A BCP-47 code paired with the exact English model-card name used in the prompt.
public struct ModelLanguage: Sendable, Hashable, Codable {
/// The BCP-47 code, e.g. `de` or `zh-Hant`.
///
/// `modelName` is never localised: it is inserted into the prompt byte for byte
/// (`docs/LANGUAGES.md` §4). Use `localizedDisplayName` for UI labels.
public struct ModelLanguage: Sendable, Hashable, Codable, Identifiable {
/// The canonical BCP-47 code, e.g. `de`, `zh-Hant` or `kk-Cyrl`.
public let code: String
/// The exact model-card name, e.g. `German` or `Traditional Chinese`.
public let modelName: String
/// The English display name, used as a fallback when `Locale` has no localised name.
public let displayName: String
/// True for right-to-left scripts.
public let isRTL: Bool
/// True for scripts that use the smaller chunk limit.
public let usesDenseScript: Bool
/// Creates a language pair.
public init(code: String, modelName: String) {
/// `Identifiable` conformance for UI lists.
public var id: String {
code
}
/// The display name in the current UI locale, never used in a prompt. When the locale only
/// has a generic name (for example “Chinese”), the catalogue's more specific name wins.
public var localizedDisplayName: String {
let localized = Locale.current.localizedString(forLanguageCode: code)
if let localized, localized.caseInsensitiveCompare(modelName) != .orderedSame {
return localized
}
return displayName
}
/// Creates a language entry.
public init(
code: String,
modelName: String,
displayName: String? = nil,
isRTL: Bool = false,
usesDenseScript: Bool = false
) {
self.code = code
self.modelName = modelName
self.displayName = displayName ?? modelName
self.isRTL = isRTL
self.usesDenseScript = usesDenseScript
}
}
@@ -0,0 +1,42 @@
import Foundation
/// Normalises numeric tokens for the semantic check in `docs/TRANSLATION_OUTPUT.md` §9.
///
/// Locale separators legitimately change during translation, so `1.5`, `1,5` and `1 5` may all
/// represent the same value. Thousands separators are removed and the decimal separator becomes
/// `.`. This never edits the translation; it only decides whether a warning is shown.
public enum NumericTokenNormalizer {
private static let regex = try? NSRegularExpression(pattern: "\\d+(?:[.,\\s]\\d+)*")
/// The normalised numeric values in `text`, in source order.
public static func numbers(in text: String) -> [String] {
guard let regex else { return [] }
let nsText = text as NSString
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
return matches.map { normalize(nsText.substring(with: $0.range)) }
}
/// Normalises one numeric token.
public static func normalize(_ raw: String) -> String {
var value = raw.filter { !$0.isWhitespace }
guard !value.isEmpty else { return value }
let hasComma = value.contains(",")
let hasDot = value.contains(".")
if hasComma, hasDot, let comma = value.lastIndex(of: ","), let dot = value.lastIndex(of: ".") {
let decimal = comma > dot ? comma : dot
let integer = value[..<decimal].filter { $0 != "," && $0 != "." }
let fraction = value[value.index(after: decimal)...].filter { $0 != "," && $0 != "." }
value = String(integer) + "." + String(fraction)
} else if hasComma || hasDot {
let separator: Character = hasComma ? "," : "."
let parts = value.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
if parts.count == 2, parts[1].count == 3, parts[0] != "0", !parts[0].isEmpty {
value = parts[0] + parts[1]
} else if separator == "," {
value = parts.joined(separator: ".")
}
}
return value
}
}
@@ -0,0 +1,101 @@
import SprachmittlerText
/// The completed validation of one translation.
public struct OutputValidation: Sendable, Equatable {
/// Every warning found, in a stable order.
public let warnings: [TranslationWarning]
/// True when at least one warning should disable Replace by default.
public var blocksReplacement: Bool {
warnings.contains(where: \.blocksReplacement)
}
/// Creates a validation result.
public init(warnings: [TranslationWarning]) {
self.warnings = warnings
}
/// A clean result.
public static let clean = OutputValidation(warnings: [])
}
/// Validation from `docs/TRANSLATION_OUTPUT.md` §4–§7. It never edits the output.
public struct OutputValidator: Sendable {
private let preambleDetector: PreambleDetector
/// Creates a validator.
public init(preambleDetector: PreambleDetector = PreambleDetector()) {
self.preambleDetector = preambleDetector
}
/// Validates a T1-normalised translation.
public func validate(
source: String,
translation: String,
doneReason: String?,
tokens: [ProtectedToken],
includeRepetition: Bool = true
) -> OutputValidation {
if translation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return OutputValidation(warnings: [.emptyOutput])
}
var warnings: [TranslationWarning] = []
if doneReason == "length" {
warnings.append(.truncated)
}
if includeRepetition, RepetitionDetector.detectsLoop(in: translation) {
warnings.append(.repetitionLoop)
}
if let line = preambleDetector.firstLine(in: translation) {
warnings.append(.preambleDetected(firstLine: line))
}
for token in uniqueTokens(tokens) where count(of: token.value, in: source) != count(
of: token.value,
in: translation
) {
warnings.append(.missingProtectedToken(token.value))
}
let sourceNumbers = Set(NumericTokenNormalizer.numbers(in: source))
let translatedNumbers = Set(NumericTokenNormalizer.numbers(in: translation))
if !sourceNumbers.isSubset(of: translatedNumbers) {
warnings.append(.numericMismatch)
}
return OutputValidation(warnings: deduplicated(warnings))
}
/// The protected tokens whose occurrence count differs between source and translation.
public func missingTokens(
source: String,
translation: String,
tokens: [ProtectedToken]
) -> [ProtectedToken] {
uniqueTokens(tokens).filter {
count(of: $0.value, in: source) != count(of: $0.value, in: translation)
}
}
private func uniqueTokens(_ tokens: [ProtectedToken]) -> [ProtectedToken] {
var seen = Set<ProtectedToken>()
return tokens.filter { seen.insert($0).inserted }
}
private func deduplicated(_ warnings: [TranslationWarning]) -> [TranslationWarning] {
var seen = Set<TranslationWarning>()
return warnings.filter { seen.insert($0).inserted }
}
private func count(of needle: String, in haystack: String) -> Int {
guard !needle.isEmpty else { return 0 }
var count = 0
var searchRange = haystack.startIndex ..< haystack.endIndex
while let range = haystack.range(of: needle, range: searchRange) {
count += 1
searchRange = range.upperBound ..< haystack.endIndex
}
return count
}
}
@@ -0,0 +1,28 @@
/// Detects a likely model preamble without rewriting it (`docs/TRANSLATION_OUTPUT.md` §6).
public struct PreambleDetector: Sendable {
/// The maximum first-line length for a preamble.
public static let maximumFirstLineLength = 80
/// Creates a detector.
public init() {}
/// Returns the suspicious first line, or nil.
///
/// The heuristic is deliberately simple: a first non-empty line of at most 80 characters
/// ending in `:` or `:`, followed by a blank line and at least one more non-empty line.
public func firstLine(in text: String) -> String? {
let lines = text.components(separatedBy: "\n")
guard let firstIndex = lines.firstIndex(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty })
else {
return nil
}
let line = lines[firstIndex].trimmingCharacters(in: .whitespaces)
guard line.count <= Self.maximumFirstLineLength, line.hasSuffix(":") || line.hasSuffix(":"),
firstIndex + 1 < lines.count,
lines[firstIndex + 1].trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
let hasMoreText = lines[(firstIndex + 2)...].contains {
!$0.trimmingCharacters(in: .whitespaces).isEmpty
}
return hasMoreText ? line : nil
}
}
@@ -0,0 +1,32 @@
import SprachmittlerText
/// Chooses the documented prompt template (`docs/TRANSLATION_OUTPUT.md` §1, ADR-012).
///
/// v1 starts with Default Translation for everything. Structured Data 1 and Delimiters are used
/// only as the single fallback after a protected token was lost.
public struct PromptPolicy: Sendable {
/// Creates a policy.
public init() {}
/// The initial prompt for a content class. v1 always returns Default Translation.
public func initialPrompt(for content: ContentClass) -> PromptVariant {
_ = content
return .defaultTranslation
}
/// The one fallback prompt for a lost protected token, or nil when no documented fallback
/// applies. The caller enforces the one-retry limit.
public func retryPrompt(for content: ContentClass, lostToken: ProtectedToken) -> PromptVariant? {
switch content {
case .json:
return .structuredData1(format: .json)
case .html:
return .structuredData1(format: .html)
case .markdown:
return .structuredData1(format: .markdown)
case .code, .delimited, .plain:
_ = lostToken
return .delimiters
}
}
}
@@ -0,0 +1,19 @@
/// The documented formats for Structured Data 1.
public enum StructuredFormat: String, Sendable, Equatable, CaseIterable {
/// JSON data.
case json = "JSON"
/// HTML markup.
case html = "HTML"
/// Markdown text.
case markdown = "Markdown"
}
/// One of the documented prompt templates (`docs/HYMT3_MODEL.md` §4).
public enum PromptVariant: Sendable, Equatable {
/// The canonical Default Translation template.
case defaultTranslation
/// The Delimiters template; used once when a protected token is lost in plain text.
case delimiters
/// Structured Data 1 with the matching format; used once for structured text.
case structuredData1(format: StructuredFormat)
}
@@ -0,0 +1,71 @@
/// Detects repetition loops in a streaming translation (`docs/TRANSLATION_OUTPUT.md` §7).
public struct RepetitionDetector: Sendable {
/// The repeated-line threshold.
public static let minimumLineLength = 8
/// How many identical consecutive lines count as a loop.
public static let lineRepeatThreshold = 6
/// The repeated-window length.
public static let windowLength = 64
/// How many identical windows count as a loop.
public static let windowRepeatThreshold = 8
/// How much trailing text is inspected for window loops.
public static let windowSearchLength = 2048
private var buffer = ""
/// Creates a detector.
public init() {}
/// Appends a delta and returns true when a loop is detected.
public mutating func append(_ delta: String) -> Bool {
buffer += delta
if buffer.count > Self.windowSearchLength * 2 {
buffer = String(buffer.suffix(Self.windowSearchLength))
}
return Self.detectsLoop(in: buffer)
}
/// Checks a complete or partial output for a loop.
public static func detectsLoop(in text: String) -> Bool {
hasRepeatedLine(in: text) || hasRepeatedWindow(in: text)
}
private static func hasRepeatedLine(in text: String) -> Bool {
let lines = text
.components(separatedBy: "\n")
.suffix(12)
.map { $0.trimmingCharacters(in: .whitespaces) }
guard !lines.isEmpty else { return false }
var run = 1
for index in 1 ..< lines.count {
if !lines[index].isEmpty, lines[index].count >= minimumLineLength, lines[index] == lines[index - 1] {
run += 1
if run >= lineRepeatThreshold {
return true
}
} else {
run = 1
}
}
return false
}
private static func hasRepeatedWindow(in text: String) -> Bool {
guard text.count >= windowLength else { return false }
let search = String(text.suffix(windowSearchLength))
let window = String(text.suffix(windowLength))
guard search.count >= windowLength * windowRepeatThreshold else { return false }
var count = 0
var range = search.startIndex ..< search.endIndex
while let found = search.range(of: window, range: range) {
count += 1
if count >= windowRepeatThreshold {
return true
}
range = found.upperBound ..< search.endIndex
}
return false
}
}
@@ -0,0 +1,107 @@
import SprachmittlerOllama
/// The documented Hy-MT3 sampling values (`docs/HYMT3_MODEL.md` §2).
public struct SamplingOptions: Sendable, Equatable {
/// `temperature`.
public var temperature: Double
/// `top_p`.
public var topP: Double
/// `top_k`.
public var topK: Int
/// `repeat_penalty`.
public var repeatPenalty: Double
/// `num_predict`.
public var numPredict: Int
/// `num_ctx`.
public var numCtx: Int
/// Creates sampling values.
public init(
temperature: Double = 0.7,
topP: Double = 0.6,
topK: Int = 20,
repeatPenalty: Double = 1.05,
numPredict: Int = 4096,
numCtx: Int = 8192
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repeatPenalty = repeatPenalty
self.numPredict = numPredict
self.numCtx = numCtx
}
/// The publisher's recommendation for 1.8B and 7B.
public static let publisherDefault = SamplingOptions()
/// Applies explicit overrides on top of these values. Publisher values are always sent; a
/// model default is never relied on, because `/api/show` exposes no sampling defaults.
public func merging(_ overrides: SamplingOverrides) -> SamplingOptions {
var merged = self
if let value = overrides.temperature {
merged.temperature = value
}
if let value = overrides.topP {
merged.topP = value
}
if let value = overrides.topK {
merged.topK = value
}
if let value = overrides.repeatPenalty {
merged.repeatPenalty = value
}
if let value = overrides.numPredict {
merged.numPredict = value
}
if let value = overrides.numCtx {
merged.numCtx = value
}
return merged
}
/// The exact Ollama option names sent on the wire.
public func chatOptions() -> ChatOptions {
ChatOptions(
temperature: temperature,
topP: topP,
topK: topK,
repeatPenalty: repeatPenalty,
numPredict: numPredict,
numCtx: numCtx
)
}
}
/// Optional per-setting overrides. Only the documented six sampling keys exist.
public struct SamplingOverrides: Sendable, Equatable {
/// `temperature` override.
public var temperature: Double?
/// `top_p` override.
public var topP: Double?
/// `top_k` override.
public var topK: Int?
/// `repeat_penalty` override.
public var repeatPenalty: Double?
/// `num_predict` override.
public var numPredict: Int?
/// `num_ctx` override.
public var numCtx: Int?
/// Creates overrides.
public init(
temperature: Double? = nil,
topP: Double? = nil,
topK: Int? = nil,
repeatPenalty: Double? = nil,
numPredict: Int? = nil,
numCtx: Int? = nil
) {
self.temperature = temperature
self.topP = topP
self.topK = topK
self.repeatPenalty = repeatPenalty
self.numPredict = numPredict
self.numCtx = numCtx
}
}
@@ -0,0 +1,78 @@
import SprachmittlerOllama
import SprachmittlerText
/// One translation request before a model family adapter shapes it.
public struct AdapterRequest: Sendable, Equatable {
/// The chunk text.
public let text: String
/// The target language.
public let target: ModelLanguage
/// The installed model tag.
public let model: String
/// The Ollama `keep_alive` value.
public let keepAlive: String
/// The documented prompt template.
public let prompt: PromptVariant
/// The sampling values.
public let sampling: SamplingOptions
/// Creates a request.
public init(
text: String,
target: ModelLanguage,
model: String,
keepAlive: String,
prompt: PromptVariant = .defaultTranslation,
sampling: SamplingOptions = .publisherDefault
) {
self.text = text
self.target = target
self.model = model
self.keepAlive = keepAlive
self.prompt = prompt
self.sampling = sampling
}
}
/// A model family adapter: the only type that knows how to turn a translation into a request.
public protocol TranslationAdapter: Sendable {
/// A stable identifier, e.g. `hy-mt3`.
var identifier: String { get }
/// The adapter version; bump when the request shape changes.
var version: Int { get }
/// True when this adapter handles `model`.
func supports(model: String) -> Bool
/// Builds the documented request for one chunk.
func makeRequest(_ request: AdapterRequest) -> ChatRequest
}
/// The adapters available in the app, in priority order.
public struct AdapterRegistry: Sendable {
private let adapters: [any TranslationAdapter]
/// Creates a registry. The production root passes `[HyMT3Adapter()]`.
public init(adapters: [any TranslationAdapter]) {
self.adapters = adapters
}
/// The first adapter that supports `model`, or nil.
public func adapter(for model: String) -> (any TranslationAdapter)? {
adapters.first { $0.supports(model: model) }
}
/// Builds a request or throws `AdapterError.noAdapter` for an unknown family. Never guesses.
public func makeRequest(_ request: AdapterRequest) throws -> ChatRequest {
guard let adapter = adapter(for: request.model) else {
throw AdapterError.noAdapter(model: request.model)
}
return adapter.makeRequest(request)
}
}
/// Errors raised while choosing an adapter.
public enum AdapterError: Error, Sendable, Equatable {
/// No adapter handles this model family.
case noAdapter(model: String)
}
@@ -0,0 +1,45 @@
/// A non-fatal validation finding shown in the panel and the CLI JSON output.
public enum TranslationWarning: Sendable, Equatable, Hashable {
/// A short first line ending in a colon was followed by a blank line and more text.
case preambleDetected(firstLine: String)
/// `done_reason` was `length`.
case truncated
/// The output repeated a line or window too many times.
case repetitionLoop
/// A protected token from the source is missing or changed in the translation.
case missingProtectedToken(String)
/// The translation was empty after T1.
case emptyOutput
/// The detected source language is the target language.
case sameLanguage(source: String, target: String)
/// A source number is absent from the translation.
case numericMismatch
/// One chunk failed; the panel keeps the partial translation.
case chunkFailed(index: Int)
}
public extension TranslationWarning {
/// A stable code for JSON output and diagnostics.
var code: String {
switch self {
case .preambleDetected: "preambleDetected"
case .truncated: "truncated"
case .repetitionLoop: "repetitionLoop"
case .missingProtectedToken: "missingProtectedToken"
case .emptyOutput: "emptyOutput"
case .sameLanguage: "sameLanguage"
case .numericMismatch: "numericMismatch"
case .chunkFailed: "chunkFailed"
}
}
/// Blocking warnings disable Replace by default (`docs/TRANSLATION_OUTPUT.md` §4–§7).
var blocksReplacement: Bool {
switch self {
case .preambleDetected, .truncated, .repetitionLoop, .missingProtectedToken, .emptyOutput, .chunkFailed:
true
case .sameLanguage, .numericMismatch:
false
}
}
}
@@ -0,0 +1,76 @@
import Foundation
import SprachmittlerCapture
/// A main-actor pasteboard fake for watcher and snapshot tests.
@MainActor
public final class FakePasteboard: PasteboardAccessing {
public private(set) var changeCount: Int
public private(set) var text: String?
public private(set) var items: [ClipboardItemData]
public private(set) var hasOwnWriteMarkers: Bool
public private(set) var stringReadCount = 0
public private(set) var snapshotCount = 0
public private(set) var writtenTexts: [String] = []
public var restoreSucceeds = true
public var snapshotSucceeds = true
public init(
changeCount: Int = 0,
text: String? = nil,
items: [ClipboardItemData] = [],
hasOwnWriteMarkers: Bool = false
) {
self.changeCount = changeCount
self.text = text
self.items = items
self.hasOwnWriteMarkers = hasOwnWriteMarkers
}
/// Simulates another app copying text.
public func simulateCopy(_ text: String?) {
self.text = text
hasOwnWriteMarkers = false
changeCount += 1
}
/// Simulates a copy that carries a transient/own marker.
public func simulateOwnMarkerCopy(_ text: String?) {
self.text = text
hasOwnWriteMarkers = true
changeCount += 1
}
public func string() -> String? {
stringReadCount += 1
return text
}
public func containsOwnWriteMarkers() -> Bool {
hasOwnWriteMarkers
}
public func snapshot() -> ClipboardSnapshot? {
guard snapshotSucceeds else { return nil }
snapshotCount += 1
return ClipboardSnapshot(items: items, changeCount: changeCount)
}
public func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches expected: Int) -> Bool {
guard restoreSucceeds, changeCount == expected else { return false }
items = snapshot.items
text = snapshot.items.first?.data["public.utf8-plain-text"]
.flatMap { String(data: $0, encoding: .utf8) }
hasOwnWriteMarkers = false
changeCount += 1
return true
}
@discardableResult
public func write(_ text: String) -> Int {
writtenTexts.append(text)
self.text = text
hasOwnWriteMarkers = true
changeCount += 1
return changeCount
}
}
@@ -0,0 +1,55 @@
import Foundation
import SprachmittlerCapture
/// A manual ticker for watcher tests. No real time passes.
///
/// `@unchecked Sendable` is safe: every mutable field is guarded by `lock`.
public final class ManualPasteboardTicker: PasteboardTicking, @unchecked Sendable {
private let lock = NSLock()
private var continuation: AsyncStream<Void>.Continuation?
private var terminated = false
private var started = false
/// Creates a manual ticker.
public init() {}
public func ticks() -> AsyncStream<Void> {
AsyncStream { continuation in
lock.lock()
self.continuation = continuation
started = true
lock.unlock()
continuation.onTermination = { [weak self] _ in
self?.markTerminated()
}
}
}
/// True once the watcher has subscribed.
public var isStarted: Bool {
lock.lock()
defer { lock.unlock() }
return started
}
/// Emits one tick.
public func tick() {
lock.lock()
let continuation = continuation
lock.unlock()
continuation?.yield(())
}
/// True once the stream has terminated.
public var isTerminated: Bool {
lock.lock()
defer { lock.unlock() }
return terminated
}
private func markTerminated() {
lock.lock()
terminated = true
lock.unlock()
}
}
@@ -0,0 +1,243 @@
import Foundation
/// Splits text at paragraph, sentence, word and grapheme boundaries with script-aware limits.
///
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
public struct Chunker: Sendable {
/// The limit for Latin, Cyrillic and Greek text.
public let latinLimit: Int
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
public let denseLimit: Int
/// Creates a chunker.
public init(latinLimit: Int = 4000, denseLimit: Int = 2000) {
self.latinLimit = latinLimit
self.denseLimit = denseLimit
}
/// The character limit that applies to `text`.
public func limit(for text: String) -> Int {
TextScript.isDense(text) ? denseLimit : latinLimit
}
/// Splits `text` into chunks of at most the script-aware limit.
public func chunks(for text: String) -> [TextChunk] {
guard !text.isEmpty else { return [] }
let limit = max(1, limit(for: text))
var pieces: [(text: String, separator: String)] = []
for unit in paragraphUnits(text) {
split(unit.text, trailing: unit.separator, limit: limit, into: &pieces)
}
return pack(mergingLeadingEmpty(pieces), limit: limit)
}
/// Reassembles chunks into the original text.
public static func reassemble(_ chunks: [TextChunk]) -> String {
chunks.sorted { $0.index < $1.index }.reduce(into: "") { result, chunk in
result += chunk.text
result += chunk.separatorAfter
}
}
// MARK: - Splitting
private func split(
_ text: String,
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
if text.count <= limit {
pieces.append((text, trailing))
return
}
let sentences = sentenceUnits(text)
if sentences.count > 1 {
splitSubunits(sentences, trailing: trailing, limit: limit, into: &pieces)
return
}
let words = wordUnits(text)
if words.count > 1 {
splitSubunits(words, trailing: trailing, limit: limit, into: &pieces)
return
}
splitGraphemes(text, trailing: trailing, into: &pieces)
}
private func splitSubunits(
_ units: [(text: String, separator: String)],
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
for (offset, unit) in units.enumerated() {
let separator = offset == units.count - 1 ? unit.separator + trailing : unit.separator
split(unit.text, trailing: separator, limit: limit, into: &pieces)
}
}
private func splitGraphemes(
_ text: String,
trailing: String,
into pieces: inout [(text: String, separator: String)]
) {
let characters = Array(text)
for (offset, character) in characters.enumerated() {
let separator = offset == characters.count - 1 ? trailing : ""
pieces.append((String(character), separator))
}
}
// MARK: - Units
private func paragraphUnits(_ text: String) -> [(text: String, separator: String)] {
guard let regex = try? NSRegularExpression(pattern: "\\n[ \\t]*\\n(?:[ \\t]*\\n)*") else {
return [(text, "")]
}
let nsText = text as NSString
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
guard !matches.isEmpty else { return [(text, "")] }
var units: [(String, String)] = []
var cursor = 0
for match in matches {
let body = nsText.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
let separator = nsText.substring(with: match.range)
units.append((body, separator))
cursor = match.range.location + match.range.length
}
let tail = nsText.substring(from: cursor)
units.append((tail, ""))
return units
}
private func sentenceUnits(_ text: String) -> [(text: String, separator: String)] {
let terminators: Set<Character> = [".", "!", "?", "。", "!", "?", "…"]
let closers: Set<Character> = ["\"", "'", "”", "’", ")", "]", "}"]
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard terminators.contains(characters[index]) else {
index += 1
continue
}
var end = index + 1
while end < characters.count, terminators.contains(characters[end]) {
end += 1
}
while end < characters.count, closers.contains(characters[end]) {
end += 1
}
guard end < characters.count, characters[end].isWhitespace else {
index = end
continue
}
var separatorEnd = end
while separatorEnd < characters.count, characters[separatorEnd].isWhitespace {
separatorEnd += 1
}
let body = String(characters[start ..< end])
let separator = String(characters[end ..< separatorEnd])
units.append((body, separator))
start = separatorEnd
index = separatorEnd
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
private func wordUnits(_ text: String) -> [(text: String, separator: String)] {
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard characters[index].isWhitespace else {
index += 1
continue
}
let body = String(characters[start ..< index])
var end = index
while end < characters.count, characters[end].isWhitespace {
end += 1
}
let separator = String(characters[index ..< end])
units.append((body, separator))
start = end
index = end
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
// MARK: - Packing
/// Keeps a leading empty body's separator (for example a text starting with `\n\n` or a long
/// over-limit text starting with whitespace) by attaching it to the first non-empty piece.
private func mergingLeadingEmpty(
_ pieces: [(text: String, separator: String)]
) -> [(text: String, separator: String)] {
var result = pieces
var prefix = ""
while let first = result.first, first.text.isEmpty {
prefix += first.separator
result.removeFirst()
}
guard !result.isEmpty else {
return prefix.isEmpty ? [] : [(prefix, "")]
}
var first = result[0]
first.text = prefix + first.text
result[0] = first
return result
}
private func pack(
_ pieces: [(text: String, separator: String)],
limit: Int
) -> [TextChunk] {
var chunks: [TextChunk] = []
var current = ""
var trailing = ""
var lastSeparator = ""
var index = 0
func emit() {
guard !current.isEmpty else { return }
chunks.append(TextChunk(index: index, text: current, separatorAfter: trailing))
index += 1
current = ""
trailing = ""
lastSeparator = ""
}
for piece in pieces {
if current.isEmpty {
current = piece.text
} else if current.count + lastSeparator.count + piece.text.count <= limit {
current += lastSeparator + piece.text
} else {
emit()
current = piece.text
}
trailing = piece.separator
lastSeparator = piece.separator
}
emit()
return chunks
}
}
@@ -0,0 +1,15 @@
/// The source-content classes from `docs/ARCHITECTURE.md` §9.1.
public enum ContentClass: String, Sendable, Equatable, CaseIterable {
/// Ordinary prose.
case plain
/// Markdown, including headings, lists, tables and fenced code.
case markdown
/// JSON data.
case json
/// HTML markup.
case html
/// Code without Markdown prose.
case code
/// Many placeholders, URLs or delimiters.
case delimited
}
@@ -0,0 +1,53 @@
import Foundation
/// A simple content classifier used only to choose a documented prompt fallback.
public struct ContentClassifier: Sendable {
private let scanner: ProtectedTokenScanner
private static let tagRegex = try? NSRegularExpression(pattern: "</?[A-Za-z][^>]*>")
/// Creates a classifier.
public init(scanner: ProtectedTokenScanner = ProtectedTokenScanner()) {
self.scanner = scanner
}
/// Classifies `text` as plain, Markdown, JSON, HTML, code or delimiter-heavy.
public func classify(_ text: String) -> ContentClass {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return .plain }
if isJSON(trimmed) {
return .json
}
if isHTML(trimmed) {
return .html
}
let fenced = trimmed.components(separatedBy: "```").count > 1
let markdownMarkers = trimmed.components(separatedBy: "\n").filter { line in
let trimmedLine = line.trimmingCharacters(in: .whitespaces)
return trimmedLine.hasPrefix("#") || trimmedLine.hasPrefix("- ") || trimmedLine.hasPrefix("* ")
|| trimmedLine.hasPrefix("> ") || trimmedLine.hasPrefix("|") || trimmedLine.hasPrefix("[")
|| trimmedLine.hasPrefix("![")
}.count
if markdownMarkers >= 1 || fenced {
return fenced && markdownMarkers == 0 ? .code : .markdown
}
let tokens = scanner.scan(trimmed)
if tokens.count >= 3 {
return .delimited
}
return .plain
}
private func isJSON(_ text: String) -> Bool {
guard text.hasPrefix("{") || text.hasPrefix("["), let data = text.data(using: .utf8) else { return false }
return (try? JSONSerialization.jsonObject(with: data)) != nil
}
private func isHTML(_ text: String) -> Bool {
guard let tagRegex = Self.tagRegex else { return false }
let range = NSRange(location: 0, length: (text as NSString).length)
return tagRegex.numberOfMatches(in: text, range: range) >= 2
}
}
@@ -0,0 +1,51 @@
import Foundation
import NaturalLanguage
/// One language hypothesis from `NLLanguageRecognizer`.
public struct LanguageDetection: Sendable, Equatable {
/// The dominant BCP-47 language code, e.g. `en` or `de`.
public let code: String
/// The recogniser confidence in `code`, from 0 to 1.
public let confidence: Double
/// Candidate codes ordered by confidence, including `code` first.
public let alternatives: [String]
/// Creates a detection value.
public init(code: String, confidence: Double, alternatives: [String]) {
self.code = code
self.confidence = confidence
self.alternatives = alternatives
}
}
/// Source-language detection. Advisory only: it never blocks translation.
public protocol LanguageDetecting: Sendable {
/// Detects the dominant language of `text`, or returns nil for empty/undecidable text.
func detect(_ text: String) -> LanguageDetection?
}
/// `NLLanguageRecognizer`-backed detection (`docs/TRANSLATION_OUTPUT.md` §8).
public struct NaturalLanguageDetector: LanguageDetecting {
/// Creates a detector.
public init() {}
/// Detects the dominant language. Short or mixed text usually reports low confidence.
public func detect(_ text: String) -> LanguageDetection? {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
let recognizer = NLLanguageRecognizer()
recognizer.processString(trimmed)
guard let dominant = recognizer.dominantLanguage else { return nil }
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
let ordered = hypotheses.sorted { lhs, rhs in
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
}.map(\.key.rawValue)
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
return LanguageDetection(
code: dominant.rawValue,
confidence: Double(hypotheses[dominant] ?? 0),
alternatives: alternatives
)
}
}
@@ -0,0 +1,39 @@
import Foundation
/// A protected token that must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
public struct ProtectedToken: Sendable, Equatable, Hashable {
/// The token kind.
public let kind: ProtectedTokenKind
/// The exact text that must appear in the translation.
public let value: String
/// Creates a protected token.
public init(kind: ProtectedTokenKind, value: String) {
self.kind = kind
self.value = value
}
}
/// The protected-token kinds from `docs/TRANSLATION_OUTPUT.md` §4.
public enum ProtectedTokenKind: String, Sendable, Equatable, CaseIterable {
/// `https://…`, `http://…`, `www.…`
case url
/// `name@example.com`
case email
/// `{{name}}`, `{{ name }}`
case mustache
/// `${name}`
case templateLiteral
/// `%s`, `%d`, `%1$@`, `%02d`
case printf
/// `` `code` ``
case codeSpan
/// A fenced code block.
case fencedCode
/// `<a href="…">`, `</div>`
case htmlTag
/// A quoted JSON key followed by `:`.
case jsonKey
/// `/Users/…`, `C:\…`
case filePath
}
@@ -0,0 +1,91 @@
import Foundation
/// Finds URLs, e-mail addresses, placeholders, code spans, HTML tags, JSON keys and paths that
/// must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
public struct ProtectedTokenScanner: Sendable {
private struct Rule {
let kind: ProtectedTokenKind
let regex: NSRegularExpression
let group: Int
}
private static let rules: [Rule] = {
func rule(
_ kind: ProtectedTokenKind,
_ pattern: String,
group: Int = 0,
options: NSRegularExpression.Options = []
) -> Rule? {
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
return nil
}
return Rule(kind: kind, regex: regex, group: group)
}
let rules: [Rule?] = [
rule(.fencedCode, "```[\\s\\S]*?```"),
rule(.codeSpan, "`[^`\\n]+`"),
rule(.htmlTag, "</?[A-Za-z][^>\\n]*>"),
rule(.url, "(?:https?://|www\\.)[^\\s<>\"']+"),
rule(.email, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
rule(.mustache, "\\{\\{\\s*[^{}\\n]+\\s*\\}\\}"),
rule(.templateLiteral, "\\$\\{[^{}\\n]+\\}"),
rule(.printf, "%(?:\\d+\\$)?[-+0#]*\\d*(?:\\.\\d+)?[sd@]"),
rule(.jsonKey, "(\"(?:[^\"\\\\]|\\\\.)*\")\\s*:", group: 1),
rule(.filePath, "(?:/(?:Users|home|var|usr|opt|tmp)/[^\\s,;:\"'<>]+|[A-Za-z]:\\\\[^\\s,;:\"'<>]+)"),
]
return rules.compactMap(\.self)
}()
/// Creates a scanner.
public init() {}
/// Scans `text` and returns the protected tokens in source order, without duplicates.
public func scan(_ text: String) -> [ProtectedToken] {
let nsText = text as NSString
let fullRange = NSRange(location: 0, length: nsText.length)
var occupied: [NSRange] = []
var tokens: [(range: NSRange, token: ProtectedToken)] = []
for rule in Self.rules {
for match in rule.regex.matches(in: text, options: [], range: fullRange) {
let range = match.range(at: rule.group)
guard range.location != NSNotFound else { continue }
if occupied.contains(where: { NSIntersectionRange($0, range).length > 0 }) {
continue
}
var value = nsText.substring(with: range)
if rule.kind == .url {
value = trimURLTail(value)
if value.count < 4 {
continue
}
}
let token = ProtectedToken(kind: rule.kind, value: value)
if tokens.contains(where: { $0.token == token }) {
continue
}
tokens.append((range, token))
occupied.append(range)
}
}
return tokens.sorted { $0.range.location < $1.range.location }.map(\.token)
}
/// Removes sentence punctuation that a URL pattern may have swallowed. A balanced closing
/// parenthesis is kept, so Wikipedia-style URLs remain intact.
private func trimURLTail(_ value: String) -> String {
var result = value
while let last = result.last, ".,;:!?".contains(last) {
result.removeLast()
}
while let last = result.last, ")]}".contains(last) {
let open: Character = last == ")" ? "(" : (last == "]" ? "[" : "{")
let opens = result.filter { $0 == open }.count
let closes = result.filter { $0 == last }.count
guard closes > opens else { break }
result.removeLast()
}
return result
}
}
@@ -0,0 +1,16 @@
/// One chunk of a translation, with the separator that followed it in the source.
public struct TextChunk: Sendable, Equatable {
/// The zero-based chunk index.
public let index: Int
/// The chunk text.
public let text: String
/// The source separator after this chunk (`"\n\n"`, `" "` or `""`).
public let separatorAfter: String
/// Creates a chunk.
public init(index: Int, text: String, separatorAfter: String) {
self.index = index
self.text = text
self.separatorAfter = separatorAfter
}
}
@@ -0,0 +1,43 @@
import Foundation
/// Input and output normalisation from `docs/TRANSLATION_OUTPUT.md` §2 and §5.
public enum TextNormalization {
/// N1–N3: line endings to `\n`, strip BOM/NUL/C0 controls (except tab and newline),
/// strip U+200B, keep ZWJ/ZWNJ, NFC, then trim outer whitespace (N2).
public static func normalizeInput(_ text: String) -> String {
let unified = unifyLineEndings(text)
let filtered = unified.unicodeScalars.filter { scalar in
switch scalar.value {
case 0, 0xFEFF, 0x200B:
return false
default:
break
}
if scalar.properties.generalCategory == .control {
return scalar.value == 0x09 || scalar.value == 0x0A
}
return true
}
let cleaned = String(String.UnicodeScalarView(filtered))
return cleaned.precomposedStringWithCanonicalMapping.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// T1: strip NUL, normalise line endings, trim outer whitespace. Internal text is untouched.
public static func normalizeOutput(_ text: String) -> String {
unifyLineEndings(text)
.replacingOccurrences(of: "\0", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Comparison normalisation for the double-copy rule: line endings and outer trimming only.
/// Internal whitespace is deliberately preserved.
public static func normalizeForComparison(_ text: String) -> String {
unifyLineEndings(text).trimmingCharacters(in: .whitespacesAndNewlines)
}
private static func unifyLineEndings(_ text: String) -> String {
text
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
}
}
@@ -0,0 +1,41 @@
/// Dense-script detection for the chunk limit (`docs/TRANSLATION_OUTPUT.md` §3).
///
/// The limit is script-based, not language-based: one CJK, Arabic, Thai or Indic character is
/// enough to select the smaller limit. Latin, Cyrillic and Greek stay on the larger limit.
public enum TextScript {
private static let denseRanges: [ClosedRange<UInt32>] = [
0x0590 ... 0x05FF, // Hebrew
0x0600 ... 0x06FF, // Arabic
0x0750 ... 0x077F, // Arabic Supplement
0x0900 ... 0x097F, // Devanagari
0x0980 ... 0x09FF, // Bengali
0x0A00 ... 0x0A7F, // Gurmukhi
0x0A80 ... 0x0AFF, // Gujarati
0x0B00 ... 0x0B7F, // Oriya
0x0B80 ... 0x0BFF, // Tamil
0x0C00 ... 0x0C7F, // Telugu
0x0C80 ... 0x0CFF, // Kannada
0x0D00 ... 0x0D7F, // Malayalam
0x0D80 ... 0x0DFF, // Sinhala
0x0E00 ... 0x0E7F, // Thai
0x0E80 ... 0x0EFF, // Lao
0x0F00 ... 0x0FFF, // Tibetan
0x1000 ... 0x109F, // Myanmar
0x1200 ... 0x137F, // Ethiopic
0x1780 ... 0x17FF, // Khmer
0x1800 ... 0x18AF, // Mongolian
0x2E80 ... 0x9FFF, // CJK, Hiragana, Katakana and Hangul compatibility
0xA960 ... 0xA97F, // Hangul Jamo Extended-A
0xAC00 ... 0xD7AF, // Hangul syllables
0xF900 ... 0xFAFF, // CJK compatibility ideographs
0xFE30 ... 0xFE4F, // CJK compatibility forms
0xFF66 ... 0xFFDC, // Half-width Katakana and Hangul
]
/// True when `text` contains at least one dense-script scalar.
public static func isDense(_ text: String) -> Bool {
text.unicodeScalars.contains { scalar in
denseRanges.contains { $0.contains(scalar.value) }
}
}
}
@@ -1,4 +1,5 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
@@ -19,7 +20,14 @@ struct CLIEnvironment: Sendable {
try OllamaChatClient(http: makeHTTPClient())
}
func makeRequestFactory(model: String) -> HyMT3RequestFactory {
HyMT3RequestFactory(model: model)
func makeRegistry() -> AdapterRegistry {
AdapterRegistry(adapters: [HyMT3Adapter()])
}
func makePipeline() throws -> TranslationPipeline {
try TranslationPipeline(
chat: makeChatClient(),
registry: makeRegistry()
)
}
}
@@ -1,5 +1,6 @@
import ArgumentParser
import Foundation
import SprachmittlerCore
import SprachmittlerOllama
enum CLIError {
@@ -18,12 +19,63 @@ enum CLIError {
} catch let validation as ValidationError {
writeError(String(describing: validation))
throw ExitCode(2)
} catch let domain as SprachmittlerError {
writeError(message(for: domain))
throw ExitCode(exitCode(for: domain))
} catch {
writeError("Error: \(error)")
throw ExitCode(1)
}
}
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
static func exitCode(for error: SprachmittlerError) -> Int32 {
switch error {
case .endpointRejected, .noAdapter, .emptyText, .textTooLong, .badRequest:
2
case .ollamaUnreachable:
3
case .modelNotInstalled:
4
default:
1
}
}
static func message(for error: SprachmittlerError) -> String {
switch error {
case let .ollamaUnreachable(url):
"Ollama is not reachable at \(url.absoluteString)."
case let .modelNotInstalled(model):
"Model not installed: \(model)"
case let .noAdapter(model):
"No translation adapter for \(model)."
case let .endpointRejected(reason):
"Endpoint rejected: \(message(for: reason))"
default:
genericMessage(for: error)
}
}
private static func genericMessage(for error: SprachmittlerError) -> String {
switch error {
case .emptyText:
"No text to translate."
case let .textTooLong(characters, limit):
"Text is too long (\(characters) characters; limit \(limit))."
case let .timeout(phase):
"Timed out while talking to Ollama (\(phase))."
case let .server(status, _):
"Ollama returned HTTP \(status)."
case .badRequest:
"Ollama rejected the request."
case .cancelled:
"Cancelled."
default:
"Translation failed."
}
}
/// 2 = endpoint/usage, 3 = unreachable, 4 = model missing, 1 = other runtime failure.
static func exitCode(for error: OllamaError) -> Int32 {
switch error {
@@ -47,12 +47,10 @@ struct TranslateCommand: AsyncParsableCommand {
try await CLIError.perform {
let environment = try endpoint.makeEnvironment()
let chat = try environment.makeChatClient()
let runner = TranslateRunner(
chat: chat,
factory: environment.makeRequestFactory(model: model)
let runner = try TranslateRunner(
pipeline: environment.makePipeline()
)
let outcome = try await runner.run(text: source, target: language)
let outcome = try await runner.run(text: source, target: language, model: model)
if json {
let data = try outcome.jsonData(includeSource: includeSource, source: source)
print(String(data: data, encoding: .utf8) ?? "{}")
@@ -1,34 +1,33 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
struct TranslateOutcome: Sendable, Equatable {
let translation: String
let model: String
let target: ModelLanguage
let metrics: ChatMetrics
let firstTokenMs: Int?
let totalMs: Int
let warnings: [TranslationWarning]
let sourceLanguage: String?
let timing: TranslationTiming
let sourceCharacters: Int
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10. `sourceLanguage` stays null
/// until T2.4; warnings stay empty until T2.5.
/// The CLI JSON contract from docs/TRANSLATION_OUTPUT.md §10.
func jsonData(includeSource: Bool, source: String) throws -> Data {
let timing: [String: Any] = [
"firstTokenMs": firstTokenMs.map { $0 as Any } ?? NSNull(),
"totalMs": totalMs,
"promptTokens": metrics.promptEvalCount.map { $0 as Any } ?? NSNull(),
"outputTokens": metrics.evalCount.map { $0 as Any } ?? NSNull(),
let timingObject: [String: Any] = [
"firstTokenMs": timing.firstTokenMs.map { $0 as Any } ?? NSNull(),
"totalMs": timing.totalMs,
"promptTokens": timing.promptTokens.map { $0 as Any } ?? NSNull(),
"outputTokens": timing.outputTokens.map { $0 as Any } ?? NSNull(),
]
var object: [String: Any] = [
"schema": "sprachmittler-translation-v1",
"sourceLanguage": NSNull(),
"sourceLanguage": sourceLanguage ?? NSNull(),
"targetLanguage": target.code,
"model": model,
"sourceCharacters": sourceCharacters,
"translation": translation,
"warnings": [String](),
"timing": timing,
"warnings": warnings.map(\.code),
"timing": timingObject,
]
if includeSource {
object["source"] = source
@@ -1,39 +1,24 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
struct TranslateRunner: Sendable {
let chat: any OllamaChatting
let factory: HyMT3RequestFactory
let pipeline: TranslationPipeline
func run(text: String, target: ModelLanguage) async throws -> TranslateOutcome {
let request = factory.translationRequest(text: text, target: target)
let started = Date()
var firstDelta: Date?
var translation = ""
var metrics = ChatMetrics.empty
for try await event in chat.chat(request) {
switch event {
case let .delta(delta):
if firstDelta == nil {
firstDelta = Date()
}
translation += delta
case let .done(_, doneMetrics):
metrics = doneMetrics
}
}
let totalMs = max(0, Int(Date().timeIntervalSince(started) * 1000))
let firstTokenMs = firstDelta.map { max(0, Int($0.timeIntervalSince(started) * 1000)) }
return TranslateOutcome(
translation: translation,
model: request.model,
func run(text: String, target: ModelLanguage, model: String) async throws -> TranslateOutcome {
let result = try await pipeline.translate(
text: text,
target: target,
metrics: metrics,
firstTokenMs: firstTokenMs,
totalMs: totalMs,
model: model,
keepAlive: HyMT3ModelPreset.defaultKeepAlive
)
return TranslateOutcome(
translation: result.translation,
model: model,
target: target,
warnings: result.warnings,
sourceLanguage: result.sourceLanguage,
timing: result.timing,
sourceCharacters: text.count
)
}
@@ -1,5 +1,6 @@
import ArgumentParser
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerTestSupport
@@ -60,18 +61,22 @@ struct CLITests {
],
onRequest: { box.record($0) }
)
let factory = HyMT3RequestFactory(model: "test-model", keepAlive: "5m")
let outcome = try await TranslateRunner(chat: chat, factory: factory)
.run(text: "Hello.", target: HyMT3Languages.german)
let model = "test-hy-mt3-model"
let pipeline = TranslationPipeline(
chat: chat,
registry: AdapterRegistry(adapters: [HyMT3Adapter()])
)
let outcome = try await TranslateRunner(pipeline: pipeline)
.run(text: "Hello.", target: HyMT3Languages.german, model: model)
#expect(outcome.translation == "Hallo")
#expect(outcome.model == "test-model")
#expect(outcome.model == model)
#expect(outcome.target == HyMT3Languages.german)
#expect(outcome.sourceCharacters == 6)
#expect(outcome.metrics.evalCount == 2)
#expect(outcome.timing.outputTokens == 2)
let request = try #require(box.request)
#expect(request.keepAlive == "5m")
#expect(request.keepAlive == HyMT3ModelPreset.defaultKeepAlive)
#expect(
request.messages.first?.content
== HyMT3Prompt.defaultTranslation(target: HyMT3Languages.german, source: "Hello.")
@@ -83,9 +88,9 @@ struct CLITests {
translation: "Hallo",
model: "test-model",
target: HyMT3Languages.german,
metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2),
firstTokenMs: 4,
totalMs: 12,
warnings: [.truncated],
sourceLanguage: "en",
timing: TranslationTiming(firstTokenMs: 4, totalMs: 12, promptTokens: 9, outputTokens: 2),
sourceCharacters: 6
)
@@ -95,8 +100,8 @@ struct CLITests {
#expect(object["targetLanguage"] as? String == "de")
#expect(object["model"] as? String == "test-model")
#expect(object["translation"] as? String == "Hallo")
#expect(object["sourceLanguage"] is NSNull)
#expect((object["warnings"] as? [Any])?.isEmpty == true)
#expect(object["sourceLanguage"] as? String == "en")
#expect(object["warnings"] as? [String] == ["truncated"])
#expect(object["source"] == nil)
let withSourceData = try outcome.jsonData(includeSource: true, source: "Hello.")
@@ -132,10 +137,16 @@ struct CLITests {
@Test func exitCodesMatchTheContract() throws {
let url = try #require(URL(string: "http://127.0.0.1:9"))
#expect(CLIError.exitCode(for: .endpointRejected(.remoteNotAllowed)) == 2)
#expect(CLIError.exitCode(for: .unreachable(url)) == 3)
#expect(CLIError.exitCode(for: .modelNotInstalled("m")) == 4)
#expect(CLIError.exitCode(for: .cancelled) == 1)
#expect(CLIError.exitCode(for: OllamaError.endpointRejected(.remoteNotAllowed)) == 2)
#expect(CLIError.exitCode(for: OllamaError.unreachable(url)) == 3)
#expect(CLIError.exitCode(for: OllamaError.modelNotInstalled("m")) == 4)
#expect(CLIError.exitCode(for: OllamaError.cancelled) == 1)
#expect(CLIError.exitCode(for: SprachmittlerError.ollamaUnreachable(url: url)) == 3)
#expect(CLIError.exitCode(for: SprachmittlerError.modelNotInstalled(model: "m")) == 4)
#expect(CLIError.exitCode(for: SprachmittlerError.noAdapter(model: "m")) == 2)
#expect(CLIError.exitCode(for: SprachmittlerError.emptyText) == 2)
#expect(CLIError.exitCode(for: SprachmittlerError.textTooLong(characters: 5000, limit: 4000)) == 2)
}
private func assertValidationError(_ arguments: [String], message: String) {
@@ -0,0 +1,78 @@
import Foundation
import SprachmittlerCapture
import SprachmittlerTestSupport
import Testing
@Suite("Clipboard snapshot")
@MainActor
struct ClipboardSnapshotTests {
@Test func snapshotCapturesEveryItemAndType() throws {
let text = Data("Hello".utf8)
let rich = Data("rich".utf8)
let image = Data([0x01, 0x02, 0x03])
let pasteboard = FakePasteboard(
changeCount: 3,
text: "Hello",
items: [
ClipboardItemData(data: ["public.utf8-plain-text": text, "public.rtf": rich]),
ClipboardItemData(data: ["public.png": image]),
]
)
let snapshot = try #require(pasteboard.snapshot())
#expect(snapshot.changeCount == 3)
#expect(snapshot.items.count == 2)
#expect(snapshot.items[0].data["public.utf8-plain-text"] == text)
#expect(snapshot.items[0].data["public.rtf"] == rich)
#expect(snapshot.items[1].data["public.png"] == image)
}
@Test func restoreOnlyWhenChangeCountMatches() throws {
let text = Data("Hello".utf8)
let pasteboard = FakePasteboard(
changeCount: 3,
text: "Hello",
items: [ClipboardItemData(data: ["public.utf8-plain-text": text])]
)
let snapshot = try #require(pasteboard.snapshot())
#expect(pasteboard.restore(snapshot, onlyIfChangeCountMatches: 3))
#expect(pasteboard.text == "Hello")
#expect(!pasteboard.hasOwnWriteMarkers)
}
@Test func anotherAppChangingTheClipboardPreventsRestore() throws {
let text = Data("Hello".utf8)
let pasteboard = FakePasteboard(
changeCount: 3,
text: "Hello",
items: [ClipboardItemData(data: ["public.utf8-plain-text": text])]
)
let snapshot = try #require(pasteboard.snapshot())
pasteboard.simulateCopy("Other")
#expect(!pasteboard.restore(snapshot, onlyIfChangeCountMatches: 3))
#expect(pasteboard.text == "Other")
}
@Test func restoreFailureIsReported() throws {
let pasteboard = FakePasteboard(changeCount: 1, text: "Hello")
let snapshot = try #require(pasteboard.snapshot())
pasteboard.restoreSucceeds = false
#expect(!pasteboard.restore(snapshot, onlyIfChangeCountMatches: 1))
}
@Test func snapshotFailureReturnsNil() {
let pasteboard = FakePasteboard()
pasteboard.snapshotSucceeds = false
#expect(pasteboard.snapshot() == nil)
}
@Test func writeAddsOwnAndTransientMarkers() {
let pasteboard = FakePasteboard()
let newCount = pasteboard.write("Hallo")
#expect(newCount == 1)
#expect(pasteboard.text == "Hallo")
#expect(pasteboard.hasOwnWriteMarkers)
#expect(pasteboard.writtenTexts == ["Hallo"])
}
}
@@ -0,0 +1,71 @@
import Foundation
import Testing
@testable import SprachmittlerCapture
@Suite("Double-copy detector")
struct DoubleCopyDetectorTests {
private let start = Date(timeIntervalSince1970: 1000)
@Test func twoIdenticalCopiesWithinTheWindowTrigger() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.3))
== .captured("Hello"))
}
@Test func slowCopiesDoNotTrigger() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.6)) == .none)
#expect(detector.record(changeCount: 3, text: "Hello", at: start.addingTimeInterval(0.7))
== .captured("Hello"))
}
@Test func differentTextDoesNotTrigger() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
#expect(detector.record(changeCount: 2, text: "World", at: start.addingTimeInterval(0.1)) == .none)
#expect(detector.record(changeCount: 3, text: "World", at: start.addingTimeInterval(0.2))
== .captured("World"))
}
@Test func emptyOrWhitespaceTextResets() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
#expect(detector.record(changeCount: 2, text: " ", at: start.addingTimeInterval(0.1)) == .empty)
#expect(detector.record(changeCount: 3, text: "Hello", at: start.addingTimeInterval(0.2)) == .none)
}
@Test func duplicateChangeCountIsIgnored() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
#expect(detector.record(changeCount: 1, text: "Hello", at: start.addingTimeInterval(0.1)) == .none)
}
@Test func comparisonTrimsAndNormalisesLineEndingsOnly() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: " Hello\r\nworld ", at: start) == .none)
#expect(detector.record(changeCount: 2, text: "Hello\nworld", at: start.addingTimeInterval(0.1))
== .captured("Hello\nworld"))
}
@Test func internalWhitespaceIsSignificant() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "a b", at: start) == .none)
#expect(detector.record(changeCount: 2, text: "a b", at: start.addingTimeInterval(0.1)) == .none)
}
@Test func resetForgetsTheRememberedCopy() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
detector.reset()
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.1)) == .none)
}
@Test func expireClearsACandidateAfterTheWindow() {
var detector = DoubleCopyDetector()
#expect(detector.record(changeCount: 1, text: "Hello", at: start) == .none)
detector.expire(at: start.addingTimeInterval(0.6))
#expect(detector.record(changeCount: 2, text: "Hello", at: start.addingTimeInterval(0.7)) == .none)
}
}
@@ -0,0 +1,124 @@
import Foundation
import SprachmittlerCore
import SprachmittlerTestSupport
import Testing
@testable import SprachmittlerCapture
@Suite("Pasteboard watcher")
@MainActor
struct PasteboardWatcherTests {
private let start = Date(timeIntervalSince1970: 2000)
@Test func readsOnlyAfterAChange() {
let pasteboard = FakePasteboard(text: "Hello")
let watcher = PasteboardWatcher(pasteboard: pasteboard)
#expect(watcher.poll(at: start) == nil)
#expect(pasteboard.stringReadCount == 0)
}
@Test func twoIdenticalCopiesAreCaptured() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start) == nil)
pasteboard.simulateCopy("Hello")
let event = watcher.poll(at: start.addingTimeInterval(0.1))
guard case let .captured(captured) = event else {
Issue.record("expected a capture")
return
}
#expect(captured.text == "Hello")
#expect(captured.source == .doubleCopy)
#expect(captured.capturedAt == start.addingTimeInterval(0.1))
}
@Test func slowCopiesDoNotTrigger() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start) == nil)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start.addingTimeInterval(0.6)) == nil)
}
@Test func tooLongTextUsesTheScriptAwareLimit() {
let latin = FakePasteboard()
let latinWatcher = PasteboardWatcher(pasteboard: latin)
latin.simulateCopy(String(repeating: "a", count: 4001))
_ = latinWatcher.poll(at: start)
latin.simulateCopy(String(repeating: "a", count: 4001))
#expect(
latinWatcher.poll(at: start.addingTimeInterval(0.1))
== .textTooLong(characters: 4001, limit: 4000)
)
let dense = FakePasteboard()
let denseWatcher = PasteboardWatcher(pasteboard: dense)
let cjk = String(repeating: "你", count: 2001)
dense.simulateCopy(cjk)
_ = denseWatcher.poll(at: start)
dense.simulateCopy(cjk)
#expect(
denseWatcher.poll(at: start.addingTimeInterval(0.1))
== .textTooLong(characters: 2001, limit: 2000)
)
}
@Test func ownWritesAreSuppressedFor750Milliseconds() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
pasteboard.simulateOwnMarkerCopy("Hallo")
#expect(watcher.poll(at: start) == .ignoredOwnWrite)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == .ignoredOwnWrite)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start.addingTimeInterval(0.8)) == nil)
pasteboard.simulateCopy("Hello")
let event = watcher.poll(at: start.addingTimeInterval(0.9))
#expect(event != nil)
}
@Test func noteOwnWriteSuppressesTheNextChange() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
watcher.noteOwnWrite(at: start)
pasteboard.simulateCopy("Hallo")
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == .ignoredOwnWrite)
}
@Test func clearForgetsTheFirstCopy() {
let pasteboard = FakePasteboard()
let watcher = PasteboardWatcher(pasteboard: pasteboard)
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start) == nil)
watcher.clear()
pasteboard.simulateCopy("Hello")
#expect(watcher.poll(at: start.addingTimeInterval(0.1)) == nil)
}
@Test func startAndStopDoNotLeakThePollTask() async {
let pasteboard = FakePasteboard()
let ticker = ManualPasteboardTicker()
let watcher = PasteboardWatcher(pasteboard: pasteboard, ticker: ticker)
watcher.start { _ in }
#expect(watcher.isRunning)
for _ in 0 ..< 1000 where !ticker.isStarted {
await Task.yield()
}
watcher.stop()
#expect(!watcher.isRunning)
for _ in 0 ..< 1000 where !ticker.isTerminated {
await Task.yield()
}
#expect(ticker.isTerminated)
}
}
@@ -0,0 +1,74 @@
import AppKit
import Foundation
import SprachmittlerCore
import SprachmittlerTestSupport
import Testing
@testable import SprachmittlerCapture
@Suite("Services provider")
@MainActor
struct ServicesProviderTests {
@Test func deliversTheSelectedTextWithoutAccessibility() throws {
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
pasteboard.clearContents()
pasteboard.setString("Hello from Services", forType: .string)
let box = CapturedBox()
let provider = ServicesProvider { box.record($0) }
var error: NSString = ""
provider.translateSelection(pasteboard, userData: "", error: &error)
let captured = try #require(box.captured)
#expect(captured.text == "Hello from Services")
#expect(captured.source == .services)
}
@Test func emptySelectionReturnsAnError() {
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
pasteboard.clearContents()
let box = CapturedBox()
let provider = ServicesProvider { box.record($0) }
var error: NSString = ""
provider.translateSelection(pasteboard, userData: "", error: &error)
#expect(error.length > 0)
#expect(box.captured == nil)
}
@Test func ownWriteMarkersAreIgnored() {
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
pasteboard.clearContents()
pasteboard.setString("Hallo", forType: .string)
pasteboard.setData(
Data(),
forType: NSPasteboard.PasteboardType("com.schihei.sprachmittler.own")
)
let box = CapturedBox()
let provider = ServicesProvider { box.record($0) }
var error: NSString = ""
provider.translateSelection(pasteboard, userData: "", error: &error)
#expect(error.length > 0)
#expect(box.captured == nil)
}
}
/// @unchecked Sendable is safe because every field is guarded by `lock`.
private final class CapturedBox: @unchecked Sendable {
private let lock = NSLock()
private var value: CapturedText?
var captured: CapturedText? {
lock.lock()
defer { lock.unlock() }
return value
}
func record(_ captured: CapturedText) {
lock.lock()
value = captured
lock.unlock()
}
}
@@ -0,0 +1,51 @@
import AppKit
import Foundation
import SprachmittlerCapture
import Testing
@Suite("System pasteboard adapter")
@MainActor
struct SystemPasteboardTests {
private func makePasteboard() -> (NSPasteboard, SystemPasteboard) {
let pasteboard = NSPasteboard(name: NSPasteboard.Name("SprachmittlerTests-\(UUID().uuidString)"))
pasteboard.clearContents()
return (pasteboard, SystemPasteboard(pasteboard: pasteboard))
}
@Test func writeAddsTextAndMarkers() {
let (pasteboard, adapter) = makePasteboard()
let before = adapter.changeCount
let after = adapter.write("Hallo")
#expect(after > before)
#expect(pasteboard.string(forType: .string) == "Hallo")
#expect(adapter.containsOwnWriteMarkers())
}
@Test func snapshotAndRestoreRoundTripMultipleTypes() throws {
let (pasteboard, adapter) = makePasteboard()
let rtf = Data("rich".utf8)
pasteboard.setString("Hello", forType: .string)
pasteboard.setData(rtf, forType: .rtf)
let snapshot = try #require(adapter.snapshot())
_ = adapter.write("Translation")
#expect(adapter.restore(snapshot, onlyIfChangeCountMatches: adapter.changeCount))
#expect(pasteboard.string(forType: .string) == "Hello")
#expect(pasteboard.data(forType: .rtf) == rtf)
}
@Test func restoreIsRefusedAfterAnotherChange() throws {
let (pasteboard, adapter) = makePasteboard()
pasteboard.setString("Hello", forType: .string)
let snapshot = try #require(adapter.snapshot())
pasteboard.clearContents()
pasteboard.setString("Other", forType: .string)
#expect(!adapter.restore(snapshot, onlyIfChangeCountMatches: snapshot.changeCount))
#expect(pasteboard.string(forType: .string) == "Other")
}
}
@@ -0,0 +1,28 @@
import SprachmittlerCore
import Testing
@Suite("Capture policy")
struct CapturePolicyTests {
@Test func emptyAndWhitespaceTextAreRejected() {
#expect(CapturePolicy.validate("") == .empty)
#expect(CapturePolicy.validate(" \n\t") == .empty)
}
@Test func latinLimitIs4000() {
#expect(CapturePolicy.validate(String(repeating: "a", count: 4000)) == .valid)
#expect(
CapturePolicy.validate(String(repeating: "a", count: 4001))
== .textTooLong(characters: 4001, limit: 4000)
)
}
@Test func denseScriptLimitIs2000() {
let valid = String(repeating: "你", count: 2000)
let tooLong = String(repeating: "你", count: 2001)
#expect(CapturePolicy.validate(valid) == .valid)
#expect(
CapturePolicy.validate(tooLong)
== .textTooLong(characters: 2001, limit: 2000)
)
}
}
@@ -0,0 +1,225 @@
import Foundation
import SprachmittlerCore
import SprachmittlerEngines
import SprachmittlerOllama
import SprachmittlerText
import Testing
@Suite("Translation pipeline")
struct TranslationPipelineTests {
private let german = HyMT3Languages.german
private let model = "test-hy-mt3"
@Test func usesTheDocumentedPromptAndReportsTheSourceLanguage() async throws {
let chat = SequencedChat(responses: [[
.delta("Hallo"), .done(reason: "stop", metrics: ChatMetrics(promptEvalCount: 9, evalCount: 2)),
]])
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
let result = try await pipeline.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
#expect(result.translation == "Hallo")
#expect(result.sourceLanguage == "en")
#expect(result.chunkCount == 1)
#expect(result.warnings.isEmpty)
let request = try #require(chat.recorded.first)
#expect(request.messages.first?.content == HyMT3Prompt.defaultTranslation(target: german, source: "Hello."))
#expect(request.options.numCtx == 8192)
}
@Test func chunksAreJoinedWithTheOriginalSeparators() async throws {
let chat = SequencedChat(responses: [
[.delta("Erster Absatz."), .done(reason: "stop", metrics: .empty)],
[.delta("Zweiter Absatz."), .done(reason: "stop", metrics: .empty)],
])
let pipeline = makePipeline(
chat: chat,
chunker: Chunker(latinLimit: 20, denseLimit: 20),
detector: FixedDetector(code: "en", confidence: 0.9)
)
let result = try await pipeline.translate(
text: "First paragraph.\n\nSecond paragraph.",
target: german,
model: model,
keepAlive: "30m"
)
#expect(result.chunkCount == 2)
#expect(result.translation == "Erster Absatz.\n\nZweiter Absatz.")
#expect(chat.recorded.count == 2)
#expect(chat.recorded[1].messages.first?.content.contains("Second paragraph.") == true)
}
@Test func retriesOnceWithTheDocumentedDelimitersPrompt() async throws {
let chat = SequencedChat(responses: [
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
[.delta("Öffne https://example.com jetzt."), .done(reason: "stop", metrics: .empty)],
])
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
let result = try await pipeline.translate(
text: "Open https://example.com now.",
target: german,
model: model,
keepAlive: "30m"
)
#expect(chat.recorded.count == 2)
#expect(chat.recorded[1].messages.first?.content.contains("retain the exact same number of delimiters") == true)
#expect(result.translation == "Öffne https://example.com jetzt.")
#expect(!result.warnings.contains {
if case .missingProtectedToken = $0 {
true
} else {
false
}
})
}
@Test func reportsASecondLostTokenWithoutASecondRetry() async throws {
let chat = SequencedChat(responses: [
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
[.delta("Öffne jetzt."), .done(reason: "stop", metrics: .empty)],
])
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
let result = try await pipeline.translate(
text: "Open https://example.com now.",
target: german,
model: model,
keepAlive: "30m"
)
#expect(chat.recorded.count == 2)
#expect(result.warnings.contains(.missingProtectedToken("https://example.com")))
}
@Test func emptyTextAndUnknownModelsFailBeforeTheNetwork() async {
let chat = SequencedChat(responses: [])
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "en", confidence: 0.9))
await #expect(throws: SprachmittlerError.emptyText) {
_ = try await pipeline.translate(text: " ", target: german, model: model, keepAlive: "30m")
}
let emptyRegistry = TranslationPipeline(
chat: chat,
registry: AdapterRegistry(adapters: []),
detector: FixedDetector(code: "en", confidence: 0.9)
)
await #expect(throws: SprachmittlerError.noAdapter(model: "llama3")) {
_ = try await emptyRegistry.translate(text: "Hello.", target: german, model: "llama3", keepAlive: "30m")
}
#expect(chat.recorded.isEmpty)
}
@Test func sameLanguageIsAnAdvisoryWarning() async throws {
let chat = SequencedChat(responses: [
[.delta("Hallo."), .done(reason: "stop", metrics: .empty)],
])
let pipeline = makePipeline(chat: chat, detector: FixedDetector(code: "de", confidence: 0.9))
let result = try await pipeline.translate(text: "Hallo.", target: german, model: model, keepAlive: "30m")
#expect(result.warnings.contains(.sameLanguage(source: "de", target: "de")))
}
@Test func truncationAndLoopsAreWarnings() async throws {
let truncated = SequencedChat(responses: [
[.delta("Hallo"), .done(reason: "length", metrics: .empty)],
])
let truncatedResult = try await makePipeline(
chat: truncated,
detector: FixedDetector(code: "en", confidence: 0.9)
)
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
#expect(truncatedResult.warnings.contains(.truncated))
let repeated = "This line repeats exactly."
let looping = SequencedChat(responses: [[
.delta(Array(repeating: repeated, count: 6).joined(separator: "\n")),
.done(reason: "stop", metrics: .empty),
]])
let loopResult = try await makePipeline(chat: looping, detector: FixedDetector(code: "en", confidence: 0.9))
.translate(text: "Hello.", target: german, model: model, keepAlive: "30m")
#expect(loopResult.warnings.contains(.repetitionLoop))
}
@Test func transportErrorsAreMappedAtTheCoreBoundary() async throws {
let url = try #require(URL(string: "http://127.0.0.1:9"))
let pipeline = TranslationPipeline(
chat: FailingChat(error: .unreachable(url)),
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
detector: FixedDetector(code: "en", confidence: 0.9)
)
await #expect(throws: SprachmittlerError.ollamaUnreachable(url: url)) {
_ = try await pipeline.translate(
text: "Hello.",
target: german,
model: model,
keepAlive: "30m"
)
}
}
private func makePipeline(
chat: any OllamaChatting,
chunker: Chunker = Chunker(),
detector: any LanguageDetecting
) -> TranslationPipeline {
TranslationPipeline(
chat: chat,
registry: AdapterRegistry(adapters: [HyMT3Adapter()]),
detector: detector,
chunker: chunker
)
}
}
private struct FixedDetector: LanguageDetecting {
let code: String
let confidence: Double
func detect(_ text: String) -> LanguageDetection? {
LanguageDetection(code: code, confidence: confidence, alternatives: [code])
}
}
private struct FailingChat: OllamaChatting {
let error: OllamaError
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
AsyncThrowingStream { continuation in
continuation.finish(throwing: error)
}
}
}
/// A chat fake that returns one response per call. `@unchecked Sendable` is safe because every
/// mutable field is guarded by `lock`.
private final class SequencedChat: OllamaChatting, @unchecked Sendable {
private let lock = NSLock()
private var responses: [[ChatEvent]]
private var requests: [ChatRequest] = []
init(responses: [[ChatEvent]]) {
self.responses = responses
}
var recorded: [ChatRequest] {
lock.lock()
defer { lock.unlock() }
return requests
}
func chat(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, any Error> {
lock.lock()
requests.append(request)
let events = responses.isEmpty ? [] : responses.removeFirst()
lock.unlock()
return AsyncThrowingStream { continuation in
for event in events {
continuation.yield(event)
}
continuation.finish()
}
}
}
@@ -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")
}
}
@@ -0,0 +1,62 @@
import Testing
@testable import SprachmittlerText
@Suite("Chunker")
struct ChunkerTests {
@Test func splitsLongLatinTextAtParagraphsAndRoundTrips() {
let paragraph = String(repeating: "The quick brown fox jumps over the lazy dog. ", count: 25)
let text = Array(repeating: paragraph, count: 9).joined(separator: "\n\n")
let chunker = Chunker()
let chunks = chunker.chunks(for: text)
#expect(chunks.count > 1)
#expect(chunks.allSatisfy { $0.text.count <= 4000 })
#expect(Chunker.reassemble(chunks) == text)
#expect(chunks.dropLast().contains { $0.separatorAfter.contains("\n\n") })
}
@Test func cjkUsesTheSmallerLimit() {
let text = String(repeating: "你好世界。", count: 900)
let chunks = Chunker().chunks(for: text)
#expect(TextScript.isDense(text))
#expect(chunks.count > 1)
#expect(chunks.allSatisfy { $0.text.count <= 2000 })
#expect(Chunker.reassemble(chunks) == text)
}
@Test func neverSplitsAGraphemeCluster() {
let family = "👨‍👩‍👧‍👦"
let text = String(repeating: family, count: 20)
let chunks = Chunker(latinLimit: 1, denseLimit: 1).chunks(for: text)
#expect(chunks.count == 20)
#expect(chunks.allSatisfy { $0.text == family })
#expect(Chunker.reassemble(chunks) == text)
}
@Test func splitsASingleLongWord() {
let text = String(repeating: "a", count: 5000)
let chunks = Chunker(latinLimit: 100, denseLimit: 100).chunks(for: text)
#expect(chunks.count >= 50)
#expect(chunks.allSatisfy { $0.text.count <= 100 })
#expect(Chunker.reassemble(chunks) == text)
}
@Test func leadingBlankLinesRoundTripExactly() {
let text = "\n\nHello world."
let chunks = Chunker().chunks(for: text)
#expect(Chunker.reassemble(chunks) == text)
}
@Test func leadingWhitespaceInLongTextRoundTripsExactly() {
let text = " " + String(repeating: "word ", count: 10)
let chunks = Chunker(latinLimit: 10, denseLimit: 10).chunks(for: text)
#expect(Chunker.reassemble(chunks) == text)
}
@Test func emptyTextHasNoChunks() {
#expect(Chunker().chunks(for: "").isEmpty)
}
}
@@ -0,0 +1,31 @@
import Testing
@testable import SprachmittlerText
@Suite("Content classifier")
struct ContentClassifierTests {
private let classifier = ContentClassifier()
@Test func classifiesPlainProse() {
#expect(classifier.classify("The quick brown fox jumps over the lazy dog.") == .plain)
#expect(classifier.classify("If x < y < z then the order is strict.") == .plain)
}
@Test func classifiesJSON() {
#expect(classifier.classify(#"{"name":"value","count":2}"#) == .json)
}
@Test func classifiesHTML() {
#expect(classifier.classify("<div><p>Hello</p></div>") == .html)
}
@Test func classifiesMarkdown() {
#expect(classifier.classify("# Heading\n\n- one\n- two") == .markdown)
}
@Test func classifiesDelimiterHeavyText() {
#expect(
classifier.classify("Use {{a}}, {{b}}, {{c}} and https://example.com today.")
== .delimited
)
}
}
@@ -0,0 +1,32 @@
import Testing
@testable import SprachmittlerText
@Suite("Language detection")
struct LanguageDetectorTests {
private let detector = NaturalLanguageDetector()
@Test func detectsGerman() throws {
let detection = try #require(
detector.detect(
"Die schnelle Katze springt über den faulen Hund. Das ist ein deutscher Satz mit genügend Wörtern."
)
)
#expect(detection.code == "de")
#expect(detection.confidence > 0.5)
}
@Test func detectsEnglish() throws {
let detection = try #require(
detector.detect(
"The quick brown fox jumps over the lazy dog. This is an English paragraph with enough words."
)
)
#expect(detection.code == "en")
#expect(detection.confidence > 0.5)
}
@Test func emptyTextHasNoDetection() {
#expect(detector.detect(" ") == nil)
#expect(detector.detect("") == nil)
}
}
@@ -0,0 +1,49 @@
import Testing
@testable import SprachmittlerText
@Suite("Protected token scanner")
struct ProtectedTokenScannerTests {
private let scanner = ProtectedTokenScanner()
@Test func findsEveryTokenKind() {
let text = """
Visit https://example.com/docs?lang=en#top and mail name@example.com.
Use {{ limit }}, ${name}, %s, %1$@ and %02d.
Inline `let x = 1` and:
```swift
let y = 2
```
<a href="https://example.com">link</a>
Path /Users/someone/file.txt and key: {"name":"value"}
"""
let kinds = Set(scanner.scan(text).map(\.kind))
#expect(kinds.contains(.url))
#expect(kinds.contains(.email))
#expect(kinds.contains(.mustache))
#expect(kinds.contains(.templateLiteral))
#expect(kinds.contains(.printf))
#expect(kinds.contains(.codeSpan))
#expect(kinds.contains(.fencedCode))
#expect(kinds.contains(.htmlTag))
#expect(kinds.contains(.jsonKey))
#expect(kinds.contains(.filePath))
}
@Test func trimsSentencePunctuationFromURLs() {
let tokens = scanner.scan("See https://example.com/a. Then https://example.com/b?x=1)")
let urls = tokens.filter { $0.kind == .url }.map(\.value)
#expect(urls.contains("https://example.com/a"))
#expect(urls.contains("https://example.com/b?x=1"))
}
@Test func ordinaryTextHasNoTokens() {
let tokens = scanner.scan("Costs 3.50 (approx.) - see the note; 100% done.")
#expect(tokens.isEmpty)
}
@Test func htmlTagKeepsItsURL() {
let token = scanner.scan("<a href=\"https://example.com\">x</a>").first { $0.kind == .htmlTag }
#expect(token?.value == "<a href=\"https://example.com\">")
}
}
@@ -0,0 +1,22 @@
import Foundation
import Testing
@testable import SprachmittlerText
@Suite("Text normalisation")
struct TextNormalizationTests {
@Test func inputNormalisationFollowsN1ToN3() {
let input = "\u{FEFF} Hello\r\nworld\u{0}\u{200B}\u{1}\u{200D}\u{200C} "
#expect(TextNormalization.normalizeInput(input) == "Hello\nworld\u{200D}\u{200C}")
}
@Test func outputOnlyTrimsAndNormalisesLineEndings() {
let output = " first line\r\n\tsecond line \n\nthird "
#expect(TextNormalization.normalizeOutput(output) == "first line\n\tsecond line \n\nthird")
}
@Test func comparisonNormalisationKeepsInternalWhitespace() {
#expect(
TextNormalization.normalizeForComparison(" a \t b\r\n") == "a \t b"
)
}
}
+36 -20
View File
@@ -145,7 +145,7 @@ flowchart TD
- `SprachmittlerCapture` is the only module that imports `ApplicationServices`/`Accessibility` and touches `NSPasteboard`. It depends on `SprachmittlerCore` for domain types and protocols.
- `SprachmittlerEval` is linked into the CLI only, never into the app.
- `sprachmittler-cli` links `SprachmittlerOllama` and `SprachmittlerEngines` directly for the M1 commands; it is never linked into the app.
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore` and `SprachmittlerOllama`; it is never linked into the app.
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore`, `SprachmittlerCapture` and `SprachmittlerOllama`; it is never linked into the app.
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
### Third-party dependencies
@@ -163,16 +163,18 @@ All other functionality uses Apple frameworks. No keyboard-shortcut library is n
```swift
// SprachmittlerCore
public struct LanguageCode: RawRepresentable, Hashable, Codable, Sendable {
public let rawValue: String // "de", "en", "zh-Hant", "pt-BR", "kk-Cyrl"
}
// Defined in SprachmittlerEngines; re-exported by SprachmittlerCore.
public typealias LanguageCode = String // "de", "en", "zh-Hant", "pt-BR", "kk-Cyrl"
public struct TargetLanguage: Hashable, Codable, Sendable, Identifiable {
public struct ModelLanguage: Hashable, Codable, Sendable, Identifiable {
public let code: LanguageCode
public let modelName: String // exact English name from the model card, e.g. "German"
public let displayName: String // localised UI name
public var id: String { code.rawValue }
public let displayName: String // English fallback; localizedDisplayName for UI
public let isRTL: Bool
public let usesDenseScript: Bool
public var id: String { code }
}
public typealias TargetLanguage = ModelLanguage
public struct CapturedText: Sendable, Equatable {
public let text: String
@@ -210,14 +212,14 @@ public struct TranslationResult: Sendable, Equatable {
}
public enum TranslationWarning: Sendable, Equatable {
case preambleDetected(line: String)
case preambleDetected(firstLine: String)
case truncated
case repetitionLoop
case missingProtectedToken(String)
case emptyOutput
case sameLanguage(source: LanguageCode, target: LanguageCode)
case chunkFailed(index: Int)
case sameLanguage(source: String, target: String)
case numericMismatch
case chunkFailed(index: Int)
}
public struct TranslationTiming: Sendable, Equatable {
@@ -228,7 +230,7 @@ public struct TranslationTiming: Sendable, Equatable {
}
public enum InsertionOutcome: Sendable, Equatable {
case replaced(by: InsertionMethod) // .accessibility, .paste
case replaced(using: InsertionMethod) // .accessibility, .paste
case copiedOnly
case failed(SprachmittlerError)
}
@@ -238,6 +240,8 @@ public enum InsertionMethod: String, Sendable {
}
```
Language and warning value types live in `SprachmittlerEngines`, because they carry model-card names and validation results: `ModelLanguage` (re-exported as `TargetLanguage`) and `TranslationWarning`. `SprachmittlerCore` re-exports both for the session and UI. `TranslationPipeline` in Core owns chunk orchestration, the one documented retry and timing.
### Error taxonomy
```swift
@@ -332,18 +336,28 @@ Full detail: `docs/SELECTION_AND_CLIPBOARD.md`.
### 7.1 Double-copy watcher (`SprachmittlerCapture`)
```swift
public protocol PasteboardWatching: Sendable {
func events() -> AsyncStream<PasteboardEvent>
@MainActor public protocol PasteboardAccessing: AnyObject {
var changeCount: Int { get }
func string() -> String?
func containsOwnWriteMarkers() -> Bool
func snapshot() -> ClipboardSnapshot?
func restore(_ snapshot: ClipboardSnapshot, onlyIfChangeCountMatches: Int) -> Bool
@discardableResult func write(_ text: String) -> Int
}
public enum PasteboardEvent: Sendable, Equatable {
case changed(changeCount: Int)
case textAvailable(String)
case ignoredOwnWrite
public struct DoubleCopyDetector { /* pure state machine */ }
@MainActor public final class PasteboardWatcher {
init(pasteboard: any PasteboardAccessing,
ticker: any PasteboardTicking = TimerPasteboardTicker())
func start(onEvent: @escaping @MainActor (PasteboardWatcherEvent) -> Void)
func stop()
func clear()
func noteOwnWrite(at: Date)
}
```
- Poll `NSPasteboard.general.changeCount` on a `@MainActor` timer every **120 ms**.
- Poll `NSPasteboard.general.changeCount` every **120 ms** on the main actor through `PasteboardTicking`.
- A candidate trigger is two changes within **500 ms** (range 300–1000 ms, setting) whose `.string` values are identical and non-empty after trimming.
- Require at least one non-whitespace character and at most `maxCharacters` (4000 Latin / 2000 CJK by default).
- Ignore changes whose pasteboard contains the app's own marker (`com.schihei.sprachmittler.own`) or `org.nspasteboard.TransientType`, and ignore all changes for 750 ms after our own write.
@@ -461,6 +475,8 @@ Thresholds are constants in one file and covered by tests. Quality failures are
Full detail: `docs/TRANSLATION_OUTPUT.md`.
`TranslationPipeline` in `SprachmittlerCore` is the shared implementation used by the CLI and the M4 session: it normalises input, detects the language, classifies content, scans protected tokens, chunks, calls the adapter, joins chunk results with the original separators, validates once, and enforces the single documented retry.
### 9.1 Input analysis (`SprachmittlerText`)
1. Normalise line endings to `\n`; strip NUL and other C0 controls except `\t` and `\n`; NFC.
@@ -474,8 +490,8 @@ Full detail: `docs/TRANSLATION_OUTPUT.md`.
| Content | Prompt |
|---|---|
| Plain prose | Documented **Default Translation** |
| Markdown / JSON / HTML | Documented **Structured Data 1** with `format_type` |
| Placeholder- or delimiter-heavy | Documented **Delimiters** |
| Markdown / JSON / HTML | Documented **Default Translation** first; **Structured Data 1** is the single fallback after a lost token |
| Placeholder- or delimiter-heavy | Documented **Default Translation** first; **Delimiters** is the single fallback after a lost token |
| User glossary (future) | Documented **Terminology** |
| User style (future) | Documented **Style** |
+17 -3
View File
@@ -110,8 +110,22 @@ Decision: `TranslationSession` is an actor with one active request. A new trigge
Consequences: Fast, predictable updates and no orphaned requests. The previous translation is lost when the user triggers a new one; that is intentional and avoids history.
## ADR-016 — Provisional M1 Engines slice for the CLI
Status: Accepted (provisional; replaced in M2)
Status: Superseded by ADR-017
Context: T1.6 needs the documented Default prompt and the exact model language name before T2.2/T2.3 exist. Putting either in the CLI target would violate documented-prompts-only and the lint rule that prompt and language literals live in `SprachmittlerEngines`.
Decision: Add a provisional `ModelLanguage` with the 16 common targets from `LANGUAGES.md` §5, the byte-exact Default Translation prompt, the documented sampling values and `HyMT3RequestFactory` in `SprachmittlerEngines`. T2.3 replaces the table with all 102 languages; T2.1/T2.2 replace the factory with `TranslationAdapter`/`HyMT3Adapter`.
Consequences: The M1 CLI translates en→de and the other common targets without a free-form prompt. Unknown codes fail before the network. Only 16 targets resolve until T2.3, and no prompt literal or model tag appears outside Engines.
Decision: Add a provisional `ModelLanguage` with the 15 common targets from `LANGUAGES.md` §5, the byte-exact Default Translation prompt, the documented sampling values and `HyMT3RequestFactory` in `SprachmittlerEngines`. T2.3 replaces the table with all 102 languages; T2.1/T2.2 replace the factory with `TranslationAdapter`/`HyMT3Adapter`.
Consequences: The M1 CLI translates en→de and the other common targets without a free-form prompt. Unknown codes fail before the network. Only 15 targets resolve until T2.3, and no prompt literal or model tag appears outside Engines.
## ADR-017 — Adapter registry in Engines; one pipeline in Core
Status: Accepted
Context: M1 needed a prompt and a request factory for the CLI before the model-family adapter existed. T2.1/T2.2 replace that factory, and both the CLI and the future panel must use the same chunking, validation and retry rules. Prompt strings must stay in `SprachmittlerEngines`; validation results must be visible to Core and the UI.
Decision: `TranslationAdapter` and `AdapterRegistry` live in `SprachmittlerEngines`. An `AdapterRequest` carries text, target, model, keep-alive, prompt variant and sampling. `HyMT3Adapter` is the only family adapter in v1; it sets the publisher sampling, `num_ctx: 8192`, exactly one user message and no system/think field. `TranslationWarning` and `ModelLanguage` (re-exported as `TargetLanguage`) also live in Engines, and `LanguageMatching` owns the canonical-code comparison. `TranslationPipeline` in `SprachmittlerCore` does normalisation, detection, classification, chunking, one documented retry after a lost protected token, validation and timing; the keep-alive value is supplied by the composition root. Core re-exports the warning and language types.
Consequences: The CLI and M4 session share one implementation. Prompt bytes and language names have one home. Adapter selection is explicit and unknown families fail with `noAdapter`. The M1 `HyMT3RequestFactory` and its 15-language table are removed. A second model family adds an adapter, not a branch in Core.
## ADR-018 — Capture behind a pasteboard protocol; Services is a first-class trigger
Status: Accepted
Context: Double copy, clipboard snapshot/restore and Services all touch `NSPasteboard`, but the state machine and watcher need deterministic tests without real time or the user's clipboard. The Services path must work with no Accessibility permission.
Decision: `SprachmittlerCapture` defines `PasteboardAccessing` and `PasteboardTicking`. `SystemPasteboard` is the only production `NSPasteboard` user; `FakePasteboard` and `ManualPasteboardTicker` live in `SprachmittlerTestSupport`. `DoubleCopyDetector` is a pure state machine over change events and an injected date. `PasteboardWatcher` polls every 120 ms, reads the string only after `changeCount` changes, suppresses own/transient changes for 750 ms, and enforces the 4000/2000 limit. `ServicesProvider` receives the system pasteboard and needs no polling or Accessibility. `AppDelegate` installs it and calls `NSUpdateDynamicServices`.
Consequences: Capture logic is unit-testable and no global key tap is needed. The Services and double-copy paths both produce `CapturedText`. The 10-app compatibility matrix remains a manual task.
+10 -7
View File
@@ -162,13 +162,16 @@ Fill in from the spike. One row per tag and direction.
| Tag | Digest (first 12) | Ollama | Direction | Works | Notes (quality, preamble, tokens, speed) |
|---|---|---|---|---|---|
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | en→de | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | de→en | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | markdown | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | json | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | | 0.40.18 | placeholders | ☐ | |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | en→de | ☐ | |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | de→en | ☐ | |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | en→de | ✅ | 33 output tokens, 0.94 s, no warnings. "Meeting" stayed as a loanword; no preamble. |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | de→en | ✅ | 26 output tokens, 0.66 s, no warnings; 9:30 and Room 4B preserved. |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | markdown | ✅ | 50 output tokens, 1.18 s, no warnings; heading, bold, code span and link URL preserved. "num_ctx setting" became "num_ctx-Einstieg" (literal-compound limitation, not edited). |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | json | ✅ | 21 output tokens, 0.57 s, no warnings; keys and structure preserved, feature values translated. |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | placeholders | ✅ | 28 output tokens, 0.72 s, no warnings; URL, e-mail, `{{name}}` and `${deadline}` preserved. |
| hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M | 262ac792aeb5 | 0.40.18 | long paragraph | ⚠️ | 4,315 varied chars → 2 chunks, 1,240 output tokens, 29.1 s, no warnings. An 8,785-char synthetic text whose source repeated identical blocks emitted a repeated window; the guard stopped it with `repetitionLoop` and missing-token warnings. Source repetition is indistinguishable from model repetition to the output-only guard. |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | en→de | ☐ | Not installed; VERIFY deferred to T2.7/T7.4. |
| hf.co/tencent/Hy-MT3-1.8B-GGUF:Q4_K_M | | | de→en | ☐ | Not installed; VERIFY deferred to T2.7/T7.4. |
Prompt-prefix note: the prefix stayed identical across the en→de runs; Ollama reported 43–773 prompt tokens depending on chunk count. The `/api/chat` final object exposes prompt/eval counts but not the cached-token count, so cache reuse is inferred from the unchanged prefix and the owner's earlier 177/178 measurement, not from a new counter.
## 8. Adding a model
+25 -12
View File
@@ -21,20 +21,20 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
- [x] T1.6 sprachmittler-cli models / show / translate — 2026-11-26
## M2 — Hy-MT3 adapter and text pipeline
- [ ] T2.1 Adapter protocol, registry, sampling merge
- [ ] T2.2 Hy-MT3 adapter and byte-exact prompt
- [ ] T2.3 Language catalogue (102 languages)
- [ ] T2.4 Language detection, content classifier, chunker
- [ ] T2.5 Protected tokens, output validator, preamble detector
- [ ] T2.6 Prompt policy and documented fallbacks
- [ ] T2.7 Compatibility spike (gate)
- [x] T2.1 Adapter protocol, registry, sampling merge — 2026-11-26
- [x] T2.2 Hy-MT3 adapter and byte-exact prompt — 2026-11-26
- [x] T2.3 Language catalogue (102 languages) — 2026-11-26
- [x] T2.4 Language detection, content classifier, chunker — 2026-11-26
- [x] T2.5 Protected tokens, output validator, preamble detector — 2026-11-26
- [x] T2.6 Prompt policy and documented fallbacks — 2026-11-26
- [x] T2.7 Compatibility spike (gate) — 2026-11-26 · 7B passed; 1.8B not installed
## M3 — Double-copy capture
- [ ] T3.1 DoubleCopyDetector state machine
- [ ] T3.2 Pasteboard watcher and own-write suppression
- [ ] T3.3 Clipboard snapshot and restore
- [ ] T3.4 Services provider and menu item
- [ ] T3.5 Manual double-copy matrix
- [x] T3.1 DoubleCopyDetector state machine — 2026-11-26
- [x] T3.2 Pasteboard watcher and own-write suppression — 2026-11-26
- [x] T3.3 Clipboard snapshot and restore — 2026-11-26
- [x] T3.4 Services provider and menu item — 2026-11-26
- [~] T3.5 Manual double-copy matrix — 2026-11-26 · code complete; 10-app matrix needs a person
## M4 — Translation session and panel
- [ ] T4.1 TranslationSession actor and epochs
@@ -107,3 +107,16 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · T1.5 · Added the provisional Engines slice (`ModelLanguage`, 16 common names, byte-exact Default prompt, documented options, request factory) and the loopback-only warm-up policy. Warm-up uses fixed `Hello.` and `num_predict: 8`; unload uses `keep_alive:"0"`.
2026-11-26 · T1.6 · Implemented `sprachmittler-cli models`, `show` and `translate` (`--text/--file`, `--target`, `--model`, `--json`, `--include-source`). Live 7B checks: models/show, en→de text, JSON with null sourceLanguage/empty warnings, unreachable exit 3. The 102-language catalogue remains T2.3.
2026-11-26 · M1 · Review fixes: 180 s URLSession request/resource budget (no 60 s pre-emption), missing-`done` is an error, CLI diagnostics go to stderr and endpoint rejection exits 2, `CLIEnvironment` is the composition root, and cancellation/URL-task-stop tests are deterministic. Both reviewers approved.
2026-11-26 · T2.1 · Added `AdapterRequest`/`TranslationAdapter`/`AdapterRegistry`, `SamplingOptions` + overrides, and exact wire-option tests. Prompt literals remain only in Engines.
2026-11-26 · T2.2 · `HyMT3Adapter` builds one user message, publisher sampling, `num_ctx: 8192`, no system/think; byte-exact golden tests for Default, Delimiters and Structured Data 1.
2026-11-26 · T2.3 · `HyMT3Languages` now has all 102 entries with exact model names, BCP-47 variants (`zh-Hant`, `pt-BR`, `nb`/`nn`, `kk-Cyrl`, `mn-Cyrl`, `ku`/`ckb`), RTL and dense-script flags.
2026-11-26 · T2.4 · Added `TextNormalization` (N1–N3, T1), `NaturalLanguageDetector`, `ContentClassifier` and the script-aware `Chunker`; join round-trips exactly, grapheme clusters are never split.
2026-11-26 · T2.5 · Added `ProtectedTokenScanner` for all ten token kinds, `OutputValidator` for empty/preamble/truncation/repetition/token/number checks, and a streaming repetition detector. No output is rewritten.
2026-11-26 · T2.6 · Added `PromptPolicy`: Default first, one documented Delimiters/Structured Data 1 retry only after a lost protected token. `TranslationPipeline` (Core) enforces the one retry and joins chunks with the source separators.
2026-11-26 · T2.7 · 7B spike: en→de, de→en, Markdown, JSON, placeholders and a 4,315-char long text passed with no warnings; an 8,785-char repetitive source hit the repetition guard. Results and timings are in `HYMT3_MODEL.md` §7. The 1.8B spike still needs the model.
2026-11-26 · T3.1 · Added the pure `DoubleCopyDetector`: 500 ms default window, identical text after line-ending/outer-trim normalisation, duplicate changeCount ignored, reset rules.
2026-11-26 · T3.2 · Added `PasteboardWatcher` (120 ms injected ticker, read only after a change, 750 ms own-write suppression, 4000/2000 script limits, clear on stop) and `SystemPasteboard`.
2026-11-26 · T3.3 · Added `ClipboardSnapshot`/`ClipboardItemData`: all items and types, forced lazy data, restore only when `changeCount` still matches, own/transient/concealed markers on writes.
2026-11-26 · T3.4 · Added `ServicesProvider` and wired `NSApp.servicesProvider` + `NSUpdateDynamicServices`; the menu-bar “Translate Clipboard Text” item now delivers a `.menu` capture. The app has a log-only sink until the M4 panel.
2026-11-26 · M3 · The capture matrix (T3.5) is intentionally still unchecked; it needs a person in 10 real apps. No Accessibility is requested on the double-copy or Services path.
2026-11-26 · M2/M3 · Review fixes: `OllamaError` is mapped to `SprachmittlerError` at the Core boundary and the CLI maps domain errors to exit 2/3/4; the chunker preserves leading empty separators; `LanguageMatching` moved to Engines and `keepAlive` is supplied by the composition root; `CapturePolicy` enforces the 4000/2000 limit and own markers for menu/Services; golden prompt tests remove exactly one fixture terminator; docs aligned (TestSupport deps, warning enum, 15 common targets, Fixtures path).
+2
View File
@@ -160,6 +160,8 @@ Info.plist:
**This table is filled in by a person, on a real Mac.** Double copy, Accessibility replacement and clipboard restoration differ in every app and cannot be tested headlessly. Until a row is tested its cells stay ☐; an untested cell is not a claim.
Implementation status (2026-11-26): T3.1–T3.4 are implemented and covered by component tests (`DoubleCopyDetector`, `PasteboardWatcher`, `ClipboardSnapshot`, `ServicesProvider`). The 4000/2000 limit and own-marker check apply to double copy, the menu item and Services (`CapturePolicy`). The matrix below is still untested; it is the T3.5 manual task.
For each app test:
1. A plain paragraph.
+1 -1
View File
@@ -21,7 +21,7 @@ Framework: **Swift Testing** (`import Testing`, `@Test`, `#expect`) for all pack
- HTTP contract tests use a serialized `URLProtocol` stub; timeout tests use `ManualSleeper` and never real time.
- Fakes live in `SprachmittlerTestSupport`: `FakePasteboard`, `FakeClock`, `FakeOllamaHTTPTransport`, `FakeOllamaCatalog`, `FakeOllamaChat`, `ManualSleeper`, `FakeTextInserter`, `FakeAccessibility`, `FakeSettingsStore`, `TemporaryDirectory`.
- Fixtures live inside their test target (SwiftPM resources must sit within the target) and are loaded with `Bundle.module`. All fixtures are **synthetic**; never add private text.
- Golden files for prompts, Markdown and JSON output live next to the tests (`Fixtures/golden/`); update them only with an explanation in the commit message.
- Golden files for prompts, Markdown and JSON output live next to the tests (`Fixtures/`); update them only with an explanation in the commit message.
## Required test cases (minimum)
+2 -3
View File
@@ -5,8 +5,7 @@ Modules: `SprachmittlerText` (analysis, chunking), `SprachmittlerEngines` (promp
## 1. Prompt policy
- **Default Translation** is the canonical prompt for v1. It is byte-exact in `docs/HYMT3_MODEL.md` §3.
- **Structured Data 1** is used for JSON, HTML and Markdown tables when the content class says so, or as a fallback if a protected token is lost in a structured source.
- **Delimiters** is the single documented retry when a protected token is lost in plain/delimited text.
- v1 starts with **Default Translation** for every content class. **Structured Data 1** (JSON/HTML/Markdown) and **Delimiters** are the only fallbacks, used once after a protected token was lost. They are selected by the deterministic `PromptPolicy`, never by a user instruction.
- **Terminology**, **Style** and **Structured Data 2** are reserved for future glossary/style/context features; not v1.
- No other prompt text is allowed. The user cannot type a prompt in v1.
@@ -109,7 +108,7 @@ Do not require exact string equality: locales legitimately change decimal and th
No source text is included unless `--include-source` is passed explicitly for debugging. Never write this JSON to disk automatically.
Until T2.4, `sourceLanguage` is `null`; until T2.5, `warnings` is empty.
Until T2.4, `sourceLanguage` is `null`; until T2.5, `warnings` is empty. As of M2 both are populated: `sourceLanguage` is the advisory `NLLanguageRecognizer` code (still nullable) and `warnings` contains the stable warning codes from `TranslationWarning.code`. `timing.promptTokens` and `timing.outputTokens` are summed over chunks and retry attempts.
## 11. Tests