MAD Designer iconMAD

Phase 6a — Connection & document — Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Give the WPF shell the connection & document layer — create a .mad from a database connection (importing its schema), edit/reconnect a document’s connection, and save/save-as — on top of Phase 5’s open/refresh/export, with launch-to-empty (all document controls disabled) and a connection wizard.

Architecture: Extend the serve protocol (CLI/Source/MADCLIServe.m) with four additive methods — create, test-connection, connection, apply-connection — each a thin wrapper over an existing engine API, and make write serialize the live document. On the .NET side, add a ConnectionSpec DTO, EngineService wrappers, a Windows Credential Manager store, a recent-files service, a connection-window view model + view, and wire the main window’s File menu + workspace gating.

Tech Stack: Objective-C (GNUstep engine, mad.exe); C# / WPF / .NET 10 (net10.0-windows); xunit.

Spec: docs/superpowers/specs/2026-11-19-phase6a-connection-document-design.md

Global Constraints

Review Focus

  1. Missing or 0-byte SQLite file on test-connection/create → a clean error (code 3), no 0-byte .mad or .sqlite3 artifact created, no crash.
  2. Server driver with no host or database → a usage error (code 1) with a clear message, before any network attempt.
  3. create into a non-existent directory → the parent directory is created (or a clean usage error), never a crash.
  4. Unknown/omitted driver token → a usage error (code 1), never a crash or an accidental SQLite default.
  5. A document with no source database (or a stale handle) on connection/apply-connection → a clean usage error, session keeps running.

Task 1: Engine — test-connection and create methods

Files:

Interfaces:

Add #import for <MAD/MADDatabase+Constructor.h> (for newDatabaseWithConnection:), <MAD/MADDatabaseConnectionsPropertiesURLProtocol.h>, and the four connection headers <MADSqlite3/MADDatabaseConnectionSqlite3.h>, <MADMySQL/MADDatabaseConnectionMySql.h>, <MADTdsClient/MADDatabaseConnectionSQLServer.h>, <MADPostgres/MADDatabaseConnectionPostgres.h>. Add static MADDatabaseType MADCLIServeDatabaseTypeForToken(NSString *token) mapping "sqlite3"→MADDatabaseTypeSqlite3, "mysql"→MADDatabaseTypeMySQL, "sqlserver"→MADDatabaseTypeTDS, "postgres"→MADDatabaseTypePostgres, else MADDatabaseTypeNotSet. Add static NSString *MADCLIServeTokenForDatabaseType(MADDatabaseType type) (the inverse).

Mirror MADMacConnectionWindowController buildConnectionWithCredentials:error:. Read driver (string token), and per driver: SQLite reads file (string, must exist and be non-empty → else error code 1); server drivers read host/database (both required → else error code 1), port (int, default 3306 mysql / 1433 sqlserver / 5432 postgres), server (SQL Server only, defaults to host), and credentials (user:password via MADCLIServeCredential). Build the concrete connection: SQLite [[MADDatabaseConnectionSqlite3 alloc] initWithUrl:]; MySQL/Postgres initWithHost:database:andPort:; SQL Server initWithHost:server:database:andPort:. Return nil + *error (code 1) on bad params.

Build the connection, then MADDatabase *db = [MADDatabase newDatabaseWithConnection:conn], id handle = [db connectWithConnection:conn credentals:creds connectionError:&err]; on failure answer code MADCLIExitDatabaseUnreachable with MADCLIDescriptionForError:. On success NSArray *tables = [db getTablesFromConnection:handle error:&err], [db closeConnection:handle], and answer { @"tableCount": @(tables.count) }.

Read path (string, required); create the parent directory first with [NSFileManager createDirectoryAtURL:[url URLByDeletingLastPathComponent] withIntermediateDirectories:YES ...] (mirroring MADCLIServeWriteCopy), answering code 1 on failure. Build the connection. Call [MADHeadlessDocument createDocumentAtURL:url withDatabaseConnection:conn credentials:creds error:&err]; on nil answer code MADCLIExitDatabaseUnreachable for a connection failure, MADCLIExitBadDocument otherwise, with MADCLIDescriptionForError:. Allocate a fresh handle (same loop as MADCLIServeOpen), register a MADCLIServeDocument holding the created MADHeadlessDocument and sourceURL = url, and answer { handle, filename, driver } using MADCLIServeDriverName:.

