mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-21 04:10:47 +02:00
implement six-skill gstack 2 runtime
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
# Tailscale ACL example for the iOS QA daemon
|
||||
|
||||
The Mac-side daemon binds the Tailscale interface only when you pass
|
||||
`--tailnet`. By default the daemon is local-USB-only. This doc walks through
|
||||
the steps to expose your iPhone to remote agents safely so they can run iOS QA over the tailnet.
|
||||
|
||||
## Threat model recap
|
||||
|
||||
- **iOS app StateServer:** loopback-only always. Reachable from the Mac via
|
||||
the CoreDevice IPv6 tunnel. Never directly bound to tailnet.
|
||||
- **Mac daemon:** owns the tailnet interface. Binds two listeners — loopback
|
||||
(full surface, never forwarded) and tailnet (locked allowlist with
|
||||
capability tiers).
|
||||
- **Auth:** Tailscale identity validation via the local `tailscaled` socket
|
||||
(`/var/run/tailscale.sock` LocalAPI WhoIs). Allowlist file at
|
||||
`~/.gstack/ios-qa-allowlist.json` is the single source of truth for who can
|
||||
do what.
|
||||
|
||||
## Step 1: Install and run Tailscale
|
||||
|
||||
```bash
|
||||
brew install --cask tailscale
|
||||
# Login + start tailscaled, then verify:
|
||||
tailscale status
|
||||
```
|
||||
|
||||
Confirm the daemon can read the LocalAPI socket:
|
||||
|
||||
```bash
|
||||
test -S /var/run/tailscale.sock && echo "socket present" || echo "MISSING"
|
||||
```
|
||||
|
||||
If missing, the daemon will refuse to open the tailnet listener (fail-closed).
|
||||
|
||||
## Step 2: Set up the daemon's ACL
|
||||
|
||||
The daemon needs to know which Tailscale identities are allowed to control
|
||||
which devices at which capability tier. The allowlist file is JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"entries": [
|
||||
{
|
||||
"identity": "you@example.com",
|
||||
"capabilities": ["restore"],
|
||||
"expires_at": null,
|
||||
"note": "Owner — full access"
|
||||
},
|
||||
{
|
||||
"identity": "ci@example.com",
|
||||
"capabilities": ["mutate"],
|
||||
"expires_at": "2026-12-31T00:00:00Z",
|
||||
"note": "CI runner — can write state but not full restore"
|
||||
},
|
||||
{
|
||||
"identity": "tag:claude-readonly",
|
||||
"capabilities": ["observe"],
|
||||
"expires_at": null,
|
||||
"note": "Agents that should only read"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Identities are canonicalized via WhoIs:
|
||||
|
||||
- **User OAuth:** `user@example.com` (no `acct:`, no domain rewriting).
|
||||
- **Tagged nodes:** `tag:<tagname>` (lowercased).
|
||||
- **Node keys:** `node:<nodekey-hex>` (rare; use tags instead).
|
||||
|
||||
Capability tiers are ordered: `observe` < `interact` < `mutate` < `restore`.
|
||||
Granting `restore` implies all lower tiers.
|
||||
|
||||
## Step 3: Mint a session token for a remote agent
|
||||
|
||||
You can let agents self-mint (if their identity is allowlisted) or you can
|
||||
mint server-side for them:
|
||||
|
||||
```bash
|
||||
# Server-side mint (owner-only, runs locally on the Mac with the device):
|
||||
gstack-ios-qa-mint --remote ci@example.com --capability mutate --ttl 1h
|
||||
|
||||
# Self-service mint (agent over tailnet):
|
||||
curl -X POST http://<mac-tailnet-ip>:9999/auth/mint \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"capability": "interact"}'
|
||||
# → {"session_token": "...", "expires_at": "...", "capability": "interact"}
|
||||
```
|
||||
|
||||
## Step 4: Tighten the Tailscale ACL (defense in depth)
|
||||
|
||||
The daemon's allowlist is the primary access control. Belt-and-suspenders:
|
||||
restrict the tailnet ACL to limit who can even *reach* the daemon port.
|
||||
|
||||
```jsonc
|
||||
// In your tailscale admin console:
|
||||
{
|
||||
"acls": [
|
||||
// Allow CI runner to reach the iOS QA Mac on port 9999 only.
|
||||
{
|
||||
"action": "accept",
|
||||
"src": ["ci@example.com"],
|
||||
"dst": ["ios-qa-mac:9999"]
|
||||
},
|
||||
// Tagged Claude agents — observe tier only (enforced by daemon, not ACL).
|
||||
{
|
||||
"action": "accept",
|
||||
"src": ["tag:claude-readonly"],
|
||||
"dst": ["ios-qa-mac:9999"]
|
||||
},
|
||||
// Default deny.
|
||||
{
|
||||
"action": "drop",
|
||||
"src": ["*"],
|
||||
"dst": ["ios-qa-mac:9999"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Audit trail
|
||||
|
||||
Every authenticated mutating request through the tailnet listener writes a
|
||||
row to `~/.gstack/security/ios-qa-audit.jsonl`:
|
||||
|
||||
```jsonl
|
||||
{"ts":"2026-05-18T14:23:00Z","identity":"ci@example.com","device_udid":"00008101-XXXX","endpoint":"/tap","session_id":"abc...","capability":"interact","request_id":"req_001","status":200}
|
||||
```
|
||||
|
||||
Rejections (no token, expired token, capability-insufficient, identity not
|
||||
allowlisted, rate limit hit) write to `~/.gstack/security/attempts.jsonl`.
|
||||
|
||||
## Rate limits
|
||||
|
||||
- `/auth/mint`: 10 mints / 60s per identity. 11th returns 429.
|
||||
- Per-tailnet-request body: 1MB hard cap (413 above).
|
||||
- Screenshot response: 10MB hard cap (500 above with sanitized error).
|
||||
|
||||
## Token lifetime
|
||||
|
||||
- Daemon-minted session tokens: default 1h TTL, max 24h via
|
||||
`--tailnet-session-ttl`.
|
||||
- Refreshable via `POST /session/heartbeat` (extends by `ttl_seconds`, capped
|
||||
at the original max).
|
||||
- Boot token (between iOS app launch and daemon rotation): ~5s lifetime —
|
||||
daemon rotates immediately on first scrape.
|
||||
|
||||
## Failure modes
|
||||
|
||||
| Symptom | Cause | Action |
|
||||
|---|---|---|
|
||||
| Daemon refuses to open tailnet listener | `/var/run/tailscale.sock` missing or permission-denied | Install Tailscale; verify `tailscale status` works as the user running daemon |
|
||||
| `403 identity_not_allowed` | identity missing from allowlist | Owner mint: `gstack-ios-qa-mint --remote <identity>` |
|
||||
| `403 capability_insufficient` | token tier below endpoint requirement | Owner mint with higher `--capability` tier |
|
||||
| `429 rate_limited` | >10 mints/min from one identity | Wait 60s; investigate why the agent is re-minting so often |
|
||||
| `409 schema_mismatch` on `/state/restore` | snapshot from older app build | Discard the snapshot; re-capture from current app build |
|
||||
@@ -0,0 +1,308 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/Bridges.swift.template
|
||||
//
|
||||
// Real UIKit-backed implementations of the three bridges StateServer
|
||||
// declares: ScreenshotBridge (PNG capture), ElementsBridge (accessibility
|
||||
// tree), MutationBridge (tap/swipe/type via accessibility actions + hit
|
||||
// testing). Everything #if DEBUG && canImport(UIKit) so Release builds
|
||||
// don't link UIKit or carry any of this code.
|
||||
//
|
||||
// Wire from the consuming app:
|
||||
//
|
||||
// #if DEBUG && canImport(UIKit)
|
||||
// import DebugBridgeUI
|
||||
// DebugBridgeUIWiring.installAll()
|
||||
// #endif
|
||||
|
||||
#if DEBUG && canImport(UIKit)
|
||||
|
||||
import DebugBridgeCore
|
||||
import DebugBridgeTouch
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
|
||||
@MainActor
|
||||
public enum DebugBridgeUIWiring {
|
||||
/// Install all three bridge resolvers. Idempotent — calling multiple
|
||||
/// times reinstalls the same closures. Must be called on @MainActor
|
||||
/// because every UIKit access requires the main actor.
|
||||
public static func installAll() {
|
||||
ScreenshotBridge.resolver = { ScreenshotBridgeImpl.capturePNG() }
|
||||
ElementsBridge.resolver = { ElementsBridgeImpl.snapshot() }
|
||||
MutationBridge.resolver = { op, payload in MutationBridgeImpl.dispatch(op: op, payload: payload) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ScreenshotBridge implementation
|
||||
|
||||
@MainActor
|
||||
enum ScreenshotBridgeImpl {
|
||||
/// Capture a PNG of the active window. Uses UIGraphicsImageRenderer
|
||||
/// (modern API, replaces UIGraphicsBeginImageContext). Returns nil if
|
||||
/// no key window is available (e.g., app backgrounded).
|
||||
static func capturePNG() -> Data? {
|
||||
guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return nil }
|
||||
let bounds = window.bounds
|
||||
let renderer = UIGraphicsImageRenderer(bounds: bounds)
|
||||
let image = renderer.image { _ in
|
||||
// drawHierarchy is the documented way to snapshot real UIKit
|
||||
// layers including layer-backed views. afterScreenUpdates: false
|
||||
// because we want the CURRENT visible state, not a forced layout.
|
||||
window.drawHierarchy(in: bounds, afterScreenUpdates: false)
|
||||
}
|
||||
return image.pngData()
|
||||
}
|
||||
|
||||
private static func activeScene() -> UIWindowScene? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.first { $0.activationState == .foregroundActive }
|
||||
?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
|
||||
}
|
||||
|
||||
private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
|
||||
scene.windows.first(where: { $0.isKeyWindow }) ?? scene.windows.first
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ElementsBridge implementation
|
||||
|
||||
@MainActor
|
||||
enum ElementsBridgeImpl {
|
||||
/// Walk the accessibility hierarchy + emit a flat list of elements.
|
||||
/// Each entry has frame (in window coords), accessibility label,
|
||||
/// identifier, traits as a bitmask, and a parent path. Skips
|
||||
/// non-accessible / hidden views.
|
||||
static func snapshot() -> [JSONDict] {
|
||||
guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return [] }
|
||||
var elements: [JSONDict] = []
|
||||
collect(view: window, parentPath: "", windowBounds: window.bounds, into: &elements)
|
||||
return elements
|
||||
}
|
||||
|
||||
private static func collect(view: UIView, parentPath: String, windowBounds: CGRect, into elements: inout [JSONDict]) {
|
||||
// Skip hidden / zero-size / off-screen subtrees early.
|
||||
if view.isHidden || view.alpha < 0.01 { return }
|
||||
|
||||
let frameInWindow = view.convert(view.bounds, to: nil)
|
||||
if !windowBounds.intersects(frameInWindow) { return }
|
||||
|
||||
let isAccessible = view.isAccessibilityElement
|
||||
let label = view.accessibilityLabel ?? ""
|
||||
let identifier = view.accessibilityIdentifier ?? ""
|
||||
let traits = Int(view.accessibilityTraits.rawValue)
|
||||
let value = (view.accessibilityValue ?? "") as String
|
||||
let className = String(describing: type(of: view))
|
||||
let path = parentPath.isEmpty ? className : "\(parentPath) > \(className)"
|
||||
|
||||
// Emit if any of:
|
||||
// - Marked accessible (covers UIKit-native widgets)
|
||||
// - Has explicit AX label / identifier
|
||||
// - Is a known interactive type (UIControl, UITextField, UIScrollView)
|
||||
// - Hosts a SwiftUI view (UIHostingController's view class)
|
||||
let isInteractive = view is UIControl || view is UIScrollView || view is UITextInput
|
||||
let isHosting = className.contains("Hosting") || className.contains("SwiftUI")
|
||||
if isAccessible || !label.isEmpty || !identifier.isEmpty || isInteractive || isHosting {
|
||||
elements.append([
|
||||
"path": path,
|
||||
"class": className,
|
||||
"label": label,
|
||||
"identifier": identifier,
|
||||
"value": value,
|
||||
"traits": traits,
|
||||
"frame": [
|
||||
"x": Int(frameInWindow.origin.x),
|
||||
"y": Int(frameInWindow.origin.y),
|
||||
"w": Int(frameInWindow.size.width),
|
||||
"h": Int(frameInWindow.size.height),
|
||||
],
|
||||
"is_user_interaction_enabled": view.isUserInteractionEnabled,
|
||||
])
|
||||
}
|
||||
|
||||
// Recurse into accessibility-elements first (some custom views vend
|
||||
// synthetic children), then UIView subviews. SwiftUI's host views
|
||||
// populate accessibilityElements lazily — many return nil before
|
||||
// VoiceOver triggers them. Force population by reading accessibilityElementCount.
|
||||
_ = view.accessibilityElementCount()
|
||||
if let axElements = view.accessibilityElements {
|
||||
for case let element as NSObject in axElements {
|
||||
if let v = element as? UIView {
|
||||
collect(view: v, parentPath: path, windowBounds: windowBounds, into: &elements)
|
||||
} else {
|
||||
// Synthetic accessibility element (no UIView). Capture frame in screen coords.
|
||||
let af = (element.value(forKey: "accessibilityFrame") as? CGRect) ?? .zero
|
||||
elements.append([
|
||||
"path": "\(path) > <synthetic>",
|
||||
"class": "AccessibilityElement",
|
||||
"label": (element.value(forKey: "accessibilityLabel") as? String) ?? "",
|
||||
"identifier": (element.value(forKey: "accessibilityIdentifier") as? String) ?? "",
|
||||
"value": (element.value(forKey: "accessibilityValue") as? String) ?? "",
|
||||
"traits": (element.value(forKey: "accessibilityTraits") as? NSNumber)?.intValue ?? 0,
|
||||
"frame": [
|
||||
"x": Int(af.origin.x),
|
||||
"y": Int(af.origin.y),
|
||||
"w": Int(af.size.width),
|
||||
"h": Int(af.size.height),
|
||||
],
|
||||
"is_user_interaction_enabled": true,
|
||||
])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// accessibilityElements is nil — iterate by index. SwiftUI uses
|
||||
// this dynamic protocol pattern; many AX elements only respond
|
||||
// to accessibilityElementCount + accessibilityElement(at:).
|
||||
let count = view.accessibilityElementCount()
|
||||
for i in 0..<count {
|
||||
guard let element = view.accessibilityElement(at: i) as? NSObject else { continue }
|
||||
if let v = element as? UIView {
|
||||
collect(view: v, parentPath: path, windowBounds: windowBounds, into: &elements)
|
||||
} else {
|
||||
let af = (element.value(forKey: "accessibilityFrame") as? CGRect) ?? .zero
|
||||
elements.append([
|
||||
"path": "\(path) > <ax\(i)>",
|
||||
"class": String(describing: type(of: element)),
|
||||
"label": (element.value(forKey: "accessibilityLabel") as? String) ?? "",
|
||||
"identifier": (element.value(forKey: "accessibilityIdentifier") as? String) ?? "",
|
||||
"value": (element.value(forKey: "accessibilityValue") as? String) ?? "",
|
||||
"traits": (element.value(forKey: "accessibilityTraits") as? NSNumber)?.intValue ?? 0,
|
||||
"frame": [
|
||||
"x": Int(af.origin.x),
|
||||
"y": Int(af.origin.y),
|
||||
"w": Int(af.size.width),
|
||||
"h": Int(af.size.height),
|
||||
],
|
||||
"is_user_interaction_enabled": true,
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
for sub in view.subviews {
|
||||
collect(view: sub, parentPath: path, windowBounds: windowBounds, into: &elements)
|
||||
}
|
||||
}
|
||||
|
||||
private static func activeScene() -> UIWindowScene? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.first { $0.activationState == .foregroundActive }
|
||||
?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
|
||||
}
|
||||
|
||||
private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
|
||||
scene.windows.first(where: { $0.isKeyWindow }) ?? scene.windows.first
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MutationBridge implementation
|
||||
|
||||
@MainActor
|
||||
enum MutationBridgeImpl {
|
||||
/// Route a mutation op to the right handler. Returns true on success,
|
||||
/// false on failure (which the StateServer surfaces as 400 to the agent).
|
||||
static func dispatch(op: String, payload: JSONDict) -> Bool {
|
||||
switch op {
|
||||
case "tap": return handleTap(payload)
|
||||
case "type": return handleType(payload)
|
||||
case "swipe": return handleSwipe(payload)
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Tap at (x, y) in window coordinates. Delegates to DebugBridgeTouch
|
||||
/// (KIF-derived in-process touch synthesis). The Obj-C target builds a
|
||||
/// real UITouch + IOHIDEvent + UIEvent and dispatches via
|
||||
/// `UIApplication.sendEvent`, which is what UIKit uses for real touches.
|
||||
/// This works for UIControl, SwiftUI Button (via iOS 18+
|
||||
/// `_UIHitTestContext`), gesture recognizers, and anything else that
|
||||
/// listens to the real event-dispatch path.
|
||||
private static func handleTap(_ payload: JSONDict) -> Bool {
|
||||
guard let x = payload["x"] as? NSNumber,
|
||||
let y = payload["y"] as? NSNumber else { return false }
|
||||
let point = CGPoint(x: x.doubleValue, y: y.doubleValue)
|
||||
guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
|
||||
return DebugBridgeTouch.sendTap(at: point, in: window)
|
||||
}
|
||||
|
||||
/// Set text on the first responder if it's a UITextField or UITextView.
|
||||
private static func handleType(_ payload: JSONDict) -> Bool {
|
||||
guard let text = payload["text"] as? String else { return false }
|
||||
guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
|
||||
guard let responder = findFirstResponder(in: window) else { return false }
|
||||
if let field = responder as? UITextField {
|
||||
field.text = text
|
||||
field.sendActions(for: .editingChanged)
|
||||
return true
|
||||
}
|
||||
if let view = responder as? UITextView {
|
||||
view.text = text
|
||||
view.delegate?.textViewDidChange?(view)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Swipe via UIScrollView programmatic scroll OR via setContentOffset on
|
||||
/// the deepest UIScrollView in the hit-tested ancestor chain. Less
|
||||
/// faithful than synthesized touches but covers common scroll scenarios.
|
||||
private static func handleSwipe(_ payload: JSONDict) -> Bool {
|
||||
guard let fx = payload["from_x"] as? NSNumber,
|
||||
let fy = payload["from_y"] as? NSNumber,
|
||||
let tx = payload["to_x"] as? NSNumber,
|
||||
let ty = payload["to_y"] as? NSNumber else { return false }
|
||||
let from = CGPoint(x: fx.doubleValue, y: fy.doubleValue)
|
||||
let to = CGPoint(x: tx.doubleValue, y: ty.doubleValue)
|
||||
|
||||
guard let scene = activeScene(), let window = activeKeyWindow(in: scene) else { return false }
|
||||
guard let hit = window.hitTest(from, with: nil) else { return false }
|
||||
|
||||
// Find the nearest enclosing UIScrollView.
|
||||
var node: UIView? = hit
|
||||
while let cur = node {
|
||||
if let scroll = cur as? UIScrollView {
|
||||
let dx = from.x - to.x
|
||||
let dy = from.y - to.y
|
||||
var off = scroll.contentOffset
|
||||
off.x = max(0, min(scroll.contentSize.width - scroll.bounds.width, off.x + dx))
|
||||
off.y = max(0, min(scroll.contentSize.height - scroll.bounds.height, off.y + dy))
|
||||
scroll.setContentOffset(off, animated: true)
|
||||
return true
|
||||
}
|
||||
node = cur.superview
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: helpers
|
||||
|
||||
private static func walkUp(_ view: UIView) -> UIView? {
|
||||
var node: UIView? = view
|
||||
while let cur = node {
|
||||
if cur is UIControl { return cur }
|
||||
node = cur.superview
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
private static func findFirstResponder(in view: UIView) -> UIResponder? {
|
||||
if view.isFirstResponder { return view }
|
||||
for sub in view.subviews {
|
||||
if let found = findFirstResponder(in: sub) { return found }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func activeScene() -> UIWindowScene? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.first { $0.activationState == .foregroundActive }
|
||||
?? (UIApplication.shared.connectedScenes.first as? UIWindowScene)
|
||||
}
|
||||
|
||||
private static func activeKeyWindow(in scene: UIWindowScene) -> UIWindow? {
|
||||
scene.windows.first(where: { $0.isKeyWindow }) ?? scene.windows.first
|
||||
}
|
||||
}
|
||||
|
||||
#endif // DEBUG && canImport(UIKit)
|
||||
@@ -0,0 +1,49 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/DebugBridgeManager.swift.template
|
||||
//
|
||||
// Bootstraps StateServer on app launch. Lives in DebugBridgeCore (no UIKit
|
||||
// dependency). The DebugOverlay install is wired separately by the consuming
|
||||
// app — it lives in DebugBridgeUI which depends on DebugBridgeCore (not the
|
||||
// other way around). Everything is #if DEBUG-gated; this file does not exist
|
||||
// in Release builds.
|
||||
|
||||
#if DEBUG
|
||||
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
public final class DebugBridgeManager {
|
||||
public static let shared = DebugBridgeManager()
|
||||
|
||||
public func start(appState: AppState) {
|
||||
// 1. Register the canonical AppState struct + accessor wiring.
|
||||
// AppStateAccessor.register(_:) is generated by gen-accessors-tool.
|
||||
AppStateAccessor.register(appState)
|
||||
|
||||
// 2. Boot the StateServer.
|
||||
StateServer.shared.start()
|
||||
|
||||
// 3. The consuming app installs DebugOverlayWindow separately. See
|
||||
// the example in DebugBridgeWiring.swift.template:
|
||||
//
|
||||
// #if canImport(UIKit)
|
||||
// DebugOverlayWindow.shared.install(recording: recording)
|
||||
// #endif
|
||||
}
|
||||
}
|
||||
|
||||
// Placeholder. gen-accessors-tool emits the real `AppStateAccessor` enum next
|
||||
// to the app's canonical state struct. Apps that haven't run codegen get a
|
||||
// stub that registers no accessors (snapshot is empty, restore returns
|
||||
// missing-key for every key).
|
||||
@MainActor
|
||||
public enum AppStateAccessor {
|
||||
public static var register: (Any) -> Void = { _ in }
|
||||
}
|
||||
|
||||
// Apps declare their canonical state struct; codegen reads it and emits
|
||||
// AppStateAccessor.register. The app's struct must be `@Observable` and
|
||||
// must hold all snapshot-eligible state in `@Snapshotable`-marked fields.
|
||||
@MainActor
|
||||
public protocol AppState: AnyObject {}
|
||||
|
||||
#endif // DEBUG
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// DebugBridgeTouch.h — public Objective-C interface for in-process touch
|
||||
// synthesis. Implementation derived from KIF (https://github.com/kif-framework/KIF),
|
||||
// MIT-licensed. The minimal subset needed to deliver a real UITouch to a
|
||||
// point on the key window, including SwiftUI Buttons via iOS 18+
|
||||
// _UIHitTestContext. DEBUG-only — never link in Release.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
#import <UIKit/UIKit.h>
|
||||
#else
|
||||
// macOS build: forward-declare UIWindow so the module compiles without UIKit.
|
||||
// The host CI runs swift build on macOS to validate the cross-platform Swift
|
||||
// surface; DebugBridgeTouch's implementation is a no-op there. On iOS the
|
||||
// real UIWindow comes from UIKit and the implementation is active.
|
||||
@class UIWindow;
|
||||
#endif
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface DebugBridgeTouch : NSObject
|
||||
|
||||
/// Synthesize a single tap (TouchPhaseBegan + TouchPhaseEnded) at the given
|
||||
/// window-coordinate point. Returns YES if the touch was delivered (a hit
|
||||
/// view was found and the event passed through UIApplication.sendEvent).
|
||||
/// On non-iOS platforms returns NO unconditionally.
|
||||
+ (BOOL)sendTapAtPoint:(CGPoint)point inWindow:(UIWindow *)window;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,301 @@
|
||||
//
|
||||
// DebugBridgeTouch.m — minimal port of KIF's in-process touch synthesis.
|
||||
// Original code: https://github.com/kif-framework/KIF — MIT-licensed
|
||||
// (Square, Inc. + KIF contributors). Adapted to a single-file, tap-only,
|
||||
// iOS 18+ aware subset for the gstack/ios-qa DebugBridge.
|
||||
//
|
||||
// Uses these private UIKit selectors (DEBUG-only; never shipped to App Store):
|
||||
// UITouch: _setLocationInWindow:resetPrevious:, _setIsFirstTouchForView:,
|
||||
// setPhase:, setTimestamp:, setView:, setWindow:, setTapCount:,
|
||||
// _setHidEvent:
|
||||
// UIEvent: _clearTouches, _addTouch:forDelayedDelivery:, _setHIDEvent:
|
||||
// UIApplication: _touchesEvent
|
||||
// UIView: _hitTestWithContext: (iOS 18+ for SwiftUI hit-testing)
|
||||
// NSObject: _UIHitTestContext contextWithPoint:radius: (iOS 18+)
|
||||
//
|
||||
// IOKit private symbols (linked dynamically via the IOKit framework on iOS):
|
||||
// IOHIDEventCreateDigitizerEvent, IOHIDEventCreateDigitizerFingerEventWithQuality,
|
||||
// IOHIDEventSetIntegerValue, IOHIDEventAppendEvent.
|
||||
|
||||
#import "DebugBridgeTouch.h"
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IOS
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <objc/runtime.h>
|
||||
#import <objc/message.h>
|
||||
#import <mach/mach_time.h>
|
||||
|
||||
#pragma mark - IOHIDEvent (private symbols from IOKit)
|
||||
|
||||
typedef struct __IOHIDEvent * IOHIDEventRef;
|
||||
|
||||
#define IOHIDEventFieldBase(type) (type << 16)
|
||||
#ifdef __LP64__
|
||||
typedef double IOHIDFloat;
|
||||
#else
|
||||
typedef float IOHIDFloat;
|
||||
#endif
|
||||
typedef UInt32 IOOptionBits;
|
||||
typedef uint32_t IOHIDDigitizerTransducerType;
|
||||
typedef uint32_t IOHIDEventField;
|
||||
|
||||
enum {
|
||||
kIOHIDDigitizerTransducerTypeStylus = 0,
|
||||
kIOHIDDigitizerTransducerTypePuck,
|
||||
kIOHIDDigitizerTransducerTypeFinger,
|
||||
kIOHIDDigitizerTransducerTypeHand
|
||||
};
|
||||
|
||||
enum {
|
||||
kIOHIDEventTypeDigitizer = 11,
|
||||
};
|
||||
|
||||
enum {
|
||||
kIOHIDDigitizerEventRange = 0x00000001,
|
||||
kIOHIDDigitizerEventTouch = 0x00000002,
|
||||
kIOHIDDigitizerEventPosition = 0x00000004,
|
||||
};
|
||||
|
||||
enum {
|
||||
kIOHIDEventFieldDigitizerX = IOHIDEventFieldBase(kIOHIDEventTypeDigitizer),
|
||||
kIOHIDEventFieldDigitizerY,
|
||||
kIOHIDEventFieldDigitizerZ,
|
||||
kIOHIDEventFieldDigitizerButtonMask,
|
||||
kIOHIDEventFieldDigitizerType,
|
||||
kIOHIDEventFieldDigitizerIndex,
|
||||
kIOHIDEventFieldDigitizerIdentity,
|
||||
kIOHIDEventFieldDigitizerEventMask,
|
||||
kIOHIDEventFieldDigitizerRange,
|
||||
kIOHIDEventFieldDigitizerTouch,
|
||||
kIOHIDEventFieldDigitizerPressure,
|
||||
kIOHIDEventFieldDigitizerAuxiliaryPressure,
|
||||
kIOHIDEventFieldDigitizerTwist,
|
||||
kIOHIDEventFieldDigitizerTiltX,
|
||||
kIOHIDEventFieldDigitizerTiltY,
|
||||
kIOHIDEventFieldDigitizerAltitude,
|
||||
kIOHIDEventFieldDigitizerAzimuth,
|
||||
kIOHIDEventFieldDigitizerQuality,
|
||||
kIOHIDEventFieldDigitizerDensity,
|
||||
kIOHIDEventFieldDigitizerIrregularity,
|
||||
kIOHIDEventFieldDigitizerMajorRadius,
|
||||
kIOHIDEventFieldDigitizerMinorRadius,
|
||||
kIOHIDEventFieldDigitizerCollection,
|
||||
kIOHIDEventFieldDigitizerCollectionChord,
|
||||
kIOHIDEventFieldDigitizerChildEventMask,
|
||||
kIOHIDEventFieldDigitizerIsDisplayIntegrated,
|
||||
};
|
||||
|
||||
// IOKit is a PRIVATE framework on iOS — we can't link it via -framework. Load
|
||||
// at runtime via dlopen/dlsym. This is the standard approach for KIF-style
|
||||
// touch synthesis on iOS, including in DEBUG-only test harnesses.
|
||||
#import <dlfcn.h>
|
||||
|
||||
typedef IOHIDEventRef (*IOHIDEventCreateDigitizerEventFn)(CFAllocatorRef, AbsoluteTime,
|
||||
IOHIDDigitizerTransducerType, uint32_t, uint32_t, uint32_t, uint32_t,
|
||||
IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat, Boolean, Boolean, IOOptionBits);
|
||||
|
||||
typedef IOHIDEventRef (*IOHIDEventCreateDigitizerFingerEventWithQualityFn)(CFAllocatorRef,
|
||||
AbsoluteTime, uint32_t, uint32_t, uint32_t, IOHIDFloat, IOHIDFloat, IOHIDFloat,
|
||||
IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat,
|
||||
IOHIDFloat, Boolean, Boolean, IOOptionBits);
|
||||
|
||||
typedef void (*IOHIDEventSetIntegerValueFn)(IOHIDEventRef, IOHIDEventField, int);
|
||||
typedef void (*IOHIDEventAppendEventFn)(IOHIDEventRef, IOHIDEventRef);
|
||||
|
||||
static IOHIDEventCreateDigitizerEventFn _IOHIDEventCreateDigitizerEvent;
|
||||
static IOHIDEventCreateDigitizerFingerEventWithQualityFn _IOHIDEventCreateDigitizerFingerEventWithQuality;
|
||||
static IOHIDEventSetIntegerValueFn _IOHIDEventSetIntegerValue;
|
||||
static IOHIDEventAppendEventFn _IOHIDEventAppendEvent;
|
||||
|
||||
static BOOL _IOKitLoaded = NO;
|
||||
static BOOL DBT_LoadIOKit(void) {
|
||||
if (_IOKitLoaded) return YES;
|
||||
void *handle = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);
|
||||
if (!handle) {
|
||||
handle = dlopen("/System/Library/PrivateFrameworks/IOKit.framework/IOKit", RTLD_NOW);
|
||||
}
|
||||
if (!handle) return NO;
|
||||
_IOHIDEventCreateDigitizerEvent = (IOHIDEventCreateDigitizerEventFn)dlsym(handle, "IOHIDEventCreateDigitizerEvent");
|
||||
_IOHIDEventCreateDigitizerFingerEventWithQuality = (IOHIDEventCreateDigitizerFingerEventWithQualityFn)dlsym(handle, "IOHIDEventCreateDigitizerFingerEventWithQuality");
|
||||
_IOHIDEventSetIntegerValue = (IOHIDEventSetIntegerValueFn)dlsym(handle, "IOHIDEventSetIntegerValue");
|
||||
_IOHIDEventAppendEvent = (IOHIDEventAppendEventFn)dlsym(handle, "IOHIDEventAppendEvent");
|
||||
_IOKitLoaded = (_IOHIDEventCreateDigitizerEvent && _IOHIDEventCreateDigitizerFingerEventWithQuality &&
|
||||
_IOHIDEventSetIntegerValue && _IOHIDEventAppendEvent);
|
||||
return _IOKitLoaded;
|
||||
}
|
||||
|
||||
static IOHIDEventRef DBT_IOHIDEventWithTouch(UITouch *touch) CF_RETURNS_RETAINED;
|
||||
static IOHIDEventRef DBT_IOHIDEventWithTouch(UITouch *touch) {
|
||||
if (!DBT_LoadIOKit()) return NULL;
|
||||
uint64_t abTime = mach_absolute_time();
|
||||
AbsoluteTime timeStamp;
|
||||
timeStamp.hi = (UInt32)(abTime >> 32);
|
||||
timeStamp.lo = (UInt32)(abTime);
|
||||
|
||||
IOHIDEventRef handEvent = _IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault,
|
||||
timeStamp, kIOHIDDigitizerTransducerTypeHand,
|
||||
0, 0, kIOHIDDigitizerEventTouch, 0,
|
||||
0, 0, 0, 0, 0,
|
||||
0, true, 0);
|
||||
_IOHIDEventSetIntegerValue(handEvent, kIOHIDEventFieldDigitizerIsDisplayIntegrated, 1);
|
||||
|
||||
uint32_t eventMask = (touch.phase == UITouchPhaseMoved)
|
||||
? kIOHIDDigitizerEventPosition
|
||||
: (kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch);
|
||||
uint32_t isTouching = (touch.phase == UITouchPhaseEnded) ? 0 : 1;
|
||||
|
||||
CGPoint loc = [touch locationInView:touch.window];
|
||||
|
||||
IOHIDEventRef fingerEvent = _IOHIDEventCreateDigitizerFingerEventWithQuality(kCFAllocatorDefault,
|
||||
timeStamp, 1, 2, eventMask,
|
||||
(IOHIDFloat)loc.x, (IOHIDFloat)loc.y, 0.0,
|
||||
0, 0, 5.0, 5.0, 1.0, 1.0, 1.0,
|
||||
(IOHIDFloat)isTouching, (IOHIDFloat)isTouching, 0);
|
||||
_IOHIDEventSetIntegerValue(fingerEvent, kIOHIDEventFieldDigitizerIsDisplayIntegrated, 1);
|
||||
|
||||
_IOHIDEventAppendEvent(handEvent, fingerEvent);
|
||||
CFRelease(fingerEvent);
|
||||
|
||||
return handEvent;
|
||||
}
|
||||
|
||||
#pragma mark - Private selectors
|
||||
|
||||
@interface UITouch ()
|
||||
- (void)setWindow:(UIWindow *)window;
|
||||
- (void)setView:(UIView *)view;
|
||||
- (void)setTapCount:(NSUInteger)tapCount;
|
||||
- (void)setTimestamp:(NSTimeInterval)timestamp;
|
||||
- (void)setPhase:(UITouchPhase)touchPhase;
|
||||
- (void)setGestureView:(UIView *)view;
|
||||
- (void)_setLocationInWindow:(CGPoint)location resetPrevious:(BOOL)resetPrevious;
|
||||
- (void)_setIsFirstTouchForView:(BOOL)firstTouchForView;
|
||||
- (void)_setHidEvent:(IOHIDEventRef)event;
|
||||
@end
|
||||
|
||||
@interface UIEvent (DBTPrivate)
|
||||
- (void)_clearTouches;
|
||||
- (void)_addTouch:(UITouch *)touch forDelayedDelivery:(BOOL)delayed;
|
||||
- (void)_setHIDEvent:(IOHIDEventRef)event;
|
||||
- (void)_setTimestamp:(NSTimeInterval)timestamp;
|
||||
@end
|
||||
|
||||
@interface UIApplication (DBTPrivate)
|
||||
- (UIEvent *)_touchesEvent;
|
||||
@end
|
||||
|
||||
@interface UIView (DBTPrivate)
|
||||
- (id)_hitTestWithContext:(id)context;
|
||||
@end
|
||||
|
||||
#pragma mark - SwiftUI-aware hit test (iOS 18+)
|
||||
|
||||
// Returns `id` because iOS 18's _hitTestWithContext: can return either a UIView
|
||||
// OR a SwiftUI.UIKitGestureContainer (a plain UIResponder, NOT a UIView).
|
||||
// The latter is the case for SwiftUI Buttons. KIF's observation: the returned
|
||||
// responder is still compatible with UITouch.setView: even when it isn't a
|
||||
// UIView — so we pass it through as-is. Filtering by isKindOfClass:UIView
|
||||
// here would drop every SwiftUI Button tap silently. Mirrors KIF PR #1323.
|
||||
static id DBT_HitTestView(UIWindow *window, CGPoint point) {
|
||||
UIView *fallback = [window hitTest:point withEvent:nil];
|
||||
|
||||
if (@available(iOS 18.0, *)) {
|
||||
Class ctxClass = NSClassFromString(@"_UIHitTestContext");
|
||||
SEL ctxSel = NSSelectorFromString(@"contextWithPoint:radius:");
|
||||
if (ctxClass && [ctxClass respondsToSelector:ctxSel] &&
|
||||
[UIView instancesRespondToSelector:@selector(_hitTestWithContext:)]) {
|
||||
id (*sendCtx)(id, SEL, CGPoint, CGFloat) =
|
||||
(id (*)(id, SEL, CGPoint, CGFloat))objc_msgSend;
|
||||
id ctx = sendCtx(ctxClass, ctxSel, point, 0);
|
||||
if (ctx) {
|
||||
id found = nil;
|
||||
UIView *current = fallback;
|
||||
while (found == nil && current != nil) {
|
||||
found = [current _hitTestWithContext:ctx];
|
||||
current = current.superview;
|
||||
}
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
#pragma mark - Public API
|
||||
|
||||
@implementation DebugBridgeTouch
|
||||
|
||||
+ (BOOL)sendTapAtPoint:(CGPoint)point inWindow:(UIWindow *)window {
|
||||
if (!window) return NO;
|
||||
|
||||
id hit = DBT_HitTestView(window, point);
|
||||
if (!hit) return NO;
|
||||
|
||||
// Build a single synthetic UITouch via private setters. Order matters —
|
||||
// setWindow: clears internal state and must come first.
|
||||
UITouch *touch = [[UITouch alloc] init];
|
||||
[touch setWindow:window];
|
||||
[touch setTapCount:1];
|
||||
[touch _setLocationInWindow:point resetPrevious:YES];
|
||||
// setView: typed UIView * but accepts SwiftUI.UIKitGestureContainer
|
||||
// (UIResponder) too — that's how SwiftUI Buttons get routed on iOS 18+.
|
||||
[touch setView:(UIView *)hit];
|
||||
[touch setPhase:UITouchPhaseBegan];
|
||||
if ([touch respondsToSelector:@selector(_setIsFirstTouchForView:)]) {
|
||||
[touch _setIsFirstTouchForView:YES];
|
||||
}
|
||||
[touch setTimestamp:[[NSProcessInfo processInfo] systemUptime]];
|
||||
if ([touch respondsToSelector:@selector(setGestureView:)] &&
|
||||
[hit isKindOfClass:[UIView class]]) {
|
||||
[touch setGestureView:(UIView *)hit];
|
||||
}
|
||||
|
||||
// Attach a real IOHIDEvent (required iOS 9+).
|
||||
IOHIDEventRef hidEventBegan = DBT_IOHIDEventWithTouch(touch);
|
||||
[touch _setHidEvent:hidEventBegan];
|
||||
|
||||
UIEvent *event = [[UIApplication sharedApplication] _touchesEvent];
|
||||
if (!event) {
|
||||
CFRelease(hidEventBegan);
|
||||
return NO;
|
||||
}
|
||||
[event _clearTouches];
|
||||
[event _setHIDEvent:hidEventBegan];
|
||||
[event _addTouch:touch forDelayedDelivery:NO];
|
||||
|
||||
[[UIApplication sharedApplication] sendEvent:event];
|
||||
CFRelease(hidEventBegan);
|
||||
|
||||
// Ended phase
|
||||
[touch setPhase:UITouchPhaseEnded];
|
||||
[touch setTimestamp:[[NSProcessInfo processInfo] systemUptime]];
|
||||
IOHIDEventRef hidEventEnded = DBT_IOHIDEventWithTouch(touch);
|
||||
[touch _setHidEvent:hidEventEnded];
|
||||
[event _clearTouches];
|
||||
[event _setHIDEvent:hidEventEnded];
|
||||
[event _addTouch:touch forDelayedDelivery:NO];
|
||||
[[UIApplication sharedApplication] sendEvent:event];
|
||||
CFRelease(hidEventEnded);
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#else // !TARGET_OS_IOS
|
||||
|
||||
// macOS / Catalyst / other non-iOS host build: no-op stub so the module
|
||||
// resolves cleanly without UIKit or IOKit. The Swift cross-platform tests
|
||||
// don't exercise touch synthesis; that's iOS-only by definition.
|
||||
@implementation DebugBridgeTouch
|
||||
+ (BOOL)sendTapAtPoint:(CGPoint)point inWindow:(UIWindow *)window {
|
||||
(void)point; (void)window;
|
||||
return NO;
|
||||
}
|
||||
@end
|
||||
|
||||
#endif // TARGET_OS_IOS
|
||||
@@ -0,0 +1,43 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/DebugBridgeWiring.swift.template
|
||||
//
|
||||
// Wiring snippet for the app's @main entry. Users paste this into their
|
||||
// App.swift inside the `init()` of the SwiftUI App struct, gated by
|
||||
// #if DEBUG. The wiring is intentionally tiny; everything heavy lives in
|
||||
// the DebugBridge target.
|
||||
|
||||
#if DEBUG
|
||||
import DebugBridge
|
||||
|
||||
@MainActor
|
||||
func startGstackDebugBridge(appState: AppState) {
|
||||
// Read --recording flag from launch arguments
|
||||
let recording = ProcessInfo.processInfo.arguments.contains("--gstack-recording")
|
||||
|
||||
// Install accessibility + screenshot + mutation bridges before starting
|
||||
// the server so the first authenticated request can use them.
|
||||
ElementsBridge.resolver = { AccessibilityScanner.snapshot() }
|
||||
ScreenshotBridge.resolver = { SnapshotCapture.capturePNG() }
|
||||
MutationBridge.resolver = { op, payload in
|
||||
MutationDispatcher.shared.run(op: op, payload: payload)
|
||||
}
|
||||
|
||||
DebugBridgeManager.shared.start(appState: appState, recording: recording)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Example usage in the app's @main entry (paste this into App.swift):
|
||||
//
|
||||
// @main
|
||||
// struct MyApp: App {
|
||||
// @State private var appState = MyAppState()
|
||||
//
|
||||
// init() {
|
||||
// #if DEBUG
|
||||
// startGstackDebugBridge(appState: appState)
|
||||
// #endif
|
||||
// }
|
||||
//
|
||||
// var body: some Scene {
|
||||
// WindowGroup { ContentView() }
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,137 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/DebugOverlay.swift.template
|
||||
//
|
||||
// DebugOverlay — on-device visual presence. Animated brand-colored border +
|
||||
// agent attribution chip + (optional) recording watermark. Renders above
|
||||
// sheets, alerts, and modals via a dedicated UIWindow with high windowLevel.
|
||||
//
|
||||
// Everything in this file is gated #if DEBUG and gone in Release.
|
||||
|
||||
#if DEBUG && canImport(UIKit)
|
||||
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
|
||||
@MainActor
|
||||
public final class DebugOverlayWindow {
|
||||
public static let shared = DebugOverlayWindow()
|
||||
|
||||
private var window: UIWindow?
|
||||
|
||||
public func install(recording: Bool = false) {
|
||||
guard window == nil else { return }
|
||||
guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else { return }
|
||||
|
||||
let w = PassThroughWindow(windowScene: scene)
|
||||
w.windowLevel = .alert + 1
|
||||
w.backgroundColor = .clear
|
||||
w.isUserInteractionEnabled = false
|
||||
|
||||
let host = UIHostingController(rootView: OverlayRoot(recording: recording))
|
||||
host.view.backgroundColor = .clear
|
||||
w.rootViewController = host
|
||||
w.isHidden = false
|
||||
|
||||
window = w
|
||||
}
|
||||
|
||||
public func setAttribution(_ identity: String) {
|
||||
OverlayAttributionState.shared.identity = identity
|
||||
}
|
||||
}
|
||||
|
||||
/// A window that lets touches pass through to underlying windows.
|
||||
private final class PassThroughWindow: UIWindow {
|
||||
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
|
||||
let view = super.hitTest(point, with: event)
|
||||
return view == rootViewController?.view ? nil : view
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class OverlayAttributionState: ObservableObject {
|
||||
static let shared = OverlayAttributionState()
|
||||
@Published var identity: String = "Claude Code (local)"
|
||||
}
|
||||
|
||||
private struct OverlayRoot: View {
|
||||
@StateObject private var attribution = OverlayAttributionState.shared
|
||||
@State private var phase: CGFloat = 0
|
||||
let recording: Bool
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
// Animated brand border
|
||||
BorderShape()
|
||||
.stroke(
|
||||
AngularGradient(
|
||||
gradient: Gradient(colors: [
|
||||
BrandColor.accent.opacity(0.0),
|
||||
BrandColor.accent.opacity(0.8),
|
||||
BrandColor.accent.opacity(0.0),
|
||||
]),
|
||||
center: .center,
|
||||
angle: .degrees(phase * 360)
|
||||
),
|
||||
lineWidth: 4
|
||||
)
|
||||
.ignoresSafeArea()
|
||||
.onAppear {
|
||||
withAnimation(.linear(duration: 2.0).repeatForever(autoreverses: false)) {
|
||||
phase = 1.0
|
||||
}
|
||||
}
|
||||
|
||||
// Attribution chip (top safe area)
|
||||
VStack {
|
||||
HStack {
|
||||
Spacer()
|
||||
Text("Driven by \(attribution.identity)")
|
||||
.font(.caption2.weight(.semibold))
|
||||
.foregroundColor(.white)
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 4)
|
||||
.background(
|
||||
Capsule().fill(BrandColor.accent.opacity(0.85))
|
||||
)
|
||||
.padding(.trailing, 12)
|
||||
.padding(.top, 8)
|
||||
Spacer().frame(width: 0)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
|
||||
// Recording watermark (diagonal, bottom-right)
|
||||
if recording {
|
||||
VStack {
|
||||
Spacer()
|
||||
HStack {
|
||||
Spacer()
|
||||
Text("AGENT DEMO")
|
||||
.font(.system(size: 10, weight: .heavy, design: .monospaced))
|
||||
.foregroundColor(.red.opacity(0.7))
|
||||
.rotationEffect(.degrees(-30))
|
||||
.padding(.trailing, 16)
|
||||
.padding(.bottom, 30)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
private struct BorderShape: Shape {
|
||||
func path(in rect: CGRect) -> Path {
|
||||
var p = Path()
|
||||
p.addRoundedRect(in: rect.insetBy(dx: 2, dy: 2), cornerSize: CGSize(width: 16, height: 16))
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
private enum BrandColor {
|
||||
// gstack brand color — resolved from DESIGN.md when codegen runs.
|
||||
// Default falls back to a deep blue.
|
||||
static let accent = Color(red: 0.0, green: 0.46, blue: 1.0)
|
||||
}
|
||||
|
||||
#endif // DEBUG && canImport(UIKit)
|
||||
@@ -0,0 +1,67 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/Package.swift.template
|
||||
//
|
||||
// Drop-in SPM package definition for the DebugBridge stack. Three targets:
|
||||
//
|
||||
// - DebugBridgeCore Swift, cross-platform (Foundation + Network).
|
||||
// Hosts the StateServer + bridge protocols.
|
||||
// - DebugBridgeTouch Objective-C, iOS-only. KIF-derived in-process touch
|
||||
// synthesis (UITouch + IOHIDEvent + iOS 18
|
||||
// _UIHitTestContext for SwiftUI Buttons).
|
||||
// - DebugBridgeUI Swift, iOS-only. ScreenshotBridge, ElementsBridge,
|
||||
// MutationBridge implementations. Depends on the other
|
||||
// two.
|
||||
//
|
||||
// The structural Release-build guard is the `.when(configuration: .debug)`
|
||||
// conditional on every consuming target's dependency. SwiftPM refuses to link
|
||||
// DebugBridge* in Release config.
|
||||
//
|
||||
// CI invariant: `swift build -c release` + `nm -j build/Release/<binary>
|
||||
// | grep -q DebugBridge && exit 1`.
|
||||
|
||||
// swift-tools-version:5.9
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "DebugBridge",
|
||||
platforms: [.iOS(.v16), .macOS(.v13)],
|
||||
products: [
|
||||
.library(name: "DebugBridgeCore", targets: ["DebugBridgeCore"]),
|
||||
.library(name: "DebugBridgeUI", targets: ["DebugBridgeUI"]),
|
||||
.library(name: "DebugBridgeTouch", targets: ["DebugBridgeTouch"]),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "DebugBridgeCore",
|
||||
dependencies: [],
|
||||
path: "Sources/DebugBridgeCore",
|
||||
swiftSettings: [
|
||||
.define("DEBUG", .when(configuration: .debug)),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "DebugBridgeTouch",
|
||||
dependencies: [],
|
||||
path: "Sources/DebugBridgeTouch",
|
||||
publicHeadersPath: "include",
|
||||
linkerSettings: [
|
||||
// IOKit is loaded dynamically via dlopen at runtime (it's a
|
||||
// private framework on iOS and can't be linked statically).
|
||||
// UIKit links normally.
|
||||
.linkedFramework("UIKit", .when(platforms: [.iOS])),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "DebugBridgeUI",
|
||||
dependencies: ["DebugBridgeCore", "DebugBridgeTouch"],
|
||||
path: "Sources/DebugBridgeUI",
|
||||
swiftSettings: [
|
||||
.define("DEBUG", .when(configuration: .debug)),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "DebugBridgeCoreTests",
|
||||
dependencies: ["DebugBridgeCore"],
|
||||
path: "Tests/DebugBridgeCoreTests"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/StateAccessor.swift.template
|
||||
// Regenerated by `swift run gen-accessors`. DO NOT EDIT.
|
||||
//
|
||||
// This file is a TEMPLATE that gen-accessors-tool fills in. The placeholders
|
||||
// are filled per-class from swift-syntax AST inspection of the app's
|
||||
// @Observable types. Only properties marked with @Snapshotable are emitted.
|
||||
//
|
||||
// {{CLASS_NAME}} — the canonical AppState struct name
|
||||
// {{APP_BUILD_ID}} — bundle short version + git SHA at codegen time
|
||||
// {{ACCESSOR_HASH}} — sha256 of accessor signatures (snapshot schema fingerprint)
|
||||
// {{ACCESSORS}} — generated register/read/write blocks per @Snapshotable field
|
||||
|
||||
#if DEBUG
|
||||
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
public enum {{CLASS_NAME}}Accessor {
|
||||
|
||||
public static func register(_ state: {{CLASS_NAME}}) {
|
||||
StateServer.shared.register(
|
||||
buildId: "{{APP_BUILD_ID}}",
|
||||
accessorHash: "{{ACCESSOR_HASH}}",
|
||||
atomicRestore: { keys in
|
||||
// Validate every key + type FIRST, then apply in one struct
|
||||
// assignment so SwiftUI observers see exactly one change.
|
||||
var snapshot = state.snapshotable
|
||||
{{VALIDATION_BLOCK}}
|
||||
// Apply atomically.
|
||||
state.snapshotable = snapshot
|
||||
return .ok
|
||||
}
|
||||
)
|
||||
{{REGISTER_BLOCK}}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // DEBUG
|
||||
@@ -0,0 +1,569 @@
|
||||
// AUTO-GENERATED from gstack/ios-qa/templates/StateServer.swift.template
|
||||
// Regenerate with: /ios-sync
|
||||
//
|
||||
// StateServer — HTTP server embedded in the iOS app under test. Loopback-only.
|
||||
// All tailnet ingress is the responsibility of the Mac-side daemon.
|
||||
//
|
||||
// Threat model: this surface is reachable from the local Mac via the CoreDevice
|
||||
// IPv6 tunnel. It MUST refuse any caller without a current bearer token. The
|
||||
// boot token is rotated within ~5 seconds of daemon spawn so anything scraping
|
||||
// os_log past that window sees a dead credential.
|
||||
|
||||
import Foundation
|
||||
import Network
|
||||
import os.log
|
||||
|
||||
#if DEBUG
|
||||
|
||||
public typealias JSONDict = [String: Any]
|
||||
|
||||
@MainActor
|
||||
public final class StateServer {
|
||||
// MARK: Public surface
|
||||
|
||||
public static let shared = StateServer()
|
||||
|
||||
// MARK: Configuration
|
||||
|
||||
private let logger = Logger(subsystem: "gstack.ios-qa", category: "StateServer")
|
||||
private let port: UInt16
|
||||
private let bootTokenPath: String
|
||||
|
||||
// Two listeners for dual-stack loopback. The fork's single-listener IPv6-only
|
||||
// binding was caught in eng + outside-voice review as incomplete.
|
||||
private var ipv6Listener: NWListener?
|
||||
private var ipv4Listener: NWListener?
|
||||
|
||||
// Auth state. The boot token is what we wrote to os_log on first launch.
|
||||
// It exists ONLY long enough for the daemon to call /auth/rotate.
|
||||
private var bootToken: String
|
||||
private var rotatedToken: String? // set after first /auth/rotate
|
||||
private var bootTokenValid: Bool = true
|
||||
|
||||
// MARK: Session lock (per-device, sliding window on mutations only)
|
||||
|
||||
private struct Session {
|
||||
let id: String
|
||||
var lastMutationAt: Date
|
||||
}
|
||||
private var activeSession: Session?
|
||||
private let sessionTtlSeconds: TimeInterval = 300 // 5 min orphan timeout
|
||||
|
||||
// MARK: Accessor registry (populated by codegen)
|
||||
|
||||
public typealias ReadHandler = () -> Any?
|
||||
public typealias WriteHandler = (Any) -> Bool
|
||||
public typealias TypeName = String
|
||||
|
||||
private var readHandlers: [String: ReadHandler] = [:]
|
||||
private var writeHandlers: [String: WriteHandler] = [:]
|
||||
private var typeNames: [String: TypeName] = [:]
|
||||
|
||||
// Atomic-restore hook. Codegen wires this to the canonical AppState struct.
|
||||
// Restore replaces the entire struct in one assignment so SwiftUI's Combine
|
||||
// pipeline observes exactly one change notification — true observable
|
||||
// atomicity. @MainActor alone doesn't guarantee that.
|
||||
public typealias AtomicRestoreFn = (JSONDict) -> RestoreResult
|
||||
public enum RestoreResult {
|
||||
case ok
|
||||
case missingKey(String)
|
||||
case typeMismatch(String)
|
||||
case schemaMismatch(expected: String, got: String)
|
||||
}
|
||||
private var atomicRestore: AtomicRestoreFn?
|
||||
|
||||
// Snapshot schema hash — written by codegen, stable across builds with
|
||||
// identical accessor signatures.
|
||||
private var accessorHash: String = "uninitialized"
|
||||
private var appBuildId: String = "uninitialized"
|
||||
|
||||
// Agent identity for the DebugOverlay attribution chip. Display-only,
|
||||
// never used for auth.
|
||||
public private(set) var lastAgentIdentity: String = "Claude Code (local)"
|
||||
|
||||
// MARK: Lifecycle
|
||||
|
||||
private init(port: UInt16 = 9999) {
|
||||
self.port = port
|
||||
self.bootToken = UUID().uuidString
|
||||
self.bootTokenPath = NSTemporaryDirectory() + "gstack-ios-qa.token"
|
||||
}
|
||||
|
||||
public func start() {
|
||||
// 1. Persist boot token to a 0600 file (best-effort fallback for the
|
||||
// daemon if os_log scrape misses).
|
||||
try? bootToken.write(toFile: bootTokenPath, atomically: true, encoding: .utf8)
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: bootTokenPath)
|
||||
|
||||
// 2. Log the boot token EXACTLY ONCE so the daemon can scrape it.
|
||||
// The daemon will rotate immediately; this log line is dead within
|
||||
// seconds.
|
||||
logger.notice("gstack-ios-qa-bootstrap token=\(self.bootToken, privacy: .public) port=\(self.port, privacy: .public) build=\(self.appBuildId, privacy: .public)")
|
||||
|
||||
// 3. Bind both IPv6 and IPv4 loopback. CoreDevice tunnel uses IPv6;
|
||||
// local tooling may use IPv4. Never bind 0.0.0.0 or ::.
|
||||
startListener(family: .ipv6)
|
||||
startListener(family: .ipv4)
|
||||
}
|
||||
|
||||
public func register(buildId: String, accessorHash: String, atomicRestore: @escaping AtomicRestoreFn) {
|
||||
self.appBuildId = buildId
|
||||
self.accessorHash = accessorHash
|
||||
self.atomicRestore = atomicRestore
|
||||
}
|
||||
|
||||
public func registerAccessor(key: String, type: String, read: @escaping ReadHandler, write: @escaping WriteHandler) {
|
||||
readHandlers[key] = read
|
||||
writeHandlers[key] = write
|
||||
typeNames[key] = type
|
||||
}
|
||||
|
||||
// MARK: Listener setup
|
||||
|
||||
private enum AddressFamily {
|
||||
case ipv4
|
||||
case ipv6
|
||||
|
||||
var host: NWEndpoint.Host {
|
||||
switch self {
|
||||
case .ipv4: return NWEndpoint.Host("127.0.0.1")
|
||||
case .ipv6: return NWEndpoint.Host("::1")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func startListener(family: AddressFamily) {
|
||||
do {
|
||||
// Binding strategy: accept connections from the device's loopback
|
||||
// AND from the CoreDevice tunnel (the USB-mounted tunnel the Mac
|
||||
// daemon uses to reach this app — appears as a non-loopback
|
||||
// utun-style interface on the device with the peer's source
|
||||
// address in the fd*/fc* ULA range). We can't use
|
||||
// params.acceptLocalOnly — Network.framework's definition of
|
||||
// "local" is strictly loopback and silently drops CoreDevice
|
||||
// tunnel peers. Instead we accept on the wildcard interface and
|
||||
// do a per-connection peer-address check below: loopback OR
|
||||
// RFC 4193 ULA (fc00::/7) → accept, everything else → cancel.
|
||||
let params = NWParameters.tcp
|
||||
params.allowLocalEndpointReuse = true
|
||||
|
||||
let listener = try NWListener(using: params, on: NWEndpoint.Port(rawValue: port)!)
|
||||
listener.stateUpdateHandler = { [weak self] state in
|
||||
Task { @MainActor in
|
||||
if case .ready = state {
|
||||
self?.logger.notice("StateServer listening on \(String(describing: family))")
|
||||
} else if case .failed(let err) = state {
|
||||
self?.logger.error("StateServer listener failed: \(err.localizedDescription, privacy: .public)")
|
||||
}
|
||||
}
|
||||
}
|
||||
listener.newConnectionHandler = { [weak self] connection in
|
||||
Task { @MainActor in
|
||||
// Defense-in-depth: even with .loopback interface gate, double-check
|
||||
// the peer is loopback. Reject otherwise.
|
||||
if let self, self.isLoopbackPeer(connection) {
|
||||
self.handle(connection)
|
||||
} else {
|
||||
connection.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
listener.start(queue: .global(qos: .userInitiated))
|
||||
|
||||
switch family {
|
||||
case .ipv6: ipv6Listener = listener
|
||||
case .ipv4: ipv4Listener = listener
|
||||
}
|
||||
} catch {
|
||||
logger.error("Listener bind failed (\(String(describing: family))): \(error.localizedDescription, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
private func isLoopbackPeer(_ connection: NWConnection) -> Bool {
|
||||
switch connection.endpoint {
|
||||
case .hostPort(let host, _):
|
||||
switch host {
|
||||
case .ipv4(let addr):
|
||||
return addr == .loopback
|
||||
case .ipv6(let addr):
|
||||
// Loopback (::1) — local same-device traffic
|
||||
if addr.isLoopback { return true }
|
||||
// CoreDevice ULA range (fd00::/8 unique-local addresses) —
|
||||
// the USB tunnel that the Mac daemon uses to reach this app.
|
||||
// Apple's CoreDevice tunnel uses fd-prefixed ULAs like
|
||||
// fd72:8347:2ead::1 (Mac-facing) and fd72:8347:2ead::2
|
||||
// (device-facing). We accept the entire ULA range since
|
||||
// the prefix is regenerated per session.
|
||||
let bytes = addr.rawValue
|
||||
if bytes.count >= 1 && (bytes[0] & 0xFE) == 0xFC {
|
||||
// RFC 4193 ULA range (fc00::/7) — fc* or fd* prefix.
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case .name(let name, _):
|
||||
return name == "localhost"
|
||||
@unknown default: return false
|
||||
}
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Request handling
|
||||
|
||||
private func handle(_ connection: NWConnection) {
|
||||
connection.start(queue: .global(qos: .userInitiated))
|
||||
receive(connection: connection, buffer: Data())
|
||||
}
|
||||
|
||||
private static let maxBodyBytes = 1_048_576 // 1MB hard cap
|
||||
|
||||
private func receive(connection: NWConnection, buffer: Data) {
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { [weak self] data, _, isComplete, error in
|
||||
guard let self else { return }
|
||||
Task { @MainActor in
|
||||
var current = buffer
|
||||
if let data = data { current.append(data) }
|
||||
if current.count > Self.maxBodyBytes {
|
||||
self.send(connection: connection, status: 413, body: ["error": "body_too_large"])
|
||||
return
|
||||
}
|
||||
if let req = self.tryParseRequest(current) {
|
||||
self.route(connection: connection, request: req)
|
||||
} else if isComplete || error != nil {
|
||||
self.send(connection: connection, status: 400, body: ["error": "bad_request"])
|
||||
} else {
|
||||
self.receive(connection: connection, buffer: current)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ParsedRequest {
|
||||
let method: String
|
||||
let path: String
|
||||
let headers: [String: String]
|
||||
let body: Data
|
||||
}
|
||||
|
||||
private func tryParseRequest(_ data: Data) -> ParsedRequest? {
|
||||
guard let headerEnd = data.range(of: Data("\r\n\r\n".utf8)) else { return nil }
|
||||
let headerData = data.subdata(in: 0..<headerEnd.lowerBound)
|
||||
let body = data.subdata(in: headerEnd.upperBound..<data.count)
|
||||
guard let headerStr = String(data: headerData, encoding: .utf8) else { return nil }
|
||||
let lines = headerStr.components(separatedBy: "\r\n")
|
||||
guard let requestLine = lines.first else { return nil }
|
||||
let parts = requestLine.components(separatedBy: " ")
|
||||
guard parts.count >= 2 else { return nil }
|
||||
|
||||
var headers: [String: String] = [:]
|
||||
for line in lines.dropFirst() {
|
||||
guard let colon = line.firstIndex(of: ":") else { continue }
|
||||
let key = String(line[..<colon]).lowercased()
|
||||
let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
|
||||
headers[key] = value
|
||||
}
|
||||
|
||||
if let lenStr = headers["content-length"], let len = Int(lenStr), body.count < len {
|
||||
return nil // need more bytes
|
||||
}
|
||||
return ParsedRequest(method: parts[0], path: parts[1], headers: headers, body: body)
|
||||
}
|
||||
|
||||
private func route(connection: NWConnection, request: ParsedRequest) {
|
||||
// Update display attribution from header (display only — never trusted
|
||||
// for auth).
|
||||
if let agent = request.headers["x-agent-identity"], !agent.isEmpty, agent.count < 200 {
|
||||
lastAgentIdentity = agent
|
||||
}
|
||||
|
||||
let path = request.path
|
||||
|
||||
// 1. Public on loopback: /healthz.
|
||||
if request.method == "GET" && path == "/healthz" {
|
||||
send(connection: connection, status: 200, body: [
|
||||
"version": "1.0.0",
|
||||
"build": appBuildId,
|
||||
"accessor_hash": accessorHash,
|
||||
])
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Auth bootstrap: /auth/rotate is the ONLY endpoint that accepts the
|
||||
// boot token. Everything else requires the rotated token.
|
||||
if request.method == "POST" && path == "/auth/rotate" {
|
||||
handleAuthRotate(connection: connection, request: request)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. All other endpoints require Bearer auth with the rotated token.
|
||||
guard authorize(request: request) else {
|
||||
send(connection: connection, status: 401, body: ["error": "unauthorized"])
|
||||
return
|
||||
}
|
||||
|
||||
switch (request.method, path) {
|
||||
case ("POST", "/session/acquire"): handleSessionAcquire(connection: connection)
|
||||
case ("POST", "/session/release"): handleSessionRelease(connection: connection)
|
||||
case ("POST", "/session/heartbeat"): handleSessionHeartbeat(connection: connection, request: request)
|
||||
case ("GET", "/state/snapshot"): handleSnapshotGet(connection: connection)
|
||||
case ("POST", "/state/restore"): handleSnapshotRestore(connection: connection, request: request)
|
||||
case ("GET", "/elements"): handleElements(connection: connection)
|
||||
case ("GET", "/screenshot"): handleScreenshot(connection: connection)
|
||||
case ("POST", "/tap"): handleMutation(connection: connection, request: request, op: "tap")
|
||||
case ("POST", "/swipe"): handleMutation(connection: connection, request: request, op: "swipe")
|
||||
case ("POST", "/type"): handleMutation(connection: connection, request: request, op: "type")
|
||||
case ("GET", let p) where p.hasPrefix("/state/"):
|
||||
let key = String(p.dropFirst("/state/".count))
|
||||
handleStateGet(connection: connection, key: key)
|
||||
case ("POST", let p) where p.hasPrefix("/state/"):
|
||||
let key = String(p.dropFirst("/state/".count))
|
||||
handleStateWrite(connection: connection, request: request, key: key)
|
||||
default:
|
||||
send(connection: connection, status: 404, body: ["error": "not_found", "path": path])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Auth
|
||||
|
||||
private func authorize(request: ParsedRequest) -> Bool {
|
||||
guard let auth = request.headers["authorization"], auth.hasPrefix("Bearer ") else { return false }
|
||||
let token = String(auth.dropFirst("Bearer ".count))
|
||||
return token == rotatedToken
|
||||
}
|
||||
|
||||
private func handleAuthRotate(connection: NWConnection, request: ParsedRequest) {
|
||||
// Validate boot token (still alive AND used only once).
|
||||
guard bootTokenValid,
|
||||
let auth = request.headers["authorization"],
|
||||
auth.hasPrefix("Bearer "),
|
||||
String(auth.dropFirst("Bearer ".count)) == bootToken else {
|
||||
send(connection: connection, status: 401, body: ["error": "boot_token_invalid"])
|
||||
return
|
||||
}
|
||||
|
||||
guard let dict = try? JSONSerialization.jsonObject(with: request.body) as? JSONDict,
|
||||
let newToken = dict["new_token"] as? String,
|
||||
newToken.count >= 16 else {
|
||||
send(connection: connection, status: 400, body: ["error": "invalid_rotate_payload"])
|
||||
return
|
||||
}
|
||||
|
||||
rotatedToken = newToken
|
||||
bootTokenValid = false
|
||||
// Best-effort scrub of on-disk boot token file.
|
||||
try? FileManager.default.removeItem(atPath: bootTokenPath)
|
||||
|
||||
logger.notice("Boot token rotated; original now invalid")
|
||||
send(connection: connection, status: 200, body: ["ok": true])
|
||||
}
|
||||
|
||||
// MARK: Session lock
|
||||
|
||||
private static let mutatingPaths: Set<String> = ["/tap", "/swipe", "/type", "/state/restore"]
|
||||
|
||||
private func mutatingPathRequiresSession(_ path: String, method: String) -> Bool {
|
||||
if method != "POST" { return false }
|
||||
if path.hasPrefix("/state/") && path != "/state/restore" { return true } // /state/<key> writes
|
||||
return Self.mutatingPaths.contains(path)
|
||||
}
|
||||
|
||||
private func requireSession(in request: ParsedRequest, connection: NWConnection) -> Bool {
|
||||
guard let id = request.headers["x-session-id"] else {
|
||||
send(connection: connection, status: 409, body: ["error": "session_required"])
|
||||
return false
|
||||
}
|
||||
guard let current = activeSession, current.id == id else {
|
||||
send(connection: connection, status: 409, body: ["error": "session_invalid_or_expired"])
|
||||
return false
|
||||
}
|
||||
// Mutation slides the lock; reads do not.
|
||||
activeSession?.lastMutationAt = Date()
|
||||
return true
|
||||
}
|
||||
|
||||
private func handleSessionAcquire(connection: NWConnection) {
|
||||
// Reap orphaned session.
|
||||
if let s = activeSession, Date().timeIntervalSince(s.lastMutationAt) > sessionTtlSeconds {
|
||||
activeSession = nil
|
||||
}
|
||||
if activeSession != nil {
|
||||
send(connection: connection, status: 423, body: ["error": "device_locked"])
|
||||
return
|
||||
}
|
||||
let id = UUID().uuidString
|
||||
activeSession = Session(id: id, lastMutationAt: Date())
|
||||
send(connection: connection, status: 200, body: [
|
||||
"session_id": id,
|
||||
"ttl_seconds": Int(sessionTtlSeconds),
|
||||
])
|
||||
}
|
||||
|
||||
private func handleSessionRelease(connection: NWConnection) {
|
||||
activeSession = nil
|
||||
send(connection: connection, status: 200, body: ["ok": true])
|
||||
}
|
||||
|
||||
private func handleSessionHeartbeat(connection: NWConnection, request: ParsedRequest) {
|
||||
guard let id = request.headers["x-session-id"],
|
||||
activeSession?.id == id else {
|
||||
send(connection: connection, status: 409, body: ["error": "session_invalid_or_expired"])
|
||||
return
|
||||
}
|
||||
activeSession?.lastMutationAt = Date()
|
||||
send(connection: connection, status: 200, body: ["ok": true, "ttl_seconds": Int(sessionTtlSeconds)])
|
||||
}
|
||||
|
||||
// MARK: State handlers
|
||||
|
||||
private func handleStateGet(connection: NWConnection, key: String) {
|
||||
guard let handler = readHandlers[key] else {
|
||||
send(connection: connection, status: 404, body: ["error": "unknown_key", "key": key])
|
||||
return
|
||||
}
|
||||
let value = handler() ?? NSNull()
|
||||
send(connection: connection, status: 200, body: ["key": key, "value": value])
|
||||
}
|
||||
|
||||
private func handleStateWrite(connection: NWConnection, request: ParsedRequest, key: String) {
|
||||
guard requireSession(in: request, connection: connection) else { return }
|
||||
guard let handler = writeHandlers[key] else {
|
||||
send(connection: connection, status: 404, body: ["error": "unknown_key", "key": key])
|
||||
return
|
||||
}
|
||||
guard let payload = try? JSONSerialization.jsonObject(with: request.body) as? JSONDict,
|
||||
let value = payload["value"] else {
|
||||
send(connection: connection, status: 400, body: ["error": "missing_value"])
|
||||
return
|
||||
}
|
||||
let ok = handler(value)
|
||||
if ok {
|
||||
send(connection: connection, status: 200, body: ["ok": true])
|
||||
} else {
|
||||
send(connection: connection, status: 400, body: ["error": "type_mismatch", "expected": typeNames[key] ?? "?"])
|
||||
}
|
||||
}
|
||||
|
||||
private func handleSnapshotGet(connection: NWConnection) {
|
||||
var keys: JSONDict = [:]
|
||||
for (k, read) in readHandlers {
|
||||
keys[k] = read() ?? NSNull()
|
||||
}
|
||||
let envelope: JSONDict = [
|
||||
"_schema_version": 1,
|
||||
"_app_build_id": appBuildId,
|
||||
"_accessor_hash": accessorHash,
|
||||
"keys": keys,
|
||||
]
|
||||
send(connection: connection, status: 200, body: envelope)
|
||||
}
|
||||
|
||||
private func handleSnapshotRestore(connection: NWConnection, request: ParsedRequest) {
|
||||
guard requireSession(in: request, connection: connection) else { return }
|
||||
guard let envelope = try? JSONSerialization.jsonObject(with: request.body) as? JSONDict else {
|
||||
send(connection: connection, status: 400, body: ["error": "invalid_json"])
|
||||
return
|
||||
}
|
||||
// Schema gate.
|
||||
if let hash = envelope["_accessor_hash"] as? String, hash != accessorHash {
|
||||
send(connection: connection, status: 409, body: [
|
||||
"error": "schema_mismatch",
|
||||
"expected_hash": accessorHash,
|
||||
"got_hash": hash,
|
||||
])
|
||||
return
|
||||
}
|
||||
guard let keys = envelope["keys"] as? JSONDict else {
|
||||
send(connection: connection, status: 400, body: ["error": "missing_keys"])
|
||||
return
|
||||
}
|
||||
guard let restore = atomicRestore else {
|
||||
send(connection: connection, status: 503, body: ["error": "atomic_restore_not_registered"])
|
||||
return
|
||||
}
|
||||
// Validate-then-apply via the codegen-supplied closure. The closure does
|
||||
// a single struct-assignment so SwiftUI sees one change notification.
|
||||
switch restore(keys) {
|
||||
case .ok:
|
||||
send(connection: connection, status: 200, body: ["ok": true])
|
||||
case .missingKey(let k):
|
||||
send(connection: connection, status: 400, body: ["error": "validation_failed", "key": k, "reason": "missing"])
|
||||
case .typeMismatch(let k):
|
||||
send(connection: connection, status: 400, body: ["error": "validation_failed", "key": k, "reason": "type-mismatch"])
|
||||
case .schemaMismatch(let expected, let got):
|
||||
send(connection: connection, status: 409, body: ["error": "schema_mismatch", "expected_hash": expected, "got_hash": got])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Stubs (real impls live in DebugBridgeManager + UIKit)
|
||||
|
||||
private func handleElements(connection: NWConnection) {
|
||||
let tree = ElementsBridge.snapshot()
|
||||
send(connection: connection, status: 200, body: ["elements": tree])
|
||||
}
|
||||
|
||||
private func handleScreenshot(connection: NWConnection) {
|
||||
if let png = ScreenshotBridge.capturePNG() {
|
||||
send(connection: connection, status: 200, body: ["png_base64": png.base64EncodedString()])
|
||||
} else {
|
||||
send(connection: connection, status: 500, body: ["error": "screenshot_unavailable"])
|
||||
}
|
||||
}
|
||||
|
||||
private func handleMutation(connection: NWConnection, request: ParsedRequest, op: String) {
|
||||
guard requireSession(in: request, connection: connection) else { return }
|
||||
guard let payload = try? JSONSerialization.jsonObject(with: request.body) as? JSONDict else {
|
||||
send(connection: connection, status: 400, body: ["error": "invalid_json"])
|
||||
return
|
||||
}
|
||||
let ok = MutationBridge.dispatch(op: op, payload: payload)
|
||||
send(connection: connection, status: ok ? 200 : 400, body: ["op": op, "ok": ok])
|
||||
}
|
||||
|
||||
// MARK: Response
|
||||
|
||||
private func send(connection: NWConnection, status: Int, body: JSONDict) {
|
||||
let json = (try? JSONSerialization.data(withJSONObject: body)) ?? Data("{}".utf8)
|
||||
let statusText: String
|
||||
switch status {
|
||||
case 200: statusText = "OK"
|
||||
case 400: statusText = "Bad Request"
|
||||
case 401: statusText = "Unauthorized"
|
||||
case 404: statusText = "Not Found"
|
||||
case 409: statusText = "Conflict"
|
||||
case 413: statusText = "Payload Too Large"
|
||||
case 423: statusText = "Locked"
|
||||
case 429: statusText = "Too Many Requests"
|
||||
case 500: statusText = "Internal Server Error"
|
||||
case 503: statusText = "Service Unavailable"
|
||||
default: statusText = "Status"
|
||||
}
|
||||
let header = "HTTP/1.1 \(status) \(statusText)\r\nContent-Type: application/json\r\nContent-Length: \(json.count)\r\nConnection: close\r\n\r\n"
|
||||
var packet = Data(header.utf8)
|
||||
packet.append(json)
|
||||
connection.send(content: packet, completion: .contentProcessed { _ in
|
||||
connection.cancel()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Bridges (implementation provided by DebugBridgeManager)
|
||||
|
||||
@MainActor
|
||||
public enum ElementsBridge {
|
||||
public static var resolver: () -> [JSONDict] = { [] }
|
||||
static func snapshot() -> [JSONDict] { resolver() }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public enum ScreenshotBridge {
|
||||
public static var resolver: () -> Data? = { nil }
|
||||
static func capturePNG() -> Data? { resolver() }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public enum MutationBridge {
|
||||
public static var resolver: (String, JSONDict) -> Bool = { _, _ in false }
|
||||
static func dispatch(op: String, payload: JSONDict) -> Bool { resolver(op, payload) }
|
||||
}
|
||||
|
||||
#endif // DEBUG
|
||||
@@ -0,0 +1,61 @@
|
||||
# TODOS.md Format Reference
|
||||
|
||||
Shared reference for the canonical TODOS.md format. Referenced by `/ship` (Step 5.5) and `/plan-ceo-review` (TODOS.md updates section) to ensure consistent TODO item structure.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
```markdown
|
||||
# TODOS
|
||||
|
||||
## <Skill/Component> ← e.g., ## Browse, ## Ship, ## Review, ## Infrastructure
|
||||
<items sorted P0 first, then P1, P2, P3, P4>
|
||||
|
||||
## Completed
|
||||
<finished items with completion annotation>
|
||||
```
|
||||
|
||||
**Sections:** Organize by skill or component (`## Browse`, `## Ship`, `## Review`, `## QA`, `## Retro`, `## Infrastructure`). Within each section, sort items by priority (P0 at top).
|
||||
|
||||
---
|
||||
|
||||
## TODO Item Format
|
||||
|
||||
Each item is an H3 under its section:
|
||||
|
||||
```markdown
|
||||
### <Title>
|
||||
|
||||
**What:** One-line description of the work.
|
||||
|
||||
**Why:** The concrete problem it solves or value it unlocks.
|
||||
|
||||
**Context:** Enough detail that someone picking this up in 3 months understands the motivation, the current state, and where to start.
|
||||
|
||||
**Effort:** S / M / L / XL
|
||||
**Priority:** P0 / P1 / P2 / P3 / P4
|
||||
**Depends on:** <prerequisites, or "None">
|
||||
```
|
||||
|
||||
**Required fields:** What, Why, Context, Effort, Priority
|
||||
**Optional fields:** Depends on, Blocked by
|
||||
|
||||
---
|
||||
|
||||
## Priority Definitions
|
||||
|
||||
- **P0** — Blocking: must be done before next release
|
||||
- **P1** — Critical: should be done this cycle
|
||||
- **P2** — Important: do when P0/P1 are clear
|
||||
- **P3** — Nice-to-have: revisit after adoption/usage data
|
||||
- **P4** — Someday: good idea, no urgency
|
||||
|
||||
---
|
||||
|
||||
## Completed Item Format
|
||||
|
||||
When an item is completed, move it to the `## Completed` section preserving its original content and appending:
|
||||
|
||||
```markdown
|
||||
**Completed:** vX.Y.Z (YYYY-MM-DD)
|
||||
@@ -0,0 +1,187 @@
|
||||
# Pre-Landing Review Checklist
|
||||
|
||||
## Instructions
|
||||
|
||||
Review the `git diff origin/main` output for the issues listed below. Be specific — cite `file:line` and suggest fixes. Skip anything that's fine. Only flag real problems.
|
||||
|
||||
**Two-pass review:**
|
||||
- **Pass 1 (CRITICAL):** Run SQL & Data Safety, Race Conditions, LLM Output Trust Boundary, Shell Injection, and Enum Completeness first. Highest severity.
|
||||
- **Pass 2 (INFORMATIONAL):** Run remaining categories below. Lower severity but still actioned.
|
||||
- **Specialist categories (handled by parallel subagents, NOT this checklist):** Test Gaps, Dead Code, Magic Numbers, Conditional Side Effects, Performance & Bundle Impact, Crypto & Entropy. See `review/specialists/` for these.
|
||||
|
||||
All findings get action via Fix-First Review: obvious mechanical fixes are applied automatically,
|
||||
genuinely ambiguous issues are batched into a single user question.
|
||||
|
||||
**Output format:**
|
||||
|
||||
```
|
||||
Pre-Landing Review: N issues (X critical, Y informational)
|
||||
|
||||
**AUTO-FIXED:**
|
||||
- [file:line] Problem → fix applied
|
||||
|
||||
**NEEDS INPUT:**
|
||||
- [file:line] Problem description
|
||||
Recommended fix: suggested fix
|
||||
```
|
||||
|
||||
If no issues found: `Pre-Landing Review: No issues found.`
|
||||
|
||||
Be terse. For each issue: one line describing the problem, one line with the fix. No preamble, no summaries, no "looks good overall."
|
||||
|
||||
---
|
||||
|
||||
## Review Categories
|
||||
|
||||
### Pass 1 — CRITICAL
|
||||
|
||||
#### SQL & Data Safety
|
||||
- String interpolation in SQL (even if values are `.to_i`/`.to_f` — use parameterized queries (Rails: sanitize_sql_array/Arel; Node: prepared statements; Python: parameterized queries))
|
||||
- TOCTOU races: check-then-set patterns that should be atomic `WHERE` + `update_all`
|
||||
- Bypassing model validations for direct DB writes (Rails: update_column; Django: QuerySet.update(); Prisma: raw queries)
|
||||
- N+1 queries: Missing eager loading (Rails: .includes(); SQLAlchemy: joinedload(); Prisma: include) for associations used in loops/views
|
||||
|
||||
#### Race Conditions & Concurrency
|
||||
- Read-check-write without uniqueness constraint or catch duplicate key error and retry (e.g., `where(hash:).first` then `save!` without handling concurrent insert)
|
||||
- find-or-create without unique DB index — concurrent calls can create duplicates
|
||||
- Status transitions that don't use atomic `WHERE old_status = ? UPDATE SET new_status` — concurrent updates can skip or double-apply transitions
|
||||
- Unsafe HTML rendering (Rails: .html_safe/raw(); React: dangerouslySetInnerHTML; Vue: v-html; Django: |safe/mark_safe) on user-controlled data (XSS)
|
||||
|
||||
#### LLM Output Trust Boundary
|
||||
- LLM-generated values (emails, URLs, names) written to DB or passed to mailers without format validation. Add lightweight guards (`EMAIL_REGEXP`, `URI.parse`, `.strip`) before persisting.
|
||||
- Structured tool output (arrays, hashes) accepted without type/shape checks before database writes.
|
||||
- LLM-generated URLs fetched without allowlist — SSRF risk if URL points to internal network (Python: `urllib.parse.urlparse` → check hostname against blocklist before `requests.get`/`httpx.get`)
|
||||
- LLM output stored in knowledge bases or vector DBs without sanitization — stored prompt injection risk
|
||||
|
||||
#### Shell Injection (Python-specific)
|
||||
- `subprocess.run()` / `subprocess.call()` / `subprocess.Popen()` with `shell=True` AND f-string/`.format()` interpolation in the command string — use argument arrays instead
|
||||
- `os.system()` with variable interpolation — replace with `subprocess.run()` using argument arrays
|
||||
- `eval()` / `exec()` on LLM-generated code without sandboxing
|
||||
|
||||
#### Enum & Value Completeness
|
||||
When the diff introduces a new enum value, status string, tier name, or type constant — OR loosens what an input accepts (a newly-accepted MIME type, file extension, or flag; a widened validator/parser/guard):
|
||||
- **Trace it through every consumer.** Read (don't just grep — READ) each file that switches on, filters by, or displays that value. If any consumer doesn't handle the new value, flag it. Common miss: adding a value to the frontend dropdown but the backend model/compute method doesn't persist it.
|
||||
- **Check allowlists/filter arrays.** Search for arrays or `%w[]` lists containing sibling values (e.g., if adding "revise" to tiers, find every `%w[quick lfg mega]` and verify "revise" is included where needed).
|
||||
- **Check `case`/`if-elsif` chains.** If existing code branches on the enum, does the new value fall through to a wrong default?
|
||||
- **Loosened acceptance breaks UNCHANGED consumers.** Widening what one function accepts often breaks a different, unchanged function downstream — which never appears in the diff. When a guard/validator/parser starts accepting a new shape, grep every consumer of that same field (MIME type, extension, status, flag) and confirm each handles it. Real miss: a client `isPdfFile` was loosened to accept a typeless `.pdf`, but the unchanged submit-path `updateFileMimeType` still forced every typeless file to `text/plain` — the PDF was sent as garbage text, not natively.
|
||||
To do this: use Grep to find all references to the sibling values (e.g., grep for "lfg" or "mega" to find all tier consumers). Read each match. This step requires reading code OUTSIDE the diff.
|
||||
|
||||
### Pass 2 — INFORMATIONAL
|
||||
|
||||
#### Async/Sync Mixing (Python-specific)
|
||||
- Synchronous `subprocess.run()`, `open()`, `requests.get()` inside `async def` endpoints — blocks the event loop. Use `asyncio.to_thread()`, `aiofiles`, or `httpx.AsyncClient` instead.
|
||||
- `time.sleep()` inside async functions — use `asyncio.sleep()`
|
||||
- Sync DB calls in async context without `run_in_executor()` wrapping
|
||||
|
||||
#### Column/Field Name Safety
|
||||
- Verify column names in ORM queries (`.select()`, `.eq()`, `.gte()`, `.order()`) against actual DB schema — wrong column names silently return empty results or throw swallowed errors
|
||||
- Check `.get()` calls on query results use the column name that was actually selected
|
||||
- Cross-reference with schema documentation when available
|
||||
|
||||
#### Dead Code & Consistency (version/changelog only — other items handled by maintainability specialist)
|
||||
- Version mismatch between PR title and VERSION/CHANGELOG files
|
||||
- CHANGELOG entries that describe changes inaccurately (e.g., "changed from X to Y" when X never existed)
|
||||
|
||||
#### Stale User-Facing Strings
|
||||
When the diff changes the CONDITION that guards a user-facing string (error message, toast, label, confirmation) WITHOUT changing the string itself, re-read the string — it can silently become misleading.
|
||||
- A message describing "all files" still says so after the logic starts counting only *some* of them (real miss: a "Total file size exceeds…" message that, after the change, sums only the non-PDF files).
|
||||
- This is stale-comment / CHANGELOG review applied to in-code copy: the string is unchanged, so a diff-scoped pass skims right past it.
|
||||
|
||||
#### LLM Prompt Issues
|
||||
- 0-indexed lists in prompts (LLMs reliably return 1-indexed)
|
||||
- Prompt text listing available tools/capabilities that don't match what's actually wired up in the `tool_classes`/`tools` array
|
||||
- Word/token limits stated in multiple places that could drift
|
||||
|
||||
#### Completeness Gaps
|
||||
- Shortcut implementations where the complete version would cost <30 minutes CC time (e.g., partial enum handling, incomplete error paths, missing edge cases that are straightforward to add)
|
||||
- Options presented with only human-team effort estimates — should show both human and CC+gstack time
|
||||
- Test coverage gaps where adding the missing tests is a "lake" not an "ocean" (e.g., missing negative-path tests, missing edge case tests that mirror happy-path structure)
|
||||
- Features implemented at 80-90% when 100% is achievable with modest additional code
|
||||
|
||||
#### Time Window Safety
|
||||
- Date-key lookups that assume "today" covers 24h — report at 8am PT only sees midnight→8am under today's key
|
||||
- Mismatched time windows between related features — one uses hourly buckets, another uses daily keys for the same data
|
||||
|
||||
#### Type Coercion at Boundaries
|
||||
- Values crossing Ruby→JSON→JS boundaries where type could change (numeric vs string) — hash/digest inputs must normalize types
|
||||
- Hash/digest inputs that don't call `.to_s` or equivalent before serialization — `{ cores: 8 }` vs `{ cores: "8" }` produce different hashes
|
||||
|
||||
#### View/Frontend
|
||||
- Inline `<style>` blocks in partials (re-parsed every render)
|
||||
- O(n*m) lookups in views (`Array#find` in a loop instead of `index_by` hash)
|
||||
- Ruby-side `.select{}` filtering on DB results that could be a `WHERE` clause (unless intentionally avoiding leading-wildcard `LIKE`)
|
||||
|
||||
#### Distribution & CI/CD Pipeline
|
||||
- CI/CD workflow changes (`.github/workflows/`): verify build tool versions match project requirements, artifact names/paths are correct, secrets use `${{ secrets.X }}` not hardcoded values
|
||||
- New artifact types (CLI binary, library, package): verify a publish/release workflow exists and targets correct platforms
|
||||
- Cross-platform builds: verify CI matrix covers all target OS/arch combinations, or documents which are untested
|
||||
- Version tag format consistency: `v1.2.3` vs `1.2.3` — must match across VERSION file, git tags, and publish scripts
|
||||
- Publish step idempotency: re-running the publish workflow should not fail (e.g., `gh release delete` before `gh release create`)
|
||||
|
||||
**DO NOT flag:**
|
||||
- Web services with existing auto-deploy pipelines (Docker build + K8s deploy)
|
||||
- Internal tools not distributed outside the team
|
||||
- Test-only CI changes (adding test steps, not publish steps)
|
||||
|
||||
---
|
||||
|
||||
## Severity Classification
|
||||
|
||||
```
|
||||
CRITICAL (highest severity): INFORMATIONAL (main agent): SPECIALIST (parallel subagents):
|
||||
├─ SQL & Data Safety ├─ Async/Sync Mixing ├─ Testing specialist
|
||||
├─ Race Conditions & Concurrency ├─ Column/Field Name Safety ├─ Maintainability specialist
|
||||
├─ LLM Output Trust Boundary ├─ Dead Code (version only) ├─ Security specialist
|
||||
├─ Shell Injection ├─ LLM Prompt Issues ├─ Performance specialist
|
||||
└─ Enum & Value Completeness ├─ Completeness Gaps ├─ Data Migration specialist
|
||||
├─ Time Window Safety ├─ API Contract specialist
|
||||
├─ Type Coercion at Boundaries └─ Red Team (conditional)
|
||||
├─ View/Frontend
|
||||
├─ Stale User-Facing Strings
|
||||
└─ Distribution & CI/CD Pipeline
|
||||
|
||||
All findings are actioned via Fix-First Review. Severity determines
|
||||
presentation order and classification of AUTO-FIX vs ASK — critical
|
||||
findings lean toward ASK (they're riskier), informational findings
|
||||
lean toward AUTO-FIX (they're more mechanical).
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fix-First Heuristic
|
||||
|
||||
This heuristic is referenced by both `/review` and `/ship`. It determines whether
|
||||
the agent auto-fixes a finding or asks the user.
|
||||
|
||||
```
|
||||
AUTO-FIX (agent fixes without asking): ASK (needs human judgment):
|
||||
├─ Dead code / unused variables ├─ Security (auth, XSS, injection)
|
||||
├─ N+1 queries (missing eager loading) ├─ Race conditions
|
||||
├─ Stale comments contradicting code ├─ Design decisions
|
||||
├─ Magic numbers → named constants ├─ Large fixes (>20 lines)
|
||||
├─ Missing LLM output validation ├─ Enum completeness
|
||||
├─ Version/path mismatches ├─ Removing functionality
|
||||
├─ Variables assigned but never read └─ Anything changing user-visible
|
||||
└─ Inline styles, O(n*m) view lookups behavior
|
||||
```
|
||||
|
||||
**Rule of thumb:** If the fix is mechanical and a senior engineer would apply it
|
||||
without discussion, it's AUTO-FIX. If reasonable engineers could disagree about
|
||||
the fix, it's ASK.
|
||||
|
||||
**Critical findings default toward ASK** (they're inherently riskier).
|
||||
**Informational findings default toward AUTO-FIX** (they're more mechanical).
|
||||
|
||||
---
|
||||
|
||||
## Suppressions — DO NOT flag these
|
||||
|
||||
- "X is redundant with Y" when the redundancy is harmless and aids readability (e.g., `present?` redundant with `length > 20`)
|
||||
- "Add a comment explaining why this threshold/constant was chosen" — thresholds change during tuning, comments rot
|
||||
- "This assertion could be tighter" when the assertion already covers the behavior
|
||||
- Suggesting consistency-only changes (wrapping a value in a conditional to match how another constant is guarded)
|
||||
- "Regex doesn't handle edge case X" when the input is constrained and X never occurs in practice
|
||||
- "Test exercises multiple guards simultaneously" — that's fine, tests don't need to isolate every guard
|
||||
- Eval threshold changes (max_actionable, min scores) — these are tuned empirically and change constantly
|
||||
- Harmless no-ops (e.g., `.reject` on an element that's never in the array)
|
||||
- ANYTHING already addressed in the diff you're reviewing — read the FULL diff before commenting
|
||||
@@ -0,0 +1,134 @@
|
||||
# Design Review Checklist (Lite)
|
||||
|
||||
> **Subset of DESIGN_METHODOLOGY** — when adding items here, also update `generateDesignMethodology()` in `scripts/gen-skill-docs.ts`, and vice versa.
|
||||
|
||||
## Instructions
|
||||
|
||||
This checklist applies to **source code in the diff** — not rendered output. Read each changed frontend file (full file, not just diff hunks) and flag anti-patterns.
|
||||
|
||||
**Trigger:** Only run this checklist if the diff touches frontend files. Use `gstack-diff-scope` to detect:
|
||||
|
||||
```bash
|
||||
source <(${GSTACK_HOME:-$HOME/.gstack}/bin/gstack-diff-scope <base> 2>/dev/null)
|
||||
```
|
||||
|
||||
If `SCOPE_FRONTEND=false`, skip the entire design review silently.
|
||||
|
||||
**DESIGN.md calibration:** If `DESIGN.md` or `design-system.md` exists in the repo root, read it first. All findings are calibrated against the project's stated design system. Patterns explicitly blessed in DESIGN.md are NOT flagged. If no DESIGN.md exists, use universal design principles.
|
||||
|
||||
---
|
||||
|
||||
## Confidence Tiers
|
||||
|
||||
Each item is tagged with a detection confidence level:
|
||||
|
||||
- **[HIGH]** — Reliably detectable via grep/pattern match. Definitive findings.
|
||||
- **[MEDIUM]** — Detectable via pattern aggregation or heuristic. Flag as findings but expect some noise.
|
||||
- **[LOW]** — Requires understanding visual intent. Present as: "Possible issue — verify visually or run /design-review."
|
||||
|
||||
---
|
||||
|
||||
## Classification
|
||||
|
||||
**AUTO-FIX** (mechanical CSS fixes only — HIGH confidence, no design judgment needed):
|
||||
- `outline: none` without replacement → add `outline: revert` or `&:focus-visible { outline: 2px solid currentColor; }`
|
||||
- `!important` in new CSS → remove and fix specificity
|
||||
- `font-size` < 16px on body text → bump to 16px
|
||||
|
||||
**ASK** (everything else — requires design judgment):
|
||||
- All AI slop findings, typography structure, spacing choices, interaction state gaps, DESIGN.md violations
|
||||
|
||||
**LOW confidence items** → present as "Possible: [description]. Verify visually or run /design-review." Never AUTO-FIX.
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
Design Review: N issues (X auto-fixable, Y need input, Z possible)
|
||||
|
||||
**AUTO-FIXED:**
|
||||
- [file:line] Problem → fix applied
|
||||
|
||||
**NEEDS INPUT:**
|
||||
- [file:line] Problem description
|
||||
Recommended fix: suggested fix
|
||||
|
||||
**POSSIBLE (verify visually):**
|
||||
- [file:line] Possible issue — verify with /design-review
|
||||
```
|
||||
|
||||
Optional: `test_stub` — skeleton test code for this finding using the project's test framework.
|
||||
|
||||
If no issues found: `Design Review: No issues found.`
|
||||
|
||||
If no frontend files changed: skip silently, no output.
|
||||
|
||||
---
|
||||
|
||||
## Categories
|
||||
|
||||
### 1. AI Slop Detection (6 items) — highest priority
|
||||
|
||||
These are the telltale signs of AI-generated UI that no designer at a respected studio would ship.
|
||||
|
||||
- **[MEDIUM]** Purple/violet/indigo gradient backgrounds or blue-to-purple color schemes. Look for `linear-gradient` with values in the `#6366f1`–`#8b5cf6` range, or CSS custom properties resolving to purple/violet.
|
||||
|
||||
- **[LOW]** The 3-column feature grid: icon-in-colored-circle + bold title + 2-line description, repeated 3x symmetrically. Look for a grid/flex container with exactly 3 children that each contain a circular element + heading + paragraph.
|
||||
|
||||
- **[LOW]** Icons in colored circles as section decoration. Look for elements with `border-radius: 50%` + a background color used as decorative containers for icons.
|
||||
|
||||
- **[HIGH]** Centered everything: `text-align: center` on all headings, descriptions, and cards. Grep for `text-align: center` density — if >60% of text containers use center alignment, flag it.
|
||||
|
||||
- **[MEDIUM]** Uniform bubbly border-radius on every element: same large radius (16px+) applied to cards, buttons, inputs, containers uniformly. Aggregate `border-radius` values — if >80% use the same value ≥16px, flag it.
|
||||
|
||||
- **[MEDIUM]** Generic hero copy: "Welcome to [X]", "Unlock the power of...", "Your all-in-one solution for...", "Revolutionize your...", "Streamline your workflow". Grep HTML/JSX content for these patterns.
|
||||
|
||||
### 2. Typography (4 items)
|
||||
|
||||
- **[HIGH]** Body text `font-size` < 16px. Grep for `font-size` declarations on `body`, `p`, `.text`, or base styles. Values below 16px (or 1rem when base is 16px) are flagged.
|
||||
|
||||
- **[HIGH]** More than 3 font families introduced in the diff. Count distinct `font-family` declarations. Flag if >3 unique families appear across changed files.
|
||||
|
||||
- **[HIGH]** Heading hierarchy skipping levels: `h1` followed by `h3` without an `h2` in the same file/component. Check HTML/JSX for heading tags.
|
||||
|
||||
- **[HIGH]** Blacklisted fonts: Papyrus, Comic Sans, Lobster, Impact, Jokerman. Grep `font-family` for these names.
|
||||
|
||||
### 3. Spacing & Layout (4 items)
|
||||
|
||||
- **[MEDIUM]** Arbitrary spacing values not on a 4px or 8px scale, when DESIGN.md specifies a spacing scale. Check `margin`, `padding`, `gap` values against the stated scale. Only flag when DESIGN.md defines a scale.
|
||||
|
||||
- **[MEDIUM]** Fixed widths without responsive handling: `width: NNNpx` on containers without `max-width` or `@media` breakpoints. Risk of horizontal scroll on mobile.
|
||||
|
||||
- **[MEDIUM]** Missing `max-width` on text containers: body text or paragraph containers with no `max-width` set, allowing lines >75 characters. Check for `max-width` on text wrappers.
|
||||
|
||||
- **[HIGH]** `!important` in new CSS rules. Grep for `!important` in added lines. Almost always a specificity escape hatch that should be fixed properly.
|
||||
|
||||
### 4. Interaction States (3 items)
|
||||
|
||||
- **[MEDIUM]** Interactive elements (buttons, links, inputs) missing hover/focus states. Check if `:hover` and `:focus` or `:focus-visible` pseudo-classes exist for new interactive element styles.
|
||||
|
||||
- **[HIGH]** `outline: none` or `outline: 0` without a replacement focus indicator. Grep for `outline:\s*none` or `outline:\s*0`. This removes keyboard accessibility.
|
||||
|
||||
- **[LOW]** Touch targets < 44px on interactive elements. Check `min-height`/`min-width`/`padding` on buttons and links. Requires computing effective size from multiple properties — low confidence from code alone.
|
||||
|
||||
### 5. DESIGN.md Violations (3 items, conditional)
|
||||
|
||||
Only apply if `DESIGN.md` or `design-system.md` exists:
|
||||
|
||||
- **[MEDIUM]** Colors not in the stated palette. Compare color values in changed CSS against the palette defined in DESIGN.md.
|
||||
|
||||
- **[MEDIUM]** Fonts not in the stated typography section. Compare `font-family` values against DESIGN.md's font list.
|
||||
|
||||
- **[MEDIUM]** Spacing values outside the stated scale. Compare `margin`/`padding`/`gap` values against DESIGN.md's spacing scale.
|
||||
|
||||
---
|
||||
|
||||
## Suppressions
|
||||
|
||||
Do NOT flag:
|
||||
- Patterns explicitly documented in DESIGN.md as intentional choices
|
||||
- Third-party/vendor CSS files (node_modules, vendor directories)
|
||||
- CSS resets or normalize stylesheets
|
||||
- Test fixture files
|
||||
- Generated/minified CSS
|
||||
@@ -0,0 +1,220 @@
|
||||
# Greptile Comment Triage
|
||||
|
||||
Shared reference for fetching, filtering, and classifying Greptile review comments on GitHub PRs. Both `/review` (Step 2.5) and `/ship` (Step 3.75) reference this document.
|
||||
|
||||
---
|
||||
|
||||
## Fetch
|
||||
|
||||
Run these commands to detect the PR and fetch comments. Both API calls run in parallel.
|
||||
|
||||
```bash
|
||||
REPO=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null)
|
||||
PR_NUMBER=$(gh pr view --json number --jq '.number' 2>/dev/null)
|
||||
```
|
||||
|
||||
**If either fails or is empty:** Skip Greptile triage silently. This integration is additive — the workflow works without it.
|
||||
|
||||
```bash
|
||||
# Fetch line-level review comments AND top-level PR comments in parallel
|
||||
gh api repos/$REPO/pulls/$PR_NUMBER/comments \
|
||||
--jq '.[] | select(.user.login == "greptile-apps[bot]") | select(.position != null) | {id: .id, path: .path, line: .line, body: .body, html_url: .html_url, source: "line-level"}' > /tmp/greptile_line.json &
|
||||
gh api repos/$REPO/issues/$PR_NUMBER/comments \
|
||||
--jq '.[] | select(.user.login == "greptile-apps[bot]") | {id: .id, body: .body, html_url: .html_url, source: "top-level"}' > /tmp/greptile_top.json &
|
||||
wait
|
||||
```
|
||||
|
||||
**If API errors or zero Greptile comments across both endpoints:** Skip silently.
|
||||
|
||||
The `position != null` filter on line-level comments automatically skips outdated comments from force-pushed code.
|
||||
|
||||
---
|
||||
|
||||
## Suppressions Check
|
||||
|
||||
Derive the project-specific history path:
|
||||
```bash
|
||||
REMOTE_SLUG=$(${GSTACK_HOME:-$HOME/.gstack}/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")
|
||||
PROJECT_HISTORY="$HOME/.gstack/projects/$REMOTE_SLUG/greptile-history.md"
|
||||
```
|
||||
|
||||
Read `$PROJECT_HISTORY` if it exists (per-project suppressions). Each line records a previous triage outcome:
|
||||
|
||||
```
|
||||
<date> | <repo> | <type:fp|fix|already-fixed> | <file-pattern> | <category>
|
||||
```
|
||||
|
||||
**Categories** (fixed set): `race-condition`, `null-check`, `error-handling`, `style`, `type-safety`, `security`, `performance`, `correctness`, `other`
|
||||
|
||||
Match each fetched comment against entries where:
|
||||
- `type == fp` (only suppress known false positives, not previously fixed real issues)
|
||||
- `repo` matches the current repo
|
||||
- `file-pattern` matches the comment's file path
|
||||
- `category` matches the issue type in the comment
|
||||
|
||||
Skip matched comments as **SUPPRESSED**.
|
||||
|
||||
If the history file doesn't exist or has unparseable lines, skip those lines and continue — never fail on a malformed history file.
|
||||
|
||||
---
|
||||
|
||||
## Classify
|
||||
|
||||
For each non-suppressed comment:
|
||||
|
||||
1. **Line-level comments:** Read the file at the indicated `path:line` and surrounding context (±10 lines)
|
||||
2. **Top-level comments:** Read the full comment body
|
||||
3. Cross-reference the comment against the full diff (`git diff origin/main`) and the review checklist
|
||||
4. Classify:
|
||||
- **VALID & ACTIONABLE** — a real bug, race condition, security issue, or correctness problem that exists in the current code
|
||||
- **VALID BUT ALREADY FIXED** — a real issue that was addressed in a subsequent commit on the branch. Identify the fixing commit SHA.
|
||||
- **FALSE POSITIVE** — the comment misunderstands the code, flags something handled elsewhere, or is stylistic noise
|
||||
- **SUPPRESSED** — already filtered in the suppressions check above
|
||||
|
||||
---
|
||||
|
||||
## Reply APIs
|
||||
|
||||
When replying to Greptile comments, use the correct endpoint based on comment source:
|
||||
|
||||
**Line-level comments** (from `pulls/$PR/comments`):
|
||||
```bash
|
||||
gh api repos/$REPO/pulls/$PR_NUMBER/comments/$COMMENT_ID/replies \
|
||||
-f body="<reply text>"
|
||||
```
|
||||
|
||||
**Top-level comments** (from `issues/$PR/comments`):
|
||||
```bash
|
||||
gh api repos/$REPO/issues/$PR_NUMBER/comments \
|
||||
-f body="<reply text>"
|
||||
```
|
||||
|
||||
**If a reply POST fails** (e.g., PR was closed, no write permission): warn and continue. Do not stop the workflow for a failed reply.
|
||||
|
||||
---
|
||||
|
||||
## Reply Templates
|
||||
|
||||
Use these templates for every Greptile reply. Always include concrete evidence — never post vague replies.
|
||||
|
||||
### Tier 1 (First response) — Friendly, evidence-included
|
||||
|
||||
**For FIXES (user chose to fix the issue):**
|
||||
|
||||
```
|
||||
**Fixed** in `<commit-sha>`.
|
||||
|
||||
\`\`\`diff
|
||||
- <old problematic line(s)>
|
||||
+ <new fixed line(s)>
|
||||
\`\`\`
|
||||
|
||||
**Why:** <1-sentence explanation of what was wrong and how the fix addresses it>
|
||||
```
|
||||
|
||||
**For ALREADY FIXED (issue addressed in a prior commit on the branch):**
|
||||
|
||||
```
|
||||
**Already fixed** in `<commit-sha>`.
|
||||
|
||||
**What was done:** <1-2 sentences describing how the existing commit addresses this issue>
|
||||
```
|
||||
|
||||
**For FALSE POSITIVES (the comment is incorrect):**
|
||||
|
||||
```
|
||||
**Not a bug.** <1 sentence directly stating why this is incorrect>
|
||||
|
||||
**Evidence:**
|
||||
- <specific code reference showing the pattern is safe/correct>
|
||||
- <e.g., "The nil check is handled by `ActiveRecord::FinderMethods#find` which raises RecordNotFound, not nil">
|
||||
|
||||
**Suggested re-rank:** This appears to be a `<style|noise|misread>` issue, not a `<what Greptile called it>`. Consider lowering severity.
|
||||
```
|
||||
|
||||
### Tier 2 (Greptile re-flags after prior reply) — Firm, overwhelming evidence
|
||||
|
||||
Use Tier 2 when escalation detection (below) identifies a prior GStack reply on the same thread. Include maximum evidence to close the discussion.
|
||||
|
||||
```
|
||||
**This has been reviewed and confirmed as [intentional/already-fixed/not-a-bug].**
|
||||
|
||||
\`\`\`diff
|
||||
<full relevant diff showing the change or safe pattern>
|
||||
\`\`\`
|
||||
|
||||
**Evidence chain:**
|
||||
1. <file:line permalink showing the safe pattern or fix>
|
||||
2. <commit SHA where it was addressed, if applicable>
|
||||
3. <architecture rationale or design decision, if applicable>
|
||||
|
||||
**Suggested re-rank:** Please recalibrate — this is a `<actual category>` issue, not `<claimed category>`. [Link to specific file change permalink if helpful]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Escalation Detection
|
||||
|
||||
Before composing a reply, check if a prior GStack reply already exists on this comment thread:
|
||||
|
||||
1. **For line-level comments:** Fetch replies via `gh api repos/$REPO/pulls/$PR_NUMBER/comments/$COMMENT_ID/replies`. Check if any reply body contains GStack markers: `**Fixed**`, `**Not a bug.**`, `**Already fixed**`.
|
||||
|
||||
2. **For top-level comments:** Scan the fetched issue comments for replies posted after the Greptile comment that contain GStack markers.
|
||||
|
||||
3. **If a prior GStack reply exists AND Greptile posted again on the same file+category:** Use Tier 2 (firm) templates.
|
||||
|
||||
4. **If no prior GStack reply exists:** Use Tier 1 (friendly) templates.
|
||||
|
||||
If escalation detection fails (API error, ambiguous thread): default to Tier 1. Never escalate on ambiguity.
|
||||
|
||||
---
|
||||
|
||||
## Severity Assessment & Re-ranking
|
||||
|
||||
When classifying comments, also assess whether Greptile's implied severity matches reality:
|
||||
|
||||
- If Greptile flags something as a **security/correctness/race-condition** issue but it's actually a **style/performance** nit: include `**Suggested re-rank:**` in the reply requesting the category be corrected.
|
||||
- If Greptile flags a low-severity style issue as if it were critical: push back in the reply.
|
||||
- Always be specific about why the re-ranking is warranted — cite code and line numbers, not opinions.
|
||||
|
||||
---
|
||||
|
||||
## History File Writes
|
||||
|
||||
Before writing, ensure both directories exist:
|
||||
```bash
|
||||
REMOTE_SLUG=$(${GSTACK_HOME:-$HOME/.gstack}/bin/remote-slug 2>/dev/null || basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)")
|
||||
mkdir -p "$HOME/.gstack/projects/$REMOTE_SLUG"
|
||||
mkdir -p ~/.gstack
|
||||
```
|
||||
|
||||
Append one line per triage outcome to **both** files (per-project for suppressions, global for retro):
|
||||
- `~/.gstack/projects/$REMOTE_SLUG/greptile-history.md` (per-project)
|
||||
- `~/.gstack/greptile-history.md` (global aggregate)
|
||||
|
||||
Format:
|
||||
```
|
||||
<YYYY-MM-DD> | <owner/repo> | <type> | <file-pattern> | <category>
|
||||
```
|
||||
|
||||
Example entries:
|
||||
```
|
||||
2026-03-13 | garrytan/myapp | fp | app/services/auth_service.rb | race-condition
|
||||
2026-03-13 | garrytan/myapp | fix | app/models/user.rb | null-check
|
||||
2026-03-13 | garrytan/myapp | already-fixed | lib/payments.rb | error-handling
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
Include a Greptile summary in the output header:
|
||||
```
|
||||
+ N Greptile comments (X valid, Y fixed, Z FP)
|
||||
```
|
||||
|
||||
For each classified comment, show:
|
||||
- Classification tag: `[VALID]`, `[FIXED]`, `[FALSE POSITIVE]`, `[SUPPRESSED]`
|
||||
- File:line reference (for line-level) or `[top-level]` (for top-level)
|
||||
- One-line body summary
|
||||
- Permalink URL (the `html_url` field)
|
||||
Reference in New Issue
Block a user