diff --git a/CLAUDE.md b/CLAUDE.md index bdf964e..adc3a0b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,21 +3,42 @@ mwb-mac is a macOS port of PowerToys "Mouse Without Borders" (MWB): one keyboard and mouse shared across up to four machines on a LAN, with clipboard sharing, that **interoperates on the wire with the unmodified -Windows MWB**. Read `README.md` for architecture, `docs/topo.md` for the -dependency map and `TODO.md` for the backlog before doing anything. The -reference implementation is checked out at -`/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/` +Windows MWB**. Read `README.md` for architecture, `docs/loop.md` for how +work is done, `docs/topo.md` for the dependency map and `TODO.md` for +the backlog before doing anything. The reference implementation is +checked out at `/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/` (commit `3104d5c`, tag v0.101.2572.0) — read it, cite it, never edit it. +## How this project is developed (the user's standing instruction) + +- **One dev loop at a time.** Never two lanes in flight. A lane is + Dev → QA → lead inspection, then the next lane starts. No worktrees + are needed for parallelism; a lane works on a branch or directly on + `main` as `docs/loop.md` says. +- **Roles are fixed**: one Dev (Opus 5) ports the feature; one QA + (Sonnet 5) reviews the *code quality and completeness of the port*; + then the lead (Fable 5.1) inspects. The lead plans and reviews; it + does not write lane code. +- **The human is the tester.** Agents do not write test suites. There is + no gate that requires tests, and no lane is "incomplete" for lacking + them. What matters is that **every feature of the Windows version is + ported and the code reads as reasonable** — the user tests the app + end-to-end at the end. +- **Commit along the way.** Dev commits as it works, in small commits + with clear messages. A commit does not need to compile. Do not + push; the lead pushes after inspection. +- **No busywork.** No placeholder tests, no coverage chasing, no + abstractions for a second user that does not exist. + ## Hard invariants (never break these) 1. **Wire compatibility is a contract, not a goal.** Packet layout, the package-type numbering, the key derivation, the cipher mode and the handshake are dictated by the Windows source (`docs/protocol.md` is our transcription, with `file:line` citations). Any difference is - a bug on our side unless the Windows source changed. Every codec - change ships with golden-byte tests whose expected bytes were - produced by the Windows algorithm, not by our own encoder. + a bug on our side unless the Windows source changed. Every constant + in the codec and crypto code carries a comment citing the Windows + line it came from. 2. **Never act on an unauthenticated packet.** No input is injected, no clipboard is written, no file is created from any packet that did not decrypt and validate under the configured security key. There @@ -31,69 +52,56 @@ reference implementation is checked out at immediately. A build that can leave a Mac with a dead keyboard does not ship. 4. **The event-tap callback never blocks.** No network, disk, locking on - contended locks, or allocation-heavy work inside the - `CGEventTap` callback; it classifies, enqueues and returns. Budget is - measured (`docs/perf/README.md`), not asserted. -5. **Synthetic input is opt-in.** Any test or tool that posts a - `CGEvent`, writes the real pasteboard or moves the real cursor runs - only with `MWB_ALLOW_INPUT_TESTS=1` set explicitly and only inside - the loopback harness. Never set that variable in CI config, a - script default or a `Makefile` target. This machine is the user's - daily driver: an agent test that hijacks the mouse is a P0 finding. + contended locks, or allocation-heavy work inside the `CGEventTap` + callback; it classifies, enqueues and returns. +5. **Agents never drive the user's input devices.** No agent runs a + build that posts `CGEvent`s, writes the real pasteboard or moves the + real cursor. Agents build; the user runs. This machine is the user's + daily driver. ## Simplicity first -- Prefer the boring, obvious implementation. If you're building an - abstraction for a second user that doesn't exist yet, stop. +- Prefer the boring, obvious implementation. Port the Windows + behaviour, not the Windows shape: `Common.cs`, `SocketStuff.cs` and + `MachineStuff.cs` are grab-bags; ours are not. - Apple frameworks first (Foundation, Network, AppKit, CoreGraphics, CryptoKit/CommonCrypto). Adding a Swift package dependency requires a written justification in the feature README. - Small functions, descriptive names, shallow nesting. Code should be readable top-to-bottom without jumping around. -- Match the style of the surrounding code (comment density, naming, - module layout). +- Match the style of the surrounding code. ## File and function size -Files and functions are sized for a human reader, not a compiler. - -- **Target 300–600 production lines per file.** At 800, consider - splitting. Above 1,200, an explicit reason not to split goes in the - feature README. Test lines do not count. -- **Functions: 10–50 lines.** Investigate anything over 80; anything +- **Target 300–600 lines per file.** At 800, split. Above 1,200, an + explicit reason goes in the feature README. +- **Functions: 10–50 lines.** Anything over 80 gets a look; anything over 150 needs a reason in a comment (a `switch` over `PackageType` is the usual one). -- **The real test is one sentence.** A human should be able to say what - a file is responsible for in one sentence and predict which parts a - change touches. Several "and" clauses mean the file wants to be - several modules. The Windows source fails this test in - `Common.cs`, `SocketStuff.cs` and `MachineStuff.cs`; do not port - their shape, port their behaviour. -- A split is a **pure move**: public names stay the same, behaviour - stays byte-identical on the wire, the test count does not drop. +- **The one-sentence test.** A human should be able to say what a file + is responsible for in one sentence. Several "and" clauses mean the + file wants to be several files. ## Swift standards -- Swift 6 language mode, strict concurrency on. `swift-format lint - --strict` clean, `swift build -Xswiftc -warnings-as-errors` clean, - `swift test` green — all three before declaring any work finished. +- Swift 6 language mode, strict concurrency on. +- `xcrun swift-format lint --strict` clean and `swift build -Xswiftc + -warnings-as-errors` clean **at the end of a lane** (`tools/gates.sh`). + Intermediate commits may be broken. - No force-unwrap (`!`), `try!`, `fatalError` or `precondition` in - production code paths; return `Result`/throw. Tests and `main.swift` + production code paths; throw or return `Result`. `main.swift` argument handling may use them. -- Public items get a one-line doc comment. Doc comments say what/why, - not how. -- Layering is enforced by SwiftPM targets, not by discipline: the - `MWBCore` target imports Foundation only (no AppKit, no CoreGraphics, - no Network) so the protocol, crypto, matrix and settings logic is - testable without a display or a network. Platform code lives in - `MWBMac`; the executable `mwb` wires them together. +- Public items get a one-line doc comment saying what/why, not how. +- Layering is enforced by SwiftPM targets: `MWBCore` imports Foundation + and CommonCrypto only (no AppKit, CoreGraphics, Network); `MWBNet` is + Network.framework; `MWBMac` is AppKit/CoreGraphics; the executable + `mwb` is the only place they meet. - C APIs (`CGEventTap`, `CommonCrypto`) are wrapped once, in one file each, behind a Swift type; nothing else touches the raw API. ## Document-based development -Every feature lives in `docs/features//README.md`. That -README is the single source of truth for the feature and must contain +Every feature lives in `docs/features//README.md` with these sections: ```markdown @@ -105,93 +113,34 @@ these sections: ## Status / TODO — checklist; keep current as you work ## Work log — dated entries by the dev agent: what was done, key decisions, deviations from plan -## QA log — dated entries by the QA agent: what was verified, - how, and findings +## QA log — dated entries by the QA agent: what was reviewed, + and findings ## Review — reserved for the lead; do not write here ``` -Rules: - -- **Dev agents**: create/update the feature README *as you work*, not at - the end. Finished TODOs get checked off in the same README. If you - change a handshake another module depends on, say so explicitly in - Handshakes and in the work log. Every fact taken from the Windows - source is cited as `App/.cs:`. -- **QA agents**: you verify, you don't redesign. Run the checks, try to - break the feature, record everything in the QA log. File concrete - findings (file:line, reproduction) — not opinions. Small unambiguous - fixes (typos, missing test assertion) you may fix directly and note it. -- **Review section** is written only by the lead agent after examining - the work. Respond to review comments by fixing and logging in the work - log, not by editing the Review section. +- **Dev agents**: update the README *as you work*, not at the end. Tick + finished items. If you change a handshake another module depends on, + say so in Handshakes and in the work log. Every fact taken from the + Windows source is cited as `App/.cs:`. +- **QA agents**: you review, you don't redesign and you don't write + tests. Read the port against the Windows source and the brief; find + what is missing, wrong or unreadable; record file:line findings in + the QA log. Small unambiguous fixes you may make directly and note. +- **Review** is written only by the lead. Respond to review comments by + fixing and logging in the work log, not by editing the Review section. - `docs/protocol.md` is the one place the wire format is written down. - A feature that learns something new about the protocol updates - `docs/protocol.md` in the same change, with the citation. + A feature that learns something new about the protocol updates it in + the same change, with the citation. ## Workflow -- Do **not** run `git commit` or `git push` — the lead reviews and - commits all work. - Do not touch files outside your feature's stated scope. If you need a change in another module, write it as a request in your README's Handshakes section and stop. -- New behavior needs tests in the same change. Every codec or crypto - change must keep the golden-byte suite green - (`swift test --filter MWBCoreTests`). -- Update `TODO.md`: check items your feature completes (leave the item - text intact). +- Update `TODO.md`: tick items your feature completes (leave the text). - Never grant, request or script macOS permissions (Accessibility, - Input Monitoring, Screen Recording) on the agent's own initiative. + Input Monitoring, Screen Recording) on an agent's own initiative. Report what is missing; the user grants it in System Settings. - -## Runaway guard (never run a suite or sweep bare) - -macOS enforces no memory cap, so the cap is ours: -`tools/guard.sh [-m GB] [-t SECONDS] -- ` kills a command's -process tree when its resident set or wall clock exceeds the limits -(defaults 8 GB / 30 min). - -- **Every `swift test`, every fuzzer, every soak test and every - two-process loopback run goes through `tools/guard.sh`** — dev, QA - and lead alike, foreground or background. -- A guard kill is a finding: report the command and the limit it hit; - do not raise the limit to make it pass. - -## Parallel lanes (the 2-agent loop) - -Up to **two dev/QA lanes may run concurrently** when — and only when — -their features do not collide in `docs/topo.md`: no shared edge between -them (no `──▶`, no `◀──▶`, and neither touching the same open handshake -in §2.9), and disjoint file sets. `docs/topo.md` is the authority; if the -collision question is not answerable from it, the features are not -proven independent and run serially. Rules for a parallel wave: - -- **The lead plans the lanes** before anything is dispatched: one brief - per lane with an explicit file-ownership list. That list is the merge - contract — a lane touches nothing outside it. A needed change to a - file the other lane owns (or to any unlisted file) is a Handshake - request in the lane's README plus a flag in its report, never a - silent edit; the lead rules on it at merge. -- **Each lane works in its own git worktree** branched from the same - trunk commit. Never two agents in one tree. Trunk stays untouched - while lanes are in flight; the lead merges each lane back only after - that lane's QA verdict and lead review, and re-runs the full gates on - the merged tree before pushing. -- **Roles per lane are unchanged**: one dev (Opus), then one QA - (Sonnet) in the same worktree, then the lead's review — so at most - 2 devs + 2 QA agents exist at once, and a lane's QA starts only when - its own dev is done. A QA rework loops inside its lane without - blocking the other lane. -- **Tracking lives in `TODO.md`**: the lead writes the wave's section - (one subsection per lane, each item naming its files) on trunk before - branching; each lane ticks only its own lines. Shared-by-nature files - (`TODO.md`, `docs/protocol.md`, `docs/perf/README.md`) may be appended - to by both lanes in their own sections — the lead resolves the - trivially-parallel merge; anything worse than trivially-parallel means - the lanes were not actually independent, which is a planning failure - to record. -- After merging, the lead updates `docs/topo.md` for any edge a lane - added or amended, so the next wave plans against reality. -- **Only one lane may hold the real input devices.** A lane whose QA - needs the loopback harness with `MWB_ALLOW_INPUT_TESTS=1` runs that - step serially, with the user warned in the report. +- Any long-running command (a build sweep, a soak, anything you are + unsure about) goes through `tools/guard.sh` (8 GB / 30 min default). + A guard kill is a finding, not a reason to raise the limit. diff --git a/Package.swift b/Package.swift index 8a4d730..c8564bf 100644 --- a/Package.swift +++ b/Package.swift @@ -18,8 +18,6 @@ let package = Package( .target(name: "MWBMac", dependencies: ["MWBCore"]), // The app: the only place MWBNet and MWBMac meet. .executableTarget(name: "mwb", dependencies: ["MWBCore", "MWBNet", "MWBMac"]), - .testTarget(name: "MWBCoreTests", dependencies: ["MWBCore"]), - .testTarget(name: "MWBNetTests", dependencies: ["MWBNet"]), ], swiftLanguageModes: [.v6] ) diff --git a/README.md b/README.md index 2dbc355..4aa857f 100644 --- a/README.md +++ b/README.md @@ -19,16 +19,16 @@ WinForms UI. Read-only. ## Status 2026-09-15: bootstrap merged — the SwiftPM skeleton builds, the gates -are green, `mwb --version` / `--check-permissions` run. Wave 1 -(`packet-codec` ‖ `cipher-stream`) is next; procedure in -[`docs/loop.md`](docs/loop.md). +are green, `mwb --version` / `--check-permissions` run. Lanes run one at +a time in the order of [`docs/loop.md`](docs/loop.md) §6; `packet-codec` +is next. There are no test suites by design: the user tests the app. ## Decisions | # | Decision | Why | |---|---|---| | D1 | **Swift 6 + SwiftPM, no Xcode project.** The `.app` bundle is assembled by `tools/bundle.sh`. | Every platform surface the port needs (event taps, event posting, pasteboard, displays, Network.framework, menu bar) is an Apple framework; a second language would add an FFI boundary for nothing. Rust was considered for the protocol core and rejected as a second build system with no consumer that needs it. | -| D2 | **Three targets, layered by import rules.** `MWBCore` (Foundation + CommonCrypto only; sans-I/O protocol state machines), `MWBNet` (Network.framework), `MWBMac` (AppKit/CoreGraphics), executable `mwb`. | Protocol, crypto, matrix and coordinate logic must be testable with no display, no network and no permissions. SwiftPM target boundaries make the layering a compile error rather than a convention. | +| D2 | **Three targets, layered by import rules.** `MWBCore` (Foundation + CommonCrypto only; sans-I/O protocol state machines), `MWBNet` (Network.framework), `MWBMac` (AppKit/CoreGraphics), executable `mwb`. | Protocol, crypto, matrix and coordinate logic stay readable and reviewable without any platform code around them. SwiftPM target boundaries make the layering a build failure rather than a convention. | | D3 | **Settings file mirrors the PowerToys schema** (`{"name":"MouseWithoutBorders","version":"1.1","properties":{...}}`, same property names and defaults) at `~/Library/Application Support/mwb-mac/settings.json`, mode 0600. Key stored in plaintext like Windows. | Boring and copy-pasteable between machines. Keychain storage for the key is a backlog item, not a v1 blocker; the threat model equals the Windows one. | | D4 | **Key mapping: Win↔Command, Alt↔Option, Ctrl↔Control**, with a static Windows-VK ↔ macOS-keycode table in `MWBCore/KeyMap.swift`. | Windows sends virtual-key codes only (protocol §5.1). A layout-independent table is the only thing both sides can agree on; a "swap Cmd/Ctrl when controlling Windows" option comes later. | | D5 | **Permissions are the user's.** The app needs Accessibility (to post and swallow events) and Input Monitoring (to listen). It detects and explains; it never scripts System Settings. The binary must carry a **stable code-signing identity** (self-signed certificate at minimum) or TCC forgets the grant on every rebuild. | macOS TCC keys grants by code signature. Ad-hoc signatures change per build. | @@ -64,14 +64,11 @@ Sources/ StatusItem.swift menu-bar UI, status colours Permissions.swift preflight/request Accessibility + Input Monitoring mwb/ executable: wires the three together, CLI flags -Tests/ - MWBCoreTests/ golden-byte vectors, property tests, state-machine tests - MWBNetTests/ loopback two-endpoint tests (no real devices) - Fixtures/ interop vectors captured from Windows (interop-vectors lane) tools/ - guard.sh runaway guard — every test run goes through it + guard.sh runaway guard for long-running commands bundle.sh SPM binary → mwb.app with Info.plist + codesign - gates.sh fmt + build-with-warnings-as-errors + test, the "done" check + gates.sh lint + MWBCore layering grep + build-with-warnings-as-errors, the "done" check + lane.sh one worktree per lane ``` ### Windows concept → macOS mapping @@ -127,7 +124,7 @@ laptops). Requirements: macOS 14+, Xcode 27 (Swift 6.4); `xcode-select -p` must point at Xcode.app. ```bash -tools/gates.sh # xcrun swift-format lint, build -warnings-as-errors, guarded swift test +tools/gates.sh # xcrun swift-format lint, MWBCore layering check, build -warnings-as-errors ``` ```bash @@ -163,9 +160,9 @@ Both are granted in System Settings by the user. The app checks with shows what is missing in the menu bar. Grants are tied to the code signature (D5). -## Running two instances for development +## Testing -The loopback harness (`Tests/MWBNetTests`) runs two `Session`s over -in-process `NWConnection`s to `localhost` on ports the test picks; no -permissions, no devices. Anything that posts real input is behind -`MWB_ALLOW_INPUT_TESTS=1` (CLAUDE.md invariant 5). +The user tests the app. Agents build `dist/mwb.app` and hand it over +with a checklist of what changed (`docs/loop.md` §7); findings come +back as `TODO.md` lines. No agent posts input events, writes the real +pasteboard or moves the cursor (CLAUDE.md invariant 5). diff --git a/TODO.md b/TODO.md index c0668af..509e3f6 100644 --- a/TODO.md +++ b/TODO.md @@ -1,258 +1,156 @@ -# TODO — mwb-mac backlog, by milestone +# TODO — mwb-mac backlog, one lane at a time -Legend: **(core)** pure logic in `MWBCore`, **(net)** `MWBNet`, **(mac)** -`MWBMac`, **(app)** executable/tooling. Section numbers are referenced -from `docs/topo.md` and feature READMEs as "TODO §n". Each lane's brief -names its files; a lane ticks only its own lines. Milestones are ordered; -lanes inside a milestone may run in parallel when `docs/topo.md` §3 -says they are independent. +Legend: **(core)** `MWBCore`, **(net)** `MWBNet`, **(mac)** `MWBMac`, +**(app)** executable/tooling. Lanes run strictly in this order +(`docs/topo.md` §3, `docs/loop.md` §6); each lane ticks only its own +lines. Items describe Windows behaviour to port, with the +`docs/protocol.md` section that specifies it. No test-writing items +exist by the user's instruction — the user tests the app. --- -## 0. Toolchain and skeleton (M0, serial — `docs/features/bootstrap`) +## 0. bootstrap (app) — done 2026-09-15 -- [x] **Unblock SwiftPM.** `swift build` failed with Command Line Tools - only (README §Build). Fixed 2026-09-15 by installing Xcode 27.0; - smoke build + XCTest verified. Recorded in the bootstrap README. -- [x] `Package.swift` with targets `MWBCore`, `MWBNet`, `MWBMac`, `mwb`, - tests `MWBCoreTests`, `MWBNetTests`; Swift 6 language mode; macOS 14 - minimum. Layering is enforced by a test in `MWBCoreTests` that - greps `Sources/MWBCore` for `import AppKit|CoreGraphics|Network` - and fails on any hit. -- [x] `tools/gates.sh`: `swift-format lint --strict --recursive Sources Tests`, - `swift build -Xswiftc -warnings-as-errors`, `tools/guard.sh -- swift test`. -- [x] `tools/bundle.sh`: release build → `dist/mwb.app` (Info.plist with - `LSUIElement = true`, bundle id `com.luciochen.mwb-mac`), - `codesign --force --sign "$MWB_SIGN_IDENTITY"`; document how to - create a self-signed identity once (D5). -- [x] `.swift-format` config; `.gitignore` (`.build/`, `dist/`). -- [x] Smoke executable: `mwb --version`, `mwb --check-permissions` - (prints preflight results, exit 0 when complete, 3 otherwise). -- [x] `docs/loop.md` (the Dev → QA → lead procedure with literal - prompts), `docs/features/TEMPLATE.md`, `tools/lane.sh`. +- [x] SwiftPM skeleton, four targets, layering enforced by `tools/gates.sh`. +- [x] `tools/gates.sh` (lint + build), `tools/bundle.sh`, `tools/lane.sh`, + `.swift-format`, `Resources/Info.plist`. +- [x] `mwb --version`, `mwb --check-permissions`. +- [x] `docs/loop.md`, `docs/features/TEMPLATE.md`. +- [x] Xcode 27.0 installed; toolchain verified. -## 1. Wire core (M1 — two lanes: `packet-codec` ‖ `cipher-stream`) +## 1. packet-codec (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift` -### 1.1 packet-codec (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `Tests/MWBCoreTests/PacketTests.swift`, `FramingTests.swift` +- [ ] `PackageType` (raw `UInt8`, every value in protocol §1.2), the + big/small rule §1.1, unknown values tolerated. +- [ ] `Packet` value type over a 32/64-byte little-endian buffer with the + union views: mouse, keyboard, nonce, postAction, machineName, + 48-byte clipboard payload at offset 16. +- [ ] ASCII, space-padded, 32-byte machine name; non-ASCII refused. +- [ ] `Framing.seal` / `Framing.open` exactly as §1.3 (checksum over + bytes 2..31 only; magic top 16 bits; bytes 1–3 zeroed on open). -- [ ] `PackageType` enum, raw `UInt8`, every value from protocol §1.2; - `isBig` rule (§1.1) as a table-driven test over all 256 byte values. -- [ ] `Packet` value type with the union views (`mouse`, `keyboard`, - `nonce`, `postAction`, `machineName`) reading/writing a fixed - 32/64-byte little-endian buffer at the documented offsets. -- [ ] `MachineName` ASCII, space-padded, trimmed; non-ASCII rejected. -- [ ] `Framing.seal(magic:bytes:)` and `Framing.open(magic:bytes:)` - exactly as §1.3, including the "only bytes 2..31" checksum and the - zeroing of bytes 1–3 on the receive side. -- [ ] Golden vectors: hand-assembled bytes for `Handshake`, `Mouse`, - `Keyboard`, `Matrix` (slot 4, both flags), `ClipboardText` chunk. - Property test: `open(seal(p)) == p` for random packets; flipping any - of bytes 2..31 is detected; flipping bytes 32..63 is **not** (pinned - as documented behaviour). +## 2. cipher-stream (core) — `Sources/MWBCore/MagicHash.swift`, `CipherStream.swift` -### 1.2 cipher-stream (core) — `Sources/MWBCore/MagicHash.swift`, `CipherStream.swift`, `Tests/MWBCoreTests/MagicHashTests.swift`, `CipherStreamTests.swift` +- [ ] `magicNumber(for:)` per §2.1 (50 001 SHA-512 rounds, `<< 23` + overlap, UTF-16 unit truncated to a byte, 32-byte buffer). +- [ ] PBKDF2-HMAC-SHA512, 100 000 rounds, 32 bytes, via CommonCrypto. +- [ ] `CipherWriter` / `CipherReader`: 16+16 cleartext header, 16-byte + sacrificial block, AES-256-CBC no padding, streaming with partial + block buffering (§2.3). Descriptions never include secrets. -- [ ] `magicNumber(for key: String) -> UInt32` per §2.1 (50 001 SHA-512 - rounds, the `<< 23` overlap, UTF-16 code unit truncation to a byte). - Pin one vector computed independently (Python transcription in - `Tests/Fixtures/magic_reference.py`, run once, result committed). -- [ ] `deriveKey(password:salt:)` = PBKDF2-HMAC-SHA512, 100 000 rounds, - 32 bytes, via CommonCrypto. Vector pinned against Python `hashlib.pbkdf2_hmac`. -- [ ] `CipherWriter` / `CipherReader`: emit/consume the 16+16 header, the - sacrificial block, then a raw AES-256-CBC no-padding stream (§2.3). - Streaming API: `write(Data) -> Data` / `read(Data) -> Data` - accumulating partial blocks; a `CipherReader` fed one byte at a time - must produce the same plaintext as one fed all at once. -- [ ] Round-trip test writer→reader; a wrong key yields garbage, not a - throw, and the caller's framing check rejects it (that is the - Windows behaviour: `InvalidKey` after >10 bad packets). -- [ ] Never log key material: a test asserts `String(describing:)` and - `debugDescription` of every crypto type omit key/salt/IV bytes. +## 3. session (core) — `Sources/MWBCore/Session.swift` -## 2. Session logic (M2 — two lanes: `session` ‖ `matrix-edge`) - -### 2.1 session (core) — `Sources/MWBCore/Session.swift`, `Tests/MWBCoreTests/SessionTests.swift` - -- [ ] Sans-I/O `Session` state machine: `feed(bytes)` → `[Event]`, - `outgoing()` → bytes; states NA…Connected per §3.2 `SocketStatus`. -- [ ] Handshake exactly as §3.2 (10× `Handshake`, nonce complement, - `HandshakeAck`, adopt peer name/id, >10 untrusted packets ⇒ - InvalidKey, self-connection detection). +- [ ] Sans-I/O state machine: `feed(bytes) -> [Event]`, `outgoing() -> Data`, + `SocketStatus` NA…Connected (§3.2). +- [ ] Handshake: 10× `Handshake`, nonce complement, `HandshakeAck`, adopt + peer name/id, >10 untrusted packets ⇒ InvalidKey, self-connection + close, >10 failures from one endpoint ⇒ give up (§3.2). - [ ] Dedup ring of 50 ids with the four exemptions (§1.4). -- [ ] Heartbeat scheduling (60 s / 300 s, `Awake` vs `Heartbeat`), `Hi` - probe counting, `ByeBye`, 25 min liveness (§3.3) — all driven by an - injected clock. -- [ ] Two `Session`s wired back-to-back in a test reach `Connected` both - ways and exchange a `Mouse` packet. +- [ ] Heartbeat 60 s / 300 s, `Awake` vs `Heartbeat`, `Hi` counting, + `ByeBye`, 25 min liveness; injected clock (§3.3). -### 2.2 matrix-edge (core) — `Sources/MWBCore/Matrix.swift`, `Edge.swift`, `Tests/MWBCoreTests/MatrixTests.swift`, `EdgeTests.swift` +## 4. matrix-edge (core) — `Sources/MWBCore/Matrix.swift`, `Edge.swift` -- [ ] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool` - (serialize/parse `Name:Id,…`, 25 min alive) per §4.1. -- [ ] `Matrix` packet encode/decode (slot in `Src`, flags in `Type`) §4.2. -- [ ] `LiveMachineMatrix`, moveLeft/Right/Up/Down, `desMachineID` / ALL. -- [ ] Edge detection §4.3 with the primary-vs-desktop rectangle rule, - 100 ms debounce, corner blocking; coordinate normalization §4.4 with - all four rectangle cases, `MOVE_MOUSE_RELATIVE` / `XY_BY_PIXEL` - biases, `NextMachine` encoding (id in `WheelDelta`). -- [ ] Table tests on 1-, 2- and 3-monitor layouts including a negative- - origin monitor left of primary. +- [ ] `Matrix` (4 slots, one/two rows, wrap), `MachinePool` + (`Name:Id,…` serialisation, 25 min alive) §4.1. +- [ ] `Matrix` packet encode/decode (slot in `Src`, flags in `Type`) §4.2; + learning peers from Heartbeat/Hello/Awake. +- [ ] `LiveMachineMatrix`, move left/right/up/down, `desMachineID`, ALL mode. +- [ ] Edge detection §4.3 (primary-vs-desktop rectangle rule, 100 ms + debounce, corner blocking) and coordinate normalisation §4.4 (all + four rectangle cases, relative-move biases, `NextMachine`). -## 3. Platform capture (M3 — two lanes: `control-channel` ‖ `event-tap`) +## 5. control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `Resolver.swift` -### 3.1 control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `Resolver.swift`, `Tests/MWBNetTests/LoopbackTests.swift` +- [ ] `NWListener` on port+1, both IP families; one `NWConnection` per + non-local matrix name; 1 s retry for 30 s; one client socket per + peer (§3.1). +- [ ] `Resolver`: `getaddrinfo` + `Name2IP` lines; optional /16 and + reverse-lookup checks (§7). +- [ ] One `Session` + one cipher pair per connection; serialised sends + with 500 ms timeout; 32-then-32 receive. +- [ ] Reconnect on path change, wake, reset, hotkey; delete `Placeholder.swift`. -- [ ] `NWListener` on port+1, all interfaces, IPv4+IPv6; one - `NWConnection` client per non-local matrix name; 1 s retry for 30 s; - dedup to one client socket per peer (§3.1). -- [ ] `Resolver`: `getaddrinfo` + `Name2IP` lines (§7); optional - same-/16 check and reverse validation as settings, off by default. -- [ ] Each connection owns one `Session` and a `CipherWriter`/`Reader` - pair per direction; send serialised through one queue with 500 ms - send timeout; receive loop reads 32 then 32. -- [ ] Reconnect on path change (`NWPathMonitor`), wake - (`NSWorkspace.didWakeNotification` is `mac`; expose a - `reopenAll()` the app calls), connection reset, hotkey. -- [ ] Loopback test: two channels on 127.0.0.1 with random ports reach - `Connected` and pass 1 000 `Mouse` packets in order with no dedup - drops; wrong key on one side ends in `InvalidKey`. +## 6. event-tap (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Sources/MWBCore/KeyMap.swift` -### 3.2 event-tap (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Sources/MWBCore/KeyMap.swift`, `Tests/MWBCoreTests/KeyMapTests.swift` +- [ ] `Permissions.request…` added to the existing preflight file. +- [ ] Session-level, head-insert, swallowing `CGEventTap` for keys, + flags, mouse, scroll; enqueue and return; pass tagged injected + events; re-enable on timeout/user-input disable (invariants 3, 4). +- [ ] Modifier tracking and hotkey matching per §4.5 with D4 mapping + (⌘=Win, ⌥=Alt); Easy Mouse modes. +- [ ] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier + VK pairs, `LLKHF` flags; `WM_*` mouse mapping, wheel ×120, + X-buttons, absolute 0..65535 moves (§5). -- [ ] `Permissions`: preflight/request Accessibility + Input Monitoring; - never loops on request; reports per-permission state. -- [ ] `EventTap`: session tap, head-insert, default (swallowing) tap for - key down/up/flagsChanged, mouse move/drag/buttons/scroll; callback - converts to a `CapturedInput` value and enqueues; returns `nil` to - swallow when the destination is remote; passes tagged injected - events through; re-enables on timeout/user-input disable - (invariant 3 and 4). -- [ ] Modifier tracking (Cmd/Ctrl/Opt/Shift) and hotkey matching per - §4.5 with D4 mapping; the tap reports `.hotkey(...)` events. -- [ ] `KeyMap`: macOS keycode → Windows VK and back, `flagsChanged` → - modifier VK down/up pairs, `LLKHF` flags, `NSEvent.ModifierFlags` - → nothing (VKs carry modifiers themselves). Table pinned by tests: - letters, digits, F1–F19, arrows, editing keys, numpad, punctuation - on US layout; unknown keys are dropped and counted. -- [ ] Mouse: `WM_*` mapping, wheel line deltas × 120, X-buttons, moves - as absolute 0..65535 against the primary display (§5.2, §4.4). +## 7. screens-cursor (mac) — `Sources/MWBMac/Screens.swift`, `Cursor.swift` -## 4. Platform injection and screens (M4 — two lanes: `input-inject` ‖ `screens-cursor`) +- [ ] Display list, primary, desktop union, corner points; refresh on + screen-parameter change. +- [ ] Park/hide cursor (primary centre-x, y=4), decouple cursor while + controlling a remote, restore on return; `HideMouse (50)` (§5.3). -### 4.1 input-inject (mac) — `Sources/MWBMac/Injector.swift` +## 8. input-inject (mac) — `Sources/MWBMac/Injector.swift` -- [ ] `Keyboard` packet → `CGEvent` key down/up with VK→keycode; modifier - VKs → `flagsChanged` with maintained flag state; `EXTENDED` ignored; - autorepeat handled by repeated downs like Windows. -- [ ] `Mouse` packet → move (absolute, §4.4 de-normalization onto the - desktop bounds), buttons with click-count tracking (double-click = - two downs within `NSEvent.doubleClickInterval`, since Windows drops - `*DBLCLK`), wheel (`WheelDelta`/120 lines), X-buttons → other - mouse buttons 3/4. -- [ ] Every posted event tagged with the injected marker (README mapping). -- [ ] `ReleaseAllKeys` equivalent on switch/lock. -- [ ] Remote Win+L → lock; remote Ctrl+Alt+Del → nothing (documented). +- [ ] `Keyboard` packet → `CGEvent` down/up via KeyMap; modifiers as + `flagsChanged`; repeat as repeated downs. +- [ ] `Mouse` packet → absolute move (de-normalise onto desktop bounds + §4.4), buttons with click-count, wheel (`WheelDelta`/120), X-buttons. +- [ ] Injected-event tag; `ReleaseAllKeys` on switch/lock; remote Win+L + → lock; remote Ctrl+Alt+Del → ignored. -### 4.2 screens-cursor (mac) — `Sources/MWBMac/Screens.swift`, `Cursor.swift` +## 9. menubar-app (app + core + mac) — `Sources/mwb/*`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBCore/Settings.swift` -- [ ] `Screens`: active displays, primary (`CGMainDisplayID`), desktop - union, corner points for `BlockMouseAtScreenCorners`; refresh on - `NSApplication.didChangeScreenParametersNotification`. -- [ ] `Cursor`: park at primary centre-x / y=4 (`HideMouse` on) or - centre; `CGAssociateMouseAndMouseCursorPosition(false)` while - controlling a remote, deltas read from the tap; restore on return - to the last local position. -- [ ] `HideMouse (50)` packet handling. +- [ ] `Settings`: PowerToys schema (README §Settings), load/save/watch, + 0600, random key / `MachineID` / `DeviceID` on first run. +- [ ] Menu-bar item with per-machine status dots in the documented + colours; matrix editor; key entry; port; toggles; Reconnect; Quit. +- [ ] Permissions onboarding; LaunchAgent install/uninstall; single + instance; logs without key material. +- [ ] Wire everything: tap → edge → session → channel → injector. +- [ ] **Hand `dist/mwb.app` to the user** with a checklist: switch by + edge and hotkey, wrap, one/two rows, keyboard with modifiers and + function keys, wheel, reconnect after sleep, wrong key, peer + killed mid-control. -## 5. Clipboard and app shell (M5 — two lanes: `clipboard-inband` ‖ `menubar-app`) +## 10. clipboard-inband (core + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift` -### 5.1 clipboard-inband (core + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift` +- [ ] Text codec `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE (§6.1); + confirm Foundation `.zlib` matches .NET `DeflateStream` by + reasoning from the docs, note the decision. +- [ ] 48-byte chunks at offset 16, `ClipboardDataEnd`, zero-padding + semantics, 1 MB limit (§6.2); PNG images. +- [ ] `NSPasteboard` polling (500 ms), 1 s suppression, write on + receive, `ShareClipboard` flag. -- [ ] Text codec: `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE - (§6.1). **First task: prove Foundation `.zlib` == .NET - `DeflateStream` on a fixture** (README mapping note); fall back to - `compression_stream` with `COMPRESSION_ZLIB` if not. -- [ ] 48-byte chunking at offset 16, `ClipboardDataEnd`, zero-padding - semantics on decode (§6.2); 1 MB in-band limit. -- [ ] Image: PNG from `NSPasteboard` (`.png`, else TIFF → PNG). -- [ ] `Pasteboard`: `changeCount` poll at 500 ms, 1 s suppression, - write on receive; never write when we were the source. -- [ ] Feature flag from `ShareClipboard`. +## 11. clipboard-bulk (net) — `Sources/MWBNet/BulkChannel.swift` -### 5.2 menubar-app (app + mac) — `Sources/mwb/*`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBCore/Settings.swift` +- [ ] Listener on port; `Clipboard (69)` broadcast; pull on + `MachineSwitched`, push on `ClipboardAsk` (§6.3). +- [ ] Bulk handshake, 1024-byte UTF-16LE `"*"` header, 1 MB + chunks, 32-byte file padding, exact-length read, atomic commit to + `~/Desktop/MouseWithoutBorders/`; 100 MB limit; `TransferFile` flag. -- [ ] `Settings`: schema per README §Settings, load/save/watch, 0600, - random key/`MachineID`/`DeviceID` on first run. -- [ ] `NSStatusItem` with per-machine status dots in the documented - colours, matrix editor (4 names, one/two rows), key entry, port, - toggles; "Reconnect", "Quit". -- [ ] Permissions onboarding panel; LaunchAgent install/uninstall. -- [ ] Single instance via pid-file lock; log to - `~/Library/Logs/mwb-mac/` with rotation, never key material. -- [ ] Lock-machine hotkey → `CGSession -suspend` (decide vs - `pmset displaysleepnow`; record). +## 12. end-to-end polish -## 6. Bulk transfer and interop (M6 — two lanes: `clipboard-bulk` ‖ `interop-vectors`) +- [ ] Driven entirely by the user's testing findings; each becomes a + line here with the lane that owns the fix. -### 6.1 clipboard-bulk (net) — `Sources/MWBNet/BulkChannel.swift` +## 13. Later (post-v1) -- [ ] Listener on port; `Clipboard (69)` broadcast on big data; - pull on `MachineSwitched`, push on `ClipboardAsk` (§6.3). -- [ ] Bulk handshake: cipher layout, one 64-byte `DATA` each way, - `ResolveID(name) == Src` gate, 1024-byte UTF-16LE header - `"*"`, 1 MB chunks, 32-byte file padding, exact-length - read, atomic temp-file commit to `~/Desktop/MouseWithoutBorders/`. -- [ ] 100 MB file limit, single file only, folders refused with the - Windows message; `TransferFile` flag. - -### 6.2 interop-vectors (tests) — `Tests/Fixtures/`, `tools/winvectors/` - -- [ ] A small .NET console program (`tools/winvectors/`, runs **on a - Windows machine with the PowerToys tree**) that links the MWB - assembly and dumps: `Get24BitHash` for 5 keys, PBKDF2 key for - fixed salt, one full encrypted control-stream capture for a - scripted handshake with fixed RNG, framed bytes for each packet - type, a deflated clipboard text fixture. -- [ ] Until a Windows machine is available: a `pcap` of a real - Windows↔Windows session (user-provided) plus the typed key lets us - decrypt and replay; document how to capture it. -- [ ] Every `[transcribed]` mark in `docs/protocol.md` flips to - `[verified]` only when a fixture from this lane pins it. - -## 7. End to end (M7, serial — needs the real devices) - -- [ ] `docs/features/end-to-end`: Mac ↔ Windows over the LAN, both - directions, checklist: switch by edge, by hotkey, wrap, one/two - rows, keyboard incl. modifiers and function keys, wheel, clipboard - text/image/file, reconnect on sleep/wake, wrong key, kill the peer - mid-control (invariant 3). -- [ ] Soak: 8 h with heartbeats and periodic switches under - `tools/guard.sh`; memory flat; tap never stays disabled. -- [ ] `docs/perf/README.md` filled with measured tap-callback and - end-to-end latencies. - -## 8. Later (post-v1, ordered by value) - -- [ ] CI on the existing Gitea runner (`.gitea/workflows/ci.yml` running - `tools/gates.sh`) — only once invariant 5 is provably safe on a - runner that shares the user's session. - [ ] Keychain storage for `SecurityKey` (D3). -- [ ] Easy Mouse fullscreen suppression + excluded apps (`NSWorkspace` - frontmost app, `NSWindow` fullscreen detection via Accessibility). -- [ ] `Heartbeat_ex` key propagation (§3.3) so a key typed on one - machine spreads. +- [ ] Easy Mouse fullscreen suppression + excluded apps. +- [ ] `Heartbeat_ex` key propagation (§3.3). - [ ] "Swap ⌘/⌃ when controlling Windows" option. -- [ ] Non-US layouts: send VKs by physical position vs by character — - needs a decision and a test matrix. -- [ ] Sparkle-style updates, notarization, Homebrew cask. +- [ ] Non-US keyboard layouts: by position vs by character. +- [ ] CI on the Gitea runner running `tools/gates.sh` (lint + build only). +- [ ] Updates, notarization, Homebrew cask. -## 9. Out of scope, with reasons (D6) +## 14. Out of scope, with reasons (D6) -- Windows service / logon-screen / UAC secure desktop control: macOS - login window cannot be driven by a user-session event tap. -- Explorer drag-and-drop (§6.4): depends on a Windows-shell helper; a - Finder equivalent is a separate design. -- Screen capture to Paint (`CaptureScreenCommand`, `ClipboardCapture`): - niche; packets are ignored and logged. +- Windows service / logon-screen / UAC secure-desktop control: the macOS + login window cannot be driven from a user-session event tap. +- Explorer drag-and-drop (§6.4): depends on a Windows-shell helper. +- Screen capture to Paint: niche; packets ignored and logged. - GPO, telemetry, `ShowOriginalUI`: Windows-only. - Animated fake cursor (`DrawMouse`): cosmetic. diff --git a/Tests/Fixtures/README.md b/Tests/Fixtures/README.md deleted file mode 100644 index b929b78..0000000 --- a/Tests/Fixtures/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Fixtures - -Golden bytes and reference scripts. Owned by the `interop-vectors` lane -(TODO §6.2); `packet-codec` and `cipher-stream` may add hand-assembled -vectors here in their own subdirectories. Nothing in this directory is -generated by our own encoder — that would test the encoder against -itself (CLAUDE.md invariant 1). diff --git a/Tests/MWBCoreTests/LayeringTests.swift b/Tests/MWBCoreTests/LayeringTests.swift deleted file mode 100644 index daea042..0000000 --- a/Tests/MWBCoreTests/LayeringTests.swift +++ /dev/null @@ -1,46 +0,0 @@ -import Foundation -import XCTest - -/// Enforces README D2 / docs/topo.md §1: `MWBCore` is pure logic and may -/// import only Foundation and CommonCrypto (plus CryptoKit for hashing). -/// A platform or network import in the core target fails this test. -final class LayeringTests: XCTestCase { - private static let forbidden = [ - "AppKit", "Cocoa", "CoreGraphics", "Carbon", "SwiftUI", "Network", "IOKit", "ApplicationServices", - ] - - func testCoreImportsOnlyFoundationAndCrypto() throws { - let core = coreSourcesDirectory() - let files = try swiftFiles(under: core) - XCTAssertFalse(files.isEmpty, "no Swift sources found under \(core.path)") - for file in files { - let text = try String(contentsOf: file, encoding: .utf8) - for (number, line) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() { - let trimmed = line.trimmingCharacters(in: .whitespaces) - guard trimmed.hasPrefix("import ") else { continue } - let module = - trimmed.dropFirst("import ".count).split(separator: " ").first.map(String.init) ?? "" - XCTAssertFalse( - Self.forbidden.contains(module), - "\(file.lastPathComponent):\(number + 1) imports \(module); MWBCore is Foundation-only (README D2)" - ) - } - } - } - - private func coreSourcesDirectory() -> URL { - // Tests/MWBCoreTests/LayeringTests.swift → repo root → Sources/MWBCore - URL(fileURLWithPath: #filePath) - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .appendingPathComponent("Sources/MWBCore", isDirectory: true) - } - - private func swiftFiles(under directory: URL) throws -> [URL] { - let keys: [URLResourceKey] = [.isRegularFileKey] - guard let walker = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: keys) - else { - return [] - } - return walker.compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } - } -} diff --git a/Tests/MWBCoreTests/VersionTests.swift b/Tests/MWBCoreTests/VersionTests.swift deleted file mode 100644 index d18df97..0000000 --- a/Tests/MWBCoreTests/VersionTests.swift +++ /dev/null @@ -1,9 +0,0 @@ -import MWBCore -import XCTest - -final class VersionTests: XCTestCase { - func testVersionLooksSemantic() { - let parts = MWBVersion.string.split(separator: "-").first?.split(separator: ".") ?? [] - XCTAssertEqual(parts.count, 3, "expected MAJOR.MINOR.PATCH[-suffix], got \(MWBVersion.string)") - } -} diff --git a/Tests/MWBNetTests/PlaceholderTests.swift b/Tests/MWBNetTests/PlaceholderTests.swift deleted file mode 100644 index 2209557..0000000 --- a/Tests/MWBNetTests/PlaceholderTests.swift +++ /dev/null @@ -1,10 +0,0 @@ -import MWBNet -import XCTest - -/// Exists so the `MWBNetTests` target is wired up before `control-channel` -/// replaces it with the loopback suite (TODO §3.1). -final class PlaceholderTests: XCTestCase { - func testTargetLinks() { - XCTAssertEqual(MWBNetPlaceholder.framework, "Network") - } -} diff --git a/docs/features/TEMPLATE.md b/docs/features/TEMPLATE.md index 820e6fe..1d10670 100644 --- a/docs/features/TEMPLATE.md +++ b/docs/features/TEMPLATE.md @@ -28,8 +28,7 @@ One paragraph: what this lane delivers, why it exists, and which ## Status / TODO -- [ ] ``: item -- [ ] `Tests//`: item +- [ ] ``: the Windows behaviour ported, with its citation - [ ] `docs/protocol.md`: citations verified / marks flipped ## Work log diff --git a/docs/features/bootstrap/README.md b/docs/features/bootstrap/README.md index f0ef641..e2cdbaf 100644 --- a/docs/features/bootstrap/README.md +++ b/docs/features/bootstrap/README.md @@ -63,7 +63,10 @@ works on this machine at all. Nothing in later lanes can start until missing) backed by `MWBMac/Permissions.swift` (preflight only). - [x] `tools/lane.sh` worktree helper; `docs/loop.md` procedure; `docs/features/TEMPLATE.md`. -- [x] `tools/gates.sh` green: 3 XCTest cases, 0 warnings, lint clean. +- [x] `tools/gates.sh` green (lint, layering grep, build). The three + XCTest cases from the first cut were removed the same day when the + user set the no-test-suites rule; the layering check moved into + `gates.sh` as a grep. - [ ] Not done, deliberately: no CI workflow. The lucisv Gitea runner exists on this Mac (`verilogrustformatter/tools/RELEASING.md`), but a CI that runs `swift test` for a project that will soon post diff --git a/docs/features/cipher-stream/README.md b/docs/features/cipher-stream/README.md index af3551e..1baca4f 100644 --- a/docs/features/cipher-stream/README.md +++ b/docs/features/cipher-stream/README.md @@ -20,15 +20,14 @@ point; there is no "better" cipher choice to make here. - **PBKDF2 goes through `CCKeyDerivationPBKDF`** with `kCCPRFHmacAlgSHA512`, 100 000 rounds, 32 bytes. Password bytes are UTF-8 of the key string — `Rfc2898DeriveBytes.Pbkdf2(string, …)` uses - UTF-8 (documented .NET behaviour). Pinned by a Python - `hashlib.pbkdf2_hmac('sha512', …)` vector. + UTF-8 (documented .NET behaviour). - **The magic hash truncates each UTF-16 code unit to a byte** (`(byte)st[i]`, `Encryption.cs:184`) and hashes a fixed 32-byte buffer; keys longer than 32 characters contribute only their first 32. The `<< 23` overlap is reproduced with `UInt32` wrapping arithmetic in the same order as the C# expression. -- **Salt and IV are fresh per direction and never reused**; Windows - tests pin uniqueness (`EncryptionTests.cs:59-68`) and so do ours. +- **Salt and IV are fresh per direction and never reused** + (`EncryptionTests.cs:59-68` documents the Windows expectation). - **The sacrificial block is part of the cipher type's contract**: the writer emits it right after the header, the reader discards the first 16 plaintext bytes. Callers never see it (topo.md handshake 2). @@ -53,7 +52,7 @@ public struct CipherReader { } ``` -`RandomBytes` is injectable so tests can pin whole streams. +`RandomBytes` is injectable so the lead can reproduce a stream by hand when checking against a Windows capture. ### Consumed @@ -61,15 +60,12 @@ public struct CipherReader { ## Status / TODO -- [ ] `Sources/MWBCore/MagicHash.swift` + `Tests/MWBCoreTests/MagicHashTests.swift` - with `Tests/Fixtures/magic_reference.py` (run once; vector committed). -- [ ] `Sources/MWBCore/CipherStream.swift`: key derivation, writer, reader. -- [ ] `Tests/MWBCoreTests/CipherStreamTests.swift`: PBKDF2 vector; - round-trip; byte-at-a-time reader equals all-at-once; unique - header per instance; wrong key ⇒ garbage without throwing; - descriptions omit secrets. -- [ ] Note in `docs/perf/README.md`: PBKDF2 at 100 000 rounds SHA-512 - costs ~N ms per connection open (measure; it is per direction). +- [ ] `Sources/MWBCore/MagicHash.swift`: `magicNumber(for:)` per §2.1, + every step cited to `Encryption.cs:173-200`. +- [ ] `Sources/MWBCore/CipherStream.swift`: PBKDF2 key derivation, + `CipherWriter`, `CipherReader` (header, sacrificial block, + streaming CBC), cited to `Encryption.cs` and `Common.cs:1528-1558`. +- [ ] `docs/perf/README.md`: note the PBKDF2 cost per connection open. ## Work log diff --git a/docs/features/packet-codec/README.md b/docs/features/packet-codec/README.md index 38dbd09..0873579 100644 --- a/docs/features/packet-codec/README.md +++ b/docs/features/packet-codec/README.md @@ -19,9 +19,8 @@ crypto. `ProcessReceivedDataEx` does, so a decoded packet's bytes 1–3 are always 0 and re-sealing is deterministic. - **The checksum covers bytes 2..31 only, even on 64-byte packets.** We - reproduce this, and pin it with a test that corrupts byte 40 of a - 64-byte packet and asserts it is *not* detected — the encryption - layer, not the checksum, is what protects the name half. + reproduce this; the encryption layer, not the checksum, is what + protects the name half. Say so in a comment at the checksum loop. - **Unknown type values decode as `.unknown(UInt8)`** rather than throwing, so a newer Windows build cannot desynchronise our framing. Size for an unknown value follows the big/small rule (`0x80` bit ⇒ 64, @@ -66,16 +65,10 @@ same change and session codes against the README. ## Status / TODO - [ ] `Sources/MWBCore/Packet.swift`: `PackageType` (every value in - protocol §1.2), `isBig`, `Packet` with union views. -- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3. -- [ ] `Tests/MWBCoreTests/PacketTests.swift`: offsets pinned per field, - big/small over all 256 values, name padding/trim, non-ASCII refused. -- [ ] `Tests/MWBCoreTests/FramingTests.swift`: hand-assembled golden - bytes for Handshake / Mouse / Keyboard / Matrix(slot 4, both - flags) / ClipboardText chunk; round-trip property test; bytes - 2..31 corruption detected; byte 40 corruption *not* detected. -- [ ] `docs/protocol.md`: add any offset or rule learned; keep - `[transcribed]` marks until interop-vectors. + protocol §1.2, cited), `isBig`, `Packet` with the union views. +- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3, each + constant cited to `SocketStuff.cs`. +- [ ] `docs/protocol.md`: add any offset or rule learned while porting. ## Work log diff --git a/docs/loop.md b/docs/loop.md index 26cddc6..13e1aef 100644 --- a/docs/loop.md +++ b/docs/loop.md @@ -3,51 +3,50 @@ **Purpose.** How a lane goes from a brief to a merged commit, who does what, and the literal prompts the lead dispatches. `CLAUDE.md` states the rules; this file is the procedure. The lead follows it verbatim so -that every lane leaves the same trail: a feature README with Work log, -QA log and Review filled in, ticked TODO lines, and a `--no-ff` merge. +every lane leaves the same trail: a feature README with Work log, QA +log and Review filled in, ticked TODO lines, and a `--no-ff` merge. + +**Standing instruction from the user (2026-09-15):** one lane at a time; +Dev commits as it goes and need not keep every commit compiling; QA +reviews code quality and completeness of the port, not tests; nobody +writes test suites — the user tests the app at the end. ## 0. Roles | role | model | owns | never | |---|---|---|---| -| **Lead** | Fable 5.1 (this session) | trunk (`main`), wave planning, briefs, dispatch, the self-inspect review, merges, commits, pushes, `docs/topo.md` | writes lane code (bootstrap was the one exception); trusts a report it has not checked | -| **Dev** | Opus | one lane in one worktree: code, tests, README Work log, ticks in Status/TODO and `TODO.md` | commits; touches files outside the brief's list; asks for permissions | -| **QA** | Sonnet | the same worktree after Dev: verification, attack tests, README QA log, a verdict | redesigns; edits anything but tests, the QA log and small unambiguous fixes it records | +| **Lead** | Fable 5.1 (this session) | `main`, briefs, dispatch, inspection, merges, pushes, `docs/topo.md` | writes lane code (bootstrap was the one exception); trusts a report it has not read against the diff | +| **Dev** | Opus 5 | one lane on branch `lane/`: the port, the README Work log, ticks in Status/TODO and `TODO.md`, small frequent commits | pushes; touches files outside the brief; writes test suites; asks for permissions | +| **QA** | Sonnet 5 | the same branch after Dev: a code-quality and completeness review, the README QA log, a verdict | redesigns; writes tests; edits beyond small unambiguous fixes it records | -"Self inspect" is the lead's review: the lead reads the diff with its own -eyes and runs the gates itself before writing the Review section. A -green QA verdict is evidence, not a decision. +"Inspect" is the lead's review: the lead reads the diff with its own +eyes and runs `tools/gates.sh` before writing the Review section. -## 1. Lifecycle of a lane +## 1. Lifecycle of a lane (strictly serial) -1. **Pick the wave.** `docs/topo.md` §3 says which two lanes may run - together. Anything not in that table runs alone. -2. **Write the brief** on `main`: `docs/features//README.md` with +1. **Write the brief** on `main`: `docs/features//README.md` with Goal, Assumptions, Handshakes and a Status/TODO whose items name - their files (template: `docs/features/TEMPLATE.md`). The file list - *is* the merge contract. Commit as `brief: `. -3. **Open the lane**: `tools/lane.sh new ` → worktree at - `../mwb-lanes/` on branch `lane/`. -4. **Dispatch Dev** with the prompt in §3, `cwd` = the worktree. Dev - finishes only when `tools/gates.sh` is green in the worktree. -5. **Dispatch QA** with the prompt in §4, same worktree. Verdict is - `PASS` or `REWORK` with file:line findings. -6. **On REWORK**, dispatch Dev again with the QA log as input. At most + their files (template: `docs/features/TEMPLATE.md`). Commit as + `brief: `. +2. **Open the lane**: `tools/lane.sh new ` → worktree at + `../mwb-lanes/` on branch `lane/`. (One worktree, so + `main` stays clean for the lead to write the next brief.) +3. **Dispatch Dev** (§3), `cwd` = the worktree. Dev commits as it goes + and finishes when every Status/TODO item is ticked or explicitly + deferred, and `tools/gates.sh` is green on the final commit. +4. **Dispatch QA** (§4), same worktree. Verdict `PASS` or `REWORK`. +5. **On REWORK**, dispatch Dev again with the QA log as input. At most two rework rounds; a third means the brief was wrong — the lead - rewrites the brief and restarts the lane. -7. **Self-inspect** (§5). Write the Review section. If review finds a - defect, it goes back to step 4 as a rework with the review text as - the finding. -8. **Merge**: on `main`, `git merge --no-ff lane/`, run - `tools/gates.sh` on the merged tree, update `docs/topo.md` for any - edge the lane added or amended, tick the wave line in `TODO.md`, - commit, push, `tools/lane.sh done `, delete the branch. -9. **Log the wave** in §8 of this file: dates, rework count, what the - brief got wrong. - -Two lanes in flight follow the same steps independently. Their merges -are sequential; the second lane's merge re-runs gates on a trunk that -already contains the first. + rewrites it. +6. **Inspect** (§5). Write the Review section (the lead commits that on + the lane branch). A defect found here goes back to step 3 as a + rework with the review text as the finding. +7. **Merge**: on `main`, `git merge --no-ff lane/`, run + `tools/gates.sh`, update `docs/topo.md` for any edge the lane added + or amended, tick the lane line in `TODO.md`, commit, push, + `tools/lane.sh done `, delete the branch. +8. **Log the lane** in §8: dates, rework count, what the brief got wrong. +9. Only now write the next brief. ## 2. What a brief must contain @@ -57,10 +56,11 @@ already contains the first. make. If the lead cannot write this section, the lane is not ready. - **Handshakes / Promised**: the public API sketched in Swift, marked "may change during the lane; README updated in the same change". -- **Handshakes / Consumed**: which other lanes' APIs it uses, by README - reference, never by reading their source for undocumented behaviour. +- **Handshakes / Consumed**: which earlier lanes' APIs it uses, by + README reference. - **Status / TODO**: 4–8 checkbox items, each naming the file(s) it - touches. The union of those files is the ownership list. + touches and the Windows behaviour it ports. The union of those files + is the ownership list. - **Citations**: every fact from the Windows source as `App/.cs:`, matching `docs/protocol.md`. @@ -73,19 +73,25 @@ README.md, docs/protocol.md, docs/topo.md, docs/features//README.md. The README's Status/TODO is your task list and its file list is the only set of files you may create or edit, plus: docs/features//README.md (Assumptions, Handshakes, Status/TODO, Work log), TODO.md (tick your own -lines only), docs/protocol.md (append citations you verified, in your -lane's own subsection), docs/perf/README.md (append measurements). +lines only) and docs/protocol.md (append citations you verified, in your +lane's own subsection). -Rules that end a lane if broken: CLAUDE.md invariants 1–5; no git commit; -no file outside the list — write a Handshake request in your README and -stop that item instead; every test run through tools/guard.sh; never set -MWB_ALLOW_INPUT_TESTS. +This is a port: read the Windows source at +/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/ +for every behaviour you implement and cite the line in a comment next +to each constant and each non-obvious rule. Port behaviour, not shape. -Done means: every Status/TODO item ticked or explicitly marked "not done, -deliberately: "; tools/gates.sh exits 0 in this worktree; the Work -log has a dated entry with decisions and deviations; any API change is -reflected in Handshakes. Report: what you built, what you deviated from, -open handshake requests, and the gates.sh tail. +Do not write test suites — the user tests the app. Commit as you go with +small, clearly named commits; a commit need not compile. Do not push. +Rules that end a lane if broken: CLAUDE.md invariants 1–5; no file +outside the list — write a Handshake request in your README and stop +that item instead; never post input events or touch the real pasteboard. + +Done means: every Status/TODO item ticked or marked "not done, +deliberately: "; tools/gates.sh exits 0 on your last commit; the +Work log has a dated entry with decisions and deviations; any API change +is reflected in Handshakes. Report: what you ported, what you deviated +from, open handshake requests, and the gates.sh tail. ``` ## 4. QA prompt (dispatch verbatim) @@ -96,78 +102,82 @@ You are QA for lane `` of mwb-mac, in worktree docs/features//README.md (all sections), then the diff: git diff main...HEAD. -Verify, do not redesign. In order: (1) run tools/gates.sh yourself; -(2) check each Status/TODO tick against the code and tests — a tick with -no test is a finding; (3) check every protocol claim in the code against -docs/protocol.md and, where cited, the Windows source at +You review code quality and completeness of the port. You do not write +tests and you do not redesign. In order: (1) run tools/gates.sh; +(2) for each Status/TODO tick, find the code that implements it and +compare against the Windows source at /Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/ -— a mismatch is a finding with both file:line references; (4) try to -break it: malformed bytes, boundary sizes, wrong key, empty/oversized -input, concurrency where the API is Sendable; add the attack as a test in -the lane's test files; (5) check CLAUDE.md file/function size limits and -the layering test; (6) confirm nothing logs key material. +— a behaviour the Windows version has that the port silently lacks, or +a constant/offset/rule that differs from docs/protocol.md, is a finding +with both file:line references; (3) read every changed file top to +bottom for readability: CLAUDE.md size limits, layering, naming, force +unwraps, dead code, comments that cite nothing; (4) confirm nothing logs +key material and nothing acts on a packet before framing + decrypt. -You may fix only typos and missing assertions, and must note each fix in -the QA log. Everything else is a finding: file:line, reproduction, and -what you expected. Write a dated QA log entry ending with a verdict line -`Verdict: PASS` or `Verdict: REWORK` and the findings list. Never set -MWB_ALLOW_INPUT_TESTS; every test run goes through tools/guard.sh. -Report the verdict and the findings. +You may fix only typos and trivially wrong comments, committing each +with a message starting `qa:` and noting it in the QA log. Everything +else is a finding: file:line, what the Windows source does, what the +port does. Write a dated QA log entry ending with `Verdict: PASS` or +`Verdict: REWORK` and the findings list. Commit the README. Report the +verdict and the findings. ``` -## 5. Lead self-inspect checklist +## 5. Lead inspection checklist Run in the worktree, by the lead, before writing Review: -- [ ] `tools/gates.sh` green, run by me. -- [ ] `git diff main...HEAD --stat`: only files in the brief's list (plus - the shared-by-nature files, in the lane's own sections). +- [ ] `tools/gates.sh` green on the lane's last commit, run by me. +- [ ] `git diff main...HEAD --stat`: only files in the brief's list plus + the shared-by-nature files, in the lane's own sections. - [ ] Read the whole diff. Every protocol constant traces to a `docs/protocol.md` line; every offset matches §1.1. -- [ ] Invariant 1: golden bytes come from a fixture or a hand assembly - in the test, never from the encoder under test. -- [ ] Invariant 2: no code path acts on a packet before framing + decrypt - succeed; no `print`/`Logger` call includes key, salt, IV or keystrokes. +- [ ] Completeness: walk the Windows feature's behaviours (the brief's + Status/TODO plus the cited source) and confirm each is present or + deliberately deferred with a reason. +- [ ] Invariant 2: no code path acts on a packet before framing + + decrypt succeed; no log line includes key, salt, IV or keystrokes. - [ ] Invariants 3–5 where the lane touches `MWBMac`. -- [ ] File sizes under 600 production lines; functions under 50 unless - commented; no `!`, `try!`, `fatalError` in `Sources/`. -- [ ] Handshakes section matches the code's public API; any change is - also in the Work log. -- [ ] The QA log's findings are each resolved in the Work log or - explicitly deferred with a TODO line. -- [ ] `TODO.md` ticks are only this lane's lines. +- [ ] Size limits; no `!`, `try!`, `fatalError` in `Sources/`. +- [ ] Handshakes match the code's public API; changes are in the Work log. +- [ ] Each QA finding is resolved in the Work log or deferred with a + TODO line. Write `## Review` with the date, verdict (merge / rework), and what to -carry into the next brief. The Review section is the only place the lead -writes in a lane's README. +carry into the next brief. -## 6. Wave schedule +## 6. Lane order -| wave | lanes | gate to start | status | -|---|---|---|---| -| 0 | bootstrap | — | merged 2026-09-15 (lead, solo) | -| 1 | packet-codec ‖ cipher-stream | wave 0 merged | briefs written; not dispatched | -| 2 | session ‖ matrix-edge | wave 1 merged | briefs to write | -| 3 | control-channel ‖ event-tap | wave 2 merged | briefs to write | -| 4 | input-inject ‖ screens-cursor | wave 3 merged; screens-cursor README published first (topo handshake 6) | | -| 5 | clipboard-inband ‖ menubar-app | wave 4 merged | | -| 6 | clipboard-bulk ‖ interop-vectors | wave 5 merged; interop-vectors needs a Windows machine (§7) | | -| 7 | end-to-end, then soak | wave 6 merged; needs real devices and `MWB_ALLOW_INPUT_TESTS=1` with the user present | | +Strictly one at a time, in this order (from `docs/topo.md` §3): + +| # | lane | status | +|---|---|---| +| 0 | bootstrap | merged 2026-09-15 (lead, solo) | +| 1 | packet-codec | brief written | +| 2 | cipher-stream | brief written | +| 3 | session | | +| 4 | matrix-edge | | +| 5 | control-channel | | +| 6 | event-tap | | +| 7 | screens-cursor | | +| 8 | input-inject | | +| 9 | menubar-app | — first user-testable milestone: two Macs, or Mac ↔ Windows, mouse and keyboard | +| 10 | clipboard-inband | | +| 11 | clipboard-bulk | | +| 12 | end-to-end polish | driven by the user's testing findings | ## 7. Escalations — things only the user can do - **Grant permissions** (Accessibility, Input Monitoring) to `dist/mwb.app` in System Settings, and create the self-signed `MWB_SIGN_IDENTITY` once (`tools/bundle.sh` header). -- **Provide a Windows machine** with PowerToys for `interop-vectors` - (or a packet capture of a Windows↔Windows session plus its key). -- **Be present** for any run with `MWB_ALLOW_INPUT_TESTS=1`; the lead - says so in the report before dispatching such a step. -- **Approve pushes** of anything beyond the merge of a reviewed lane. +- **Test the app.** After lane 9 and after every lane thereafter the + lead hands the user a `dist/mwb.app` and a short checklist of what + changed; findings come back as TODO lines for the next lane. +- **Provide a Windows machine** with PowerToys for real interop checks. -## 8. Wave log +## 8. Lane log -- **2026-09-15, wave 0 (bootstrap)** — done by the lead alone at the - user's request. No Dev/QA round. What the brief got wrong: nothing - yet; the toolchain assumption (Xcode required) held. `swift-format` - is not on `PATH` — the gate calls it through `xcrun`. +- **2026-09-15, lane 0 (bootstrap)** — done by the lead alone at the + user's request. `swift-format` is not on `PATH`; the gate calls it + through `xcrun`. Later the same day the user set the standing + instruction at the top of this file; loop rewritten to match. diff --git a/docs/topo.md b/docs/topo.md index 4867c03..b187c12 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -2,10 +2,9 @@ **Purpose.** The map an agent reads before touching anything: which targets depend on which, which features consume which, and where the two -graphs meet. It exists to make parallel multi-agent development safe — -every edge below is an interface somebody can break. An absent edge is -only a candidate for independent work: confirm imports, shared files and -open handshakes before assigning ownership. +graphs meet. It exists so each lane starts only after everything it +consumes is merged, and so the lead knows which interfaces a lane can +break — every edge below is one. Sources of truth this document is derived from (and defers to on conflict): `Package.swift`, each `docs/features//README.md` @@ -83,16 +82,13 @@ lead's; a lane needing a change there files a Handshake request. ## 2. Feature dependency graph -### 2.1 Milestone order (sequencing, `─▶`) +### 2.1 Lane order (sequencing, `─▶`) ``` -bootstrap ─▶ { packet-codec ‖ cipher-stream } - ─▶ { session ‖ matrix-edge } - ─▶ { control-channel ‖ event-tap } - ─▶ { input-inject ‖ screens-cursor } - ─▶ { clipboard-inband ‖ menubar-app } - ─▶ { clipboard-bulk ‖ interop-vectors } - ─▶ end-to-end ─▶ soak +bootstrap ─▶ packet-codec ─▶ cipher-stream ─▶ session ─▶ matrix-edge + ─▶ control-channel ─▶ event-tap ─▶ screens-cursor ─▶ input-inject + ─▶ menubar-app (first user-testable build) + ─▶ clipboard-inband ─▶ clipboard-bulk ─▶ end-to-end polish ``` ### 2.2 Consumption edges (`──▶`) @@ -109,13 +105,14 @@ bootstrap ─▶ { packet-codec ‖ cipher-stream } | clipboard-inband | packet-codec | 64-byte chunk packets | | clipboard-bulk | cipher-stream, packet-codec, clipboard-inband | stream layout, `DATA`, header/text format | | menubar-app | every `MWBCore` type, control-channel, event-tap, screens-cursor | wiring | -| interop-vectors | packet-codec, cipher-stream, clipboard-inband | fixtures are tests for these | | end-to-end | all | | ### 2.3 Handshakes (`◀──▶`) — all open at planning time -Numbered so lanes can cite them. A lane that needs one not listed here -files it in its README and flags it in its report; the lead adds it. +Numbered so lanes can cite them. With serial lanes a handshake is simply +"the earlier lane publishes, the later lane consumes as published"; the +list still matters because it names the APIs the lead checks at +inspection. 1. **packet-codec ◀──▶ session**: the `Packet` API shape (value type with typed union views, `Data` in/out). packet-codec proposes in its @@ -141,19 +138,32 @@ files it in its README and flags it in its report; the lead adds it. 8. **menubar-app ◀──▶ everyone**: `Settings` is the one struct passed down; lanes read fields, never the file. -## 3. Which pairs may run in parallel +## 3. Lane order -Proven independent by disjoint files **and** no edge above: +Lanes run **one at a time** (CLAUDE.md, the user's standing +instruction), so this section is an order, not a parallelism proof. The +order follows the consumption edges in §2.2: nothing is started before +everything it consumes is merged. -| wave | lane A | lane B | shared files | -|---|---|---|---| -| 1 | packet-codec | cipher-stream | none (both create their own files; `Package.swift` untouched) | -| 2 | session | matrix-edge | none; both consume packet-codec read-only | -| 3 | control-channel | event-tap | none; different targets | -| 4 | input-inject | screens-cursor | **edge 6** — screens-cursor publishes its API in its README first; input-inject codes against the README. Acceptable only because the API is two rectangles. | -| 5 | clipboard-inband | menubar-app | `Settings.swift` is menubar-app's; clipboard reads `ShareClipboard` via a constructor parameter, not the struct | -| 6 | clipboard-bulk | interop-vectors | `Tests/Fixtures/` is interop-vectors'; bulk adds tests under `Tests/MWBNetTests/` only | +| # | lane | consumes (must be merged first) | +|---|---|---| +| 1 | packet-codec | bootstrap | +| 2 | cipher-stream | bootstrap | +| 3 | session | packet-codec, cipher-stream | +| 4 | matrix-edge | packet-codec | +| 5 | control-channel | session, cipher-stream, packet-codec | +| 6 | event-tap | matrix-edge | +| 7 | screens-cursor | matrix-edge | +| 8 | input-inject | event-tap (KeyMap), matrix-edge, screens-cursor | +| 9 | menubar-app | all of the above — the first build the user can test | +| 10 | clipboard-inband | packet-codec, menubar-app (Settings) | +| 11 | clipboard-bulk | cipher-stream, packet-codec, clipboard-inband | +| 12 | end-to-end polish | everything; driven by the user's testing | -Anything not in this table runs serially. `TODO.md`, `docs/protocol.md` -and `docs/perf/README.md` are shared-by-nature: append in your own -section only. +`interop-vectors` is no longer a lane: there are no test suites. If a +Windows machine becomes available, the lead verifies protocol facts by +hand against a capture and flips `[transcribed]` marks in +`docs/protocol.md`. + +`TODO.md`, `docs/protocol.md` and `docs/perf/README.md` are +shared-by-nature: append in your own section only. diff --git a/tools/gates.sh b/tools/gates.sh index df9e2d3..ae10911 100755 --- a/tools/gates.sh +++ b/tools/gates.sh @@ -1,32 +1,25 @@ #!/usr/bin/env bash -# The definition of "done" for every lane (CLAUDE.md, Swift standards): +# The definition of "done" for a lane's final commit (CLAUDE.md, Swift +# standards). No test suites by the user's instruction — the user tests. # 1. swift-format lint --strict is clean -# 2. swift build with warnings as errors is clean -# 3. swift test is green, under the runaway guard -# Exit 0 only if all three pass. Run from anywhere; operates on the repo -# that contains this script (so it works inside a lane worktree). -# -# Usage: tools/gates.sh [--no-test] +# 2. MWBCore imports only Foundation / CommonCrypto / CryptoKit (README D2) +# 3. swift build with warnings as errors is clean +# Exit 0 only if all pass. Operates on the repo containing this script, +# so it works inside a lane worktree. set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) cd "$root" -run_tests=1 -[ "${1:-}" = "--no-test" ] && run_tests=0 - echo "== gate 1/3: swift-format lint --strict" -xcrun swift-format lint --strict --recursive Sources Tests Package.swift +xcrun swift-format lint --strict --recursive Sources Package.swift -echo "== gate 2/3: swift build -Xswiftc -warnings-as-errors" -swift build -Xswiftc -warnings-as-errors 2>&1 | grep -v '^\[' || true -# grep swallows the exit status; re-check with a cheap incremental build. -swift build -Xswiftc -warnings-as-errors >/dev/null - -if [ "$run_tests" = 1 ]; then - echo "== gate 3/3: swift test (guarded: 8 GB / 15 min)" - # pipefail is set, so a guard kill or a failing test fails this line. - tools/guard.sh -m 8 -t 900 -- swift test 2>&1 | grep -E "Executed|error:|failed|passed after" | tail -20 -else - echo "== gate 3/3: skipped (--no-test)" +echo "== gate 2/3: MWBCore layering" +if grep -rnE '^\s*import (AppKit|Cocoa|CoreGraphics|Carbon|SwiftUI|Network|IOKit|ApplicationServices)\b' Sources/MWBCore; then + echo "gates: MWBCore may import only Foundation, CommonCrypto and CryptoKit (README D2)" >&2 + exit 1 fi + +echo "== gate 3/3: swift build -Xswiftc -warnings-as-errors" +swift build -Xswiftc -warnings-as-errors 2>&1 | grep -v '^\[' || true +swift build -Xswiftc -warnings-as-errors >/dev/null echo "== gates: all green"