Note: MADCLIDocument has no public initialiser to adopt a document. Add a tiny -initWithDocument:sourceURL: to MADCLIDocument so the created in-memory document (already connected) is adopted rather than re-read from disk.

Add MADCLIServeMethodTestConnection = @"test-connection" and MADCLIServeMethodCreate = @"create" constants and the two else if branches.

Run: pwsh -File .\Windows\Engine\build.ps1 -SkipToolchain Expected: build completes, Windows/Engine/build/mad.exe regenerated, tests green.

Add a private static string ChinookSqlite() = Path.Combine(RepoRoot(), "MADDesigner", "Resources", "Assets", "Samples.xcassets", "Data", "chinook.dataset", "chinook.sqlite3"). Add tests:

Run: dotnet test .\Windows\Client\Mad.Client.Tests (from Windows/Client) Expected: all tests pass including the three new ones.

git add CLI/Source/MADCLIServe.m CLI/Source/MADCLIDocument.h CLI/Source/MADCLIDocument.m Windows/Client/Mad.Client.Tests/MadEngineClientTests.cs
git commit -s -m "Phase 6a: serve create and test-connection methods"

Task 2: Engine — connection, apply-connection, and live write

Files:

Interfaces:

Given handle, read entry.document.document.database.databaseConnection. If SQLite, read file from the MADDatabaseConnectionsPropertiesURL databaseUrl.path; else read host/port/database/server from MADConnectionsPropertiesProtocol. Answer { "driver": MADCLIServeTokenForDatabaseType(type), ... }. Missing connection → code 1.

Build the connection, then verify it (connect → on failure code 3 → on success closeConnection:). Apply to the live document: if entry.document.document is a MADHeadlessDocument, call applyDatabaseConnection:; else call updateDatabaseWithConnection: (the protocol method). Answer {}.

Replace the MADHeadlessDocument documentWithContentsOfURL:entry.sourceURL read with: id<MADDocumentDataProtocol> proto = entry.document.document; if it is a MADHeadlessDocument, write that live instance via writeToURL:reproducible:error:; otherwise (Apple) keep the re-open-from-sourceURL fallback. Keep the out/reproducible params and the {path, bytes} result unchanged.

Add the two constants and else if branches.

Run: pwsh -File .\Windows\Engine\build.ps1 -SkipToolchain Expected: build completes, tests green.

Run: dotnet test .\Windows\Client\Mad.Client.Tests (from Windows/Client) Expected: all pass.

git add CLI/Source/MADCLIServe.m Windows/Client/Mad.Client.Tests/MadEngineClientTests.cs
git commit -s -m "Phase 6a: serve connection, apply-connection, live write"

Task 3: ConnectionSpec model and EngineService wrappers

Files:

Interfaces:

ConnectionSpecTests.cs:

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter ConnectionSpecTests Expected: FAIL (types not defined).

Add the types with the exact members above. DriverFromToken throws ArgumentException on unknown tokens.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter ConnectionSpecTests Expected: PASS.

Add a private static Dictionary<string, object?> ConnectionParams(ConnectionSpec spec) (driver token + file for SQLite, else host/port/database/server/credentials). Implement the five methods via the existing CallAsync + JSON parsing (matching OpenAsync/DescribeAsync style): CreateAsync returns OpenResult (handle/filename/driver); ConnectionAsync returns a ConnectionSpec; WriteAsync returns WriteResult.

In EngineServiceTests.cs:

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter EngineServiceTests Expected: PASS.

git add Windows/App/Mad.Designer.Windows/Models/ConnectionSpec.cs Windows/App/Mad.Designer.Windows/Models/Schema.cs Windows/App/Mad.Designer.Windows/Engine/EngineService.cs Windows/App/Mad.Designer.Windows.Tests/ConnectionSpecTests.cs Windows/App/Mad.Designer.Windows.Tests/EngineServiceTests.cs
git commit -s -m "Phase 6a: ConnectionSpec model and EngineService wrappers"

Task 4: Windows Credential Manager store

Files:

Interfaces:

