feat(m0): complete scaffold, logging and signature checks (T0.2-T0.6)

Add os.Logger categories, OSSignposter wrapper and shortHash helper; enforce exact Debug/Release/install signatures; lint tests; update M0 docs and progress.
This commit is contained in:
schihei committed 2026-11-26 12:33:51 +01:00
1 parent 374085ec2f
commit 7ca5c710ec
17 files changed
+331 -9

No files matched your search

+5
View File
@@ -1,10 +1,15 @@
import AppKit
import os
import SprachmittlerCore
/// Lifecycle glue: composition root, Services provider, double-copy watcher, termination.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private let loggers = Loggers(subsystem: Bundle.main.bundleIdentifier ?? "Sprachmittler")
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.
//
+3 -1
View File
@@ -42,7 +42,9 @@ app: build-app
install: build-app
@pkill -x Sprachmittler 2>/dev/null || true
ditto "$(APP_PATH)" "$(INSTALL_DIR)/Sprachmittler.app"
codesign --force --sign - "$(INSTALL_DIR)/Sprachmittler.app"
codesign --force --sign - --options runtime \
--entitlements App/Sprachmittler.entitlements "$(INSTALL_DIR)/Sprachmittler.app"
scripts/check-signature.sh "$(INSTALL_DIR)/Sprachmittler.app" install
open "$(INSTALL_DIR)/Sprachmittler.app"
fixtures:
@@ -0,0 +1,21 @@
/// Log categories from ARCHITECTURE §15.
public enum LogCategory: String, CaseIterable, Sendable {
/// Double-copy detection and capture.
case capture
/// Pasteboard polling and own-write suppression.
case pasteboard
/// Translation session lifecycle.
case session
/// Ollama HTTP client.
case ollama
/// Prompt and adapter construction.
case engine
/// Output validation.
case validate
/// Accessibility or paste insertion.
case insert
/// Panel presentation.
case panel
/// Settings persistence.
case settings
}
@@ -0,0 +1,15 @@
import CryptoKit
import Foundation
/// Privacy-safe helpers for log values (SP-2).
public enum LogRedaction {
/// Returns the first 12 lowercase hex characters of the SHA-256 digest of `value`.
///
/// Use this for identifiers that must be correlatable across log lines without revealing
/// the original text. Always log the result with `privacy: .private`; SECURITY_PRIVACY
/// §Logging requires the private qualifier for correlation hashes as well.
public static func shortHash(_ value: String) -> String {
let digest = SHA256.hash(data: Data(value.utf8))
return digest.prefix(6).map { String(format: "%02x", $0) }.joined()
}
}
@@ -0,0 +1,31 @@
import os
/// Factory for the app's `os.Logger` and `OSSignposter` instances.
///
/// The subsystem is supplied by the composition root (the app bundle identifier or the CLI
/// subsystem); this module never hard-codes one.
///
/// ## Leaf modules
/// `SprachmittlerOllama` and `SprachmittlerEngines` cannot import Core. When they gain logging,
/// the composition root passes `Logger` values created here into their initializers. A leaf that
/// needs signposts uses an `OSSignposter` with the literal names from ARCHITECTURE §15. Do not
/// add a Core dependency to a leaf module.
public struct Loggers: Sendable {
/// The `os.Logger` subsystem, normally the app bundle identifier.
public let subsystem: String
/// Creates a factory for the given subsystem.
public init(subsystem: String) {
self.subsystem = subsystem
}
/// Returns the logger for one ARCHITECTURE §15 category.
public func logger(_ category: LogCategory) -> Logger {
Logger(subsystem: subsystem, category: category.rawValue)
}
/// Returns the signposter for one ARCHITECTURE §15 category.
public func signposts(_ category: LogCategory) -> Signposts {
Signposts(subsystem: subsystem, category: category)
}
}
@@ -0,0 +1,13 @@
import os
/// A started signpost interval.
///
/// The value is intentionally not `Sendable`: an interval must begin and end on the same task.
/// Obtain one from ``Signposts/begin(_:)`` and pass it to ``Signposts/end(_:)``.
public struct SignpostInterval {
/// The interval name.
public let name: SignpostName
let state: OSSignpostIntervalState
let signposter: OSSignposter
}
@@ -0,0 +1,33 @@
/// Signpost interval names from ARCHITECTURE §15.
public enum SignpostName: String, CaseIterable, Sendable {
/// Double-copy detection, from the second copy to a captured text.
case capture
/// Panel presentation.
case panel
/// An Ollama request, from send to the final delta.
case request
/// The first translation token.
case firstToken
/// The full translation of one chunk.
case translate
/// Output validation.
case validate
/// Writing the translation to the clipboard.
case copy
/// Accessibility or paste insertion.
case insert
/// `OSSignposter.beginInterval` requires a `StaticString`, so each case maps to its own literal.
public var literal: StaticString {
switch self {
case .capture: "capture"
case .panel: "panel"
case .request: "request"
case .firstToken: "firstToken"
case .translate: "translate"
case .validate: "validate"
case .copy: "copy"
case .insert: "insert"
}
}
}
@@ -0,0 +1,29 @@
import os
/// Thin wrapper around `OSSignposter` that uses the names from ARCHITECTURE §15.
///
/// Leaf modules cannot import Core; the composition root can pass an `OSSignposter` directly to
/// them, using the literal names in ARCHITECTURE §15.
public struct Signposts: Sendable {
private let signposter: OSSignposter
init(subsystem: String, category: LogCategory) {
signposter = OSSignposter(subsystem: subsystem, category: category.rawValue)
}
/// Starts an interval; pair it with ``end(_:)`` on the same task.
public func begin(_ name: SignpostName) -> SignpostInterval {
let state = signposter.beginInterval(name.literal)
return SignpostInterval(name: name, state: state, signposter: signposter)
}
/// Ends an interval started by ``begin(_:)``.
public func end(_ interval: SignpostInterval) {
interval.signposter.endInterval(interval.name.literal, interval.state)
}
/// Emits a single signpost event.
public func event(_ name: SignpostName) {
signposter.emitEvent(name.literal)
}
}
@@ -0,0 +1,16 @@
import Testing
@testable import SprachmittlerCore
/// T0.4: SP-2 allows short hashes in logs, never the underlying text.
@Suite("Log redaction")
struct LogRedactionTests {
@Test func shortHashIsStableTwelveHexAndOpaque() {
let hash = LogRedaction.shortHash("hello")
#expect(hash == "2cf24dba5fb0")
#expect(hash == LogRedaction.shortHash("hello"))
#expect(hash.count == 12)
#expect(hash.allSatisfy { $0.isHexDigit && !$0.isUppercase })
#expect(hash != LogRedaction.shortHash("hello!"))
#expect(!hash.contains("hello"))
}
}
@@ -0,0 +1,54 @@
import os
import Testing
@testable import SprachmittlerCore
/// T0.4: the logging helper must stay in sync with ARCHITECTURE §15.
@Suite("Logging contract")
struct LoggingContractTests {
@Test func categoriesMatchArchitecture() {
#expect(LogCategory.allCases.map(\.rawValue) == [
"capture",
"pasteboard",
"session",
"ollama",
"engine",
"validate",
"insert",
"panel",
"settings",
])
}
@Test func signpostNamesMatchArchitecture() {
#expect(SignpostName.allCases.map(\.rawValue) == [
"capture",
"panel",
"request",
"firstToken",
"translate",
"validate",
"copy",
"insert",
])
}
/// `OSSignposter.beginInterval` needs a `StaticString`; this catches a hand-written switch drift.
@Test func signpostLiteralsMatchRawValues() {
for name in SignpostName.allCases {
#expect(String(describing: name.literal) == name.rawValue)
}
}
@Test func loggersWorkForEveryCategory() {
let loggers = Loggers(subsystem: "test.sprachmittler")
for category in LogCategory.allCases {
loggers.logger(category).debug("logging contract test")
let signposts = loggers.signposts(category)
let interval = signposts.begin(.capture)
#expect(interval.name.rawValue == "capture")
signposts.end(interval)
signposts.event(.panel)
}
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ Goal: an empty but correctly configured project that builds, tests and launches
| Task | Description | AC | Req |
|---|---|---|---|
| T0.1 | The kit ships `Packages/SprachmittlerKit/Package.swift` with placeholder sources, tests and synthetic fixtures. Verify it resolves and builds; replace placeholder enums as modules gain real types. | `swift build --package-path Packages/SprachmittlerKit` and `make test` succeed; fixture-loading test passes. | R048 |
| T0.2 | Complete the `App/` sources (stubs shipped): `SprachmittlerApp` with a `MenuBarExtra`, `Settings` scene and quit item; `Info.plist` (`LSUIElement`, `NSServices`, ATS local networking); non-sandboxed entitlements. | `make app` builds; the menu-bar icon appears and no Dock icon is shown; `codesign -d --entitlements -` shows exactly `app-sandbox = false`. | R021, R041, R049 |
| T0.2 | Complete the `App/` sources (stubs shipped): `SprachmittlerApp` with a `MenuBarExtra`, `Settings` scene and quit item; `Info.plist` (`LSUIElement`, `NSServices`, ATS local networking); non-sandboxed entitlements. | `make app` builds; the menu-bar icon appears and no Dock icon is shown; the entitlements file contains exactly `app-sandbox = false`. A Debug signature may additionally carry Xcode's injected `get-task-allow`; Release and the `make install` signature must not. `scripts/verify.sh` checks the Debug and Release signatures; `make install` checks the installed one. | R021, R041, R049 |
| T0.3 | Validate the shipped `project.yml` and `make generate`; set your own bundle ID prefix. | `xcodegen generate` produces a project that builds in Xcode and via `xcodebuild`. | R049 |
| T0.4 | Run the shipped `scripts/verify.sh`, `.swiftformat`, `.swiftlint.yml`; fix issues so the gate is green on the scaffold. Add `os.Logger` categories and an `OSSignposter` wrapper in `SprachmittlerCore`. | `make verify` runs end-to-end; logging helper used in a test. | R033, R050 |
| T0.5 | Run `make doctor`: OpenCode 2.x installed, `opencode.json` parses as native V2, agents/commands/skills discovered, `opencode debug config` shows the permission rules. | `make doctor` green; `/status` works in OpenCode. | R048 |
+12 -6
View File
@@ -5,12 +5,12 @@ The agent updates this file at the end of every task: check the box, add the ISO
Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
## M0 — Scaffold and tooling
- [ ] T0.1 Package.swift, module placeholders, fixtures load
- [ ] T0.2 App sources, Info.plist, menu-bar stub, entitlements
- [ ] T0.3 project.yml / XcodeGen
- [ ] T0.4 verify script, format/lint, logging + signposts
- [ ] T0.5 OpenCode 2.x doctor
- [ ] T0.6 Environment record and smoke run
- [x] T0.1 Package.swift, module placeholders, fixtures load — 2026-11-26
- [~] T0.2 App sources, Info.plist, menu-bar stub, entitlements — 2026-11-26 · signatures automated; visual menu-bar/Settings/Quit confirmation pending
- [x] T0.3 project.yml / XcodeGen — 2026-11-26
- [x] T0.4 verify script, format/lint, logging + signposts — 2026-11-26
- [~] T0.5 OpenCode 2.x doctor — 2026-11-26 · doctor green; `/status` needs an interactive TUI run
- [x] T0.6 Environment record and smoke run — 2026-11-26
## M1 — Ollama text client
- [ ] T1.1 Capture fixtures, resolve VERIFY items
@@ -94,3 +94,9 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · kit · Owner reference run recorded: 255 output tokens, 43.07 tok/s, 5.97 s warm, 177/178 prompt tokens cached.
2026-11-26 · kit · `make smoke` passed with 7B Q4_K_M: 34 output tokens in 2.89 s, 45.81 tok/s, cold load 2.05 s.
2026-11-26 · kit · `make fixtures` captured version, tags, ps, show, en→de, de→en, Markdown, truncated and missing-model fixtures. Digest `262ac792aeb5`.
2026-11-26 · T0.1 · Verified `swift build` and `make test`; the text and Ollama fixture-loading tests pass through `Bundle.module`. Placeholder enums stay until their modules gain real types.
2026-11-26 · T0.2 · Debug + Release builds and signatures pass via `scripts/check-signature.sh`; an install-style re-sign preserves only `app-sandbox=false` plus Hardened Runtime. The app launches as a `UIElement` (no Dock icon); visual menu-bar/Settings/Quit confirmation is still pending.
2026-11-26 · T0.3 · `xcodegen generate` and Debug/Release `xcodebuild` pass; the generated project stays git-ignored. Bundle prefix remains the provisional `de.schihei`.
2026-11-26 · T0.4 · Added the 9 `os.Logger` categories, 8 `OSSignposter` intervals and a 12-hex `shortHash`; contract tests pass. `verify.sh` now lints Tests and checks Debug + Release signatures; `make install` preserves entitlements and Hardened Runtime. Leaf logging seam for M1/M2 is documented; `shortHash` must be logged with `privacy: .private`.
2026-11-26 · T0.5 · `make doctor` green; native V2 config resolves; agents/commands/skills and the `/status` command file are present. `/status` itself still needs one interactive TUI run.
2026-11-26 · T0.6 · `make smoke` with 7B Q4_K_M: 35 output tokens, 0.86 s warm, 46.96 tok/s, URL preserved. Environment table was already filled.
+1
View File
@@ -26,6 +26,7 @@ These are hard requirements. The `swift-reviewer` agent checks every change agai
- App Sandbox: **disabled** (ADR-003), because Accessibility replacement requires it. Hardened Runtime: **enabled**.
- Entitlements are exactly `com.apple.security.app-sandbox = false`. No network entitlement is needed outside the sandbox.
- Xcode may inject `get-task-allow` into a Debug signature for the debugger. Release and the `make install` signature contain only `com.apple.security.app-sandbox = false`; `scripts/verify.sh` and `make install` check the signatures with `scripts/check-signature.sh`, and `scripts/privacy-check.sh` checks the entitlements file.
- No `com.apple.security.cs.allow-unsigned-executable-memory`, `disable-library-validation`, `allow-jit` or other hardened-runtime exceptions.
- ATS: `NSAllowsLocalNetworking = true` only. No `NSAllowsArbitraryLoads`.
- Info.plist: `LSUIElement = true`, `NSServices` for "Translate with Sprachmittler", no microphone/camera/screen/Input Monitoring/Apple Events usage descriptions.
+3
View File
@@ -22,6 +22,9 @@ settings:
Release:
SWIFT_TREAT_WARNINGS_AS_ERRORS: YES
GCC_TREAT_WARNINGS_AS_ERRORS: YES
# Debug keeps Xcode's injected get-task-allow for the debugger; Release carries only the
# explicit app-sandbox=false entitlement (SECURITY_PRIVACY, T0.2).
CODE_SIGN_INJECT_BASE_ENTITLEMENTS: NO
packages:
SprachmittlerKit:
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Verify a signed Sprachmittler.app has the expected entitlements and, where required,
# Hardened Runtime. Called by scripts/verify.sh and `make install` (T0.2, SP-10).
#
# Usage: scripts/check-signature.sh <app-path> <debug|release|install>
set -euo pipefail
cd "$(dirname "$0")/.."
APP="${1:-}"
PROFILE="${2:-}"
if [[ -z "$APP" || ! -d "$APP" ]]; then
echo "usage: scripts/check-signature.sh <app-path> <debug|release|install>" >&2
exit 2
fi
case "$PROFILE" in
debug | release | install) ;;
*)
echo "unknown profile '$PROFILE' (expected debug, release or install)" >&2
exit 2
;;
esac
command -v jq >/dev/null || { echo "jq required (brew install jq)" >&2; exit 1; }
codesign --verify --strict "$APP"
tmp=$(mktemp "${TMPDIR:-/tmp}/sprachmittler-entitlements.XXXXXX")
err=$(mktemp "${TMPDIR:-/tmp}/sprachmittler-entitlements-error.XXXXXX")
trap 'rm -f "$tmp" "$err"' EXIT
# codesign writes the entitlement plist to stdout. Capture stderr separately so a signing
# failure is visible, without printing the executable path on every successful run.
if ! codesign -d --entitlements :- "$APP" > "$tmp" 2> "$err"; then
cat "$err" >&2
exit 1
fi
if ! json=$(plutil -convert json -o - "$tmp"); then
echo "✗ $PROFILE signature: no readable entitlements" >&2
exit 1
fi
app_sandbox=$(jq -r 'if has("com.apple.security.app-sandbox") then .["com.apple.security.app-sandbox"] else "missing" end' <<<"$json")
if [[ "$app_sandbox" != "false" ]]; then
echo "✗ $PROFILE signature: com.apple.security.app-sandbox must be false (ADR-003)" >&2
exit 1
fi
get_task_allow=$(jq -r 'if has("com.apple.security.get-task-allow") then .["com.apple.security.get-task-allow"] else "absent" end' <<<"$json")
keys=$(jq -r 'keys[]' <<<"$json" | sort)
if [[ "$PROFILE" == "debug" ]]; then
# Xcode normally injects get-task-allow for the debugger, but the AC only requires that it
# may be present. Accept either the exact sandbox-only set or sandbox + get-task-allow=true.
if [[ "$get_task_allow" == "true" ]]; then
expected=$'com.apple.security.app-sandbox\ncom.apple.security.get-task-allow'
suffix=" + get-task-allow"
elif [[ "$get_task_allow" == "absent" ]]; then
expected='com.apple.security.app-sandbox'
suffix=""
else
echo "✗ debug signature: get-task-allow must be true when present" >&2
exit 1
fi
else
expected='com.apple.security.app-sandbox'
if [[ "$get_task_allow" != "absent" ]]; then
echo "✗ $PROFILE signature: get-task-allow must not be present" >&2
exit 1
fi
codesign -dvv "$APP" 2>&1 | grep -Eq 'flags=.*runtime' \
|| { echo "✗ $PROFILE signature: Hardened Runtime flag is missing" >&2; exit 1; }
suffix=" + Hardened Runtime"
fi
if [[ "$keys" != "$expected" ]]; then
echo "✗ $PROFILE signature: unexpected entitlements" >&2
diff <(printf '%s\n' "$expected") <(printf '%s\n' "$keys") >&2 || true
exit 1
fi
echo "✓ $PROFILE signature: app-sandbox=false$suffix"
+3
View File
@@ -18,6 +18,9 @@ h=$(hits 'Log(ger)?\.[a-z]+\(.*\\\((text|translation|prompt|string|pasteboard|ap
[[ -n "$h" ]] && { report "SP-2: possible content logging without privacy: .private"; echo "$h"; }
h=$(hits '^\s*(print|debugPrint|NSLog)\(' $SRC -g '!**/sprachmittler-cli/**')
[[ -n "$h" ]] && { report "SP-2: print/NSLog outside the CLI"; echo "$h"; }
# short hashes are correlatable; they are still logged with privacy: .private
h=$(hits 'shortHash' $SRC -g '!**/LogRedaction.swift' | rg -v 'privacy: *\.private' || true)
[[ -n "$h" ]] && { report "SP-2: shortHash must be logged with privacy: .private"; echo "$h"; }
# SP-3: no telemetry or crash-reporting SDKs
h=$(hits -i 'firebase|crashlytics|sentry|amplitude|mixpanel|segment\.io|appcenter|bugsnag|datadog' Packages/SprachmittlerKit/Package.swift project.yml $SRC)
+11 -1
View File
@@ -10,7 +10,7 @@ step "Format check"
if command -v swiftformat >/dev/null; then swiftformat App "$PKG" --lint; else echo "skip: swiftformat not installed"; fi
step "Lint"
if command -v swiftlint >/dev/null; then swiftlint lint --strict --quiet App "$PKG/Sources"; else echo "skip: swiftlint not installed"; fi
if command -v swiftlint >/dev/null; then swiftlint lint --strict --quiet App "$PKG/Sources" "$PKG/Tests"; else echo "skip: swiftlint not installed"; fi
step "Shell syntax"
for f in scripts/*.sh; do bash -n "$f"; done
@@ -37,6 +37,16 @@ if command -v xcodegen >/dev/null && command -v xcodebuild >/dev/null; then
xcodegen generate --spec project.yml --quiet
xcodebuild -project Sprachmittler.xcodeproj -scheme Sprachmittler -configuration Debug \
-derivedDataPath .build/xcode -destination 'platform=macOS,arch=arm64' -quiet build
scripts/check-signature.sh .build/xcode/Build/Products/Debug/Sprachmittler.app debug
else
echo "skip: xcodegen/xcodebuild not available (make bootstrap)"
fi
step "Release build and signature"
if command -v xcodegen >/dev/null && command -v xcodebuild >/dev/null; then
xcodebuild -project Sprachmittler.xcodeproj -scheme Sprachmittler -configuration Release \
-derivedDataPath .build/xcode-release -destination 'platform=macOS,arch=arm64' -quiet build
scripts/check-signature.sh .build/xcode-release/Build/Products/Release/Sprachmittler.app release
else
echo "skip: xcodegen/xcodebuild not available (make bootstrap)"
fi