Commit Graph
22 Commits
Author SHA1 Message Date
james.maes 3cf0d396ea test(10-02c): add InProcessAwareDispatchRoutingTests for B-01b regression coverage
- 5 cases at the dispatch routing boundary: in-process route, stdio fallthrough,
  confirmation gate preservation, late-registration timing, observer parity.
- All FAIL until InProcessAwareToolDispatcher composite + InProcessConfirmationCache land.
- Bug: B-01 wired catalog enumeration (10-02b) but missed dispatch routing —
  MCPToolDispatcher only knows the 3 stdio tools, so when the model emitted
  tool_use for get_active_audio_route, dispatch failed and the failure
  surfaced as visible chat text.
2026-05-07 11:15:54 -05:00
james.maesandClaude Opus 4.7 c5c5072b5d feat(10-02b): add toolDescription to InProcessTool + toolSchemas() projection
Adds the substrate that the production fix at App/AppDelegate.swift:1274
needs to source the tool catalog from the in-process registry instead of
the hardcoded empty array.

Protocol change:
- InProcessTool gains `var toolDescription: String { get }` — a
  human-readable one-line description surfaced in the Anthropic / Ollama
  tools[] payload's `description` field. Named `toolDescription` (not
  `description`) to avoid colliding with CustomStringConvertible.

All 7 production InProcessTool implementations updated with descriptions
calibrated to drive correct tool selection by the model:
- list_audio_devices, get_active_audio_route, get_self_state,
  list_camera_devices (Phase 10-01 self-knowledge tools)
- search_memory, forget_fact, search_conversation (Phase 7 memory tools)

Registry change:
- InProcessToolRegistry.toolSchemas() projects every registered tool to
  a ToolSchema(name, description, inputSchema) suitable for the LLM
  request body. Returns name-sorted for prompt-cache determinism.
- Adds AgentCore import to InProcessToolRegistry for the ToolSchema type.

Test coverage:
- InProcessToolRegistrySchemasTests asserts all 7 tools project
  correctly with non-empty descriptions and inputSchema bytes.
- All 85 existing MCP tests pass unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 07:28:20 -05:00
james.maes 1952e74c8a test(10-01): add Wave-0 RED stubs for four self-knowledge MCP tools
- ListAudioDevicesToolTests, GetActiveAudioRouteToolTests,
  GetSelfStateToolTests, ListCameraDevicesToolTests — Stub-style
  dispatchers (D-31) drive each tool through its JSON encode path.
- MCPRuntimeWiringTests/registersFourSelfKnowledgeTools — asserts the
  four tool names register in InProcessToolRegistry AND each carries
  requiresConfirmation == false (D-10).
- All five fail to compile until Task 2 ships the production types
  (AudioDeviceListing/Entry, ActiveAudioRouteDispatching/Route,
  SelfStateDispatching/State, CameraDeviceListing/Entry, four tool
  structs). RED confirmed via `cannot find type ...` diagnostics.
2026-05-06 15:18:33 -05:00
james.maesandClaude Opus 4.7 f9cd25d66e chore(test-naming): converge on Mock/Fake/Stub convention; document in CLAUDE.md; rename worst-mismatch stragglers
Per audit-2026-05-04 P2-15: 26 Mock*, 21 Fake*, 12 Stub* across the test
corpus, often used interchangeably for the same role. New CLAUDE.md
section "Test naming conventions" (line 127) sets the rule:

- Mock*: records calls AND returns scripted responses (assertion driver).
- Stub*: returns canned data without recording (deterministic input).
- Fake*: alternative implementation with realistic behavior (in-memory
  state-holder).