CredentialStoreTests.cs uses an in-memory fake ICredentialStore (a test double) to pin the contract: Save_ThenTryRead_RoundTrips, TryRead_MissingKey_ReturnsFalse, Delete_ThenTryRead_ReturnsFalse.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter CredentialStoreTests Expected: FAIL.

WindowsCredentialStore P/Invokes CredReadW/CredWriteW/CredDeleteW from advapi32.dll with CRED_TYPE_GENERIC (1), target = "MAD/" + key, and CRED_PERSIST_LOCAL_MACHINE. Save/Delete throw on failure; TryRead returns false on not-found. Wrap each credential in try/finally to CredFree the blob.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter CredentialStoreTests Expected: PASS.

git add Windows/App/Mad.Designer.Windows/Infrastructure/ICredentialStore.cs Windows/App/Mad.Designer.Windows/Infrastructure/WindowsCredentialStore.cs Windows/App/Mad.Designer.Windows.Tests/CredentialStoreTests.cs
git commit -s -m "Phase 6a: Windows Credential Manager store"

Task 5: Recent-files service

Files:

Interfaces:

RecentFilesServiceTests.cs with a temp file path: Add_ThenGet_ReturnsMostRecentFirst, Add_DeduplicatesExistingPath, Add_CapsAtTen, Remove_RemovesPath, Get_OnMissingFile_ReturnsEmpty.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter RecentFilesServiceTests Expected: FAIL.

Persist to a JSON array via System.Text.Json. Add moves to front, dedupes, trims to 10, writes atomically (temp + move). Get returns an empty list on missing/corrupt file.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter RecentFilesServiceTests Expected: PASS.

git add Windows/App/Mad.Designer.Windows/Infrastructure/RecentFilesService.cs Windows/App/Mad.Designer.Windows.Tests/RecentFilesServiceTests.cs
git commit -s -m "Phase 6a: recent-files service"

Task 6: DocumentViewModel — file path, save/save-as, apply connection

Files:

Interfaces:

In DocumentViewModelTests.cs:

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter DocumentViewModelTests Expected: FAIL.

Set FilePath in OpenAsync; add a private LoadAsync(OpenResult open, string path) (describe + query + reset rows) called by both OpenAsync and a new AdoptAsync(OpenResult open, string path); add SaveAsync/SaveAsAsync(path) (via WriteAsync) and ApplyConnectionAsync(spec) (via ApplyConnectionAsync + RefreshAsync) and GetConnectionAsync() (via ConnectionAsync). Add SaveCommand/SaveAsCommand gated on HasDocument, and register them in RaiseCanExecuteChanged.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter DocumentViewModelTests Expected: PASS.

git add Windows/App/Mad.Designer.Windows/ViewModels/DocumentViewModel.cs Windows/App/Mad.Designer.Windows.Tests/DocumentViewModelTests.cs
git commit -s -m "Phase 6a: document save/save-as and apply connection"

Task 7: ConnectionWindowViewModel

Files:

Interfaces:

ConnectionWindowViewModelTests.cs (construct with an in-memory fake ICredentialStore):

Note: the view model’s engine calls are thin; test the pure parts (visibility, default ports, Spec) against a real EngineService only where a fixture exists, and use TestConnectionCommand against the real SQLite chinook fixture (copy to temp) to assert StatusText contains "Found 11 schema tables".

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter ConnectionWindowViewModelTests Expected: FAIL.

Raise IsSqlite/IsServer/IsSqlServer and reset Port to the driver default whenever Driver changes (mirroring the Mac’s port-default logic: only bump to the new driver default when the current port is 0 or another driver’s default). TestConnectionCommand → TestConnectionAsync(Spec) → StatusText = $"Connected! Found {n} schema tables." or an error. SubmitCommand → edit mode: set ResultSpec = Spec, Submitted = true; create mode: resolve path via createPath (append .mad if missing), CreateAsync, save credentials when SaveCredentials && server && CredentialKey != null, set Created/CreatePath.

Run: dotnet test .\Windows\App\Mad.Designer.Windows.Tests --filter ConnectionWindowViewModelTests Expected: PASS.

