Skip to content
Pace
Esc
↑↓navigate↵open⌘Jpreview
On this page

Pace - Key Files

This is the per-file reference for Pace’s source, scripts, and bundled resources. It is the canonical home for the table that previously lived inline in the repository AGENTS.md; the architecture narrative stays in the architecture docs and links here.

File Lines Purpose
leanring_buddyApp.swift ~340 Menu bar app entry point. Uses @NSApplicationDelegateAdaptor with CompanionAppDelegate which validates the local tool registry at startup, warms only the selected local planner, creates the notch/panel managers, starts CompanionManager, launches versioned onboarding when needed, handles pace:// deeplinks, and optionally installs runtime smoke hooks. Pace has no Dock icon; its resizable Command Center opens only on request.
PaceDeepLinkParser.swift ~77 Pure parser for the pace:// URL scheme (listen, chat, watch, panel). Reject-on-ambiguity rules, percent-decoding via URLComponents, and a hard 500-char chat-text cap because deeplinks are an external input surface.
CompanionManager.swift ~1336 Class declaration and stored properties only — the god-class shell after Phase A decomposition.
CompanionManager+AgentLoop.swift ~4015 AI response routing and execution, including selected-planner teaching requests, same-lease awaited lessons, remote/mute-safe speech handling and owned replay after host finalization.
PaceTurnLease.swift ~30 Pure generation registry used to reject cancelled or superseded routing results and queued planner speech before they can mutate the active turn.
CompanionManager+PrivateBindings.swift ~905 Permission polling, LM Studio reachability, barge-in VAD, wake-word, shortcut bindings.
CompanionManager+Lifecycle.swift ~1000 start()/stop(), permission requests, avatar/deeplink/chat entry points, and FIFO typed-turn queue draining between complete voice-agent turns.
CompanionManager+LocalRetrieval.swift ~570 Local retrieval context, connector refresh, source management.
CompanionManager+ConversationMemory.swift ~450 Accepted request and assistant-event recording, interrupted turn finalization, thread memory, episodic facts from genuine user turns.
CompanionManager+TrustSurfacesRuntime.swift ~280 Undo banner, reply replay, failure narration.
CompanionManager+MorningTriage.swift ~270 Morning triage daily brief and watch-mode toggle.
CompanionManager+PostureWatch.swift ~340 Posture watch, watch-mode events, approval, tool-debug helpers.
CompanionManager+LocalMemoryCommands.swift ~620 Remember-site and local-memory commands, unified automation discovery/dispatch over bundled/user definitions and bounded Pace Programs, local natural-language catalog matching, explicit Shortcut routing, immediate local responses, and MCP context.
CompanionManager+DemonstrationFlow.swift ~170 Demonstration flow record/stop/replay.
CompanionManager+PlannerTierPicker.swift ~210 Planner tier picker and Direct-API keys.
CompanionManager+UnifiedMemoryDualWrite.swift ~115 Unified memory Phase 2 dual-write.
CompanionManager+UnifiedMemoryUIAccessors.swift ~100 Unified memory Phase 4 accessors and resync.
CompanionManager+CloudBridge.swift ~75 Cloud bridge setters and consent.
CompanionManager+ProactivitySettings.swift ~50 Proactive nudge toggles and profile setter.
CompanionManager+ProactivePipeline.swift ~35 PaceProactivityPipeline forwarders.
PaceScreenContextService.swift ~820 @MainActor coordinator extracted from CompanionManager during Wave 7b. Owns the per-screen VLM analysis cache (keyed by PaceScreenAnalysisCacheIdentity, value PaceCachedScreenAnalysis), the PTT-press prewarm Task<PaceScreenContextPrewarmedSnapshot?, Never>, and the AX + OCR + VLM merge logic. Public surface: prewarmScreenContext(reason:), consumeInFlightPrewarmedSnapshot(), hasInFlightPrewarmedTask, buildUserPromptWithLocalVLMContextIfEnabled(...), cachedDescriptionIfFresh(screenLabel:maxAgeSeconds:referenceDate:), invalidateAllCachedAnalysis(reason:). Reads the live Read My Screen toggle through an injected () -> Bool closure so the user-facing preference still lives on CompanionManager. Cache reuse requires identical image bytes, analyzer identity, display geometry, and local VLM/native OCR capabilities. Every changed image is re-read, including small label and coordinate changes.
Powers/Images/PaceImageGeneration.swift ~360 Typed image request/artifact/state, isolated authenticated Codex native image client, process-thread-only output discovery, ImageIO size/type validation and private nonsymlink artifact storage.
Powers/Images/PaceImageOverlayController.swift ~181 Shared source-ordered image/diagram draining, generation/dismissal leases, consent/cancellation, retained successful artwork and bounded follow-up context.
Powers/Images/PaceImageOverlay.swift ~165 Transparent native image panel, graphite progress/chrome, zoom, accessible pointer/hover controls and native Save dialog.
leanring-buddyTests/PaceImageGenerationTests.swift ~865 Request/routing contracts, process isolation, artifact containment/type/size, stale dismissal and edit history, ordered drain and opt-in actual Codex generation/edit integration.
Powers/Teaching/PaceDiagramDocument.swift ~289 Validated visual document, optional bounded lesson, array/figure exclusivity, semantic reference checks and backward-compatible flowchart routing.
Powers/Teaching/PaceDiagramOverlayController.swift ~324 Diagram and awaited lesson playback owner. Immutable step snapshots, focus/reveal/control state, pause/replay ownership, stable history identities and dismissal generations.
Powers/Teaching/PaceDiagramOverlay.swift ~501 Native nonactivating teaching islands, content-measured header/caption, compact accessible playback controls and click-through flowchart gaps.
Powers/Teaching/PaceFigureScene.swift ~125 Bounded Codable solid geometry and aircraft template contract, semantic explanation links, named teaching viewpoints, control commands, transform/mesh/index validation and complexity budgets.
Powers/Teaching/PaceFigureView.swift ~708 RealityKit geometry reuse, precise semantic anchors, picking/orbit/zoom, trusted hinge/slide groups and motion-aware fitted camera.
Powers/Teaching/PaceTeachingTemplateCatalog.swift ~201 Trusted detailed teaching geometry, semantic IDs/anchors, bounded motion, prompt metadata and authored physical lesson fixtures.
Powers/Teaching/PaceTeachingArrayIllustration.swift ~139 Bounded token/matrix/metric data and native interactive array view, including a staged next-token training fixture.
Powers/Teaching/PaceFigureCameraFraming.swift ~70 Pure perspective fit for rotated, unzoomed object bounds and viewport aspect ratio; keeps complete figures framed while preserving intentional zoom.
Powers/Teaching/PaceAircraftFigureBuilder.swift ~680 Authored conceptual airliner geometry: smooth fuselage, airfoil wings, cockpit and cabin glazing, hollow nacelles, fans, seams and hinged flight-control surfaces.
leanring-buddyTests/PaceFigureSceneTests.swift ~275 Solid-scene boundaries, presentation-command validation, native geometry/hinge checks and opt-in authenticated Codex aircraft authoring and guided controls.
leanring-buddyTests/PaceFigureCameraFramingTests.swift ~105 Camera clipping regression, orbit/aspect corner projection checks, manual zoom behavior and invalid input boundaries.
CompanionSystemPrompt.swift ~211 The system prompt sent to the local planner on every turn. Extracted to its own file because it’s a behavior contract — small wording changes here change end-to-end behavior, so it deserves its own diff-able artifact. Generates the available local-tool docs from PaceToolRegistry and documents v10 dictate/edit/action JSON contracts.
PaceTagParsers.swift ~175 Pure isolation-free parsers for the inline tag dialect the planner emits: [POINT:x,y], [DONE], the transcriptIsLikelyScreenReferential keyword heuristic, and readMaxAgentStepCount. Extracted from CompanionManager so each parser is unit-testable in isolation. The PointingParseResult struct also lives here.
PaceUserPreferencesStore.swift ~370 Typed key namespace + load/save helpers for boolean user preferences (useLocalVLMForScreenContext, isWalkingAvatarEnabled, isPaceCursorEnabled, areCursorAnnotationsEnabled, requiresActionApproval). Replaces hand-rolled UserDefaults patterns with stringly-typed keys. @Published properties still live on CompanionManager; this owns only the storage layer.
PaceCursorShape.swift ~50 CodexArrowShape — the SwiftUI Shape Pace renders as its on-screen cursor. Extracted from OverlayWindow.swift so the shape can be reused without dragging the whole overlay machinery along.
PaceOverlayPillViews.swift ~155 Reusable SwiftUI voice-state views (WhisperFlowVoicePillView, BlueCursorSpinnerView) retained for future cursor modes. The active conversation indicator now lives in PaceMenuBarOverlay.swift.
MenuBarPanelManager.swift ~660 Connected Seamless conversation panel: reserves the physical camera in its header, clips fixed-width chat during expansion/collapse, hands visibility back to the ambient notch and guards interrupted dismissal. Standard anchored fallback remains on notchless displays, honoring the alternate chat preference; shortcut, deep-link, smoke hooks, wake/display changes and outside-click dismissal share the lifecycle.
PaceChatAppearance.swift ~135 Typed, versioned chat appearance, finite bounds, shared native presentation helpers and the MainActor UserDefaults store.
PaceChatAppearanceEditor.swift ~140 Native chat appearance editor with an isolated draft preview, Reset, Cancel and apply-on-Done persistence.
PaceCompletedTurnCounter.swift ~85 Default-off local daily totals for screen-context replies and confirmed single actions. The Privacy view reads the last seven UTC days and clears the totals on opt-out.
leanring-buddyTests/PaceCompletedTurnCounterTests.swift ~60 Outcome eligibility, opt-in, once-per-turn counting, UTC reporting and clearing on opt-out.
PaceDialogueTranscriptModel.swift ~120 Pure Dialogue timeline mapping with exact-turn routine activity grouping, standalone unlinked receipts, visible attention records and identity-based streaming retirement.
PaceChatPowerCatalogView.swift ~540 Compact inventory, direct discovery from chat, ranked search across powers, actions, workflows and connections, keyboard navigation, and editable example requests.
PaceDialogueChatComponents.swift ~610 Shared native Dialogue messages, bilingual original/replay controls, activity disclosures and current-turn status and microphone controls for both chat renderers.
PacePanelChatView.swift ~500 Pure-black Dialogue quick chat, also embedded in the Seamless notch. Quiet user turns, unboxed replies, bilingual playback, compact activity, Main chat and message threads share the existing composer, microphone, queue, stop and settings callbacks.
PaceChatPanelView.swift ~600 Phase 1 of the premium chat panel (PRD docs/product/prds/premium-chat-panel.md), rendered only when useChatPanelAsPrimarySurface is ON. Header strip (voice state and chat options), transcript column merging chat bubbles with inline tool-activity rows (running/done/failed), morning-brief and meeting cards as inline transcript cards, live speech + streaming-reply bubbles, and a permanently docked input that submits through PaceChatSession.submitUserMessage → submitChatTranscriptFromChatSession. All pure rendering decisions live in PaceChatTranscriptModel; auto-scroll respects Reduce Motion.
PaceChatTranscriptModel.swift ~415 Pure, isolation-free (nonisolated) mapping layer behind PaceChatPanelView. Maps PaceChatMessage → transcript row models (alignment + tint decisions), PaceActionExecutionObservation / PaceActionRunRecord → tool-activity row models (three-state running/done/failed contract, superseded-planned dedupe, one-line summaries, SF Symbol names), merges both into a deterministic chronological thread, and owns the empty-state decision. Unit-tested off the main actor in PaceChatTranscriptModelTests.
scripts/check-voice-diagram-contracts.mjs ~13 Node adapter that forwards CodeVetter checks to the authoritative isolated XCTest runner for voice endpointing, shortcut ownership and diagram routing.
scripts/check-codex-answer-contracts.mjs ~48 Broad Node adapter for Codex answer, action, teaching, memory, display and speech contracts through the isolated native test runner; foreground-dependent AppKit checks may require interactive acceptance.
scripts/check-fast-answer-contracts.mjs ~17 Focused Node test adapter for credential sources, everyday API answers, bounded fallback and CLI-direct tier contracts through the isolated native test runner.
scripts/check-app-target-contracts.mjs ~20 Focused Node test adapter for MCP target recovery, stopped action queues, observation approvals and concise conversation feedback through the isolated native test runner.
scripts/render-pace-icons.swift ~73 Native SwiftUI asset generator; compiles with PaceBrandMark.swift to render all app icon sizes and matching local web identity files.
PaceBrandMark.swift ~48 Shared open-loop P vector used by standalone chat and the template menu-bar fallback; native app icon assets are rendered from this geometry.
PaceSeamNotchSurface.swift ~295 Connected ambient notch surface and shared header, always-visible microphone and Pace mark, rounded lower corners, reduced-motion-aware hover/press feedback, configured hotkey hints, active status row and capture/off-device indicators.
PaceMenuBarOverlay.swift ~630 Hardware-derived Living Notch NSPanel. Reserves the actual camera between compact icon caps at idle, opens chat after a cancellable hover dwell and guards immediate reopening, yields to the connected conversation on click and restores the ambient surface after collapse. Retains active companion/capture and amber off-device disclosure, recalculates on wake/display changes, honors Reduce Motion and uses a conventional status item on unsupported displays.
PaceActiveDisplayCoordinator.swift ~350 Shared typed display routing for the ambient notch and existing conversation. Follows app activation, active Space, clicks and bounded focused-window AX bounds; coalesces stale reads, ignores Pace focus, and reasserts native windows without activation.
PaceMenuBarOccupancyMonitor.swift ~180 Bounded background reads of top-level menu item geometry and WindowServer status-item bounds. Refreshes on app activation and a tolerant two-second timer; crowded or unavailable geometry yields the ambient notch to a native status item and lets menus draw above attached chat. Reads no menu text, captures no pixels and installs no input hooks.
CompanionPanelView.swift ~850 SwiftUI panel content for the menu bar dropdown. Shows companion status, turn HUD state including unsupported local-only requests and clickable clarification options, push-to-talk instructions, main planner plus answer-planner status, local model status, ASR provider readiness, TTS voice quality, read-screen toggle, cursor annotation toggle, action approval toggle, watch-mode toggle, core permission rows, local-tool permission preflight rows, recent action results, local memory and retrieval summaries, settings-window entry point, and quit button. Dark aesthetic using DS design system.
PaceMainWindow.swift ~100 Owns the single resizable Command Center NSWindow plus the destination router that reuses the window, honors explicit routes, and restores the last valid destination.
PaceMainView.swift ~325 Settings shell with one Essentials landing page and focused detail navigation. Preserves explicit destination routes and existing management views without a sidebar; details return directly to Settings.
PaceEssentialsSettingsView.swift ~445 Flat graphite Essentials sheet: selected reasoner, local voice, screen and pointer controls, session-only Watch mode, risky-action approval, actual shortcut keycaps, and collapsed Privacy/Advanced routes. Existing preferences and consent setters remain authoritative.
PaceSettingsWindow.swift ~30 Compatibility facade that routes legacy Settings call sites to the requested destination in the single Command Center window.
PaceOnboardingView.swift ~1025 Cinematic, skippable and reversible first-run journey: ignition, consolidated live permissions, typed or spoken production first command, truthful outcome classification, and signal-to-notch handoff with semantic type, Reduce Motion, and cancellation-safe transitions.
PaceOnboardingWindow.swift ~70 Hosts the versioned onboarding journey in a centered native window and exposes both first-launch and replay entry points.
OverlayWindow.swift ~1180 Full-screen transparent overlay hosting the blue cursor and response placement. Handles cursor animation, element pointing with bezier arcs, multi-monitor coordinate mapping, fade-out transitions, and Reduce Motion fallback that snaps pointing/return movement and suppresses nonessential bubble/fade animation.
CompanionResponseOverlay.swift ~380 SwiftUI view for the response text bubble displayed next to the cursor in the overlay.
PaceScreenReadActivity.swift ~30 Main-actor activity leases shared by screenshot capture, local OCR, and screen-context analysis. Concurrent reads keep the notch eye and cyan logo highlight visible until the final read finishes; no sampling timer or artificial delay.
leanring-buddyTests/PaceScreenReadActivityTests.swift ~60 Overlapping read, failure, and cancellation cleanup checks for the screen-reading indicator.
CompanionScreenCaptureUtility.swift ~132 Multi-monitor screenshot capture using ScreenCaptureKit. Returns labeled image data for each connected display.
PaceActionObservationWaiter.swift ~80 FastPath’s generic bounded action-to-state waiter. Checks lightweight AX-visible focus/window state immediately, then polls through caller-specific 200 ms click or 600 ms agent-loop fallback windows, returning typed changed/timed-out/cancelled outcomes; click timeout retains one full-tree verification.
PaceScreenImageDiffer.swift ~105 Cheap image-diff gate for screen captures. Downsamples screenshots into grayscale fingerprints and reports mean pixel delta + changed-pixel ratio so Pace can reuse cached screen analysis when only trivial visual noise changed.
PaceScreenWatchMode.swift ~237 Shared immutable screen observation, permission-gated three-second sampling, nonawaiting sample fan-out, and meaningful-change publisher.
PaceScreenWatchNoteCoordinator.swift ~129 Quiet local OCR notes with one actual operation, one latest pending observation, global attempt budget, revocation epochs, redaction and deterministic excerpt selection.
leanring-buddyTests/PaceScreenWatchNoteTests.swift ~674 Fake-OCR/clock tests for quiet baseline notes, occupancy and rate limits, lifecycle/source revocation, persisted retention, isolated source preferences, and quoted lexical/unified recall after embedding suspension.
PaceScreenSuggestionCoordinator.swift ~283 Typed grounded offers, strict untrusted-output boundary, redaction, latest-only scheduling, cancellation generations, fresh-evidence validation, dedup and delivered follow-up anchors.
CompanionManager+ScreenSuggestions.swift ~530 Watch runtime lifecycle, quiet-note wiring and session privacy gates, native OCR, isolated selected-planner requests, aggregate disclosure leases, assistant-only persistence and notification/TTS delivery. Explicit notification actions enter the shared typed conversation.
PaceScreenSuggestionNotification.swift ~260 One live screen-suggestion notification, session UUID deduplication, exact-offer actions, a nonactivating top-right SwiftUI panel, reduced-motion transitions and a quiet local arrival chime.
PaceWatchModeCommandParser.swift ~71 Pure parser for explicit watch-mode voice commands. Routes start/stop phrases before the planner so mode changes stay local and cheap.
Powers/Teaching/PaceVisualFindCommandParser.swift ~235 Pure parser for “find <text> on screen” / “show me where <text> is” voice commands. Requires an explicit screen marker (“on screen”/“on the screen”/“on my screen”) OR the “show me where … is” form so plain “find my keys” chitchat never matches; extracts the query (strips wrapping quotes + a leading article + trailing locator words). Routed AFTER the skill parser in the agent loop so “run the find skill” stays a skill run. Returns PaceVisualFindCommand (nil on empty query).
Powers/Teaching/PaceVisualFindService.swift ~250 @MainActor deterministic OCR-grounded screen-text search — no LLM. findAndMark(query:overlayController:visionOCRClient:) captures screens via CompanionScreenCaptureUtility, OCRs each via PaceVisionOCRClient.recognizeText(...) (same call PaceScreenContextService makes), substring-matches the query, converts each padded pixel box to an AppKit-global rect with the same pattern as PaceAnnotationActionDrainer, and draws red rectangles via PaceAnnotationOverlayController.setAnnotations(...) (cap 20, cursor-screen-first, first match labelled). Pure nonisolated helpers (matchBoxes, paddedPixelBoundingBox, truncatedMatchLabel, convertPixelBoxToAppKitGlobalRect, orderCapturesCursorScreenFirst, spokenConfirmation) are unit-tested without capture/OCR.
PaceShortcutsAutomationProvider.swift ~340 Local-only macOS Shortcuts discovery and deterministic command routing. Runs bounded, cancellation-aware Shortcuts CLI processes off the main actor; normalizes and caches successful catalogs for five minutes; recognizes explicit list/run commands; exact-matches installed display names; and builds the existing typed .runShortcut action plan without adding catalog metadata to planner prompts or conversation memory.
PaceAutomationDefinition.swift ~655 Versioned deterministic automation model, strict registry/allowlist validation, required-preference preflight, bundled discovery, isolated atomic user-definition storage, privacy-pinned structured-output decoding, and all-or-nothing compiler into the existing PaceActionTagParser execution-plan seam. Invalid user files are isolated; definitions containing unknown, input-injection, opaque, networked, destructive, or partially parsed calls never enter the executable catalog.
PaceManagedPowerStore.swift ~485 Exact power command parser and typed management facade over existing automation/program/skill artifacts, protected capabilities, atomic validated updates with recovery revisions, persistent execution state and reversible owned-artifact archive.
CompanionManager+Powers.swift ~265 Shared power command routing, authoring commit boundary, saved-snapshot execution authorization, media/speech tool lifecycle binding and canonical conversation delivery.
PaceSpokenPowerRecovery.swift ~130 Bounded catalog-name ranking and expiring immutable spoken-Power choices; no approximate execution.
CompanionManager+SpokenPowerRecovery.swift ~100 Local voice/chip confirmation routing before general planning, with exact artifact revalidation and no awaited Shortcut discovery.
leanring-buddyTests/PaceSpokenPowerRecoveryTests.swift ~250 Actual misheard requests, nearest-name choices, voice-only routing, mutation isolation, stale/disabled/replaced/expired selection and explicit confirmation.
leanring-buddyTests/PaceWhisperVocabularyTests.swift ~25 Bounded real decoder prompt-token options, immutable partial/final vocabulary, no forced prefix and unchanged file/language settings.
PaceLocalMediaCatalog.swift ~125 Bounded bundled and explicitly imported GIF/PNG asset catalog, content/frame/size validation, immutable owned copy, hash/provenance manifest and collision protection.
PaceMediaOverlayController.swift ~435 Typed catalog/SVG/card presentation in nonactivating panels, renderer readiness, generation-scoped dismissal and authorized card interactions.
PacePowerCard.swift ~100 Strict bounded card/page/choice data validation and authorized local selection/navigation state.
PacePowerCardView.swift ~130 Native black teaching cards, optional SVG illustration, choice feedback and Back/Next controls; no generated callbacks.
leanring-buddyTests/PacePowerCardTests.swift ~130 Actual worker and manager creation/run boundary, invalid whole-plan rejection, durable interaction history, disabled/stale presentation checks.
PaceGeneratedSVG.swift ~190 Bounded XML vector-source validator, canonical serializer, strict element/attribute/CSS subset and resource/entity rejection.
PaceGeneratedSVGRenderer.swift ~170 Public SwiftUI WebView renderer with nonpersistent website data with content scripts disabled, host CSP, resource rules, bounded readiness, navigation denial and teardown.
scripts/GeneratedSVGOverlayProbe.swift ~105 Standalone nonactivating, click-through renderer probe and native PNG pixel inspector; exposes only its owned window ID and polls an explicit stop marker.
scripts/check-generated-svg-overlay.py ~155 Bounded swiftc-only rendered regression with owned-window capture, four alpha-zero corners, visible blue-pixel assertion, private source-hashed evidence and owned-process cleanup.
leanring-buddyTests/PaceGeneratedSVGTests.swift ~190 Generated source validation, actual worker serialization and WebKit data-image rendering, whole-plan rejection and late-cancellation checks.
PaceAutomationCatalog.swift ~440 Non-persisted catalog over typed definitions, bounded Pace Programs, recorded flows, skills, and installed Shortcuts. In addition to exact list/run commands, derives invocation evidence and performs conservative exact-alias and local-embedding matching with absolute-score and winner-margin gates; token overlap never authorizes execution.
PaceProgrammableSkill.swift ~880 Versioned Program AST, strict tagged decoder, declarative v1 validation/compiler and single-body JavaScript v2 schema, atomic program storage and structured authoring.
PaceJavaScriptPowerWire.swift ~35 Data-only XPC contract, typed request/action/response envelopes and shared computation budgets.
PaceJavaScriptPowerRuntime.swift ~160 Async isolated-worker lifecycle with exactly-once continuation, bounded cancellation and complete typed-plan materialization; JavaScript authoring prompt.
PacePowerJavaScriptService/main.swift ~220 Persistent sandboxed XPC broker, bounded helper pipes, serial PID ownership/reaping, monotonic watchdog and owned-child cancellation.
PacePowerJavaScriptWorker/main.swift ~110 Per-evaluation helper inheriting the broker sandbox, public JavaScriptCore, frozen compute SDK and inert typed action serialization.
PaceJavaScriptPowerTests.swift ~380 Actual XPC boundary, runtime budgets/cancellation, generated code persistence, two-turn authoring, preflight and managed authorization checks.
PaceAutomationIntentResolver.swift ~150 Second-stage Apple Foundation Models resolver for close embedding candidates. It uses a fresh on-device typed-output session, cannot promote entries outside the embedding shortlist, validates the returned opaque candidate identifier, can request clarification or decline a match, and is never called for clear winners or unrelated below-threshold turns.
PaceIntentClassifier.swift ~470 Rule-based local classifier for routing turns into chitchat, pure knowledge, screen description, screen action, phone-large-model, or unknown. Pure-knowledge turns skip screen capture and use the text-only planner path.
PaceRequestFeedback.swift ~45 Honest microphone preparation/transcription/working states, elapsed-time labels and human-readable request feedback.
leanring-buddyTests/PaceRequestFeedbackTests.swift ~110 Passive entry/reply visibility, microphone button transitions, loading rejection, direct capture errors and cancelled/remote reply suppression.
PaceTurnHUDState.swift ~349 Small user-visible turn status model plus first-pass clarification/unsupported helpers. Tracks listening, understanding, acting, clarification, done, failed, and unsupported local-only states for the panel/cursor surfaces without involving the planner. Clarifies ambiguous edit/destructive commands, resolves clicked clarification options by rewriting ambiguous pronouns into explicit targets, and blocks cloud/large-model escalation requests with local-only copy. Also defines the visual-target ambiguity clarification model (PaceClickTargetOption, PacePendingClickTargetClarification, PaceClickTargetClarificationBuilder) that reuses the same .clarification HUD shape so near-tied click candidates render as option chips and resolve to the chosen candidate’s exact target.
PaceUtteranceEndpointDetector.swift ~135 Lightweight hands-free speech-pause detector and callback coordinator. Uses raw RMS from the existing microphone tap, adaptive background thresholds, buffer-duration timing, capture-generation guards and bounded listening; physical hold-to-talk stays release-driven.
PacePushToTalkManager.swift ~1250 Push-to-talk voice pipeline (previously BuddyDictationManager). Handles microphone capture via AVAudioEngine, provider-aware permission checks, keyboard/button dictation sessions, provider partial hypotheses, immediate provisional partial display with LocalAgreement-gated speculative actions, transcript finalization, shortcut parsing, contextual transcription phrases, and live audio-level reporting for waveform feedback. Also owns the lazy engine close (engine kept warm 10s after release so back-to-back PTT skips prepare+start) and the speculative fast-action trigger (stable partial matching a deterministic fast-action fires before PTT release; final-transcript dedup is punctuation-insensitive).
PaceLatencyBudget.swift ~220 Per-turn latency budget tracker. startTurn/mark/finishTurn capture every pipeline stage (PTT press → STT → intent → VLM → planner first-token/total → tool exec → TTS) and emit one structured BUDGET= log line per turn, with a rolling 50-turn p50/p90 window for the HUD and benchmark scripts.
PaceSubagentCommandParser.swift ~189 Deterministic parser for parallel-subagent voice commands (“research X, Y, and Z”). Trigger keyword must start the command (politeness prefixes stripped); pronoun-only fragments are rejected so conversational phrases never spawn agents. Returns subtasks + merge strategy for the coordinator.
PaceSubagentCoordinator.swift ~377 Runs a parsed subagent batch: spawns up to 4 concurrent headless planner turns via an AsyncSemaphore, tracks per-subagent state, merges results (concatenate / Apple-FM summarize / first-wins), retains at most 20 completed batches.
PaceDictationFastPath.swift ~115 Zero-latency dictation lane: “type …” / “dictate …” transcripts skip planner/VLM/TTS entirely — deterministic PaceDictationPostProcessor cleanup, optional Apple FM disfluency pass, then CGEvent typing into the focused field. “write” deliberately does not trigger (compose intents belong to the planner).
PaceAmbientContextStore.swift ~309 Always-on ambient context snapshot (frontmost app, AX window title + top-level role counts, clipboard change metadata, display count, time-of-day), polled every 3s on a main-runloop timer and injected into the planner system prompt as <ambient_context>, replacing a VLM round-trip for “what app am I in”-class context.
PaceCompanionWorldModel.swift ~434 Pure typed evidence layer for the default-off Always-On Companion Mode: validated non-identifying observations, coarse zones, provenance, bounded atomic JSON persistence, confidence-decayed derived hypotheses, correction supersession, and exact last-seen/change/presence queries.
PaceCompanionModePolicy.swift ~326 Default-off companion preferences, deterministic lifecycle state machine, intervention scoring, silence-first show/queue/ask/speak/discard policy, deduplication, cooldowns, and negative-feedback thresholds.
PacePerceptionCoordinator.swift ~218 Injected perception-source adapter boundary and event-driven actor coordinator. Enforces one expensive analysis per source, equivalent-burst coalescing, stale-candidate dropping, lifecycle-generation invalidation, and immediate task/source cancellation.
PaceCompanionMemoryPolicy.swift ~499 Deterministic episodic/semantic/spatial/routine promotion over typed companion evidence, confidence reinforcement/decay/contradiction, bounded episode compaction, time/entity/place queries, dedicated local-retrieval documents, uncertainty-aware last-seen/usual wording, and coordinated evidence/index/pending-candidate clear operations. Routine promotion requires three unique supporting observations by default.
PaceCompanionPerceptionSources.swift ~361 Dependency-injected, separately permissioned camera and ambient-voice adapters. Camera sampling is capped at 2 FPS and motion/object-gated into named zones; ambient audio uses local VAD/wake gating and bounded post-wake on-device STT sessions. Optional diarization emits session-only speaker labels. Also maps non-identifying person presence and user-taught objects into expiring typed observations without retaining raw frames/audio.
PaceCompanionCameraCaptureClient.swift ~340 Production observe-only AVFoundation camera client: permission/device handling, capped low-rate sampling, 32×24 luma motion estimation, Vision person rectangles, session-local non-identifying tracks, and region-scoped Vision feature-print matching for explicitly taught objects. Full frames never leave the capture callback or reach persistence.
PaceTaughtObjectStore.swift ~60 Template and error types for explicitly taught object labels and secure Vision feature-print archives. No source photo is persisted.
PaceCompanionPrivacyAndResources.swift ~193 Fail-closed companion privacy and resource invariants: loopback validation, privacy-pinned planner factory, sensitive-app deny list, pre-persistence redaction, bounded raw-data buffers, sampling/concurrency/battery/thermal/storage budgets, and observable accepted/dropped/model-call/raw-buffer/idle metrics.
PaceExistingPerceptionAdapters.swift ~207 Zero-duplicate-loop adapters over the existing ambient-context publisher and explicit Watch Mode event publisher, a bounded take-once ephemeral screen-frame store, fail-closed privacy-pinned local screen-client construction, and targeted post-change screen interpretation with sensitive-app denial/redaction.
PaceCompanionWakeGate.swift ~620 Production local pre-STT wake path using AVAudioEngine and direct Core ML inference over a bounded 2-second PCM ring. It expects PaceWakeWordClassifier labels hey_pace and background, requires consecutive high-confidence windows, releases the mic before bounded PTT handoff, and fails closed on permission/model/label/audio errors without invoking Speech.framework.
Resources/PaceWakeWordClassifier.mlpackage 2.5 MB Bundled raw-PCM Core ML wake model: normalized mono 16 kHz [1, 32000] input, background/hey_pace output, Apache speech-embedding backbone plus Pace MIT temporal head. See docs/product/pace-wake-word-classifier.md.
PaceCompanionObservationPresenter.swift ~360 Deterministic typed-observation-to-card/speech/clarification mapping with provenance, non-identifying person copy, deduplication, queueing, and independent output preferences. Delegates decisions to PaceCompanionInterventionPolicy.
PaceCompanionObservationCardView.swift ~90 Shared silent companion card rendered in the panel/chat surfaces with provenance, confidence, observation time, and explicit dismissal.
PaceCompanionControlCenter.swift ~136 Main-actor control/presentation model for default-off enable, independent default-off source/card/speech opt-ins, pause, retention, storage usage, source/all clearing, model readiness, runtime state, active sources, and last-observation time.
PaceCompanionRuntime.swift ~280 Default-off lifecycle composition wired into CompanionManager.start()/stop(). Starts only explicitly enabled sources, prepares the fail-closed pre-STT wake gate, derives structured observations into memory/retrieval, and routes optional card/speech presentations through intervention policy and live restraint.
PaceCompanionSettingsTab.swift ~250 Settings → Companion surface for iPad pairing/status plus enable/pause, camera/voice/screen/Mac-context consent, independent silent/spoken output gates, runtime/readiness status, retention/storage, and per-source/all clear controls. Every interactive control has explicit pointer hover behavior.
PaceCompanionServer.swift ~690 Bonjour-advertised, TLS-PSK Mac adapter for one paired PacePad. Owns pairing/session authentication, heartbeat/reconnect state, bounded audio/still ingress, local transcription and physical-scene analysis handoff, semantic presence ingestion, and assistant/proactive output forwarding; it creates no planner or memory system.
CompanionManager+PacePad.swift ~45 Small PacePad entry/output seam over the canonical Mac conversation pipeline. Mutes Mac TTS for iPad-originated turns and injects one-turn physical-scene context without changing the stored user transcript.
PaceShared/PaceCompanionProtocol.swift ~445 Versioned semantic message schema plus payload, identity, session, credential, media, heartbeat, privacy-gate, and reconnect-policy validation for the local companion connection.
PaceShared/PaceCompanionFrameCodec.swift ~150 Length-prefixed JSON-plus-binary framing, strict header/payload bounds, incremental stream decoding, and bounded message-ID replay protection.
PaceShared/PaceCompanionSecurity.swift ~125 Strict six-digit pairing normalization, exact 256-bit credential validation/generation, HKDF TLS-PSK derivation, session-bound HMAC proof, and constant-time proof comparison.
PaceShared/PaceCompanionKeychain.swift ~70 Shared generic-password Keychain persistence for the paired-device credential using WhenUnlockedThisDeviceOnly; no UserDefaults or log storage.
PaceShared/PaceCompanionNetwork.swift ~145 TLS 1.3 Network.framework parameter construction and shared framed connection wrapper over bounded stream decoding.
PaceShared/PaceCompanionPhysicalSceneRequestParser.swift ~45 Conservative explicit-request parser that permits one physical-scene still for direct visual questions while rejecting incidental room/camera mentions.
PacePad/PacePadApp.swift ~30 iPad application entry point and foreground lifecycle wiring for the persistent companion surface.
PacePad/PacePadViewModel.swift ~810 Main-actor iPad orchestration for connection state, 60-second-bounded tap-to-talk and interruption, persistent accessible responses, actionable permission recovery, camera requests, semantic presence, pause/mute, brightness restoration, assistive-technology-safe auto-hiding controls, low-energy ambient idle, and night mode.
PacePad/PacePadClient.swift ~440 Bonjour browser and authenticated client session with numeric pairing, Keychain reconnect, stale-session rejection, heartbeats, exponential recovery, and typed utterance/presence/still/privacy messages.
PacePad/PacePadRootView.swift ~1120 Adaptive always-on SwiftUI companion surface where the whole iPad becomes Pace’s polished deep-blue CRT face, with an inky navy canvas, shallow screen bezel, static raster, layered phosphor features, hidden system chrome, compact game-like privacy HUD, one-tap control drawer, modal pairing accessibility, routed signal states, periodic pixel relocation, and Reduce Motion handling.
PacePad/PacePadAudioRecorder.swift ~100 One-turn AAC microphone recorder using the voice-chat audio session; loads the completed turn and removes its temporary file immediately. The view model enforces the 60-second turn limit.
PacePad/PacePadSpeechPlayer.swift ~60 AVSpeechSynthesizer response player with speaking-state callbacks and immediate stop support.
PacePad/PacePadCameraService.swift ~310 Front-camera service with background-queue AV capture lifecycle, rotation-aware ≤1 fps Vision human-rectangle presence detection, stability gating, requested-next-frame JPEG generation, and immediate privacy-state pause.
leanring-buddyTests/PaceCompanionProtocolTests.swift ~310 Focused framing, payload-bound, session, replay, pairing-proof, privacy-gate, heartbeat, reconnect, and semantic-validation coverage for the shared companion protocol.
leanring-buddyTests/PacePadPhysicalSceneRequestParserTests.swift ~30 Positive and negative coverage for the explicit physical-scene phrases that permit one expiring camera still.
BuddyTranscriptionProvider.swift ~110 Protocol surface and provider factory for voice transcription backends. Sessions receive per-turn contextual phrase hints. Factory reads TranscriptionProvider Info.plist key, and when unset AUTO-PREFERS WhisperKit if the model is on disk (the install-time presence is the user’s opt-in signal). Explicit appleSpeech / apple always wins over an installed WhisperKit; explicit whisperKit falls back to Apple Speech with a “WhisperKit fallback” display-name suffix if the model is missing. isWhisperKitModelInstalledOnDisk() is a cheap FileManager probe — the pipeline itself still loads lazily on first session.
AppleSpeechTranscriptionProvider.swift ~152 Default on-device transcription provider backed by Apple’s Speech framework (SFSpeechRecognizer with requiresOnDeviceRecognition=true). Applies Pace’s local contextual phrases through contextualStrings; also carries the explicit WhisperKit fallback display name when needed.
WhisperKitTranscriptionProvider.swift ~325 Production local ASR using the small English base.en CoreML model in Application Support. Shared lazy pipeline; streaming partials and final transcription reject silence through Silero.
PaceTranscriptionContextualPhraseBuilder.swift ~80 Local vocabulary-hint builder for ASR. Combines the frontmost app name, Pace product/runtime terms, and PaceToolRegistry names/aliases and prioritizes saved Power names before the phrase cap. Apple Speech and WhisperKit receive the same per-capture snapshot.
PaceUtilityCommand.swift ~84 Shared text/voice commands for read-aloud, explicit Kokoro, audio-file transcription and Sparkle update checks.
PaceSileroSpeechDetector.swift ~23 Bundled Silero v6 CoreML speech gate shared by streaming and file transcription.
PaceCaptureAcknowledgement.swift ~72 Capture-identity gate for processed PCM, exactly-once post-tap receipt and rejection of stale recognition callbacks.
PaceLocalAgreementStabilizer.swift ~66 Provider-agnostic LocalAgreement-style partial transcript stabilizer. Emits only word prefixes that agree across consecutive hypotheses, never retracts stable text, and is wired into PacePushToTalkManager for current provider partials while remaining reusable by the real WhisperKit streaming bridge.
GlobalPushToTalkShortcutMonitor.swift ~190 Owns the Fn+P worker and legacy listen-only tap, publishes capture transitions, and audits shortcut events.
PaceFunctionPEventTap.swift ~85 Dedicated event loop for Fn+P chord interception and release recovery.
GlobalChatShortcutMonitor.swift ~200 Sibling of GlobalPushToTalkShortcutMonitor for the notch chat-input shortcut. Reads NotchChatShortcut from Info.plist (default commandShiftP, accepts commandShiftK / commandShiftSpace / controlShiftP / controlShiftSpace), runs a listen-only CGEvent tap, and emits chatShortcutPressed on every match. CompanionManager flips isNotchChatInputFocused = true and posts .paceShowPanel so the notch panel surfaces and focuses the TextField.
LocalVLMClient.swift ~590 Screen-analysis client abstraction plus LM Studio loopback-HTTP implementation and in-process runtime placeholder. PaceScreenAnalysisClientFactory reads ScreenAnalysisProvider, returns the HTTP client by default, and falls back to HTTP when inProcess / coreML / mlx is requested before the runtime bridge exists. The HTTP client sends one screenshot + structured prompt, parses LocalVLMScreenAnalysis, synthesizes a compact description from element labels/text when the model omits one, and falls back to regex JSON extraction when the model strays from strict JSON.
leanring-buddyTests/PaceScreenContextServiceTests.swift ~255 Synthetic screen-context regressions for small AX/OCR changes, exact-image cache reuse, OCR survival on VLM failure, text-only CLI native OCR, and planner-capability cache isolation. Injects AX/OCR/VLM fixtures without screen capture or model calls.
PaceVisionOCRClient.swift ~240 Apple Vision VNRecognizeTextRequest wrapper. Returns [RecognizedTextBox] in screenshot pixel space. PaceScreenContextMerger.enrich fuses VLM elements with OCR text by bbox overlap (>50%), appending up to 30 orphan OCR boxes as static_text elements. Lets the 2B VLM stay fast while the OCR layer guarantees verbatim text fidelity. Wires PaceVisionOCRLanguageResolver at init so Vision biases by Locale.preferredLanguages (with automaticallyDetectsLanguage=true on macOS 13+), and pipes both per-box text and the cross-line merger join through PaceOCRPostProcessor for NFC normalisation + soft-wrap dehyphenation.
PaceVisionOCRLanguageResolver.swift ~80 Pure helper that intersects Locale.preferredLanguages with VNRecognizeTextRequest.supportedRecognitionLanguages() and falls back to ["en-US"] when empty. Stolen from auge — gives non-English UIs first-class OCR fidelity instead of mis-recognising umlauts/CJK as garbled ASCII. Vision-free + actor-free so it’s trivially unit-testable.
PaceOCRPostProcessor.swift ~100 Pure deterministic OCR cleanup. joinSingleLineTextsDehyphenated([...]) joins per-line OCR boxes with single-space separator, dropping soft-wrap hyphens at line breaks (current line ends with - after a lowercase letter AND next line starts lowercase). normalizeUnicodeForOCRComparison(_:) precomposes diacritics to NFC so the click-candidate scorer’s string match compares like with like. Stolen from auge’s --clean flag idea, but pure-deterministic so it doesn’t pay the FM round-trip on every screenshot.
PaceOCRDataDetector.swift ~160 Foundation NSDataDetector over OCR’d screen text — extracts typed entities (phone, email, URL, date, postal address) deterministically with zero LLM cost. Returned via the value type PaceDetectedEntity. renderEntitiesForPlannerPrompt(_:) emits a labelled PHONE: …\nEMAIL: … block; called from PaceScreenContextService.formatScreenAnalysisForPrompt so every per-screen prompt section carries a deduped, capped-at-10 typed-entity list. Stolen from macOS’s built-in.
PaceAppIntents.swift ~240 App Intents surface for Pace. Four intents — PaceConversationIntent, PaceStartListeningIntent, PaceShowPanelIntent, PaceSetWatchModeIntent — mirror the pace:// deeplink command set 1:1 and route through the new public CompanionAppDelegate.executePaceExternalCommand(_:) shim. PaceAppShortcuts: AppShortcutsProvider registers voice phrases (“Ask Pace”, “Show Pace”, “Toggle watch mode in Pace”) for Siri / Spotlight / Shortcuts discoverability. Free-form String params can’t be interpolated into Siri phrases (metadata processor limitation), so the conversation intent uses Siri’s own parameter-request flow.
PaceAppleNLEmbeddingClient.swift ~95 PaceTextEmbedding conformer backed by Apple’s NaturalLanguage NLEmbedding.sentenceEmbedding(for:). 300-dim, on-device, ships with macOS 12+, no Apple Intelligence dependency. Lazy-loaded per language (caches [NLLanguage: NLEmbedding] behind an NSLock since the cache map is not thread-safe). Lower quality than nomic via LM Studio, but free + always available so semantic recall keeps working on a clean Mac.
PaceChainedTextEmbeddingClient.swift ~100 Tries an explicitly enabled in-process MLX PaceTextEmbedding first; on throw, wrong cardinality, or all-zero vectors falls back to Apple NaturalLanguage. Default memory and automation routing stay in-process so background embedding work cannot evict the conversational model from LM Studio.
PaceSpotlightMemoryIndexer.swift ~168 Allowed-memory Spotlight upserts under Pace’s own domain, excluding passive screen history. Serializes one-time legacy-domain cleanup and pending writes, retains the latest pending snapshot, retries failed cleanup on later sync, and exposes injected operations plus pure mapping helpers for tests.
PaceActiveCallDetector.swift ~210 While a known call app is open, polls other processes’ audio I/O metadata without recording; excludes Pace’s own PID and retains the pause for unreadable metadata.
PaceFocusModeMonitor.swift ~100 @MainActor ObservableObject wrapping Intents.INFocusStatusCenter. start() calls requestAuthorization exactly once and observes INFocusStatusCenterFocusStatusDidChangeNotification. Publishes isCurrentlyInUserFocus. Denied-permission users silently report “not focused” so missing permission can never lock Pace out of talking. Fed into PaceRestraintContext.isInUserFocusMode, which PaceRestraintGate.decide treats as queue-until-idle. Requires NSFocusStatusUsageDescription in Info.plist.
PaceMessageShareService.swift ~50 @MainActor wrapper over NSSharingServicePicker(items:).show(...) for sharing a single message body. Used by the chat message context menu so right-click on any chat message → Copy / Share… menu. Whitespace-only input short-circuits so the share sheet never opens with nothing to send. macOS enumerates every install share destination (Messages, Mail, Notes, AirDrop, third-party share extensions) — no per-target integrations to maintain.
PaceTranslationAvailabilityChecker.swift ~35 Tiny wrapper over Translation.LanguageAvailability (macOS 15+). Returns .installed / .supportedButNotDownloaded / .unsupportedLanguagePair / .translationFrameworkUnavailable so callers know whether on-device translation can run offline for a (sourceLanguage, targetLanguage) pair right now. The full TranslationSession.translate API requires a SwiftUI .translationTask view modifier — a session is created by the modifier and handed to a closure — so headless translation needs a hidden host view + actor channel (deferred). Availability probe ships standalone because it’s a clean async API. resolveUserTargetLanguageCode(preferredLanguagesFromLocale:) normalises BCP-47 tags (“en-US” → “en”, “zh-Hans-CN” → “zh”) for the probe.
PaceThermalStateAdvisor.swift ~155 @MainActor ObservableObject subscribing to ProcessInfo.thermalStateDidChangeNotification. Maps the four thermal levels to a typed PaceThermalRecommendation (.unrestricted / .dampenSpeculativeRace / .dampenBackgroundLoops / .suspendBackground) and exposes four pure per-surface gates (shouldRunSpeculativeRace, shouldRunProactiveSurfaces, shouldRunWatchModeAtFullCadence, shouldRunScreenContextPrewarm). Currently gates the speculative-race site at CompanionManager line ~5462; remaining surfaces (watch mode, proactive scheduler, prewarm) still need to opt in.
PaceIDEContextDetector.swift ~250 Recognises eight IDE bundle identifiers (Xcode, VS Code, Cursor, Sublime Text, JetBrains family, Zed, Nova, TextMate) and parses their window titles into a typed PaceIDEContext (IDE name, focused file name, optional absolute path). Window title comes from a CGWindowListCopyWindowInfo reader at PaceScreenContextService.frontmostWindowTitleForFrontmostApp() — no AX permission needed. When a recognised IDE is frontmost, buildPromptFromEnrichedAnalyses prepends Editor context:\nide: …\nfocused file: …\n to the planner prompt so “summarize this function” / “what does this file do” turns get filename context for free. Pure parsing per IDE; not a real LSP (semantic file tree + type info is a separate future product surface).
PaceMemoryEntryEnricher.swift ~135 Pure write-time enrichment for PaceMemoryEntry.structured. Combines NLTagger (.nameType, joinNames) for persons/places/organizations with PaceOCRDataDetector for phones/emails/urls/dates. Result keys are stable (persons / places / organizations / phones / emails / urls / dates); values are sorted + comma-joined so two enrichments of the same text produce byte-identical JSON. Wired into CompanionManager.recordConversationTurn — every turn now carries entity metadata at the first save. Returns nil for entries with no extractable entities (saves a few JSON bytes per entry vs writing an empty dict).
PaceAudioFileTranscriber.swift ~383 Local audio-file decoding and transcription with WhisperKit base.en, Silero silence rejection, and on-device Apple Speech fallback. Reachable from Shortcuts and the typed/voice transcribe audio command.
PaceLazyEmbeddingScheduler.swift ~80 @MainActor extraction of the off-hot-path embedding scheduler that used to live inline in CompanionManager.scheduleLazyEmbedding. Explicit init dependencies (memoryIndex, embeddingClientFactory, onEmbeddingsPersisted callback) — same shape as the Wave 7b PaceScreenContextService split. Cardinality-mismatched / throwing-client / empty-input paths all leave the index nil-embedded rather than write partial state; semantic recall falls through to BM25 in that case. The CompanionManager method is now a one-line delegate.
BuddyPlannerClient.swift ~560 Protocol the active planner conforms to (generateResponseStreaming, displayName, supportsImageInput) + factory that returns the configured main planner, fast text-only answer planner, and privacy-pinned local planners. Feature-specific JSON structurers use makeLocalOnlyTextPlannerForPrivacyPinnedFeatures() so their own contracts are not forced into the main v10 action envelope. The factory dispatches on PacePlannerTier first (Local / CLI bridge / CLI direct / Direct API / Apple FM), with bundled MLX taking precedence over LM Studio only when enabled.
PaceMLXPlannerClient.swift ~260 In-process MLX planner with explicit chat roles, fresh per-request token cache, bounded streaming generation, and shared Hugging Face model assets. Feature-specific JSON prompts bypass the action-planning scaffold.
PaceMLXHuggingFaceIntegration.swift ~175 Shared complete-snapshot cache reuse across standard and MLX 2 roots, plus MLX 3 protocol adapters for the official Hugging Face downloader and tokenizer; provider libraries own caching, downloads and tokenization. Used by the local planner, VLM and embedder.
PaceMLXEmbeddingClient.swift ~180 In-process MLX embedder — runs mlx-community/nomic-embed-text-v1.5 (default) via mlx-swift-lm MLXEmbedders. Conforms to PaceTextEmbedding so it slots into PaceChainedTextEmbeddingClient.makePaceDefault(). Same #if canImport(MLXEmbedders) guard pattern as the planner client; isRuntimeAvailable flips true once the SPM dep is linked. Activated when PaceBundledModelsSettings.isUsingMLXInProcessEmbedder() is true; falls through directly to Apple NaturalLanguage without asking LM Studio to load another model.
PaceBundledModelsSettings.swift ~180 UserDefaults-backed toggle + model-identifier configuration for the in-process MLX runtime. isUsingMLXInProcessPlanner() / isUsingMLXInProcessEmbedder() short-circuit to false when the respective client’s isRuntimeAvailable == false, so a missing SPM dependency can’t accidentally route turns to a runtime that isn’t linked. runtimeStatusSummary(...) renders the Settings → Models status row. Empty/whitespace model identifiers are refused so a slip in Settings can’t brick the next inference call. Default state is OFF — existing users see byte-identical behaviour until they opt in.
PaceBundledModelsSettingsTab.swift ~940 Settings → Models tab. Surfaces the runtime-status row (green check vs yellow warning), four toggles (in-process MLX planner / embedder / VLM / Qwen3 TTS), per-model HuggingFace identifier text fields with Apply buttons, a “Download now” prefetch button with real NSProgress %, and a quality-caveat block explaining the 3-4 point gap vs qwen3-30b-a3b on the FM-fixture set. Toggles disable when the respective client’s isRuntimeAvailable == false. Also hosts the RAM-aware memoryBudgetSection (backed by PaceModelMemoryBudget) with a planner-brain picker that routes through CompanionManager.selectPlannerTierWithConsent and a VLM size picker whose fit math updates live.
PaceModelMemoryBudget.swift ~490 Pure, testable RAM-budget model — the one source of truth for each on-device model role’s estimated resident-RAM cost (planner / vision / STT / TTS / embedder variants). evaluate(configuration:usableBudgetGB:) returns the per-model breakdown + fits/over-budget verdict; largestVLMThatFits(...) picks the biggest vision tier a budget affords; plannerMemoryVariant(forTier:...) maps a PacePlannerTier (cloud/Apple-FM → ≈0 local RAM) to its memory variant. No UI/persistence/network — only reads ProcessInfo.physicalMemory.
PaceMLXScreenAnalysisClient.swift ~250 Phase C: in-process VLM via mlx-swift-lm MLXVLM. Conforms to PaceScreenAnalysisClient so the existing PaceScreenContextService consumes it without changes. Default model is mlx-community/Qwen3-VL-4B-Instruct-4bit (MLXVLM supports Qwen3-VL natively). Image bytes flow ScreenCaptureKit → NSImage → CGImage → CIImage into UserInput.Image. Prompt + system instruction are byte-identical to the LM Studio HTTP client so the same LocalVLMScreenAnalysis JSON parser handles the output. Regex-fallback extraction for “model emitted stray prose preamble”. Activated when PaceBundledModelsSettings.isUsingMLXInProcessVLM() returns true; trumps the LM Studio HTTP path. Same model → same quality; the win is dropping the HTTP loopback and the max-loaded-models=2 brittleness.
PaceQwen3TTSClient.swift ~200 Phase D: in-process TTS via WhisperKit’s TTSKit module (default Qwen3 TTS). Conforms to BuddyTTSClient with full barge-in / manualStop / naturalCompletion stop-reason propagation matching LocalTTSClient’s contract. isCurrentlySpeakingOrPending flips true synchronously on speakText so the CompanionManager poll loop sees us as speaking from t=0. Activated when PaceBundledModelsSettings.isUsingQwen3TTSInProcess() returns true; trumps LocalServerTTSClient (Kokoro sidecar) and LocalTTSClient (Apple AVSpeechSynthesizer). No Kokoro Swift port required — WhisperKit ships a finished TTSKit product (the Argmax team did the StyleTTS2-equivalent work) so Phase D collapsed from a multi-week port to a single integration commit.
LocalPlannerClient.swift ~690 Text-only OpenAI-compatible chat-completions client for a local reasoner. SSE streaming, parses choices[0].delta.content. Discards images (logs a notice) — relies on upstream VLM element map being prepended to userPrompt. Defensive stripThinkingBlocks helper removes <think>…</think> from streamed content for thinking-mode models. Retries empty HTTP-200 user-facing streams with prompt caching disabled, then falls back to a non-streaming local completion before surfacing failure. Endpoint construction is guarded by PaceLocalEndpointGuard so bad plist values cannot route prompts to remote hosts.
CloudBridgePlannerClient.swift ~220 Opt-in BuddyPlannerClient conformer that routes turns through the sibling local-ai Node bridge (http://localhost:3456), which spawns the user’s already-authenticated Claude Code, Codex, or Gemini CLI. Parses the bridge’s data: {"text":"..."} / data: [DONE] SSE shape (different from OpenAI’s format). Discards images; surfaces upstream errors as PaceCloudBridgeError.upstream. This is the ONLY intentional break of the no-cloud-LLM principle — consent-gated and default-off.
PaceCloudBridgeConsent.swift ~290 Pure state module for the cloud-bridge feature. Defines PaceCloudBridgeMode (off/hybrid/alwaysBridge), PaceCloudBridgeUpstream (claude/codex/gemini), PaceCloudBridgeConfiguration, and PaceCloudBridgeConsent with UserDefaults persistence under the pace.cloudBridge. prefix. Enforces the 24-hour soak period before alwaysBridge is available via canEnableAlwaysBridge(now:). Transport-aware for .cliDirect: a SEPARATE direct-spawn consent record (hasAcceptedDirectSpawnConsent() / acceptDirectSpawnConsent()) + its own soak clock (markDirectSpawnFirstUsedIfUnset / canRunDirectSpawnTurn(now:)) so accepting the Node-bridge path does NOT auto-grant the direct-spawn path (different data path). revokeConsentAndResetAllBridgeState() clears both.
PaceBoundedTextAnswerPlanner.swift ~455 Typed everyday-answer purpose and consent-gated factory selection for automatic Codex. Validates completed Luna turns for early delivery, buffers generic clients, and promotes once on invalid/unavailable answers or a pre-answer timeout, preserves account/cancellation failures, and seals accepted answers through cleanup errors without exposing provisional output. Also owns the separate consent/Read My Screen-gated passive-screen Responses adapter, completed spoken-only validation and one original-payload selected-Codex fallback.
PaceEverydayAnswerClient.swift ~235 Current-question-only everyday protocol plus a separate typed passive-screen request/entry. Shares ephemeral Luna Responses HTTP/SSE, API-key lookup, completion/consent checks and metadata-only usage/image-size audit. Everyday requests retain fixed instructions and no history, images or ambient inputs.
PacePlannerCredentialStore.swift ~360 Explicit Infisical metadata configuration for fast OpenAI answers, bounded CLI retrieval with no secret files or diagnostic output, shared in-memory credential cache and cancellation-safe callers. Sleep-inclusive expiry and a short failure backoff bound repeated lookup cost. Unconfigured installs retain the existing Keychain source. Records source/outcome/timing metadata only.
PaceLocalCLIPlannerClient.swift ~770 BuddyPlannerClient conformer that direct-spawns the claude/codex CLI (PaceLocalCLIUpstream) per turn — no Node bridge, only the CLI on PATH. Powers both the .research lane override and the .cliDirect general tier. Ports CodeVetter’s stream-json parsing (PaceLocalCLIStreamJSONParser), claude --resume <session_id> prefix-cache reuse, and --bare when ANTHROPIC_API_KEY is set. Records a PaceAPIAuditLog planner.cliDirect entry (target = upstream executable, char-counts only) on every turn — success and failure — so off-device egress is always logged. Preflight helpers isUpstreamBinaryOnPath(_:) / missingBinaryPreflightMessage(for:) surface a plain-language “is codex on PATH?” hint before a turn instead of a silent hang.
PaceLocalEndpointGuard.swift ~220 Shared fail-closed validator for local model HTTP roots. Allows only http/https loopback hosts (localhost, 127.0.0.0/8, ::1) and falls back to the default LM Studio localhost URL when planner/VLM plist configuration points at a remote or LAN endpoint. Separate validatedCloudBridgeURL(from:) function for the bridge endpoint so future guard tightening on the planner path doesn’t accidentally affect the bridge. Separate validatedDirectAPIURL(from:) function for the BYO-key Direct API entry point — allows https to any host (consented cloud egress), allows http only for loopback hosts (so local OpenAI-compatible proxies still work for testing), rejects plaintext to non-loopback hosts so a pasted key can never leave Pace in the clear.
DirectAPIPlannerClient.swift ~350 BuddyPlannerClient conformer for BYO-key cloud endpoints (Anthropic / OpenAI / OpenRouter / Custom). OpenAI-compatible SSE streaming over a per-call URLSession; loads the API key from PaceKeychainStore at request time only (never held on the client). Sets x-api-key + anthropic-version for Anthropic, Authorization: Bearer for the others. Same <think>…</think> stripper as LocalPlannerClient. Surfaces 401 as .invalidAPIKey, every other non-2xx as .httpError(statusCode, bodyExcerpt) so users see the verbatim upstream error. Writes one PaceAPIAuditLog line per call: provider + model + char-counts + turn-id + outcome — NEVER message content.
PacePlannerTierStore.swift ~310 Pure state module for the planner tier picker. Defines PacePlannerTier (local/cliBridge/cliDirect/directAPI/appleFoundationModels — additive; legacy values decode unchanged), PaceDirectAPIProvider (anthropic/openai/openrouter/custom) with built-in endpoint URLs + default model identifiers, the .cliDirect upstream (cliDirectUpstream: PaceLocalCLIUpstream, key pace.planner.tier.cliDirect.upstream, default .codex), PacePlannerTierConfiguration snapshot, and UserDefaults persistence under pace.planner.tier. prefix. Does NOT touch Keychain — keys live exclusively in PaceKeychainStore. First-launch tier resolution: loadConfiguration() calls hasAnyPlannerTierUserDefaultsState() and only applies the new Apple-FM-first default to clean installs; existing users keep their pinned tier byte-identically. Apple Intelligence availability resolves via SystemLanguageModel.default.availability (cached per process) and selects between .appleFoundationModels (when available — zero external install needed) and .local (fall back to LM Studio). The pure helper defaultTierForFirstLaunch(appleIntelligenceAvailable:) is unit-testable.
PaceKeychainStore.swift ~145 Minimal kSecClassGenericPassword wrapper. Service com.pace.app.plannerAPIKeys, account names directAPI.<provider>.apiKey. kSecAttrSynchronizable=false (never syncs via iCloud), kSecAttrAccessibleWhenUnlocked. Never logs key material. Only legal entry point for API keys anywhere in the codebase — nothing else reads or writes API key bytes.
BuddyTTSClient.swift ~155 Shared enqueue speech, precise awaited utterance API and strictly parsed per-utterance speech profile; unsupported backends fail explicit profiles before onset; selected-provider factory.
LocalServerTTSClient.swift ~542 Loopback Kokoro synthesis and serialized playback with identity-based onset/completion, immutable utterance profiles, profile-scoped outage memos, retained drain task, cancellation fencing and bounded retries. Default speech retains Apple fallback; explicit Japanese fails closed.
LocalTTSClient.swift ~452 Local Apple speech with utterance-specific start/completion delegates, queue watchdog, native-idle reconciliation, identity fencing and cancellation cleanup.
PaceTTSVoiceResolver.swift ~91 Shared TTS voice selection and panel summary. Premium/Enhanced Apple voices win even when a compact fallback voice is configured, so installing a better voice automatically upgrades playback on restart.
StreamingSentenceTTSPipeline.swift ~565 Consumes planner streamed text and dispatches complete sentences to TTS as they arrive, instead of waiting for the full response. Cuts perceived time-to-first-spoken-word from ~3s to ~500ms. Strips <think> blocks + <tool_calls> + action tags + [POINT] before sentence segmentation. Owns markIntentCommitted() + TTFSW logging — called from CompanionManager at PTT-release. Now also publishes the speakable-safe prefix via @Published inFlightStreamedText so the in-window chat surface can render “Pace is typing…” without re-routing the planner stream, and exposes setMutedForCurrentTurn(_:) so chat-mode mute drops audio for one turn without affecting the live text stream. Also owns prepareForSupersedingStreamWithinTurn() (speculative-race supersede reset — stops playback + clears the dispatch cursor so a different winning stream replays cleanly without re-logging TTFSW) and the firstSpokenWordCharacterCount probe the race reads for its supersede window.
PaceSpeculativePlannerRace.swift ~390 Wave 4 speed lever, wired into the agent-loop first step (see Plan-act-observe). raceSpeculative(...) runs the Apple FM lite planner against the full VLM-fed planner concurrently and returns PaceSpeculativeRaceResult (outcome + BOTH planners’ final text, so the caller always parses actions from the full text). SpeculativeRaceCoordinator routes the winner’s accumulated chunks through onToken, handles the 500 ms / 60-char supersede, and streams every chunk once a path is the established winner. PaceSpeculativeRaceWinnerBox (@MainActor) backs the winner-flip + stale-lite-dispatch guard in CompanionManager.performFirstStepSpeculativePlannerRace. Pure coordinator logic unit-tested in PaceSpeculativePlannerRaceTests.
PaceChatSession.swift ~685 Live transcript over the local paceHistory retrieval index. Stable event identifiers join optimistic typed input, voice input and committed output. Message roots scope replies, drafts, navigation and planner history. Typed Watch offers drive the persistent unread cue and read-through acknowledgement marker; unsent drafts and TTS mute remain session-only.
PaceConversationRecorder.swift ~82 Typed ConversationEvent model and main-actor recorder. Upserts accepted requests, assistant narration and delivery-state changes to the existing local retrieval store and live chat under the same event identity.
PaceChatPowerCatalog.swift ~90 Local snapshot of a listed power inventory. Stores identifiers, descriptions and available controls with the original reply and validates explicit selections against the live inventory.
PaceChatTurnQueue.swift ~55 Small in-memory FIFO for complete typed turns submitted while Pace is busy. Each entry snapshots the transcript, per-turn TTS mute choice, and optional optimistic chat-row identifier. It intentionally serializes full turns because speech, memory, approval, and Mac actions share one authoritative agent loop.
PaceDeterministicAnswerParser.swift ~175 Narrow, exact local arithmetic parser for routine two-operand calculations. It bypasses generative planning, preserves the normal conversation/TTS surface, handles divide-by-zero explicitly, and leaves open-ended math questions on the planner path.
PaceSkillsView.swift ~680 Settings → Powers. Searches built-in powers, saved programs, taught powers, bundled workflows, actions, and configured MCP connections.
PaceUsageAnalyticsView.swift ~400 Settings → Local usage. Groups recorded events by built-in power and subsystem and pairs workflow lifecycle records for run counts and latency percentiles.
Resources/usage-powers.json — Maps audit operation names to built-in powers for historical Usage breakdowns.
PaceSkillLoader.swift ~640 Loads, parses, serializes, and writes .skill.md skills (Claude-Code-compatible NL-step format) from Resources/skills/ (bundled) and ~/Library/Application Support/Pace/skills/ (user). Read side: parse, loadAllSkills, toPlannerPrompt (a step with a non-nil toolCall renders instruction (use tool: <json>) in the registry’s tool-call dialect; steps without one render byte-identically to before). Run-time enforcement: preflightRequiredPreferences(for:memoryStore:) — deterministic, no-LLM gate sharing the typed-automation PaceLocalMemoryStoreReadable seam, called by the .run case before dispatch. Teach side (teachable-skills PRD): serialize (inverse of parse, round-trips), atomic save / deleteUserSkill / listUserSkills (same temp-file+rename pattern as PaceFlowStore), skillStructuringSystemPrompt + skillFromStructuredJSON (local-planner NL→skill), structureSkillDeterministically (no-model fallback splitter), and skillFromForm (Settings typed authoring). Slug reuses PaceFlowStore.slug(for:). Foundation-only + unit-testable — the one model call lives in CompanionManager.handleTeachSkillCommand.
PaceSkillRunJournal.swift ~200 Writes local workflow starts and outcomes to rotating skill-runs.jsonl records. Local usage pairs them by workflow and run ID. New records preserve millisecond precision.
PaceAutomationCommandParser.swift ~325 Deterministic pre-planner transcript parsers (no model, no screen) for natural-language automation creation, cron scheduling, background agents, meeting mode, and skills. Creation parsers are anchored and capture the untouched task description before list/run branches or semantic catalog matching.
PaceStarterPromptCatalog.swift ~225 Pure state + content module for the first-run “Try these” card pinned to the top of the notch panel. Defines PaceStarterPrompt, the deterministic 6-prompt PaceStarterPromptCatalog.all list (calendar / timer / open Safari / what’s on my screen / remember preferred browser / what did I do today), and PaceStarterPromptStore — UserDefaults-backed first-seen + tried-set + dismissed-at state under the pace.firstRun. prefix. isVisible(now:) is the single visibility decision: hide after explicit dismissal, hide after 4-of-6 tried, hide after 24h from first seen. resetVisibility() brings the card back without wiping the tried set. No telemetry, no LLM call — fully local state.
PaceTelemetryLog.swift ~160 Single os.Logger (subsystem com.pace.app, category metrics) for performance metrics. Emits TTFSW=NNNms, TTFT=NNNms, and privacy-safe RAG=NNNms count-only retrieval metrics to the macOS unified log alongside the existing print(…) calls, so scripts/benchmark_ttfsw.sh can aggregate per-turn latency without scraping the Xcode console. Also emits the automation-evidence signals ACTIVATE class=… outcome=… ver=… build=… (first successful local action, once per launch) and FAIL kind=… outcome=… ver=… build=… (privacy-safe failure class from PaceFailureKind.stableLogIdentifier). Every field is privacy: .public; no transcript, screen context, action target, or key material is accepted. See docs/operations/automation-evidence-matrix.md.
PaceActionApproval.swift ~220 Pure approval-gate helper for action execution. Applies the destructive-only approval policy, decides when routine local actions can suppress initial spoken feedback from parsed plans or planner text, builds popup copy from the risk-labelled action summary, and makes allow-once vs cancel behavior unit-testable without posting real Mac actions.
PaceRuntimeSmokeTestHooks.swift ~235 Disabled runtime hooks. Authored lift-system, Pi camera and next-token lessons additionally require the local-development build flag and use normal manager-owned lesson playback.
Powers/Coding/PaceCodingPower.swift ~34 The eleventh preinstalled power. Owns coding_session metadata, retained coding intent recognition and selected-planner instructions. Existing codex_session still opens Warp.
Powers/Coding/PaceCodingSessionModels.swift ~145 Strict start/resume/status/cancel commands, typed session/thread/turn identities, canonical approval scopes, lifecycle states and coding events.
Powers/Coding/PaceCodingSessionCoordinator.swift ~570 Retained coding owner with at most four isolated workspace slots. Validates immutable workspaces/effective policy, fences stream generations and shutdown, correlates ordered events, scopes approvals and persists lifecycle state.
Powers/Coding/PaceCodingAppServerTransport.swift ~280 Private owned stdio Codex process. Metadata-only MCP inventory, process-local tool/config restrictions, JSON-RPC framing/correlation, bounded requests, audit and awaited process-group cleanup.
Powers/Coding/PaceCodingSessionStore.swift ~51 Versioned private atomic session catalog and last-readable recovery copy. Stores identities/state, never task replay or a parallel transcript.
CompanionManager+Coding.swift ~170 Selected-planner coding request/approval/executor path, model-free local status/cancel, canonical event subscription and turn-owned foreground speech. Background results remain written.
Powers/PacePowerCatalog.swift ~104 Typed preinstalled power catalog, unique tool ownership, contextual instruction composition and startup validation. Permission metadata discloses use without granting authority.
Powers/Automation/PaceAutomationPower.swift ~50 Preinstalled automation power; owns its tool definitions and applicable planner instructions.
Powers/ComputerUse/PaceComputerUsePower.swift ~273 Preinstalled computeruse power; owns its tool definitions and applicable planner instructions.
Powers/ComputerUse/PaceInitialInspectionPlanResolver.swift ~90 Pure, whole-request window-inventory resolver. Produces one typed Peekaboo window.list envelope for eligible default Codex foreground turns; execution and follow-up answers remain in the main agent loop.
Powers/Images/PaceImagesPower.swift ~35 Preinstalled images power; owns its tool definitions and applicable planner instructions.
Powers/Integration/PaceIntegrationPower.swift ~35 Preinstalled integration power; owns its tool definitions and applicable planner instructions.
Powers/Productivity/PaceProductivityPower.swift ~138 Preinstalled productivity power; owns its tool definitions and applicable planner instructions.
Powers/Productivity/PaceToDoPower.swift ~190 Built-in To-do List Power. Routes Apple Reminders commands locally and requires a unique task match before completing it.
Powers/Research/PaceResearchPower.swift ~37 Preinstalled research power; owns its tool definitions and applicable planner instructions.
Powers/Screen/PaceScreenPower.swift ~34 Preinstalled screen power; owns its tool definitions and applicable planner instructions.
Powers/Teaching/PaceTeachingPower.swift ~152 Teaching tool definitions and planner contracts for guided lessons, native templates, data-driven arrays, pointing and annotations.
Powers/Text/PaceTextPower.swift ~30 Preinstalled text power; owns its tool definitions and applicable planner instructions.
Powers/Voice/PaceVoicePower.swift ~46 Preinstalled voice power; owns its tool definitions and applicable planner instructions.
PaceVisualActionDrainer.swift ~86 Ordered visual dispatch with caller/dismissal leases, awaited lesson speech metadata and retained written responses before forwarding remaining actions.
PaceToolRegistry.swift ~587 Typed local tool lookup and validation over definitions owned by the preinstalled power providers. Validation checks enum coverage, duplicate names/aliases, required metadata, valid JSON schema examples, canonical tool fields, drift against the bundled v10 registry artifact, and presence/shape of the bundled v10 planner response schema artifact. Notes supports create/append/search actions through the same registry entry. MCP actions use a generic external-tool risk label because their exact semantics live in the configured server.
Resources/v10-actions/registry.json ~29 Bundled v10 action registry artifact. Mirrors PaceToolRegistry canonical kinds, tool names, aliases, risk labels, and schema examples so startup validation can catch prompt/parser/executor drift before the app handles a user action.
Resources/v10-actions/pace-fm-response-v10.schema.json ~94 Bundled v10 planner response schema artifact. Documents the typed spokenText/intent/payload envelope, single-action {name,args} calls, multi-call payloads, and dictate/edit fields; startup validation checks it is present and structurally recognizable.
PaceMailDraftStreaming.swift ~283 Incremental v10 Mail.draft detector for incomplete nested planner JSON plus action-plan helper for removing the already-streamed compose action. Lets the manager stream body text into Mail while the planner is still generating when action approval is off, then finalize without creating a duplicate draft.
PaceStreamingPlannerFieldDetector.swift ~200 Incremental v10 detector for dictate/edit/AX.setValue text fields during planner streaming (v0.3.14).
PaceRemoteModelManifest.swift ~90 Optional remote JSON manifest cache (RemoteModelManifestURL) that overrides bundled MLX model identifiers between Sparkle releases.
PaceDictationPostProcessor.swift ~115 Rule-backed local cleanup scaffold for v10 dictate intents. Handles spoken punctuation, basic prose capitalization, and first-pass code-mode function-call cleanup before typed dictation reaches the executor.
PaceVoiceEditProcessor.swift ~192 Rule-backed selected-text edit scaffold. Parses common voice-edit commands and transforms selected text for shorten, make direct, grammar cleanup, replace X with Y, delete last sentence, and bullets before the executor writes through AX.
PaceActionExecutor.swift ~860 Class declaration, stored properties, init/callbacks, and top-level helper types (PaceActionTagParser, PaceFastActionCommandParser, grouped plans, click-candidate scoring/ambiguity) after Phase B decomposition.
PaceActionExecutor+EntryPoint.swift ~272 One canonical action-plan dispatcher with exact dispatched-prefix receipts, the observations-only compatibility entry point, single-action dispatch and streaming Mail draft entry.
PaceActionExecutor+Mouse.swift ~435 Clicks, clipboard, window snap, scroll.
PaceActionExecutor+SystemToolsAppsMedia.swift ~370 Open app/URL, timers, flows, download, Music, volume, brightness.
PaceActionExecutor+SystemToolsCalendarReminders.swift ~185 Calendar reads/event creation and Reminders.
PaceActionExecutor+SystemToolsNotesMail.swift ~800 Finder, Notes, Mail compose/streaming, Contacts recipient resolution.
PaceActionExecutor+SystemToolsIntegrations.swift ~225 Things, Shortcuts, Messages, AppleScript helpers, auxiliary key events.
PaceActionExecutor+Keyboard.swift ~758 Type, edit, undo, key press and MCP calls, with bounded read-only app-instance discovery, short user-facing failures and preserved fresh-planning/approval boundaries.
PaceActionExecutorCoordinateConversion.swift ~65 Screenshot-pixel → CG-global coordinate conversion (Wave 6a precedent).
PaceActionResultCenter.swift ~126 UI-friendly action run records with typed target-resolution state, human summaries and separate opt-in diagnostics; mixed results retain earlier completed-action receipts.
PaceToolCallDebugLog.swift ~190 Plain DTO (PaceToolCallDebugRecord) for the Settings → Debug “Tool calls” view. Captures, per turn: transcript, routing lane (fast path / text-only / planner), which planner produced the audio (incl. speculative-race lite-won-with-no-screen), screen element count, the planner’s RAW output (pre-strip), parsed tool calls, and dispatch outcome — so a turn that spoke but did nothing becomes legible. CompanionManager owns the capped list (recentToolCallDebugRecords, newest first, ≤25, session-only); captures are written at the fast-path, text-only, and agent-loop-post-execution sites.
PaceDebugSettingsTab.swift ~210 Settings → Debug tab view. Renders recentToolCallDebugRecords as per-turn cards (lane badge, routing, planner path, element count, what-you-heard-vs-screen, raw planner output, parsed tool calls, dispatch). Read-only diagnostics; a Clear button calls CompanionManager.clearToolCallDebugRecords().
PaceToolPreflight.swift ~230 Pure preflight checks for local tool plans. Reports disabled actions, missing Accessibility/Calendar/Reminders permissions, Automation prompt warnings, and missing configured MCP server names before approval/execution.
PaceMCPClient.swift ~700 Stdio MCP bridge. Peekaboo and Playwright use the official Swift MCP SDK with serialized persistent sessions, live schemas, structured content and metadata, bounded calls, and no mutation retries. All configured servers use the same SDK sessions and discovered schemas.
PacePowerConnection.swift ~45 Live searchable MCP connection metadata, browser aliases and a focused route into connection settings.
PaceMCPServerCatalog.swift ~335 Curated MCP installers including pinned computer/browser helpers and official Linear read-only OAuth through mcp-remote. Atomic config merges preserve user entries.
PacePrivacyDashboardView.swift ~590 Privacy sidebar entry for PaceMainWindow. Reads-only from PaceAPIAuditLog — no new tracking added. Renders a headline card (0 bytes when no off-device calls, X KB to <target> otherwise), an off-device audit table with target/byte/outcome columns, per-tier turn counts (Local planner / Apple FM / CLI bridge / Direct API), a permissions-vs-last-used cross-reference, and a fixed data-residency claim paragraph. PacePrivacyDashboardAggregator and PacePrivacyByteFormatter are the pure helpers unit-tested in isolation.
PaceLocalMemoryStore.swift ~127 UserDefaults-backed local memory for durable preferences such as preferred browser, preferred notes app, and default reminder list. Includes a small voice-command parser; preferred browser affects open_url.
PaceThreadMemory.swift ~300 Pure two-tier in-context memory: verbatim window of the last K turn pairs (default 4) plus a rolling summary of everything older. Owns no I/O — exposes record(...), injectionPrefix(), verbatimWindow(), applySummaryUpdate(...), sessionDidIdle(...), resetSession(...), and a monotonic reserveNextSummaryVersion() counter so detached summarizer calls finishing out of order are dropped at update time. Session-scoped in memory; persisted across relaunch by PaceThreadMemoryStore.
PaceThreadSummarizer.swift ~210 Detached FM call that rolls the displaced verbatim turn into the summary. PaceThreadFoundationModelSummarizer uses Apple FM with a single-field @Generable envelope (PaceThreadSummaryResponse); PaceThreadLMStudioSummarizer is the loopback-guarded OpenAI-compatible fallback. Prompt constants live in PaceThreadSummarizerPrompt so behavior-changing edits diff cleanly. Fire-and-forget — the user-facing planner turn never awaits this.
PaceThreadMemoryStore.swift ~75 On-device persistence so the conversation survives quit/relaunch. Reads/writes a single atomic JSON (~/Library/Application Support/Pace/thread-memory.json) holding a PaceThreadMemorySnapshot (session id, verbatim window, rolling summary, version counters). load / save / clear. PaceThreadMemory stays I/O-free — it only produces/consumes the snapshot; CompanionManager wires restore-at-start() + save-after-every-turn/summary/reset, and clear() on explicit reset or when thread memory is disabled. Policy: resume always, until reset (no staleness expiry).
PaceMemoryEntry.swift ~40 Unified-memory value type. One Codable PaceMemoryEntry per memory — kind (conversationTurn/fact/preference/journalEvent/summary), text, structured fields, source (reuses PaceRetrievalSource), timestamps, [Float]? embedding, confidence, topicTags, tombstone. Plus PaceMemoryEntryKind. Pure data.
PaceMemoryIndex.swift ~320 @MainActor in-memory CRUD + brute-force cosine ranking over PaceMemoryEntry. upsert / activeEntries / tombstone / purgeTombstonesOlderThan / setEmbedding / rankBySemanticSimilarity(topN:) / replaceAll. Skips no-embedding / dimension-mismatch / zero-vector entries; deterministic tie-break by id. No I/O.
PaceMemoryStore.swift ~75 The only disk-touching part of unified memory. Atomic JSON at ~/Library/Application Support/Pace/memory-index.json (corrupt/missing → [], never blocks launch). Mirrors PaceThreadMemoryStore. CompanionManager restores at start(), dual-writes every turn + extracted fact (with lazy detached embeddings), and persists after each mutation.
PaceMemoryRetriever.swift ~200 THE single recall path (unified-memory Phases 3+5). @MainActor class: embeds the query through PaceTextEmbedding (Apple NaturalLanguage by default, or explicitly enabled in-process MLX) and ranks the unified index by cosine; when embeddings are unavailable it falls back to PaceMemoryIndex.rankByKeywordSimilarity (BM25) over the SAME index — two ranking modes, one store. Drops excluded + sensitive-topic entries, renders one LOCAL CONTEXT (memory) block. CompanionManager.appendLocalRetrievalContext calls ONLY this (the legacy parallel lexical-injection path is retired); gated by useUnifiedMemoryRecall (default on).
PaceLocalRetrieval.swift ~1616 Local-only RAG store, now the connector INGESTION layer (no longer a recall path — recall moved to PaceMemoryRetriever over the unified index, which is resynced from here via CompanionManager.syncConnectorsIntoUnifiedMemory). Defines PaceRetrievalStore / PaceRetriever, retrieval document/status types, file-root preferences, secret-path exclusion, route-aware context policy, persisted source enablement, JSON persistence under Application Support, BM25-style lexical ranking (rerankedLocalContextBlock, retained + tested but no longer called in production), source clearing/status, local preference, recent Pace-history, screen-watch + app-usage journals, competitive-research seeds, and an explicit-root file connector that refuses sensitive paths. Still read by the morning-brief composer. INTENTIONALLY RETAINED as the structured operational layer — full deletion (rewriting connectors to emit PaceMemoryEntry directly) was scoped and decided against: it re-platforms working non-recall infra (enablement, statuses, journals, morning-brief reads, chat-history backing) for zero user-facing gain.
PaceScreenWatchJournal.swift ~296 Existing persisted screen-history journal with content-aware dedup, bounded excerpts and buckets, seven distinct activity dates, restart rehydration, and shared source-specific quoted recall formatting.
PaceAppUsageJournal.swift ~161 Pure day-bucketed journal of foreground app usage for the appUsageHistory retrieval source. Accumulates per-app foreground minutes and switch counts from activation events, renders duration-sorted day documents, keeps 7 days, and rehydrates across restarts. Needs no screenshots or permissions.
PaceAppUsageTracker.swift ~91 Thin @MainActor AppKit glue between NSWorkspace.didActivateApplicationNotification and PaceAppUsageJournal. Flushes into retrieval on every app switch plus a tolerant 5-minute timer; started/stopped by the appUsageHistory source toggle and app lifecycle.
PaceResearchJournal.swift ~270 Pure day-bucketed journal of research-lane turns for the researchHistory retrieval source. One rolling document per day of {question, answer} entries, same-day question dedupe, 100-entry cap, 30-day retention, restart rehydration parsing its own line format. Recorded by the isResearchTurn-guarded fire-once hook in CompanionManager+AgentLoop; exposes entriesReverseChronological() / removeEntry(withId:) for the Memory-tab list. Mirrors PaceScreenWatchJournal’s shape.
PaceTasksSettingsTab.swift ~250 Settings → Tasks tab. Observes PaceCronScheduler.shared and lists recurring tasks with a humanized interval (pure humanizedInterval(_:)), a “Skips weekends” note, next-run/last-started status, pause/delete, typed creation, durable background results, cancellation, and confirmed retry.
PaceSystemAudioCapture.swift ~636 Meeting mode controller + SCStream delegate. PaceMeetingModeController (singleton, @MainActor) starts an SCStream for system audio + a PaceMeetingAudioRecorder for mic audio, then on stop runs the full pipeline: segment → transcribe → build notes → journal. State machine: inactive → starting → active → transcribing → synthesizing → inactive. Retriever + a privacy-pinned LOCAL planner are injected via setters to avoid a singleton init cycle; start/stop are guarded by a lifecycle-generation token against MainActor reentrancy, the transcription backend follows the Settings preference, and a mid-meeting SCStream death is surfaced via systemAudioDroppedMidMeeting + a notes-summary caveat. The delegate downmixes multi-channel SCStream audio to mono; RMS levels hop to the main actor for the panel meter (updateSystemAudioLevel), while raw samples are pushed straight to the recorder’s off-main serial writer via the @Sendable sink from makeSystemSampleSink() (no per-buffer main-actor hop).
PaceMeetingAudioRecorder.swift ~674 @MainActor two-track meeting audio recorder. Owns mic via AVAudioEngine input tap (resampled to a true 16 kHz mono through one continuous AVAudioConverter, boxed in MicSampleConverter so conversion runs on the tap thread) + makeSystemSampleSink() / appendSystemSamples(_:) for the SCStream delegate. Each track drains through a MeetingTrackWriter — an AsyncStream fed by the capture callbacks and consumed by a single detached task that does Float32→PCM16 conversion + FileHandle writes off the main actor and in FIFO order (replacing per-buffer Task { @MainActor } hops that had no ordering guarantee). Per-track first-sample anchors (from the writer’s final state) feed the segmenter’s cross-track alignment; recording keeps nothing in RAM (tracks read back from the finalized WAVs at stop). Writes two RIFF WAV files (16-bit PCM) with .part suffix; stop() finishes+drains both writers, patches the RIFF header with real chunk sizes, and atomically renames to final. crashRepairAllMeetingRecordings() statically sweeps every meeting directory at launch (and from Settings), patching only the RIFF size fields so the recorded sample rate is preserved; pruneMeetingRecordings(olderThanDays:) applies the retention preference to the audio itself. Recording dir: ~/Library/Application Support/Pace/meetings/<id>/.
PaceMeetingTurnSegmenter.swift ~336 Pure nonisolated enum — energy-based turn segmentation over two meeting audio tracks. Accelerate vDSP_rmsqv over 20 ms windows with hysteresis (silence 0.01, speech 0.04, min turn 600 ms, max silence gap 400 ms). Echo trimming: when both tracks exceed the speech threshold in the same window, the louder track wins — compared on an aligned global timeline via per-track startOffsetSeconds window padding. Turn sample ranges are clamped to each track’s own buffer (the final RMS window is zero-padded and the window count is the cross-track max). No I/O, no async — fully unit-testable.
PaceMeetingNotesBuilder.swift ~370 @MainActor structured-notes synthesis. Drives a BuddyPlannerClient conformer with a profile-rendered JSON-only prompt to produce {summary, actionItems, decisions}. Takes a profile: PaceMeetingNoteProfile = .general (default reproduces the legacy PaceMeetingNotesPrompt output). Resolves optional action-item transcript grounding (resolveSource): a planner-supplied quote matched case/space-insensitively against captured turns (longest match wins) → PaceMeetingActionItemSource{timestamp, quote}. Lenient decoder; on planner failure/malformed JSON → synthesisFailed: true with transcript preserved. Empty transcript → empty notes, no planner call. Defines PaceMeetingNotes, PaceMeetingTurnRecord, PaceMeetingActionItem (+ optional source), PaceMeetingActionItemSource.
PaceMeetingNoteProfile.swift ~200 Pure PaceMeetingNoteProfile value type (slug/name/description/sections/emit + grounding flags + optional voiceAliases) shaping how notes are organized per meeting type. renderSystemPrompt() builds the JSON-only synthesis prompt; the built-in .general profile renders byte-for-byte identical to the legacy PaceMeetingNotesPrompt (the compatibility anchor). Lenient init(from:) defaults voiceAliases to [] so pre-existing/user profiles decode. Meetily-informed but Pace-native — keeps the stable {summary, actionItems, decisions} output contract.
PaceMeetingNoteProfileLibrary.swift ~290 Pure loader/validator following Pace’s bundled-resource + user-override pattern: bundled Resources/meeting-note-profiles/<slug>.json (general, standup, one-on-one) + user overrides from ~/Library/Application Support/Pace/meeting-note-profiles/ (override-by-slug, malformed user files soft-skipped). Startup validation via PaceToolRegistry.validateForAppStartup (loud for bundled). Pure precedence resolver resolveProfile(explicit → non-general default → inferred → general) + shouldInfer(...) predicate.
PaceMeetingNotesJournal.swift ~320 Pure per-meeting journal for the meetingNotes retrieval source. One document per meeting (not day-bucketed), natural-language rendering of summary + action items + decisions for BM25 recall (“what did we decide in standup?”). Action items include transcript grounding ([ref: "quote"]) for who-agreed-what recall; robust right-to-left parse-back round-trips text/owner/due/quote. 30-day retention, restart rehydration, mirrors PaceScreenWatchJournal’s shape.
PaceFileDownload.swift ~98 Request type and pure helpers for the download_file tool: http(s)-only URL validation that refuses embedded credentials, filename sanitization that reduces path-like names to their final component, and Finder-style collision suffixing.
PaceTimerService.swift ~210 Timer skill: PaceTimerStore JSON-persists active timers under Application Support, PaceTimerScheduler (@MainActor) owns the live Timer objects + fires the spoken nudge through CompanionManager’s TTS callback, and PaceTimerDurationParser turns “3 minutes” / “30s” / “2 hours” / plain seconds into a TimeInterval. Past-due timers fire on rehydrate so a quit/restart doesn’t silently swallow an egg-timer.
PaceMorningBriefBuilder.swift ~220 Pure deterministic composer for the daily morning brief. Takes typed PaceMorningBriefInputs (today’s calendar events, unread mail count + top sender/subject, open reminders due today, yesterday’s top app + minutes, yesterday’s watch highlight) and returns one spoken-ready paragraph. Each clause is omitted when its source is empty; the all-empty fallback is “your morning’s clear.” No LLM call — keeps the brief cheap, predictable, and unit-testable.
PaceFailureNarrator.swift ~190 Pure deterministic composer for the plain-language failure surface. Takes a typed PaceFailureKind (planner offline, missing permission, click missed, sidecar TTS offline, MCP server not configured, cloud-bridge upstream error) and returns a spoken-ready string plus an optional PaceFailureSuggestion panel hint (open Settings, open specific permission, run the TTS sidecar script, configure MCP server, open the local-ai bridge folder). No LLM call — mirrors the table-driven shape of PaceMorningBriefBuilder. CompanionManager.speakPlainLanguageFailure(_:context:) routes the composed string through PaceRestraintGate.decide(...) so failure speech stays silent during a Zoom/active call. PaceFailureKind.stableLogIdentifier maps each case to a privacy-safe fixed string for PaceTelemetryLog.recordFailure — it deliberately drops associated values (click target labels, MCP server names, cloud-bridge provider names) that could leak user content.
PaceMorningTriageScheduler.swift ~320 @MainActor proactive scheduler for the daily weekday morning brief. Owns a single Timer that fires at the user-configured local time, skips weekends via Calendar.nextDate(after:matching:matchingPolicy:), gates speech through PaceRestraintGate (active-call → park brief on pendingMorningBriefCard panel surface instead), records the brief in paceHistory retrieval, and exposes deliverNowForTesting() for the Settings “Send it now” preview button. Source fetching is injected as a closure so the scheduler stays testable without EventKit, Mail AppleScript, or live retrieval state. Default OFF — CompanionManager.start() only calls start() when isMorningTriageEnabled is true.
PaceFlowReplay.swift ~165 Pure model + voice-command parser + replay heuristic. Defines PaceRecordedFlow / PaceRecordedStep, PaceFlowCommandParser (“remember this flow as …”, “do ”), and PaceFlowReplayPlanner (pause-before-send heuristic + replay observation strings). Wave 3a split out the persistent store (PaceFlowStore.swift) and the live event recorder (PaceFlowRecorder.swift); this file no longer owns either runtime layer.
PaceFlowStore.swift ~245 JSON-backed persistence for user-recorded PaceRecordedFlow values — one file per flow under ~/Library/Application Support/Pace/flows/<slug>.json. Atomic temp-file + rename writes (same shape as PaceMCPCatalogInstaller). Public API is save / load / delete / listAll / rename plus slug(for:) and a one-shot migrateLegacyUserDefaultsFlowsIfNeeded(...). listAll() is sorted by createdAt desc. Slug normalization lowercases, collapses non-alphanumerics into -, and caps at 64 characters.
PaceFlowRecorder.swift ~960 @MainActor final class that turns live user input into PaceRecordedStep values via a listen-only CGEventTap for .leftMouseDown / .rightMouseDown / .keyDown / .flagsChanged. State machine: idle → recording → stopped(reason:). Stops after 60s idle or when macOS disables input capture. The command handler saves captured steps and reports interruptions. A failed save retains the steps for retry. Per-focus typing buffers capped at 256 chars defend against runaway typing OOM. Secure (AXSecureTextField) focus suppresses keystroke capture entirely and emits a typeText(secure: true) placeholder on flush. Mouse-down rebuilds an AX role-path via AXUIElementCopyElementAtPosition + parent climb; clicks with no pressable AX ancestor are dropped (no pixel-only steps). Modifier + key emits keyShortcut(key:); bare return/escape/tab/arrows/Fn-keys also emit as shortcuts so the replayer doesn’t try to type them. NSWorkspace.didActivateApplicationNotification emits activateApp(bundleIdentifier:) with consecutive-dup suppression. recordEventForTesting / recordAppActivationForTesting / fireIdleTimeoutForTesting are test seams.
Resources/automations/<identifier>.json — Nineteen bundled deterministic starter manifests plus automation-index.json, the inventory authority that survives Xcode’s flattened resource copying without a hard-coded Swift count. The set covers Notes templates, Calendar reads, timers, Finder locations, current-window layouts, media control, weekly review, and end-of-day reset; every manifest includes natural invocation examples and compiles completely during startup validation.
PaceEmbeddingReranker.swift ~165 Embedding-backed re-ranking over the lexical retrieval store via the OpenAI-compatible /v1/embeddings endpoint (LM Studio). Best-effort: any endpoint/decode failure returns lexical order unchanged; blended min-max scores with semantic tie-breaks.
PacePostureAnalyzer.swift ~145 Pure posture-classification logic for the camera posture watch. Median-calibrated baseline from face-rectangle geometry, sinking/leaning thresholds, consecutive-bad-sample hysteresis, and an alert cooldown — all unit-testable without a camera.
PacePostureMonitor.swift ~190 Thin AVFoundation/Vision glue for the posture watch. Low-res capture session, lock-gated one-frame-per-10s throttle on the video queue, VNDetectFaceRectanglesRequest, feeds PacePostureAnalyzer; frames never leave memory. Off by default behind the isPostureWatchEnabled preference; nudges speak through the existing TTS only when no turn is in flight.
PaceCompetitiveResearchSeeds.swift ~90 Built-in local retrieval seed documents for competitor/product research that should be available without fetching the web at runtime. Seeds cover Project Minimi (ambient memory for Claude), Dayflow (private work journal + LM Studio), and the local private-voice-assistant category (Dottie/OpenFelix patterns vs Pace’s on-device agent loop).
PaceSpotlightRetrievalConnector.swift ~320 Spotlight/NSMetadataQuery file discovery source for local retrieval. Searches only explicit configured roots, filters secret paths and unsupported extensions, loads allowed text files through the existing file connector, and exposes an injected candidate provider for tests without relying on the machine Spotlight index.
PaceCalendarRetrievalConnector.swift ~220 Permission-aware Calendar source for local retrieval. Reads EventKit events only when full Calendar access already exists, maps compact event snapshots into retrieval documents, reports denied/restricted/write-only permission as skipped source status, and never requests permission from the retrieval path.
PaceRemindersRetrievalConnector.swift ~264 Permission-aware Reminders source for local retrieval. Reads open and recently completed EventKit reminders only when full Reminders access already exists, maps compact snapshots into retrieval documents, reports denied/restricted/write-only permission as skipped source status, and never requests permission from the retrieval path.
PaceContactsRetrievalConnector.swift ~198 Permission-aware Contacts source for local retrieval. Reads contact names, nicknames, organizations, titles, and email addresses only when Contacts access already exists, maps compact snapshots into retrieval documents, reports denied/restricted permission as skipped source status, and never requests permission from the retrieval path.
PaceNotesRetrievalConnector.swift ~184 Read-only Apple Notes source for local retrieval. Uses AppleScript only on user-triggered source refresh/reset, maps compact note snapshots into retrieval documents, strips simple Notes HTML from indexed text, and reports Automation denial/read failure as skipped source status.
PaceMailRetrievalConnector.swift ~209 Read-only Apple Mail inbox source for local retrieval. Uses AppleScript only on user-triggered source refresh/reset, maps compact message snapshots into retrieval documents, caps indexed message bodies, and reports Automation denial/read failure as skipped source status.
PaceAXTargeter.swift ~135 Accessibility-tree pre-pass for single clicks. Given a CG global point, calls AXUIElementCopyElementAtPosition, climbs up to a pressable role (AXButton, AXLink, AXMenuItem, etc.), and fires AXUIElementPerformAction(kAXPressAction). Returns false on miss so the executor falls back to CGEvent.
PaceAvatarOverlay.swift ~470 Small walking-character SwiftUI overlay in its own NSPanel. PaceAvatarOverlayManager owns lifecycle + position; PaceAvatarWalkController drives horizontal movement + idle pauses + mouth-open state based on CompanionVoiceState. Click triggers paceAvatarTapped which opens the menu-bar panel.
DesignSystem.swift ~340 Branded SaaSMakerUI palette and shared native design tokens for graphite surfaces, local/off-device signal colors, semantic outcomes, radii, motion, and pointer cursor behavior.
PaceNativeInterfaceModel.swift ~820 Pure signal/panel-state presentation, hardware-derived Living Notch and connected conversation placement, notch-versus-status-item home resolution, reversible versioned onboarding progression/persistence and delayed-transition guards, truthful first-command outcomes, and plain-language primary/advanced Command Center routing shared by Pace’s native surfaces.
PaceSignalView.swift ~220 Production-state adapters plus reduced-motion-aware code-native signal and notch geometry. Timeline-driven rendering exists only for active semantic states and decorative paths stay out of the accessibility tree.
PaceAnalytics.swift ~73 Local-only analytics shim. Keeps existing call sites stable while intentionally avoiding network telemetry, transcript upload, response upload, or cloud SDK initialization.
WindowPositionManager.swift ~151 Window placement helpers plus System Settings deep links for Accessibility, Screen Recording, Speech Recognition, Calendar, Reminders, and Automation permissions.
AppBundleConfiguration.swift ~28 Runtime configuration reader for keys stored in the app bundle Info.plist.
PaceAXScreenReader.swift ~455 Accessibility-tree screen reader. Walks the frontmost window’s AX hierarchy in unscaled global points, then applies the selected capture’s actual pixel ratio once; filters other displays without guessing their Retina density.
PaceLMStudioModelLoader.swift ~400 LM Studio model lifecycle helper. Warm-loads only the effective LM Studio planner (including factory fallbacks) and independently enabled LM Studio screen-analysis model through loopback requests, then keeps eligible models warm. Effective CLI direct screen turns bypass local VLM warmup. LM Studio owns unloading so a quitting Pace process cannot race and break a new launch.
AppleFoundationModelsPlannerClient.swift ~340 Apple on-device Foundation Models planner conformer using the @Generable typed-output path (PaceFMTurnResponse). Preferred pure-knowledge answer planner when Apple Intelligence is available.
PacePlannerModelResolver.swift ~206 Resolves which loaded LM Studio model should serve the planner role, extracting parameter sizes from common model-name patterns and excluding VLMs/embedding models.
PaceScreenContextScaler.swift ~95 Maps VLM element coordinates between downsampled-screenshot space and full screenshot/display space, including multi-monitor origin handling.
PaceFMTurnResponse.swift ~110 @Generable typed response envelope for the Apple Foundation Models planner path.
scripts/test-pace.sh ~200 Runs the unit-test suite TCC-safely: xcodebuild test into an isolated /tmp DerivedData path with code signing disabled, so the interactive Pace.app’s permissions stay untouched. Prints a structured pass/fail summary via xcresulttool. The standard way for agents to run tests.
scripts/agent-testing/commands.manifest.json ~30 Bounded adapter for the shared agent-testing runner; selects non-voice command unit contracts.
scripts/agent-testing/verify-commands.mjs ~100 Independent xcresult verifier requiring fresh results and all selected checks without skips or failures; does not claim native acceptance.
scripts/agent-testing/verify-commands.test.mjs ~45 Fault checks for stale, missing, failed, skipped, duplicated, and inconsistent command-test results.
scripts/check-swift-format.mjs ~120 Changed-line Swift format ratchet. Compares against the PR/push base, runs the Xcode toolchain’s swift-format, and fails only diagnostics on changed Swift lines while reporting historical file debt separately.
scripts/check-unused-code.mjs ~50 Periphery no-regression gate over the isolated test index. Enforces the repository-owned 80-finding review baseline rather than treating dynamically referenced Swift declarations as automatically safe to delete.
scripts/check-duplication.mjs ~60 jscpd Swift production-clone gate with an exact 1,442-line / 1.7331% no-regression baseline.
scripts/check-dependency-risk.mjs ~60 Audits the root docs and website lockfiles, rejects critical or new high advisories, and accepts only the exact IDs tracked in the repository baseline issue.
scripts/http-cache-security.test.mjs ~86 Exercises the installed Astro HTTP-cache consumer in each independent lock scope; verifies protected response handling, policy serialization, permitted public caching, age bounds, and request identity.
scripts/verify.sh ~67 Pre-commit gate: runs test-pace.sh, optionally followed by diag-pace.py --quick --eval. Non-zero exit on any failure for safe && git commit chaining.
scripts/start-tts-server.sh ~80 Launches the pinned Kokoro TTS sidecar via uvx/mlx-audio on port 8880; ordinary startup retains English extras until explicit --install-japanese validates UniDic and writes an atomic support receipt, enabling the shared Japanese installer/server environment.
scripts/test-start-tts-server.py ~110 Stubbed uvx/UniDic acceptance for unchanged English startup, Japanese environment identity, complete dictionary validation, idempotence and failed-install receipts; no model downloads or audio server.
scripts/tts-fixture-server.py ~93 Silent native audio integration fixture with request capture, delayed synthesis, retry, split, transport and invalid-WAV cases.
scripts/mcp-fixture-server.py ~109 Stdlib-only stdio MCP fixture server speaking Pace’s newline-delimited JSON-RPC dialect (echo/fail/sleep tools). Used by PaceMCPClientIntegrationTests and the SETUP_LOCAL.md “verify your MCP setup” recipe.
scripts/cloud-bridge-fixture-server.py ~70 Stdlib HTTP fixture for CloudBridgePlannerClientTests. Serves the local-ai bridge SSE shape (data: {"text":"..."} / data: [DONE]) on a configurable port, with a trigger_error mode for error-path tests.
scripts/benchmark_ttfsw.sh ~140 Aggregates per-turn TTFSW + TTFT samples from the macOS unified log. Three modes: --last 10m (default 30m), --live (stream until Ctrl-C), --file path (parse a saved log). Outputs a markdown stats table — paste into PRs / landing page.
scripts/smoke-runtime-hooks.sh ~122 Launches the Debug app with PACE_ENABLE_SMOKE_HOOKS=1 and verifies panel show/hide, cursor annotation off/on state, synthetic clarification show/resolve state, click-target clarification, all-fail observation breadcrumb, and approval-popup cancellation.
scripts/smoke-real-apps.sh ~95 Real-app smoke: Notes/Safari activate + Mail mailto compose timing + executor dry-run unit tests. No Pace UI driving required.
scripts/smoke-executor-surface.sh ~55 Executor PRD runner: dry-run tests, v10 schema fixtures, runtime hooks (when Debug Pace.app exists), real-app smoke.
scripts/eval-v10-gate.sh ~55 Pre-ship v10 gate: unit tests + schema fixtures + FM sweep when Apple Intelligence is ready.
scripts/generate-og-image.sh ~30 Rasterize website/public/og-image.svg → og-image.png via qlmanage or rsvg-convert.
website/scripts/merge-blume-docs.test.mjs ~55 Regression fixtures for browser-relative and same-origin rendered documentation link validation.
website/src/config/{page-markdown,source-fragments,documentation-surfaces,markdown-documents}.ts ~140 total Public Markdown from the same Workbench, original documentation, and authored prose sources as HTML; explicit public route catalog and shared representation handler.
website/src/config/{faq,pricing,changelog,compared}-content.ts · website/src/content/fragments/*.html ~700 total Shared public copy and data for HTML and Markdown. Fragments are authored source markup; no rendered-page scraping.
website/src/lib/source-fragment-markdown.mjs · website/src/lib/agent-surfaces/ ~45 plus generated helpers Bounded prose-fragment serializer and vendored SaaS Maker readability protocol; update generated helpers through the canonical sync script.
website/src/pages/{ai,llms,llms-full}.txt.ts · website/src/pages/api/md/[document].ts ~20 total Generated public discovery, attribution policy, and route metadata.
website/scripts/{finalize-readability,check-readability,check-readability-runtime}.mjs ~170 total Metadata-only build finalization, full public-route coverage, and actual middleware protocol checks against emitted assets.
scripts/generate-release-info.sh ~110 Parse appcast.xml and write website/src/config/release-info.json (latest + 10 most recent releases) at website prebuild time. Now also records sourceRevision (short git SHA) so the landing build is tied to a repo commit per the automation evidence matrix. Fails soft (`
scripts/check-landing-health.sh ~130 Privacy-safe landing acquisition + manifest consistency check for the automation matrix. Verifies release-info.json is parseable and carries sourceRevision, appcast.xml latest enclosure URL matches release-info.json latest downloadURL, and (unless --offline) the canonical root, /download route, and appcast feed all respond 200. No cloud analytics, no tracking pixel — only plain HTTP GETs against public surfaces.
scripts/automation-readiness.sh ~280 Layered build/release/activation/failure/distribution evidence for the HeyPace automation matrix. Each layer (--landing, --build, --tests, --simulator, --signing, --device, --distribution, --activation, --failure, --release-readiness) is independently reportable; --all runs every non-build layer. Exit 0 = pass, 1 = fail, 2 = blocked (needs human action). The --signing layer only checks for the PRESENCE of a Developer ID cert via security find-identity — never exports or prints key material.
scripts/release-readiness.sh ~210 Aggregate a Foundry-readable receipt to releases/readiness-receipt.json without signing, publishing, enrolling a device, or deploying production. Records the status of every evidence layer, the source git revision/branch/dirty flag, the latest app version/build, and distributionApprovalRequired: true. --no-build skips the slow build/tests layers (records them as blocked). Exit 0 = pass, 1 = fail, 2 = blocked.
scripts/ensure-sm-ui-bundle.sh ~20 Verify or copy the SaaSMakerUI resource bundle into Pace.app before packaging; fail clearly when unavailable.
scripts/ensure-sm-ui-bundle.test.mjs ~60 Synthetic packaging tests for missing/present/copied font bundles and release entry-point gates.
docs/operations/automation-evidence-matrix.md ~120 Privacy-safe build, release, activation, failure, distribution, and Foundry evidence contracts for HeyPace. Defines the layered evidence model (landing/build/tests/simulator/signing/device/distribution/activation/failure/release-readiness), the current evidence state, the privacy boundary invariant, and the Foundry integration scope. Implements the heypace-automation-readiness capability from the automate-heypace OpenSpec change.
scripts/train-pace-tuned-model.sh ~70 Pace-tuned LoRA training scaffold (check prerequisites, print MLX command, emit remote manifest JSON).
docs/current/plans/autonomous-companion-consolidation.md ~170 Canonical product-level handoff for turning the implemented perception, memory, proactivity, background-work, and action primitives into one dependable companion. Records the remaining integration and self-learning gaps, five live acceptance stories, validation gates, and recommended resume order.
scripts/export-pace-tuned-turns.sh ~45 Copy opt-in ~/Library/Application Support/Pace/pace-tuned-turns.jsonl into evals/pace-tuned-export/.
leanring-buddy/PaceTunedTurnExporter.swift ~170 Opt-in anonymized local planner turn export (Settings → Models).
scripts/eval-v10-schema-fixtures.py ~151 Deterministic v10 planner-response schema fixture gate. Reads the bundled pace-fm-response-v10.schema.json artifact and validates every fixture under evals/v10-schema-fixtures/ without calling LM Studio or testing a model.
scripts/eval-fm.sh ~245 Runs the Apple Foundation Models planner against every evals/fm-fixtures/*.txt fixture with the @Generable typed-output path. Compiles a Swift program once, then iterates fixtures so the FM state stays warm. Prints spokenText, pointAtElementId, clickElementId per fixture. Used as the FM baseline for eval-planners.py.
scripts/eval-planners.py ~1090 Head-to-head planner comparison. Takes a list of model identifiers (“fm” delegates to eval-fm.sh; any other name is treated as an LM Studio model id loaded via lms load). Sends each through the same fixture set with the same JSON schema, scores against EXPECT_* fields, and emits a markdown scorecard. Also supports V10_MODE fixtures (see evals/pace_v10.py): sends the real production v10 decode-constrained envelope and scores the DECODED action list. Pinning multiple LM Studio models needs LM Studio Settings → max-loaded-models ≥2.
scripts/experiment-jev-planner.py ~813 Offline EXPERIMENT (not wired into the app): iterative “best next step?” loop where TypeSafe Jev (cloud; direct API with TYPESAFE_API_KEY, else keyless classifier.dev) the local LM Studio model, or Jeff (local MLX, optional compatible tools adapter) routes to one of the 29 registry tools / ASK_USER / RESPOND / DONE, the local model fills args, execution is simulated. Scores against the evals/fm-fixtures* sets. Results + write-up in evals/jev-experiment/.
scripts/experiment-jeff-tools-native.py ~65 Offline Jeff tools adapter evaluation with upstream option order and wording; maps answer_directly to RESPOND in the shared simulated loop. Explicit DONE selection is not measured.
scripts/generate-router-step-states.py ~2400 Next-step router data generator (PRD next-step-router.md milestone 2a; stdlib only, no network): writes UNLABELLED planner step states (request + screen elements + completed steps) to evals/router-data/{train,sealed}.jsonl + coverage.json. Request text comes from offline paraphrase corpora (evals/intent-corpus, MASSIVE en-US, OpenVoiceOS, ToolACE) via a documented intent→label mapping; templates only for screens/results and sparse tools. Sealed ~10% split partitioned by phrasing skeleton; fixture USER lines excluded. Reuses experiment-jev-planner.py helpers. --extra-scenarios-only writes train-extra/sealed-extra/coverage-extra (goal-phrased, disfluent and ambiguous click states from router-goal-click-catalog.py) without touching the base files.
scripts/router-goal-click-catalog.py ~770 Hand-written data for the router’s abstract-click scenarios: 23 app screen contexts with 263 goal→element targets (561 phrasings), app-purpose dock goals, attribute-pick list domains, and an ambiguous contrast set (two elements fit → ASK_USER). Avoids reusing harness fixture instances.
scripts/label-router-step-states.py ~120 Next-step router teacher labelling (milestone 2b): sends each SYNTHETIC step state through the harness’s route_with_jev (TypeSafe direct API, needs TYPESAFE_API_KEY) and appends teacher_label / teacher_probabilities (current registry and control labels) / teacher_confidence / teacher_input_identity to evals/router-data/{train,sealed}.labelled.jsonl. Resume requires matching state and serializer/input identity; legacy, changed or duplicate states fail before calls. Training-time only; nothing user-derived is sent.
scripts/router-policy-cases.py ~88 Freezes explicitly machine-generated, disjoint policy evaluation/calibration bundles and byte hashes; not human gold.
scripts/test_experiment_jev_planner.py ~58 Scorer regression checks for mixed refusal/click expectations, wrong targets and errors.
scripts/test_router_policy_cases.py ~70 Frozen provenance, hash/identity, completed-state and model-free baseline checks.
scripts/test_train_router_student.py ~153 Rejects legacy or drifted checkpoint metadata and teacher-input identity, validates producer/resume binding, and checks rejection before model loading.
scripts/train-router-student.py ~534 Next-step router student (milestone 3; torch + transformers, offline after the base encoder is cached): distils the teacher labels into a ModernBERT-base 32-way classifier (alpha·KL to teacher probabilities + (1−alpha)·CE on the hard label), input = the harness’s router_input_text (screen elements trimmed first if over 512 tokens). Deterministic id-hash validation split, low-confidence rows → evals/router-data/review.jsonl, never trains on sealed. Fits one temperature, reports validation/sealed accuracy, ECE, per-scenario accuracy, MPS/CPU latency; writes evals/router-data/student/<run>/ (gitignored). Its StudentRouter backs the harness’s --arms student.
evals/pace_tool_source.py ~24 Shared offline reader for tool schemas and descriptions owned by preinstalled powers; preserves typed planner ordering and rejects missing or duplicate owners.
leanring-buddyTests/PaceTeachingLessonTests.swift ~711 Lesson schema, compact trusted-template boundaries, awaited progression, pause/manual control, muted history, follow-up reuse, shared drainer acceptance, opt-in planner latency comparison and noncatalog generalization probes.
leanring-buddyTests/PaceTeachingManagerTests.swift ~669 Manager speech/history ownership, muted/remote turns, early native preview eligibility, exploration-safe authored answers, owned failure cleanup and stale-response fences.
leanring-buddyTests/PaceServerSpeechLifecycleTests.swift ~275 Real silent-WAV completion, per-utterance Japanese voice/language through whole-utterance retries, rejection before split playback, isolated outages, fail-closed fallback, delayed cancellation and reentrant stop acceptance.
scripts/check-power-contracts.mjs ~50 Native power contract gate preserving its 28 speech/teaching/image/annotation/prompt suites and adding saved-power CRUD, automation/program/skill and permission boundaries (37 distinct suites).
evals/pace_v10.py ~400 Shared helpers for the v10 action-quality eval (V10_MODE fixtures). Provides V10_RESPONSE_FORMAT (mirror of LocalPlannerClient.v10ResponseFormat — payload free except a typed calls sub-schema), build_agent_mode_system_prompt() (verbatim CompanionSystemPrompt prose blocks + a tool list auto-derived from PaceToolRegistry.swift), and decode_v10_actions() (mirror of PaceActionTagParser.parsePlannerActions — turns an envelope into the executable action list). Keep in sync with those three Swift files.
scripts/eval-memory-recall.py ~230 Recall-QUALITY eval for unified memory. Scores two rankers over inline fixtures whose queries use DIFFERENT words than the expected memory: a keyword/BM25 baseline (stopwords mirror PaceMemoryIndex, runs with no model — expected to MISS the lexically-divergent rows) vs. semantic cosine over LM Studio /v1/embeddings (the production path — should rescue them). Markdown scorecard; semantic auto-skips with a clear message when LM Studio is unreachable. Exits non-zero only when a reachable semantic run fails to rescue every no-overlap case, so it can gate CI once the embedding model is a fixture.
scripts/eval-locomo-recall.py ~190 Runs Pace’s embedding recall against the public LoCoMo long-term-memory benchmark (raw.githubusercontent.com/snap-research/locomo/main/data/locomo10.json, fetched to /tmp), and doubles as a prototyping bench for recall improvements before porting to PaceMemoryRetriever. Indexes dialog content, embeds each question with the production embedding model, ranks, reports retrieval recall@k (gold-evidence turn in top-k) overall + by LoCoMo category. Flags: --window N (group N turns/unit), --date (session-date prefix), --hybrid (RRF-fuse BM25 + semantic). Default reproduces the naive per-turn semantic baseline. Measured lift (2 convs, 231 Qs, nomic): baseline recall@1/5 = 33/63%; +windowing+date+hybrid = 49/74% (temporal @5 76→87%; hybrid slightly regresses multi-hop@1).
scripts/eval-locomo-qa.py ~190 Full LOCAL answer-accuracy pipeline on LoCoMo — the apples-to-apples metric vs. market memory tools. retrieve (nomic + window3 + date + hybrid RRF) → answer (google/gemma-3-12b from retrieved context, may use world knowledge) → LLM-judge (same local model, lenient semantic match matching how Mem0/Zep/ByteRover score). Retry-hardened HTTP. Firmest result (190 Qs / 3 convs): ~70% (single-hop 83, open-domain 74, multi-hop 67, temporal 58) — above Mem0 (62–67), just under Zep/LangMem (75–79), fully on-device. (A 56-Q sample read 77%; the bigger run settled it to a stabler 70%. A too-strict judge + memory-only prompt earlier understated it to 54%.) Still a local gemma judge — a GPT-4o judge could move it a few points.
scripts/diag-pace.py ~1060 Pace runtime self-diagnostic. Exercises the exact LM Studio call pattern Pace uses every turn (VLM + planner alternating), measures TTFT, flags model thrashing, asserts VLM JSON decodes into LocalVLMScreenAnalysis. With --eval also runs the full FM-fixture set through the configured planner and folds the pass count + mean latency into the same PASS/FAIL board. Read Info.plist directly so it tests exactly what Pace will use at runtime.
evals/fm-fixtures/*.txt — Plain-text fixtures consumed by eval-fm.sh + eval-planners.py + diag-pace.py. Each declares USER:, ELEMENT: lines, plus optional EXPECT_POINT_ID / EXPECT_CLICK_ID / EXPECT_POINT_ID_ONE_OF / SPOKEN_MUST_CONTAIN / SPOKEN_MUST_NOT_CONTAIN / SPOKEN_MAX_WORDS scoring metadata. See evals/fm-fixtures/README.md for the full schema.
evals/v10-schema-fixtures/*.json — Deterministic v10 planner-response examples labelled schema-valid or schema-invalid. Used by scripts/eval-v10-schema-fixtures.py to catch envelope/schema drift before model evals or runtime-default switches.
evals/fm-fixtures-actions/*.txt — V10 action-quality fixtures (draw / open_app-vs-open_url / multi-step skill). Set V10_MODE: true; scored against the DECODED action list via evals/pace_v10.py. Cover the three live action-quality failures the typed/free-text fixtures never exercised. See evals/README.md.
Source Approx. lines Purpose
PaceJapanesePractice.swift ~230 Session-only Japanese practice mode, bounded bilingual reply contract, one-call teacher instructions and existing chat control.
leanring-buddyTests/PaceJapanesePracticeTests.swift ~580 Practice/parser/history/profile/default-language checks and opt-in local Japanese/English WAV transcription qualification.
leanring-buddyTests/PaceCaptureAcknowledgementTests.swift ~590 Post-tap receipt ordering, mute and history preservation, empty/cancel/stale capture safety and old-finalization timer cancellation.
leanring-buddyTests/PaceDialogueTranscriptModelTests.swift ~100 Exact-turn activity grouping, retained receipt bodies, unlinked records, visible failure/approval, caption metadata and streaming identity checks.
leanring-buddyTests/PaceDialogueReplayTests.swift ~265 Per-message replay, both mute boundaries, immediate mute and Stop, canonical history and draft preservation through the manager fixture.
leanring-buddyTests/StreamingSentenceTTSPipelineProfileOnsetTests.swift ~75 Controlled Japanese utterance onset/completion and stale-onset rejection for latency and spoken-character accounting.
PaceCLIProcessRunner.swift ~233 Cancellable bounded subprocess stream with UTF-8 framing, private stderr capture and awaited owned-worker/process-group teardown.
PaceDesktopRequests.swift ~300 Typed browser/profile, native capture, meeting control, and folder-specific interactive Codex-in-Warp actions.
PaceScreenRecordingController.swift ~140 Owned native main-display recording lifecycle, bounded stop and shutdown, and saved-movie validation.
scripts/setup-whisperkit.py ~57 Standard-library provisioner for pinned English base.en and optional --multilingual base assets and local tokenizers under Application Support.
../leanring-buddyTests/PaceInventoryContextBenchmarkTests.swift ~112 Opt-in, fixed synthetic two-window answer comparison through the selected Codex CLI. Alternates frozen broad context and scoped inventory context; validates both answers and performs no desktop actions.

| Resources/OpenSourceNotices.txt | license text | Offline copyright and licenses for pinned Swift dependencies and optional external helpers, opened from About. |

Was this page helpful?