Systems, AWP, Spec Kitby Michael Wybraniec

MikesHub internals: port ownership, reclaim, and AWP-paced Tauri

How a local demo desk classifies hijacked ports via cwd, snapshots lsof once, opens DBeaver in an isolated workspace — built under Spec Kit + AWP, not vibes.
Read in:

MikesHub is a Tauri 2 + React desk for waking local demos from hub.yaml: Start/Stop, Preview, links, Ports & Apps, schema, DBeaver. The interesting part is not the chrome — it is how the hub decides that :5173 belongs to you, how it stops the wrong holder before Start, and how one lsof pass feeds both UI tables without melting the machine.

I built it with Cursor agents, but the pacing was not chat roulette. Feature work sat under Spec Kit (001-local-project-hub). Day-to-day agent behaviour followed AWP (Agentic Workflow Protocol — agentic-sdlc/AWP.md on this site’s repo and sibling projects): human leads, awp update → awp commit → awp next, commitStandard, no invented scope. Spec Kit owns the feature contract; AWP owns how the agent is allowed to move.

Ports & Apps: enrolled ports are reserved; ownership is process cwd (and args). Banner shows declared conflicts (:3000, :8088). Green chips are hub-known listeners; red are conflicted or contested.

A TCP LISTEN on a declared port is necessary but not sufficient. Vite loves :5173. If another repo already holds it, marking this project running is a lie — and Preview opens the wrong app.

Classification is a three-state hold on each (declared_port, project_path):

// apps/hub/src-tauri/src/ports/ownership.rs

pub enum PortHold {
    Free,
    HeldByOwner,
    Hijacked,
}

pub fn processes_belong_to_project(port: &ListeningPort, project_path: &str) -> bool {
    port.processes.iter().any(|proc| {
        path_belongs(&proc.cwd, project_path) || path_belongs(&proc.args, project_path)
    })
}

pub fn classify_hold(live: Option<&ListeningPort>, project_path: &str) -> PortHold {
    match live {
        None => PortHold::Free,
        Some(row) if processes_belong_to_project(row, project_path) => PortHold::HeldByOwner,
        Some(_) => PortHold::Hijacked,
    }
}

path_belongs normalises separators and accepts exact path, prefix (project/…), or args that embed the project root (common for node …/project/node_modules/…). Infra services (postgres, redis, classic 5432/6379) are claimed in the UI but ignored for ports_live / Running — a shared DB must not make every enrolled app look up.

Reconcile folds that into project status:

// apps/hub/src-tauri/src/ports/mod.rs — reconcile_live_status (excerpt)

let live_rows = list_system_listening(std::slice::from_ref(project)).unwrap_or_default();
let mut owned_live = false;
for service in &project.manifest.services {
    let Some(port) = service.port else { continue };
    if is_infra_service(service) {
        continue;
    }
    let row = live_rows.iter().find(|p| p.port == port);
    if classify_hold(row, &project.path) == PortHold::HeldByOwner {
        owned_live = true;
        break;
    }
}
project.ports_live = owned_live;

Multi-service vertical (insurance-vertical): UI :5810, API :3810, Postgres :5433, worker without a listen port. The sticky note is the contract: reload hub.yaml → stop wrong holders → scripts.start.

On Start, if a reserved app port is Hijacked, the hub TERMs those PIDs, invalidates the listen cache, waits briefly for the OS to release sockets, then runs scripts.start. Skipping infra avoids murdering a shared Postgres because your UI port was free.

// apps/hub/src-tauri/src/ports/mod.rs — reclaim_mismatched_ports (core loop)

for service in &project.manifest.services {
    let Some(port) = service.port else { continue };
    if is_infra_service(service) {
        continue;
    }
    let Some(row) = all.iter().find(|p| p.port == port) else {
        continue;
    };
    if classify_hold(Some(row), &project.path) != PortHold::Hijacked {
        continue;
    }
    for proc in &row.processes {
        if !pids.contains(&proc.pid) {
            pids.push(proc.pid);
        }
    }
    notes.push(format!(
        "Stopped wrong holder on :{} ({}) — reserved for {} / {}",
        port,
        holder_summary(row),
        project.manifest.name,
        service.name
    ));
}

listening::invalidate_listen_cache();
let killed = listening::kill_pids(&pids, false)?;
std::thread::sleep(Duration::from_millis(500));

Early Ports UI felt sticky because every tick did multiple lsof/ps walks (per-project reconcile + dual tables + aggressive React loading thrash). The fix is boring systems work:

  • Global listen cache (TTL ~4s), invalidated on kill / refresh
  • ports_snapshot: one scan → decorate declared matches → derive service runtimes
  • projects_snapshot: clone without re-reconciling every project
  • UI: soft poll (no full-panel spinner), floor ≥5s, mount cards XOR table
// apps/hub/src-tauri/src/commands/ports.rs