git add Windows/App/Mad.Designer.Windows/ViewModels/ConnectionWindowViewModel.cs Windows/App/Mad.Designer.Windows.Tests/ConnectionWindowViewModelTests.cs
git commit -s -m "Phase 6a: connection window view model"

Task 8: ConnectionWindow view and wiring

Files:

Interfaces:

A Window titled “Database Connection Settings” (edit) / “Create a New Mobile Analytics Document (.mad)” (create). Driver ComboBox (SQLite / MySQL / Microsoft SQL Server / PostgreSQL); SQLite file TextBox + “Choose File…” Button (visibility bound to IsSqlite); Host/Port/Database/Username/Password (+ Server Instance for SQL Server) bound with IsServer/IsSqlServer; a “Save password in Windows Credential Manager” CheckBox; a status TextBlock; buttons “Test Connection”, “Create Document…” / “Save & Refresh”, “Cancel”.

ConnectionWindow.xaml.cs opens an OpenFileDialog for SQLite (.sqlite3;.db;.sqlite) and a SaveFileDialog for the create path; DialogResult set on submit/cancel. The create-path delegate and file chooser delegate are wired into the view model.

Add OpenConnectionWindow(bool isEdit): build the ConnectionWindowViewModel (with ICredentialStore, an initial spec from Document.GetConnectionAsync() for edit, and a createPath save dialog for create); show ConnectionWindow as a modal; on create, await Document.AdoptAsync(vm.Created!, vm.CreatePath!) and add to recent files; on edit, await Document.ApplyConnectionAsync(vm.ResultSpec!).

Run: dotnet build .\Windows\App\Mad.Designer.Windows\Mad.Designer.Windows.csproj Expected: build succeeds.

git add Windows/App/Mad.Designer.Windows/Views/ConnectionWindow.xaml Windows/App/Mad.Designer.Windows/Views/ConnectionWindow.xaml.cs Windows/App/Mad.Designer.Windows/MainWindow.xaml.cs
git commit -s -m "Phase 6a: connection window view"

Task 9: File menu, workspace gating, empty launch, command-line open

Files:

Interfaces:

Add NewDocumentCommand, SaveCommand, SaveAsCommand, EditConnectionCommand, and a RecentFiles observable list + OpenRecentCommand. Remove the London auto-open from InitializeAsync (leave it opening a command-line path only). Inject a RecentFilesService and a Func<string?>? open/save path provider.

Add a Menu (File → New Document…, Open…, Save, Save As…, Database Connection…, Recent Files submenu; plus the existing Open…/About). Bind the Query/Designer/Viewer TabControl.IsEnabled to Document.HasDocument and each document command’s Command to the corresponding Document/VM command (Refresh/Export/Save/Save As gated on HasDocument).

Read Environment.GetCommandLineArgs() for a non-exe argument ending in .mad; on startup open it, otherwise show the empty state (no dialog, no auto-open). Keep OnClosed → _engine.DisposeAsync().

Run: dotnet build .\Windows\App\Mad.Designer.Windows\Mad.Designer.Windows.csproj then dotnet test .\Windows\App\Mad.Designer.Windows.Tests Expected: build succeeds, all tests pass (existing London/About/licence tests plus the new ones).

git add Windows/App/Mad.Designer.Windows/ViewModels/MainWindowViewModel.cs Windows/App/Mad.Designer.Windows/MainWindow.xaml Windows/App/Mad.Designer.Windows/MainWindow.xaml.cs Windows/App/Mad.Designer.Windows/App.xaml.cs
git commit -s -m "Phase 6a: file menu, workspace gating, empty launch"

Task 10: Documentation, push, and summary

Files:

In docs/project/MAD_WINDOWS.md §6d, add the four methods to the method table and a sentence that write now serializes the live document. In Windows/README.md, add the create/test-connection/connection/apply-connection methods to the serve paragraph and note the WPF launch-to-empty + connection wizard.

Write C:\dev\mad-win-reports\phase6a-summary.md covering what was built, the protocol extension, the WPF architecture, and how it was validated (create → describe → refresh → test-connection).

git push origin windows-engine

Expected: push succeeds; DCO + Linux verification remain green; PR #32 stays draft.

Verify git log shows the Phase 6a commits on windows-engine; do not merge to master.