Renamed 15 worst-mismatch stragglers in the older corpus (per audit
constraint, did NOT touch types added in today's P1+P2 fix commits):

Stub* → Mock* (records + scripts):
- HybridSearchTests:    StubEmbedder → MockEmbedder
- HybridSearchTests:    StubStore → MockStore
- SessionHistoryTests:  StubStore → MockStore
- InProcessMemoryToolsTests: StubHybrid → MockHybrid
- InProcessMemoryToolsTests: StubHistory → MockHistory
- InProcessMemoryToolsTests: StubForget → MockForget

Mock* → Stub* (canned data, no recording):
- STTBackendSwitchTests: MockSpeechAnalyzerBridge → StubSpeechAnalyzerBridge
- STTBackendSwitchTests: MockWhisperKitBridge → StubWhisperKitBridge
- VoiceWiringTests:      MockVADEngineForW4 → StubVADEngineForW4
- VoiceWiringTests:      MockSTTProviderForW4 → StubSTTProviderForW4
- VoiceWiringTests:      MockTTSForW4 → StubTTSForW4
- VoiceWiringTests:      MockOrchestratorForW4 → StubOrchestratorForW4
- VoiceWiringTests:      MockBannerForW4 → StubBannerForW4
- VoiceWiringTests:      MockBusForW4 → StubBusForW4

Fake* → Mock* (records + scripts):
- WebviewBridgeOutboundTests:        FakeJSEvaluator → MockJSEvaluator
- HudStateCoordinatorBusWiringTests: FakeJSEvaluator → MockJSEvaluator
  (the comment on the type already said "Records each call for assertion")

Skipped per audit constraint:
- StubCapture/StubSink (Vision FrameAttachConfirmSendWiringTests, P1+P2)
- MockVADEngine + MockOrchestratorForController siblings (Voice
  VoiceControllerTests/VADGatedSessionTests, today's track-B churn)

Tests pass: Voice 87+23, MCP 85, Memory 88, Bus 58, AgentCore 19+72,
Vision 19, Shell 7+5. App target builds clean.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 16:42:16 -05:00
james.maesandClaude Opus 4.7 57847f2f58 chore(test-seams): move _test*/_force* seams from public to internal
Per audit-2026-05-04 P2-14: VoiceController._forceState,
_testFireSpeechEnd, _testCurrentSttSessionId were declared `public`
solely so XCTest could see them. Same for MCPClient._testHandle and
MCPServerHandle._testProcessIdentifier. These leaked test-only entry
points into each package's public API — anyone importing Voice could
call _forceState(.speaking) from production code.

Voice (4 seams): public → internal. Voice tests already use
@testable import Voice, so no test-side change required.

MCP (2 seams): public → @_spi(Testing) public. MCP tests opt in
via @testable @_spi(Testing) import JarvisMCP. The Harness package
(non-test) consumes _testHandle / _testProcessIdentifier for the
MCPCrashRunner SIGKILL recipe — opt in via @_spi(Testing) import.
@testable alone does NOT expose @_spi symbols — the SPI must be
explicitly imported, which is the desired discipline (each consumer
acknowledges they're reaching past the public ABI).

6 test seams total moved off the public ABI. Voice + MCP tests
pass (87 + 85). Harness builds clean.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 16:22:14 -05:00
james.maes 9fc8d44340 refactor(07-05): extract ChildSpawnGate into JarvisChildSpawn target (Rule 3 deviation)
[Rule 3 - Blocking] VllmMlxSidecar (Task 4) needs ChildSpawnGate but
packages/Vision can't depend on JarvisMCP without transitively pulling
AgentOrchestrator (which would violate VISION-03 boundary).

Solution: hoist ChildSpawnGate.swift into a new JarvisChildSpawn SPM
target inside the MCP package. JarvisMCP keeps the same singleton via
the new dep; Vision can now depend on JarvisChildSpawn alone.

- New target JarvisChildSpawn (only depends on swift-log)
- JarvisMCP gains JarvisChildSpawn as a dependency
- MCPServerHandle.swift / MCPClient.swift gain 'import JarvisChildSpawn'
- ChildSpawnGate uses Logger directly instead of MCPLogChannel.logger
  (avoids dragging MCPLogChannel into the standalone target)
- Tests updated to '@testable import JarvisChildSpawn'
- All 3 ChildSpawnGate tests pass; full MCP build clean
2026-04-29 17:51:18 -05:00
james.maes a5107218e8 test(07-03): add failing in-process MCP tools + Bus session-history tests
- InProcessMemoryToolsTests: dispatch coverage for search_memory,
  search_conversation, forget_fact through InProcessToolRegistry; stub
  dispatchers; requiresConfirmation gate (D-02 forget_fact only);
  unknown-tool error
- SessionHistoryOutboundTests: BusOutbound.sessionHistory round-trip +
  shape ("type":"sessionHistory") + version constant present

RED: tests reference InProcessTool, InProcessToolRegistry,
SearchMemoryTool, SearchConversationTool, ForgetFactTool, plus
BusOutbound.sessionHistory + Bus.TurnRow — none exist yet.
2026-04-29 17:08:05 -05:00
james.maesandClaude Opus 4.7 af1c7700d7 fix(05-review): WR-06 make MCPClient.callTool arguments optional
Match the SDK's `Client.callTool(name:arguments:)` signature where
`arguments: [String: Value]?` is optional. Callers can now invoke
no-arg tools without manually passing `[:]`. MCPToolDispatcher now
preserves the JSON-RPC `arguments: null` vs `arguments: {}`
distinction by passing `nil` when the model emits no args bytes.

Updated MCPClientCalling protocol + MockClient conformer in
MCPToolDispatcherTests to match the optional shape. Added
test_callTool_withoutArguments_isAccepted that exercises the default
nil parameter.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 16:36:05 -05:00
james.maesandClaude Opus 4.7 7ee91ae578 fix(05-review): WR-03 explicit cancellation handling on broker timer
Replaced `try? await Task.sleep + Task.isCancelled` with an explicit
do/catch that early-returns on CancellationError. Previously the
`try?` swallowed the cancellation error and a window opened between
sleep returning and Task.isCancelled being observed during which a
cancelled timer could still fire .timeout. Today the broker's
first-write-wins guard saves us, but a future contributor removing
that guard would silently introduce double-resolve.

Adds test_response_atTimerBoundary_firstWriteWins_noDoubleResolve —
loops 10x at a 50ms timeout, sends .deny at T+49ms, asserts the
broker resolves exactly once (deny OR timeout, both legal) and dismiss
fires exactly once. Catches double-resolve regressions.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 16:30:32 -05:00
james.maesandClaude Opus 4.7 094c067b94 fix(05-review): WR-02 hold broker and presenter strongly through holder
Previously ConfirmationPresenter held broker as `weak var` and
ConfirmationPresenterHolder held its inner presenter as `weak var` —
a doubly-weak chain that could silently break Approve/Deny button
responses if either side deinit'd during a pending request. The user
would see the panel close on Approve, then the orchestrator would
hang for 60s until the broker's timer fired .timeout.

Switched both to strong references. The cycle motivation
(broker → presenter → broker) is broken by the holder indirection:
broker holds the holder, holder holds presenter strongly, presenter
holds broker strongly. The chain is acyclic when read top-down because
the broker does not hold the presenter directly.

Documents the lifecycle invariant on MCPRuntime: AppDelegate must hold
runtime strongly for the lifetime of the process; orchestrator must
not outlive the runtime.

Adds ConfirmationLifecycleTests with three guards:
- canonical hold pattern always resolves Approve
- wedged presenter (never calls broker.response) still resolves via
  timeout — the timer is the load-bearing fallback
- source-level: ConfirmationPresenter declares `let broker:` (strong),
  not `weak var broker:`

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 16:28:54 -05:00
james.maesandClaude Opus 4.7 6cbe8a551c fix(05-review): CR-04 remove LSBackgroundOnly from mcp-clipboard
LSBackgroundOnly: true silently denied NSPasteboard.general access on
macOS Sonoma+ (Apple feedback FB13402281 lineage). LSUIElement: true
already suppressed the Dock icon — both keys together were redundant
and one was actively breaking pasteboard reads. Removed
LSBackgroundOnly per Option A in REVIEW 05; LSUIElement stays.

Adds test_get_clipboard_seeded_returnsSeededString_CR04 that seeds
NSPasteboard.general with a UUID-tagged string in the parent test
process, then asserts the helper's response is EXACTLY that string
(not the silent-empty marker that the pre-fix LSBackgroundOnly
configuration produced). Skips on headless CI where the parent
can't write the pasteboard.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 16:21:47 -05:00
james.maesandClaude Opus 4.7 d07ac08f0e fix(05-review): CR-03+WR-04 String toolUseId and success-path toolCallEnd
CR-03: BusGateway's toolUseId parameter is now String (matching the bus
schema's Phase 2 closed contract) instead of UUID. Previously the
dispatcher synthesized `UUID(uuidString: toolUse.id) ?? UUID()`, which
silently produced a fresh random UUID for every Anthropic 'toolu_…' or
Ollama free-form id — breaking correlation across bus / replay /
orchestrator. The original String id now flows verbatim from
toolCallStart through argsPreviewUpdate to toolCallEnd. The broker's
internal UUID is now a fresh-per-call value and does NOT replace the
bus-facing id.

WR-04: ConfirmingToolDispatcher now emits toolCallEnd(ok: true, …) on
the success path so bus consumers (HUD ToolCallCard) transition
Running → Completed. On dispatch error post-approval, toolCallEnd
fires with ok: false carrying the error description before re-throwing.

Adds three new tests (busToolUseId verbatim across emissions, non-UUID
id flows through, success path emits 3 events). Updates SpyBus and
SpyBus-equivalent in MCPRuntimeWiringTests to use String toolUseId.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 15:54:34 -05:00
james.maesandClaude Opus 4.7 65c88d2a28 fix(05-review): CR-01 close pipe FDs on MCPServerHandle init-failure paths
Both initialize-failure throw arms in MCPServerHandle.start() (the
client.connect() catch and the helperMissingToolsCapability guard) now
call a new closeParentPipeEnds helper before throwing. Without this,
each failed start() leaked 3 parent-side pipe FDs (stdin write, stdout
read, stderr read) — Foundation's Pipe deinit doesn't close FDs when
the underlying FileHandle was created with closeOnDealloc:false (the
default), and terminateProcessImmediately only SIGKILLs the child.

Adds MCPServerHandleInitFailureFDLeakTests with four structural
assertions: helper exists, closes all three retained ends, both throw
arms call it, cleanup precedes the throw on both arms.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 15:48:39 -05:00
james.maes 738f88a1c9 feat(05-05): ConfirmingToolDispatcher — broker-gated wrapper + 9 tests
Closes MCP-04 (full args-redaction seal pre-approval) and SEC-08
(defense-in-depth args masking on the bus). Final wiring of AGENT-11's
timeout-as-deny semantics — .timeout outcome triggers a JarvisLogChannel.mcp
WARNING line + ConfirmationError.timedOut throw.

- Public actor ConfirmingToolDispatcher conforms to ToolDispatcher and
  composes around an inner ToolDispatcher (production: MCPToolDispatcher).
  Plan 04-04's orchestrator code is unchanged; the gating happens by
  composition.
- Pre-approval bus emission's argsPreview is the literal
  '{"awaitingApproval":true}' seal. Post-approval, a follow-up
  updateArgsPreview carries the sanitized real args.
- BusGateway protocol abstracts the three bus surfaces the dispatcher
  needs (start / update / end). App-level wiring implements it.
- defaultLogWarning routes to swift-log Logger(label: 'mcp') with a
  'subsystem=ConfirmingToolDispatcher' metadata key. Tests inject a
  recording closure.
- 9 tests: pass-through fast path; awaiting-approval seal ordering;
  approve / deny / timeout / barge outcomes; inner-error propagation
  after approval; sync requiresConfirmation delegation; explicit
  args-redaction-before-approval invariant. test_OC_T1_timeoutLogsWarning
  name fixed by plan medium-finding.
2026-04-25 14:25:42 -05:00
james.maes 5d8ef0c2ec feat(05-05): ConfirmationBroker FSM + 60s timeout + 9 RED→GREEN tests
Closes MCP-09 (broker FSM, first-write-wins on .approve / .deny / .timeout
/ .barge) and AGENT-11 (60s timeout-as-deny via Task.sleep with sub-second
test-injection knob).

- ConfirmationOutcome.swift defines the four-outcome enum, matching
  ConfirmationError throw-type, and ConfirmationPresenting protocol so the
  broker can compile + test against an actor mock without pulling AppKit.
- ConfirmationBroker.swift is a public actor whose serial executor IS the
  synchronization primitive; no locks, no atomics. The 'resolved' guard
  inside response(id:outcome:) enforces MCP-09 first-write-wins.
- 9 tests cover the four-outcome happy paths, the sub-second timeout, the
  late-hop no-op invariants (after .approve and after .timeout), the
  concurrent-response race, the unknown-id no-op, and the dismiss-once
  lifecycle invariant.
2026-04-25 14:20:21 -05:00
james.maes a48c7f7e0f test(05-04): RED — MCPToolDispatcherTests + AgentCore SPM dep
8 tests covering the ToolDispatcher conformance:
- happy-path text concat + sanitize (zero-width + bidi stripped)
- multi-block .text concatenation
- under-cap passthrough vs over-cap boundary marker
- error propagation from client
- synchronous (nonisolated) requiresConfirmation read
- ToolResultObserver receives both pre- and post-sanitize bytes
- observer NOT called on error

Adds the asymmetric MCP→AgentCore SPM dependency (MCP imports
AgentCore + AgentOrchestrator; AgentCore intentionally does NOT
depend on MCP — the orchestrator stays provider-agnostic and only
sees the protocol). This deviates from Plan 05-01's stated isolation
of MCP from AgentCore; the deviation is the intentional bridge
between the two packages. No cycle.
2026-04-25 13:59:35 -05:00
james.maes 2648a24793 test(05-04): RED — ToolRegistryTests for tool→server lookup
5 tests covering register / unknown / requiresConfirmation /
toolNames-sorted / overwrite-existing semantics. ToolRegistry is
the value-type snapshot MCPToolDispatcher captures at init so the
protocol's nonisolated requiresConfirmation(toolName:) can read
synchronously without an actor hop.
2026-04-25 13:56:46 -05:00
james.maes 6be0561a69 test(05-04): RED — SanitizeForModelTests for SEC-07 pipeline
18 tests covering the byte-stream sanitize + head-truncate boundary:
- C0/DEL/bidi-override/bidi-isolate/zero-width/BOM stripping
- per-line cap at 4096 bytes with `…[line-truncated]` marker
- newline preservation (split-first pattern)
- UTF-8 totality on garbage input
- head-truncate cap (8192) with byte-count marker
- prepareForBoundary fixed-order guard (sanitize → headTruncate)
  using a 10000→2500-byte distinguisher input that proves the
  reverse order would leak a truncation marker
- prepareForBoundary does NOT wrap (wrap is orchestrator-side)
2026-04-25 13:55:48 -05:00
james.maes c9a58b42e2 feat(05-02): xcodegen wiring + Copy Helpers script + integration tests
project.yml:
- Register swift-sdk @ 0.12.0 as a top-level package (consumed by both
  helper targets; same exact version as packages/MCP/Package.swift)
- Add mcp-time and mcp-clipboard application targets with per-config
  signing (Debug=ad-hoc CODE_SIGNING_ALLOWED=NO, Release=hardened
  runtime + --options=runtime --timestamp). Each target carries its
  own CODE_SIGN_ENTITLEMENTS pointing at mcp-servers/<helper>/Support/
- Each helper has a postBuildScript that copies its source
  .entitlements into <bundle>/Contents/Resources/ where codesign.sh
  expects it (per P1-05 contract)
- Jarvis target depends on both helpers (embed=false, link=false —
  helpers are independent .app subprocesses, not linked frameworks)

DEVIATION (Rule 3, blocking issue): xcodegen 'copyFiles' phase doesn't
resolve target products from BUILT_PRODUCTS_DIR — it expects file
paths relative to SRCROOT. The plan's
'files: [mcp-time.app, mcp-clipboard.app]' produced an empty
Contents/Helpers/ at build time. Switched to a postBuildScript on
Jarvis ('Copy MCP helpers into Contents/Helpers/') that 'cp -R' from
BUILT_PRODUCTS_DIR. This matches the plan's deviation_rules clause #1
('If xcodegen doesn't directly support nested .app bundles via
Contents/Helpers/<Name>.app/, generate the helper bundles via
separate xcodebuild targets and copy them in via a Build Phase
script.'). Code Sign On Copy stays disabled — codesign.sh's
deepest-first walker is the authoritative signer.

DEVIATION (Rule 1, bug): mcp-time/Sources/mcp-time/main.swift renamed
to MCPTimeMain.swift to fix Xcode's '@main attribute cannot be used
in a module that contains top-level code' error. Same root cause as
mcp-clipboard's earlier rename — when the file is named main.swift,
Xcode treats it as a script and rejects @main on a struct.
Standalone 'swift build' tolerated it; xcodebuild does not.

Integration tests (packages/MCP/Tests/MCPTests/):
- HelperBundleLocator.swift: shared resolver, env override →
  Bundle.main walk → DerivedData walk (Release-preferred; skips Debug
  builds with adjacent <helper>.debug.dylib because Xcode 26's
  incremental-link artifact has a code signature mismatch with the
  parent and dyld rejects on subprocess launch)
- MCPTimeIntegrationTests: round-trip get_time, parse via
  ISO8601DateFormatter, assert ±60s of Date()
- MCPClipboardIntegrationTests: round-trip get_clipboard, accept any
  of (text/empty/refusal) outcomes since the test runner's pasteboard
  state is unknown

DEVIATION (Rule 1, bug): Both integration tests use synchronous
'await client.shutdown()' rather than 'defer { Task { await ... } }'.
Fire-and-forget shutdown leaks helper stdio FDs into the next test;
ChildSpawnGate's DEBUG-only fatalError precondition (FD must be
CLOEXEC) crashes the next spawn. Discovered when MCPRestartTests ran
after the integration tests in the same suite.

Verification:
- swift test --package-path packages/MCP: 18/18 pass (16 from 05-01
  + 2 new integration). FD leak baseline=4 final=4 delta=0
- swift test --package-path mcp-servers/mcp-clipboard: 6/6 pass
- xcodegen generate: clean
- xcodebuild Release build: SUCCEEDED end-to-end (codesign + verify)
- Both helper bundles signed with empty entitlements; 0 apple-events
- 0 CodeSignOnCopy=YES, 0 --deep in pbxproj
2026-04-25 13:04:15 -05:00
james.maes 5fee4060e1 feat(05-01): per-server restart mutex + 100-cycle FD-leak test
- MCPServerHandle.claimOrShareRestart(buildTask:): atomic claim-or-share
  primitive that runs entirely under handle actor isolation. The closure-
  based design ensures the Task is only constructed inside the actor's
  serial execution, so concurrent callers can't race past the slot check
  and stampede the spawn path.
- MCPClient.callTool: layers the per-server mutex on top —
    1. await any in-flight restart; then
    2. if still crashed, claim-or-share the slot (claimant runs start();
       sharers await the same task);
    3. dispatch through the SDK client.
  Slot is cleared on both success and failure paths so a future call
  after a failed restart can attempt again. No backoff/retry inside the
  mutex — RESEARCH A5 contract.
- MCPServerHandle.start: pin PID at terminationHandler wire time so a
  STALE handler from a prior helper (post-restart) cannot flip
  isCrashed=true on the LIVE process; handleTermination(forPID:) early-
  returns when self.process.processIdentifier != pid.
- MCPServerHandle.start: set FD_CLOEXEC on the parent-side pipe ends
  (stdin write, stdout read, stderr read) immediately after Process.run().
  Foundation creates Pipe FDs without O_CLOEXEC; without this retrofit
  the Debug-build ChildSpawnGate fatalErrors when a subsequent spawn
  sweeps the parent FD table. CLOEXEC at FD-creation time is the gate's
  primary defense per RESEARCH Pitfall #8.
- MCPRestartTests: 4 tests
    1. test_singleCrash_followedBy_callTool_succeedsAfterRestart
    2. test_concurrentCallsDuringRestart_shareOneRestart  (8-way contention,
       tally side-channel verifies exactly 2 helper starts: initial + 1 restart)
    3. test_inFlightCallTool_duringCrash_throws_serverCrashed (mock_slow
       call SIGKILL'd mid-flight)
    4. test_100_crashCycles_noFDLeak  (baseline=4, final=4, delta=0)

Plan: 05-01 Task 3 of 3.
2026-04-25 10:57:07 -05:00
james.maes 8dbd6f0c87 feat(05-01): MCPServerHandle + MCPClient happy path + MockHelper fixture
- MCPServerHandle actor: spawns helper via ChildSpawnGate.shared.prepare(),
  sets process.environment = minimalEnvironment, launches with 3 Pipes,
  closes child-side pipe ends in the parent (FD-leak guard for restart
  cycles), wires StdioTransport with EXPLICIT FileDescriptor args (single-
  line so the grep gate matches literally), connects SDK Client, asserts
  Initialize.Result.capabilities.tools != nil, drains stderr to log channel,
  installs terminationHandler -> handleTermination async path.
- MCPServerHandle.callTool wraps the SDK's (content, isError?) tuple back
  into CallTool.Result so downstream consumers see the documented type.
  Errors during a call are translated to JarvisMCPError.serverCrashed only
  when isCrashed is set; otherwise rethrown verbatim.
- MCPClient actor: registry of MCPServerHandle keyed by server name,
  toolToServer name lookup populated from each helper's tools/list.
  Restart-mutex layering arrives in Task 3.
- ToolMetadata struct: name + server + requiresConfirmation. Plan 05-04
  /05-05 consume this for dispatch routing + confirmation broker.
- MockHelper fixture (test-only, internal to JarvisMCPTests): SDK Server
  with mock_echo + mock_slow tools, MOCK_HELPER_CRASH_AFTER env knob to
  exit(137) after N calls, MOCK_HELPER_TALLY_PATH side channel for
  restart-cycle counting.
- MockHelperBuilder: shells out to `swift build -c release` once per test
  run, caches the binary URL.
- Tests: 4 happy-path tests (echo round-trip, spawn-failed, helperMissing,
  toolMetadata) + 3 source-level Pitfall #1 regression guards.

Plan: 05-01 Task 2 of 3.
2026-04-25 10:40:34 -05:00
james.maes 896d7fb49a feat(05-01): JarvisMCP scaffold + SDK v0.12.0 pin + ChildSpawnGate
- New SPM package packages/MCP/ with library/target named JarvisMCP
  (avoids name collision with the SDK's MCP product/target — mirrors
  the JarvisLogging convention).
- Pins modelcontextprotocol/swift-sdk at exact 0.12.0 (no range float;
  pre-1.0 SDK). Resolves cleanly under Swift 6.3 toolchain.
- ChildSpawnGate.shared singleton with FD_CLOEXEC sweep (fatalError
  in DEBUG, retrofit + warn in RELEASE) + minimalEnvironment constant
  ['PATH': '/usr/bin:/bin'].
- JarvisMCPError surface (helperMissing / helperMissingToolsCapability /
  startupTimeout / serverCrashed / spawnFailed) — distinct from SDK's
  MCP.MCPError type.
- MCPLogChannel.logger(label:) factory routes all package log lines
  through 'jarvis.mcp.<label>' for grep-able provenance.
- Tests: SDK pin + tools-version >= 6.1 host check (2/2);
  ChildSpawnGate env + prepare + child env-isolation (3/3).

Plan: 05-01 Task 1 of 3.
2026-04-25 10:33:08 -05:00