pub fn ports_snapshot(state: State<'_, AppState>) -> HubResult<PortsSnapshot> {
    // One listen scan (cached briefly) drives both tables — avoid double lsof/ps.
    let projects = state.projects_snapshot();
    let listening = ports::list_system_listening(&projects)?;
    let services = ports::list_service_runtimes_from(&projects, &listening);
    let total_rss_bytes = listening.iter().map(|p| p.rss_bytes).sum();
    Ok(PortsSnapshot {
        services,
        listening,
        total_rss_bytes,
        total_rss_human: listening::format_bytes(total_rss_bytes),
    })
}

The scan path itself is still expensive by nature: lsof -nP -iTCP -sTCP:LISTEN, then batch ps + lsof -a -d cwd -p … for RSS/cwd/parent. Caching is what makes polling acceptable.

// apps/hub/src-tauri/src/ports/listening.rs — cache gate

fn cached_or_scan() -> HubResult<Vec<ListeningPort>> {
    {
        let guard = LISTEN_CACHE.lock();
        if let Some(cache) = guard.as_ref() {
            if cache.at.elapsed() < LISTEN_CACHE_TTL {
                return Ok(cache.ports.clone());
            }
        }
    }
    let ports = scan_listening_ports()?;
    *LISTEN_CACHE.lock() = Some(ListenCache {
        at: Instant::now(),
        ports: ports.clone(),
    });
    Ok(ports)
}

Project desk for krishna360: links include Database schema (ER + open DBeaver). Connection details resolve from the project’s local env files (never committed); cloud dashboard URLs stay out of screenshots.

Three failure modes taught the API:

  1. .status() on the DBeaver binary — GUI never exits → Tauri invoke hangs forever.
  2. openConsole=true — DBeaver’s instance server opens an SQL editor tab and skips connectToDataSource (navigator connect).
  3. Shared personal workspace — demos polluted with every other connection; the hub writes a project-only datasource file instead of reusing your personal graph.

The path that works: write an isolated Eclipse workspace under Application Support, quit only prior MikesHub-workspace PIDs, spawn with -newInstance -data <ws> -closeTabs -con '…|openConsole=false|connect=true|…' — credentials come from the project’s local env at runtime and are not embedded in hub.yaml or blog assets.

// apps/hub/src-tauri/src/db/mod.rs — open_dbeaver (shape)

let workspace = mikeshub_dbeaver_workspace()?;
write_project_only_datasource(/* id, host, user, jdbc — sole connection */)?;

quit_mikeshub_dbeaver(&ws); // do not quit the user’s main DBeaver

Command::new(&bin)
    .args([
        "-newInstance",
        "-data", &ws,
        "-closeTabs",
        "-con", &con, // openConsole=false · connect=true — no secrets in this snippet
        "-bringToFront",
    ])
    .spawn()?; // never .status() on the GUI process

hub.yaml is the contract you commit. Auto-detect is useful once; afterwards Update must merge: keep custom ports/scripts/links, append only new services — matched by name or role heuristics (api/web/db) or same port.

// apps/hub/src-tauri/src/enroll.rs — merge_with_existing (service merge)

for svc in detected.services {
    let exists = merged.iter().any(|m| {
        let a = m.name.to_lowercase();
        let b = svc.name.to_lowercase();
        a == b
            || (is_api_role(&a) && is_api_role(&b))
            || (is_web_role(&a) && is_web_role(&b))
            || (is_db_role(&a) && is_db_role(&b))
            || m.port == svc.port
    });
    if !exists {
        merged.push(svc);
    }
}
detected.services = dedupe_services(merged);

That is why AUDIT4 can declare Nuxt :4444 plus mcp-ai-act :8088 (API and static UI on the same port) without Enroll “refresh” wiping the hand-written Start that runs both trees.

flowchart TB
  subgraph Contract["Spec Kit — feature authority"]
    S[spec.md]
    P[plan.md]
    T[tasks.md]
  end
  subgraph Pace["AWP — agent pacing"]
    U[awp update]
    C[awp commit]
    N[awp next]
    U --> C --> N
  end
  subgraph Human["Human gates"]
    H[clarify scope · accept diffs · no silent initiative]
  end
  Contract --> Pace
  Pace --> Human
  Human -->|merge| Git[(hub.yaml + Rust/TS)]

Spec Kit answered what MikesHub is (wake demos, ports view, links, Start Spec). AWP answered how the agent may proceed: read AWP.md on any awp* command; never skip update → commit → next without permission; ask when “next to the end” is ambiguous; never put “AI” in commit messages; park surprises in Unplanned Tasks.

Useful agent wins under that envelope: ownership/reclaim design, listen-cache + snapshot, DBeaver CLI archaeology, monorepo local-env resolution (nested app folders). Useful human vetoes: no live Vite iframe inside the hub; never wait on DBeaver’s process; never dump the personal DBeaver graph into a demo; never commit credentials into hub.yaml or screenshots.

If you only need a prettier npm run dev, skip MikesHub. If you run many stacks and have been bitten by shared ports and half-started multi-repo demos, the leverage is the ownership model + reclaim + a single listen snapshot — with Spec Kit for the product spine and AWP so the agent does not outrun the contract.

Michael Wybraniec

Michael Wybraniec

System Design, GenAI Automation & Architecture