From d2f44177726ecc2bcf1cdaffbd79291de5b59db5 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 16 Nov 2026 13:51:51 -0800 Subject: [PATCH 01/18] chore(porch): bugfix-1901 init bugfix --- .../status.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml new file mode 100644 index 000000000..548dbdd7b --- /dev/null +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -0,0 +1,14 @@ +id: bugfix-1901 +title: afx-tower-is-not-running-repor +protocol: bugfix +phase: investigate +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-16T21:51:51.349Z' +updated_at: '2026-11-16T21:51:51.351Z' From ca6417930f38300bac01ffaba114ae34fa7152ca Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 17 Nov 2026 10:09:35 -0800 Subject: [PATCH 02/18] [Bugfix #1901] WIP: investigate notes before reboot (no code yet) --- codev/state/bugfix-1901_thread.md | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 codev/state/bugfix-1901_thread.md diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md new file mode 100644 index 000000000..1a8e028ad --- /dev/null +++ b/codev/state/bugfix-1901_thread.md @@ -0,0 +1,48 @@ +# bugfix-1901 thread + +Issue #1901: afx reports "Tower is not running" under high load while Tower is up; the real +`/health` probe error is discarded. + +## 2026-11-16 — investigate (in progress, no code written yet) + +**Where I stopped:** still in the porch `investigate` phase (`porch done` not yet run). Root cause +is mostly established (below). Next step: confirm it **without machine load**, using a stalled local +HTTP server or an injected fetch, then signal PHASE_COMPLETE. + +### Architect ruling (binding) +- **No synthetic machine load on this Mac, ever.** My repro ran 36 CPU-burner `node -e` loops for + ~90 s, twice. Load reached 76 and slowed the owner's machine. Reproduce only with an injected + slow/failing fetch in a unit test, or one stalled local HTTP server. +- Run only the test files I touch until the PR step. + +### Findings so far +- `TowerClient.isRunning()` (`packages/sdk/src/tower-client.ts` ~L358) collapses every `/health` + failure to `false`. `request()` maps its catch to `{status: 0, error}`, and the error is dropped. +- Also: the `message.includes('ECONNREFUSED')` check in `request()` likely never matches with Node's + undici fetch, because the thrown error is `TypeError: fetch failed` and the code lives on + `err.cause`. This needs confirming with a closed port; that test is load-free. +- Tower binds `127.0.0.1:4100` (IPv4 only). The client uses `localhost`, which resolves to + `[::1, 127.0.0.1]`, so `::1` is refused and `127.0.0.1` connects. Happy-eyeballs is not the cause + in the data below. +- Probe that mirrors the SDK request (fresh node process per probe, captures the cause chain): + - load ~13: 200/200 ok, p95 1.1 s. + - load ~44: 59/300 failed, and **every failure was `TimeoutError` after the 10 s + `AbortSignal.timeout`**. There were no ECONNREFUSED/ECONNRESET failures. + - curl at load ~40: **connect was always ≤ 8 ms** (kernel accepts immediately), but + time-to-first-byte reached 29 s on `/api/version`, and `/health` did not answer within 40 s. +- So, on this machine: **Tower is listening but answers slowly** (CPU starvation of Tower's single + event loop). It is not an accept-queue or connect failure. `/health` is the heaviest route: it runs + `getInstances()` plus a full `ps -A -ww` census (~1.2 MB, 757 lines) per request + (`process-census.ts`, 5 s ps timeout). Caveat: my probes ran 10–12 `/health` calls concurrently, + which inflated this. + +### Planned fix (per the issue's Fix section) +One shared helper over the SDK probe that classifies the failure: +- connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" +- timeout / reset / bad response → retry once after a short pause; if that also fails, report + "Tower did not answer /health () after N ms; it appears to be up, retry", with no + suggestion to start Tower. + +Route `send`, `interrupt`, `reset`, `rename`, `ide`, `status`, `self-refresh` and the other +`isRunning()` callers through that helper. Unit tests use an injected fetch, as the issue's Testing +section describes. From 06ee5a00c75aed703fdddcf076a21452f974f588 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:57:30 -0800 Subject: [PATCH 03/18] [Bugfix #1901] Investigate: root cause and scope --- codev/state/bugfix-1901_thread.md | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md index 1a8e028ad..9ffb04514 100644 --- a/codev/state/bugfix-1901_thread.md +++ b/codev/state/bugfix-1901_thread.md @@ -36,6 +36,40 @@ HTTP server or an injected fetch, then signal PHASE_COMPLETE. (`process-census.ts`, 5 s ps timeout). Caveat: my probes ran 10–12 `/health` calls concurrently, which inflated this. +## 2026-11-24 — investigate complete (resumed after reboot) + +Load-free repro (`scratchpad/repro/stalled.mjs`: local servers on ephemeral ports, nothing +touching Tower or machine load) feeds each shape through an exact copy of the SDK's catch mapping: + +| endpoint | fetch throws | `request()` keeps | `isRunning()` | +|---|---|---|---| +| nothing listening | `TypeError: fetch failed`, `cause.code=ECONNREFUSED` | `"fetch failed"` | false | +| listening, never answers | `TimeoutError` | `"Request timeout"` | false | +| listening, resets | `TypeError: fetch failed`, `cause.code=ECONNRESET` | `"fetch failed"` | false | + +**Root cause.** +1. `isRunning()` returns a bare boolean, so every failure shape becomes "Tower is not running" in + the callers. +2. `request()`'s `message.includes('ECONNREFUSED')` is dead code under Node's fetch, because the + errno code lives on `err.cause`. So even the raw result cannot tell refused from reset. +3. Under load the live failure mode is (2) in the table: Tower is listening, but its event loop is + starved past the 10 s abort. + +**Worse adjacent paths found (same false negative, destructive follow-on):** +- `afx workspace start` (`start.ts`): a false negative calls `towerStart()`. That probes + `/api/status` with a 2 s timeout, decides "port in use but not responding", and **SIGTERMs the PID + on 4100, i.e. the live Tower**. Running `afx tower start` by hand, as the old message suggests, + hits the same branch. +- `afx workspace stop` (`stop.ts`): a false negative skips the Tower kills but still runs + `clearRuntime()`, wiping the builder registry while Tower keeps those builders running. +- `rename.ts`, `shell.ts` and `open.ts` print "not running" for any `status === 0`. +- `ide.ts` is already correct: it uses `http.request`, so `err.code` is reliable, and it reports + timeouts separately. No change needed. + +**Scope:** fits BUGFIX (estimate ~250 LOC with tests). One open decision is flagged to the +architect, not changed here: `towerStart()`'s zombie-kill policy, i.e. what `afx tower start` +should do when the port is held but `/api/status` misses a 2 s probe. + ### Planned fix (per the issue's Fix section) One shared helper over the SDK probe that classifies the failure: - connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" From 5667adef3005d99c777726b8de16cf4e1eb703c1 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:59:49 -0800 Subject: [PATCH 04/18] [Bugfix #1901] Record architect ruling: towerStart in scope --- codev/state/bugfix-1901_thread.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md index 9ffb04514..2ec4d390c 100644 --- a/codev/state/bugfix-1901_thread.md +++ b/codev/state/bugfix-1901_thread.md @@ -70,6 +70,25 @@ touching Tower or machine load) feeds each shape through an exact copy of the SD architect, not changed here: `towerStart()`'s zombie-kill policy, i.e. what `afx tower start` should do when the port is held but `/api/status` misses a 2 s probe. +### Architect ruling 2026-11-24: towerStart in this PR, option (b) +1. `towerStart` goes through the same `probeHealth` helper. + - not-running (refused): start, as today. + - running: say it is already running, as today. + - unresponsive: **do not kill**. Exit non-zero and print the listening PID and its command + line. Say that if the machine is busy the user should wait and retry, and that to replace the + process deliberately they run `afx tower stop` and then `afx tower start`. Stopping a Tower is + a human decision, never a side effect of start. +2. `afx tower stop` must still stop an unresponsive Tower. Verified: `towerStop()` kills the PIDs + from `getProcessesOnPort()` (lsof) and does no health probe. Leave it unrouted. +3. Tests use a stalled local server (child process, ephemeral port): + - start does not signal the PID and exits non-zero with the message; + - a refused port starts normally; + - stop still kills the stalled server. +4. This is Tower lifecycle code: dispatch the Windows workflow on the branch and link the run in + the PR. +5. The PRFT write-up gives the towerStart change its own paragraph, as a behaviour change: start no + longer replaces a hung Tower by itself. + ### Planned fix (per the issue's Fix section) One shared helper over the SDK probe that classifies the failure: - connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" From 7b10defc8ed6239447b69bbc695e7ca920b3bf93 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:59:52 -0800 Subject: [PATCH 05/18] chore(porch): bugfix-1901 fix phase-transition --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index 548dbdd7b..3369b8f10 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -1,7 +1,7 @@ id: bugfix-1901 title: afx-tower-is-not-running-repor protocol: bugfix -phase: investigate +phase: fix plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-16T21:51:51.351Z' +updated_at: '2026-11-24T20:59:52.373Z' From 98d72e49ffa92131f7cb8281335d735df3c43566 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:11:02 -0800 Subject: [PATCH 06/18] [Bugfix #1901] Fix: tell "Tower not running" from "Tower not answering" Under load a live Tower accepts the connection at once but its starved event loop misses the 10 s request timeout. isRunning() collapsed that (and resets) to false, so commands said "Tower is not running. Start it with: afx tower start" while Tower was up. - sdk: TowerClient.probeHealth() classifies one /health probe as running / not-running (connection refused) / unresponsive (with the reason). A localhost refusal counts only when every address refused. Generic failures keep the cause code (fetch failed: ECONNRESET). requestTimeoutMs option (default 10 000). - cli: lib/tower-check.ts checkTower() is the one gate: refused reads "not running"; anything else is retried once after 1 s, then reported with the underlying error and no advice to start Tower. - send, interrupt, reset, self-refresh, sweep-husks, add/remove-architect and status go through it. workspace start/stop stop on an unresponsive Tower instead of starting a second one or clearing live runtime state. - rename, shell and open say "not running" only for a refused connection. - afx tower start no longer SIGTERMs a port holder that did not answer: it exits non-zero naming the PID and command line, and leaves replacing it to afx tower stop. Stop is unchanged and still stops a hung Tower. --- .../src/agent-farm/commands/interrupt.ts | 6 +- .../codev/src/agent-farm/commands/open.ts | 31 ++++++---- .../codev/src/agent-farm/commands/rename.ts | 4 +- .../codev/src/agent-farm/commands/reset.ts | 6 +- .../src/agent-farm/commands/self-refresh.ts | 9 +-- .../codev/src/agent-farm/commands/send.ts | 10 +++- .../codev/src/agent-farm/commands/shell.ts | 5 +- .../codev/src/agent-farm/commands/start.ts | 10 +++- .../codev/src/agent-farm/commands/status.ts | 15 +++-- .../codev/src/agent-farm/commands/stop.ts | 11 +++- .../agent-farm/commands/tower-sweep-husks.ts | 7 ++- .../codev/src/agent-farm/commands/tower.ts | 58 +++++++++++-------- .../commands/workspace-add-architect.ts | 7 ++- .../commands/workspace-remove-architect.ts | 7 ++- .../codev/src/agent-farm/lib/tower-check.ts | 56 ++++++++++++++++++ .../codev/src/agent-farm/lib/tower-client.ts | 1 + packages/sdk/src/tower-client.ts | 58 ++++++++++++++++--- 17 files changed, 226 insertions(+), 75 deletions(-) create mode 100644 packages/codev/src/agent-farm/lib/tower-check.ts diff --git a/packages/codev/src/agent-farm/commands/interrupt.ts b/packages/codev/src/agent-farm/commands/interrupt.ts index 76bda52b0..c9712105a 100644 --- a/packages/codev/src/agent-farm/commands/interrupt.ts +++ b/packages/codev/src/agent-farm/commands/interrupt.ts @@ -22,6 +22,7 @@ import type { InterruptOptions } from '../types.js'; import { logger, fatal } from '../utils/logger.js'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { detectWorkspaceRoot, detectCurrentBuilderId, architectSenderId } from './send.js'; export async function interrupt(options: InterruptOptions): Promise { @@ -46,8 +47,9 @@ export async function interrupt(options: InterruptOptions): Promise { } const client = new TowerClient(); - if (!(await client.isRunning())) { - fatal('Tower is not running. Start it with: afx tower start'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + fatal(tower.message); } try { diff --git a/packages/codev/src/agent-farm/commands/open.ts b/packages/codev/src/agent-farm/commands/open.ts index 6c6d0500b..6e7ceb8d0 100644 --- a/packages/codev/src/agent-farm/commands/open.ts +++ b/packages/codev/src/agent-farm/commands/open.ts @@ -16,10 +16,14 @@ interface OpenOptions { } /** - * Try to create a file tab via the Tower API - * Returns the file tab ID if successful, null if Tower not available + * Try to create a file tab via the Tower API. On failure, `refused` says whether nothing was + * listening (Tower not running); any other failure has already been reported (#1901). */ -async function tryTowerApi(client: TowerClient, workspacePath: string, filePath: string): Promise { +async function tryTowerApi( + client: TowerClient, + workspacePath: string, + filePath: string, +): Promise<{ ok: true; tabId: string } | { ok: false; refused: boolean }> { const encodedPath = encodeWorkspacePath(workspacePath); const result = await client.request<{ id: string; existing?: boolean }>( @@ -36,7 +40,11 @@ async function tryTowerApi(client: TowerClient, workspacePath: string, filePath: if (result.data.existing) { logger.info('(File was already open)'); } - return result.data.id; + return { ok: true, tabId: result.data.id }; + } + + if (result.connectionRefused) { + return { ok: false, refused: true }; } if (result.error) { @@ -45,7 +53,7 @@ async function tryTowerApi(client: TowerClient, workspacePath: string, filePath: logger.kv('File', filePath); } - return null; + return { ok: false, refused: false }; } /** @@ -89,17 +97,18 @@ export async function open(options: OpenOptions): Promise { // Try to use Tower API const client = new TowerClient(); - const tabId = await tryTowerApi(client, workspacePath, filePath); + const opened = await tryTowerApi(client, workspacePath, filePath); - if (tabId) { + if (opened.ok) { // Tab created server-side — dashboard picks it up via state polling. // No need to open a browser; the user already has the dashboard open. return; } - // Tower not available - tell user to start it - logger.error('Tower is not running.'); - logger.info('Start it with: afx tower start'); - logger.info('Then try again: afx open ' + options.file); + if (opened.refused) { + logger.error('Tower is not running.'); + logger.info('Start it with: afx tower start'); + logger.info('Then try again: afx open ' + options.file); + } process.exit(1); } diff --git a/packages/codev/src/agent-farm/commands/rename.ts b/packages/codev/src/agent-farm/commands/rename.ts index 2eb1ac639..bcefbb414 100644 --- a/packages/codev/src/agent-farm/commands/rename.ts +++ b/packages/codev/src/agent-farm/commands/rename.ts @@ -40,8 +40,10 @@ export async function rename(options: RenameOptions): Promise { fatal('Cannot rename builder/architect terminals'); } else if (result.status === 404) { fatal('Session not found — it may have been closed'); - } else if (result.status === 0) { + } else if (result.connectionRefused) { fatal('Tower is not running'); + } else if (result.status === 0) { + fatal(`Tower did not answer (${result.error}); it appears to be up, retry`); } else { fatal(result.error || 'Rename failed'); } diff --git a/packages/codev/src/agent-farm/commands/reset.ts b/packages/codev/src/agent-farm/commands/reset.ts index 0512a519e..fc6ed1e32 100644 --- a/packages/codev/src/agent-farm/commands/reset.ts +++ b/packages/codev/src/agent-farm/commands/reset.ts @@ -20,6 +20,7 @@ import { existsSync, readFileSync, readdirSync, writeFileSync, statSync } from 'node:fs'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { logger, fatal } from '../utils/logger.js'; import { MAX_MESSAGE_BYTES, messageLimitError } from '../utils/message-format.js'; import { findBuilderById } from '../lib/builder-lookup.js'; @@ -109,8 +110,9 @@ export async function refresh(options: ResetOptions): Promise { } const client = new TowerClient(); - if (!(await client.isRunning())) { - fatal('Tower is not running. Start it with: afx tower start'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + fatal(tower.message); } const addendum = buildAddendum(options); diff --git a/packages/codev/src/agent-farm/commands/self-refresh.ts b/packages/codev/src/agent-farm/commands/self-refresh.ts index c4db610f8..2f4bea845 100644 --- a/packages/codev/src/agent-farm/commands/self-refresh.ts +++ b/packages/codev/src/agent-farm/commands/self-refresh.ts @@ -41,6 +41,7 @@ import { existsSync, readFileSync, realpathSync, statSync, unlinkSync, writeFile import { isAbsolute, relative, resolve, sep } from 'node:path'; import { execFileSync } from 'node:child_process'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { logger, fatal } from '../utils/logger.js'; import { getBuilder } from '../state.js'; import { getConfig } from '../utils/index.js'; @@ -277,11 +278,11 @@ export async function selfRefresh(options: SelfRefreshOptions): Promise { // proceed with Tower down — reporting a clean dry run in that state would be // the rehearsal lying about the thing most likely to stop the real run. const client = new TowerClient(); - if (!(await client.isRunning())) { + const tower = await checkTower(client); + if (tower.state !== 'running') { fatal( - 'Tower is not running, so the post-clear re-entry cannot be scheduled. Refusing to ' + - 'clear — a cleared builder with no re-entry is a builder nobody is coming back for. ' + - 'Start it with: afx tower start', + `${tower.message}\nThe post-clear re-entry cannot be scheduled, so refusing to clear — ` + + 'a cleared builder with no re-entry is a builder nobody is coming back for.', ); return; } diff --git a/packages/codev/src/agent-farm/commands/send.ts b/packages/codev/src/agent-farm/commands/send.ts index 53a08462c..1ec57ecca 100644 --- a/packages/codev/src/agent-farm/commands/send.ts +++ b/packages/codev/src/agent-farm/commands/send.ts @@ -22,6 +22,7 @@ import { matchBuilderRow, parseBuilderWorktreePath, type BuilderWorktreeRow } fr import { BUILDER_WORKTREE_ENV } from '../../lib/agent-env.js'; import { hostPaths } from '../../lib/platform/host-paths.js'; import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { ARCHITECT_NAME_PATTERN, MAX_ARCHITECT_NAME_LENGTH } from '../utils/architect-name.js'; import { MAX_MESSAGE_BYTES, messageLimitError } from '../utils/message-format.js'; import { formatVerdict, isUnverifiableVerdict } from '@cluesmith/codev-sdk/hold-verdict'; @@ -501,10 +502,13 @@ export async function send(options: SendOptions): Promise { // it may be retried. const client = new TowerClient(); const retry = retryBudget(options.retry ?? 0); - while (!(await client.isRunning())) { - if (!(await retry('Tower is not running; nothing has been sent.'))) { - fatal('Tower is not running. Start it with: afx tower start'); + let tower = await checkTower(client); + while (tower.state !== 'running') { + const why = tower.state === 'not-running' ? 'Tower is not running' : `Tower did not answer /health (${tower.error})`; + if (!(await retry(`${why}; nothing has been sent.`))) { + fatal(tower.message); } + tower = await checkTower(client); } if (options.all) { diff --git a/packages/codev/src/agent-farm/commands/shell.ts b/packages/codev/src/agent-farm/commands/shell.ts index 1f1acf01e..bb913bc4e 100644 --- a/packages/codev/src/agent-farm/commands/shell.ts +++ b/packages/codev/src/agent-farm/commands/shell.ts @@ -38,8 +38,9 @@ async function tryTowerApi( return { ok: true, connectionRefused: false }; } - // status=0 means the request never reached the server (ECONNREFUSED, timeout, etc.) - const connectionRefused = result.status === 0; + // Only a refused connection means nothing is listening. A timeout (status 0 too) comes from a + // Tower that accepted the connection, so it is reported as an error, not "not running" (#1901). + const connectionRefused = result.connectionRefused === true; return { ok: false, connectionRefused, error: result.error }; } diff --git a/packages/codev/src/agent-farm/commands/start.ts b/packages/codev/src/agent-farm/commands/start.ts index 005d28d2c..85232b0d6 100644 --- a/packages/codev/src/agent-farm/commands/start.ts +++ b/packages/codev/src/agent-farm/commands/start.ts @@ -10,6 +10,7 @@ import { getConfig } from '../utils/index.js'; import { logger, fatal } from '../utils/logger.js'; import { openBrowser } from '../utils/shell.js'; import { getTowerClient, DEFAULT_TOWER_PORT } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { towerStart } from './tower.js'; /** @@ -30,8 +31,13 @@ export async function start(options: StartOptions = {}): Promise { // Create tower client const client = getTowerClient(); - // Check if tower is running - const towerRunning = await client.isRunning(); + // Check if tower is running. Only a refused connection means "start one": a Tower that + // accepted the connection but did not answer is left alone, never replaced (#1901). + const tower = await checkTower(client); + if (tower.state === 'unresponsive') { + fatal(tower.message); + } + const towerRunning = tower.state === 'running'; if (!towerRunning) { logger.info('Starting tower daemon...'); diff --git a/packages/codev/src/agent-farm/commands/status.ts b/packages/codev/src/agent-farm/commands/status.ts index ccca45314..4500f6967 100644 --- a/packages/codev/src/agent-farm/commands/status.ts +++ b/packages/codev/src/agent-farm/commands/status.ts @@ -8,6 +8,7 @@ import { loadState } from '../state.js'; import { logger } from '../utils/logger.js'; import { getConfig } from '../utils/config.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { getTypeColor } from '../utils/display.js'; import { currentArchitectName } from '../utils/architect-name.js'; import { discoverBuilders, type StoredBuilderIdentity } from '../servers/overview.js'; @@ -356,7 +357,8 @@ export async function status(options: StatusOptions = {}): Promise { // Try tower API first (Phase 3 - Spec 0090) const client = getTowerClient(); - const towerRunning = await client.isRunning(); + const tower = await checkTower(client); + const towerRunning = tower.state === 'running'; // Builder ownership (`spawnedByArchitect`) lives in state.db, so load it up // front — it's the canonical owner source whether or not Tower is running. @@ -516,9 +518,14 @@ export async function status(options: StatusOptions = {}): Promise { return; } - // Tower not running - show message and fall back to local state - logger.kv('Tower', chalk.gray('not running')); - logger.info(`Run 'afx tower start' to start the tower daemon`); + // Tower not reachable - show why and fall back to local state + if (tower.state === 'unresponsive') { + logger.kv('Tower', chalk.yellow('not answering')); + logger.warn(tower.message); + } else { + logger.kv('Tower', chalk.gray('not running')); + logger.info(`Run 'afx tower start' to start the tower daemon`); + } showArtifactConfig(workspacePath); diff --git a/packages/codev/src/agent-farm/commands/stop.ts b/packages/codev/src/agent-farm/commands/stop.ts index 4bba83bfa..c67cf7c3c 100644 --- a/packages/codev/src/agent-farm/commands/stop.ts +++ b/packages/codev/src/agent-farm/commands/stop.ts @@ -6,9 +6,10 @@ */ import { loadState, clearRuntime, getArchitects } from '../state.js'; -import { logger } from '../utils/logger.js'; +import { logger, fatal } from '../utils/logger.js'; import { getConfig } from '../utils/config.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; /** * Stop all agent farm processes @@ -24,7 +25,13 @@ export async function stop(): Promise { // Try tower API first (Phase 3 - Spec 0090) const client = getTowerClient(); - const towerRunning = await client.isRunning(); + // An unresponsive Tower is not a stopped one: the legacy path below would clear the + // runtime state of builders that are still running (#1901). + const tower = await checkTower(client); + if (tower.state === 'unresponsive') { + fatal(tower.message); + } + const towerRunning = tower.state === 'running'; if (towerRunning) { logger.info('Deactivating workspace via tower...'); diff --git a/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts b/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts index ea9a34deb..60723a38e 100644 --- a/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts +++ b/packages/codev/src/agent-farm/commands/tower-sweep-husks.ts @@ -5,6 +5,7 @@ import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { confirm } from '../../lib/cli-prompts.js'; import type { HuskCandidate } from '../lib/tower-client.js'; @@ -39,9 +40,9 @@ function printCandidates(candidates: HuskCandidate[]): void { export async function towerSweepHusks(options: TowerSweepHusksOptions = {}): Promise { const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx tower start`.'); + const tower = await checkTower(client); + if (tower.state !== 'running') { + logger.error(tower.message); process.exitCode = 1; return; } diff --git a/packages/codev/src/agent-farm/commands/tower.ts b/packages/codev/src/agent-farm/commands/tower.ts index 5188ae430..d75c6fbb5 100644 --- a/packages/codev/src/agent-farm/commands/tower.ts +++ b/packages/codev/src/agent-farm/commands/tower.ts @@ -8,10 +8,11 @@ import http from 'node:http'; import { logger, fatal } from '../utils/logger.js'; import { spawn, type SpawnOptions } from 'node:child_process'; import { getConfig } from '../utils/config.js'; -import { DEFAULT_TOWER_PORT, AGENT_FARM_DIR } from '../lib/tower-client.js'; +import { DEFAULT_TOWER_PORT, AGENT_FARM_DIR, TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; +import { listProcessCensus } from '../servers/process-census.js'; import { ensureLocalKey } from '@cluesmith/codev-core/auth'; import { TOWER_KEY_HEADER } from '@cluesmith/codev-types'; -import { isPortAvailable } from '../utils/shell.js'; import Database from 'better-sqlite3'; import { openDatabase } from '../../lib/sqlite.js'; import { getGlobalDbPath } from '../db/index.js'; @@ -108,10 +109,28 @@ function logToFile(message: string): void { } /** - * Check if a port is already in use (inverse of isPortAvailable from shell utils) + * Why `afx tower start` refuses a port whose holder accepted the connection but did not + * answer (#1901): name the process, so the reader can see whether it is a Tower, and leave + * replacing it to them. */ -async function isPortInUse(port: number): Promise { - return !(await isPortAvailable(port)); +async function unresponsivePortMessage(port: number, tower: { error: string; elapsedMs: number }): Promise { + const pids = getProcessesOnPort(port); + let describe = (pid: number): string => `PID ${pid}`; + if (pids.length > 0) { + try { + const census = await listProcessCensus(); + describe = (pid) => `PID ${pid}: ${census.find((p) => p.pid === pid)?.cmdline || '(command line not readable)'}`; + } catch (err) { + describe = (pid) => `PID ${pid} (process table unreadable: ${err instanceof Error ? err.message : String(err)})`; + } + } + return [ + `A process is listening on port ${port} but did not answer /health within ` + + `${Math.round(tower.elapsedMs / 1000)} s (${tower.error}):`, + ...(pids.length > 0 ? pids.map((pid) => ` ${describe(pid)}`) : [' (no listening PID found)']), + 'If the machine is busy, wait and run afx tower start again.', + 'To replace it deliberately: afx tower stop, then afx tower start.', + ].join('\n'); } /** @@ -245,28 +264,17 @@ export async function towerStart(options: TowerStartOptions = {}): Promise return; } - // Check if already running and responding - if (await isServerResponding(port)) { - const dashboardUrl = `http://localhost:${port}`; - logger.info(`Tower already running at ${dashboardUrl}`); + // Only a refused connection means "start one" (#1901). A process that accepted the connection + // but did not answer is, under load, usually a live Tower: stopping it is a human's decision + // (afx tower stop), never a side effect of start. + const tower = await checkTower(new TowerClient({ port, host: '127.0.0.1' })); + if (tower.state === 'running') { + logger.info(`Tower already running at http://localhost:${port}`); return; } - - // Check if port is in use but not responding (zombie process?) - if (await isPortInUse(port)) { - logger.warn(`Port ${port} is in use but tower not responding. Attempting cleanup...`); - logToFile(`Port ${port} in use but not responding, attempting cleanup`); - const pids = getProcessesOnPort(port); - for (const pid of pids) { - try { - process.kill(pid, 'SIGTERM'); - logToFile(`Killed process ${pid} on port ${port}`); - } catch { - // Process may have already exited - } - } - // Wait for port to be released - await new Promise((r) => setTimeout(r, 1000)); + if (tower.state === 'unresponsive') { + logToFile(`Port ${port} held but /health unanswered (${tower.error}); refusing to start`); + fatal(await unresponsivePortMessage(port, tower)); } const config = getConfig(); diff --git a/packages/codev/src/agent-farm/commands/workspace-add-architect.ts b/packages/codev/src/agent-farm/commands/workspace-add-architect.ts index 2780f31e4..7febb9a61 100644 --- a/packages/codev/src/agent-farm/commands/workspace-add-architect.ts +++ b/packages/codev/src/agent-farm/commands/workspace-add-architect.ts @@ -15,6 +15,7 @@ import { getConfig } from '../utils/index.js'; import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; import { validateArchitectName } from '../utils/architect-name.js'; export interface WorkspaceAddArchitectOptions { @@ -49,9 +50,9 @@ export async function workspaceAddArchitect( } const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx workspace start` first.'); + const tower = await checkTower(client, { startCommand: 'afx workspace start' }); + if (tower.state !== 'running') { + logger.error(tower.message); process.exit(1); } diff --git a/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts b/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts index 60018ec55..bf939c541 100644 --- a/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts +++ b/packages/codev/src/agent-farm/commands/workspace-remove-architect.ts @@ -13,6 +13,7 @@ import { getConfig } from '../utils/index.js'; import { logger } from '../utils/logger.js'; import { getTowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; export interface WorkspaceRemoveArchitectOptions { name: string; @@ -35,9 +36,9 @@ export async function workspaceRemoveArchitect( } const client = getTowerClient(); - const towerRunning = await client.isRunning(); - if (!towerRunning) { - logger.error('Tower is not running. Start it with `afx workspace start` first.'); + const tower = await checkTower(client, { startCommand: 'afx workspace start' }); + if (tower.state !== 'running') { + logger.error(tower.message); process.exit(1); } diff --git a/packages/codev/src/agent-farm/lib/tower-check.ts b/packages/codev/src/agent-farm/lib/tower-check.ts new file mode 100644 index 000000000..c1acf79e4 --- /dev/null +++ b/packages/codev/src/agent-farm/lib/tower-check.ts @@ -0,0 +1,56 @@ +/** + * The one Tower liveness gate every CLI command goes through (#1901). + * + * A bare `isRunning()` boolean turned every `/health` failure into "Tower is not running. + * Start it with: afx tower start". Under heavy load a live Tower accepts the connection at + * once but its starved event loop misses the 10 s request timeout, so commands told people to + * start a second Tower while the first was up. Here only a refused connection reads as "not + * running". Anything else is retried once after a short pause, then reported with the + * underlying error and no advice to start Tower. + */ + +import type { TowerHealthProbe } from './tower-client.js'; + +export const TOWER_RETRY_DELAY_MS = 1000; + +export type TowerCheck = + | { state: 'running' } + | { state: 'not-running'; message: string } + | { state: 'unresponsive'; message: string; error: string; elapsedMs: number }; + +export interface TowerCheckOptions { + /** The command a "not running" message tells the reader to run. */ + startCommand?: string; + retryDelayMs?: number; +} + +export async function checkTower( + client: { probeHealth(): Promise }, + options: TowerCheckOptions = {}, +): Promise { + const startedAt = Date.now(); + let probe = await client.probeHealth(); + if (probe.state === 'unresponsive') { + await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? TOWER_RETRY_DELAY_MS)); + probe = await client.probeHealth(); + } + + switch (probe.state) { + case 'running': + return { state: 'running' }; + case 'not-running': + return { + state: 'not-running', + message: `Tower is not running. Start it with: ${options.startCommand ?? 'afx tower start'}`, + }; + case 'unresponsive': { + const elapsedMs = Date.now() - startedAt; + return { + state: 'unresponsive', + error: probe.error, + elapsedMs, + message: `Tower did not answer /health (${probe.error}) after ${elapsedMs} ms; it appears to be up, retry`, + }; + } + } +} diff --git a/packages/codev/src/agent-farm/lib/tower-client.ts b/packages/codev/src/agent-farm/lib/tower-client.ts index 1a263f114..b1a0abe30 100644 --- a/packages/codev/src/agent-farm/lib/tower-client.ts +++ b/packages/codev/src/agent-farm/lib/tower-client.ts @@ -54,6 +54,7 @@ export { type TowerWorkspace, type TowerWorkspaceStatus, type TowerHealth, + type TowerHealthProbe, type TowerTunnelStatus, type TowerStatus, type TowerTerminal, diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index fa93b9ecb..6273ff5cd 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -184,6 +184,16 @@ export interface TowerHealth { timestamp: string; } +/** + * One `/health` probe, classified (#1901). `not-running`: the connection was refused, so + * nothing is listening. `unresponsive`: something accepted the connection but did not answer + * healthily; `error` carries the reason. + */ +export type TowerHealthProbe = + | { state: 'running'; health: TowerHealth } + | { state: 'not-running' } + | { state: 'unresponsive'; error: string }; + /** Issue #1227: a shellper the husk sweep would reap (or has reaped). */ export interface HuskCandidate { pid: number; @@ -261,6 +271,11 @@ export interface TowerClientOptions { * to the global fetch, which exists in browsers, Node 18+, and React Native. */ fetchFn?: typeof fetch; + /** + * How long one request may wait for Tower's answer, in ms. Defaults to 10 000. A test against + * a deliberately stalled server sets it short (#1901). + */ + requestTimeoutMs?: number; } // ── Client ───────────────────────────────────────────────────── @@ -271,10 +286,18 @@ import { encodeWorkspacePath } from './workspace.js'; * Whether a fetch failure was a refused TCP connection: nothing was listening, so the * request provably never reached Tower. Node's fetch reports it as `fetch failed` with the * `ECONNREFUSED` on `err.cause`, which a check of `err.message` alone never sees (#1950). + * + * `localhost` resolves to both `::1` and `127.0.0.1`, and when every address fails Node's cause + * is an AggregateError whose `code` is copied from the FIRST attempt only. Tower binds IPv4, so + * that first attempt is always a refused `::1`; the connection counts as refused only when every + * attempt was (#1901), or a refused `::1` would mask a `127.0.0.1` that failed some other way. */ function isConnectionRefused(err: unknown): boolean { if (!(err instanceof Error)) return String(err).includes('ECONNREFUSED'); - const cause = (err as { cause?: { code?: unknown; message?: unknown } }).cause; + const cause = (err as { cause?: { code?: unknown; message?: unknown; errors?: unknown } }).cause; + if (Array.isArray(cause?.errors) && cause.errors.length > 0) { + return cause.errors.every((attempt) => (attempt as { code?: unknown } | null)?.code === 'ECONNREFUSED'); + } return ( err.message.includes('ECONNREFUSED') || cause?.code === 'ECONNREFUSED' || @@ -311,6 +334,7 @@ export class TowerClient { private readonly baseUrl: string; private readonly getAuthKey: () => string | null; private readonly fetchFn: typeof fetch; + private readonly requestTimeoutMs: number; constructor(portOrOptions?: number | TowerClientOptions) { let options: TowerClientOptions; @@ -324,6 +348,7 @@ export class TowerClient { this.baseUrl = `http://${host}:${port}`; this.getAuthKey = options.getAuthKey ?? (() => null); this.fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis); + this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; } /** @@ -348,7 +373,7 @@ export class TowerClient { const response = await this.fetchFn(`${this.baseUrl}${path}`, { ...options, headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (!response.ok) { @@ -371,13 +396,30 @@ export class TowerClient { if (message.includes('timeout')) { return { ok: false, status: 0, error: 'Request timeout' }; } - return { ok: false, status: 0, error: message }; + // Node's fetch says only `fetch failed`; the reason (ECONNRESET, …) is on the cause (#1901). + const causeCode = (err as { cause?: { code?: unknown } } | null)?.cause?.code; + return { ok: false, status: 0, error: typeof causeCode === 'string' ? `${message}: ${causeCode}` : message }; } } - async isRunning(): Promise { + /** + * Probe `/health` once and say why it failed, not just that it did (#1901). Only a refused + * connection means nothing is listening; a timeout, a reset, an error status or an unreadable + * body all come from something that accepted the connection, which under load is usually a + * live Tower whose event loop is starved. Retrying, and wording the result for a person, is + * the caller's policy. + */ + async probeHealth(): Promise { const result = await this.request('/health'); - return result.ok && result.data?.status === 'healthy'; + if (result.ok && result.data?.status === 'healthy') return { state: 'running', health: result.data }; + if (result.connectionRefused) return { state: 'not-running' }; + if (result.status === 0) return { state: 'unresponsive', error: result.error ?? 'no response' }; + if (!result.ok) return { state: 'unresponsive', error: `HTTP ${result.status}: ${result.error}` }; + return { state: 'unresponsive', error: `reported status ${JSON.stringify(result.data?.status)}` }; + } + + async isRunning(): Promise { + return (await this.probeHealth()).state === 'running'; } async getHealth(): Promise { @@ -727,7 +769,7 @@ export class TowerClient { async renameTerminal( sessionId: string, name: string, - ): Promise<{ ok: boolean; status: number; data?: { id: string; name: string }; error?: string }> { + ): Promise<{ ok: boolean; status: number; data?: { id: string; name: string }; error?: string; connectionRefused?: boolean }> { return this.request<{ id: string; name: string }>(`/api/terminals/${sessionId}/rename`, { method: 'PATCH', body: JSON.stringify({ name }), @@ -765,7 +807,7 @@ export class TowerClient { method: 'POST', headers, body, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (!response.ok) { const text = await response.text(); @@ -1038,7 +1080,7 @@ export class TowerClient { const response = await this.fetchFn(`${this.baseUrl}${path}`, { ...options, headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); const text = await response.text(); let body: unknown = null; From 5522a861e6d57785f9e7a52f2f412fc3631b7c54 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:11:07 -0800 Subject: [PATCH 07/18] [Bugfix #1901] Test: only a refused connection reads as "Tower not running"; start never stops a stalled holder - bugfix-1901-tower-check: injected fetch through the real CLI client. Refused gives "not running"; a reset or timeout followed by success passes silently; two failures give "did not answer" with the error and no suggestion to start Tower. - bugfix-1901-tower-start-unresponsive: a real child process that accepts and never answers, on an ephemeral port. Start signals nothing, exits non-zero and names the PID and command line; a refused port starts normally; stop still kills the stalled holder. The first test fails on the pre-fix tower.ts (start SIGTERMed the holder). - sdk probeHealth cases, including a refused ::1 not masking another failure on 127.0.0.1 (fails without the every-address rule). - Existing Tower mocks gain probeHealth mapped from their isRunning mock. The #1691 and windows-launch towerStart tests stub the probe, which otherwise would reach the live Tower on 4100. --- .../air-1893-status-live-state.test.ts | 1 + .../air-1950-send-exit-retry.test.ts | 1 + ...x-1691-tower-start-surface-refusal.test.ts | 12 +- .../__tests__/bugfix-1901-tower-check.test.ts | 73 +++++++++ ...gfix-1901-tower-start-unresponsive.test.ts | 146 ++++++++++++++++++ .../__tests__/send-hold-warning.test.ts | 1 + .../src/agent-farm/__tests__/send.test.ts | 1 + .../__tests__/spec-1057-status-owner.test.ts | 1 + .../__tests__/spec-1273-interrupt.test.ts | 1 + .../__tests__/spec-1273-reset-command.test.ts | 1 + .../__tests__/spec-1313-status-held.test.ts | 1 + .../spec-1470-self-refresh-command.test.ts | 1 + .../status-fleet-observability.test.ts | 1 + .../__tests__/status-naming.test.ts | 2 + .../__tests__/tower-sweep-husks.test.ts | 1 + .../__tests__/tower-windows-launch.test.ts | 11 +- .../sdk/src/__tests__/tower-client.test.ts | 43 ++++++ 17 files changed, 291 insertions(+), 7 deletions(-) create mode 100644 packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts create mode 100644 packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts diff --git a/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts b/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts index 10b7f177b..3147be31f 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1893-status-live-state.test.ts @@ -29,6 +29,7 @@ vi.mock('../state.js', () => ({ loadState: (...a: any[]) => mockLoadState(...a) vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), getOverview: (...a: any[]) => mockGetOverview(...a), diff --git a/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts b/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts index 8ed098a31..a4eb15bce 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1950-send-exit-retry.test.ts @@ -18,6 +18,7 @@ vi.mock('../lib/tower-client.js', async (importOriginal) => ({ ...(await importOriginal()), TowerClient: class { isRunning = isRunningMock; + probeHealth = async () => ((await isRunningMock()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = sendMessageMock; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts index 1de7fbcee..0dfd78619 100644 --- a/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1691-tower-start-surface-refusal.test.ts @@ -38,18 +38,18 @@ const h = vi.hoisted(() => { vi.mock('../lib/tower-client.js', () => ({ DEFAULT_TOWER_PORT: 4100, AGENT_FARM_DIR: h.agentFarmDir, + // towerStart's "is one already up?" probe (#1901): nothing is listening, so it spawns. + TowerClient: class { + async probeHealth() { + return { state: 'not-running' }; + } + }, })); vi.mock('../utils/config.js', () => ({ getConfig: () => ({ serversDir: h.agentFarmDir }), })); -// isPortInUse() = !isPortAvailable(); "available" keeps towerStart off the -// zombie-cleanup branch and straight onto the spawn path. -vi.mock('../utils/shell.js', () => ({ - isPortAvailable: vi.fn(async () => true), -})); - // The readiness probe uses http.request; a request that immediately errors makes // isServerResponding() resolve false (the port never comes up on a refusal). vi.mock('node:http', () => { diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts new file mode 100644 index 000000000..0167f408a --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-check.test.ts @@ -0,0 +1,73 @@ +/** + * Issue #1901 — every CLI command's Tower gate goes through `checkTower`. + * + * Under heavy load a live Tower accepts the connection at once but its starved event loop misses + * the request timeout. The old gate (`isRunning()`, a bare boolean) reported that as "Tower is not + * running. Start it with: afx tower start". These tests drive the real CLI client with an + * injected fetch, the way Node's fetch fails, and pin the three outcomes the issue asks for. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { TowerClient } from '../lib/tower-client.js'; +import { checkTower } from '../lib/tower-check.js'; + +const errno = (code: string) => Object.assign(new Error(`connect ${code}`), { code }); +/** Node's fetch over `localhost`: one attempt per address, wrapped as the cause. */ +const refused = () => + Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new AggregateError([errno('ECONNREFUSED'), errno('ECONNREFUSED')], ''), { code: 'ECONNREFUSED' }), + }); +const reset = () => Object.assign(new TypeError('fetch failed'), { cause: errno('ECONNRESET') }); +const timeout = () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); +const healthy = () => + ({ ok: true, status: 200, json: async () => ({ status: 'healthy' }), text: async () => '' }) as Response; + +/** A fetch that plays `steps` in order: an Error is thrown, anything else is returned. */ +function scriptedFetch(...steps: Array<() => Error | Response>) { + const queue = [...steps]; + return vi.fn(async () => { + const step = queue.shift(); + if (!step) throw new Error('scriptedFetch: called more times than scripted'); + const outcome = step(); + if (outcome instanceof Error) throw outcome; + return outcome; + }) as unknown as typeof fetch & ReturnType; +} + +const clientWith = (fetchFn: typeof fetch) => new TowerClient({ port: 4199, getAuthKey: () => null, fetchFn }); + +describe('checkTower (#1901)', () => { + it('says "not running" and suggests starting Tower only when the connection is refused', async () => { + const fetchFn = scriptedFetch(refused); + const check = await checkTower(clientWith(fetchFn), { retryDelayMs: 0 }); + expect(check).toEqual({ state: 'not-running', message: 'Tower is not running. Start it with: afx tower start' }); + expect(fetchFn).toHaveBeenCalledTimes(1); + }); + + it('passes silently when a reset is followed by a healthy answer', async () => { + const fetchFn = scriptedFetch(reset, healthy); + expect(await checkTower(clientWith(fetchFn), { retryDelayMs: 0 })).toEqual({ state: 'running' }); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); + + it('passes silently when a timeout is followed by a healthy answer', async () => { + const fetchFn = scriptedFetch(timeout, healthy); + expect(await checkTower(clientWith(fetchFn), { retryDelayMs: 0 })).toEqual({ state: 'running' }); + }); + + it('after two failures reports the underlying error and never suggests starting Tower', async () => { + const fetchFn = scriptedFetch(timeout, reset); + const check = await checkTower(clientWith(fetchFn), { retryDelayMs: 0 }); + expect(check.state).toBe('unresponsive'); + if (check.state !== 'unresponsive') return; + expect(check.message).toMatch(/^Tower did not answer \/health \(fetch failed: ECONNRESET\) after \d+ ms; it appears to be up, retry$/); + expect(check.message).not.toContain('not running'); + expect(check.message).not.toContain('afx tower start'); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); + + it('names the caller\'s own start command in the "not running" message', async () => { + const check = await checkTower(clientWith(scriptedFetch(refused)), { startCommand: 'afx workspace start' }); + expect(check).toMatchObject({ message: 'Tower is not running. Start it with: afx workspace start' }); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts new file mode 100644 index 000000000..3b464125c --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-tower-start-unresponsive.test.ts @@ -0,0 +1,146 @@ +/** + * Issue #1901 — `afx tower start` must never stop a Tower because the machine is busy. + * + * The old start probed `/api/status` with a 2 s timeout and, when that missed, decided "port in + * use but not responding", SIGTERMed every PID on the port and started a new Tower. Under load + * that PID is the live Tower. Start now probes `/health` through `checkTower`: a refused port is + * started on as before; a holder that accepted the connection but did not answer is left alone, + * named, and the command exits non-zero. Replacing it is `afx tower stop`, which must still work. + * + * The stalled holder is a real child process listening on an ephemeral port that never answers, + * so these tests cannot reach the developer's Tower on 4100. Only the client's request timeout is + * shortened (300 ms); the fetch, the port lookup and the process table are real. + */ + +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; +import type { ChildProcess } from 'node:child_process'; +import fs from 'node:fs'; +import net from 'node:net'; +import path from 'node:path'; + +const h = vi.hoisted(() => { + const nodeOs = require('node:os') as typeof import('node:os'); + const nodePath = require('node:path') as typeof import('node:path'); + const nodeFs = require('node:fs') as typeof import('node:fs'); + const nodeEvents = require('node:events') as typeof import('node:events'); + const dir = nodeFs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), 'af-1901-')); + // A dummy compiled server so towerStart takes the `node ` branch; spawn is stubbed. + nodeFs.writeFileSync(nodePath.join(dir, 'tower-server.js'), '// stub'); + const fakeDaemon = () => Object.assign(new nodeEvents.EventEmitter(), { pid: 999_999, unref: () => {} }); + return { dir, fakeDaemon }; +}); + +vi.mock('../lib/tower-client.js', async (importOriginal) => { + const actual = await importOriginal(); + class ShortTimeoutTowerClient extends actual.TowerClient { + constructor(options: import('../lib/tower-client.js').TowerClientOptions = {}) { + super({ ...options, getAuthKey: () => null, requestTimeoutMs: 300 }); + } + } + return { ...actual, AGENT_FARM_DIR: h.dir, TowerClient: ShortTimeoutTowerClient }; +}); + +vi.mock('../utils/config.js', () => ({ + getConfig: () => ({ serversDir: h.dir }), +})); + +vi.mock('node:child_process', async () => { + const actual = await vi.importActual('node:child_process'); + return { ...actual, spawn: vi.fn(() => h.fakeDaemon()) }; +}); + +const { towerStart, towerStop } = await import('../commands/tower.js'); +const { spawn: daemonSpawn } = await import('node:child_process'); +const { spawn: realSpawn } = await vi.importActual('node:child_process'); + +const STALLED_SERVER = "require('node:http').createServer(() => {}).listen(0, '127.0.0.1', function () { console.log(this.address().port); })"; + +/** A process that accepts every connection on its port and never answers. */ +async function startStalledServer(): Promise<{ child: ChildProcess; port: number }> { + const child = realSpawn(process.execPath, ['-e', STALLED_SERVER], { stdio: ['ignore', 'pipe', 'inherit'] }); + children.push(child); + const port = await new Promise((resolve, reject) => { + child.stdout!.once('data', (chunk) => resolve(Number(String(chunk).trim()))); + child.once('exit', (code) => reject(new Error(`stalled server exited before listening (code ${code})`))); + }); + return { child, port }; +} + +async function refusedPort(): Promise { + const server = net.createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as net.AddressInfo; + await new Promise((resolve) => server.close(() => resolve())); + return port; +} + +const isAlive = (child: ChildProcess) => child.exitCode === null && child.signalCode === null; + +const children: ChildProcess[] = []; +let stderr: string[]; + +beforeEach(() => { + stderr = []; + vi.mocked(daemonSpawn).mockClear(); + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + stderr.push(args.map(String).join(' ')); + }); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit:${code ?? 0}`); + }) as never); +}); + +afterEach(() => { + vi.restoreAllMocks(); + for (const child of children.splice(0)) { + if (isAlive(child)) child.kill('SIGKILL'); + } +}); + +afterAll(() => { + fs.rmSync(h.dir, { recursive: true, force: true }); +}); + +describe('afx tower start against a port it cannot get an answer from (#1901)', () => { + it('signals nothing, exits non-zero, and names the process holding the port', async () => { + const { child, port } = await startStalledServer(); + const kill = vi.spyOn(process, 'kill'); + + await expect(towerStart({ port, wait: false })).rejects.toThrow('process.exit:1'); + + expect(kill).not.toHaveBeenCalledWith(child.pid, expect.anything()); + expect(isAlive(child)).toBe(true); + expect(daemonSpawn).not.toHaveBeenCalled(); + + const output = stderr.join('\n'); + expect(output).toContain(`A process is listening on port ${port} but did not answer /health`); + expect(output).toContain(`PID ${child.pid}: `); + expect(output).toContain('createServer'); + expect(output).toContain('If the machine is busy, wait and run afx tower start again.'); + expect(output).toContain('To replace it deliberately: afx tower stop, then afx tower start.'); + expect(output).not.toContain('Tower is not running'); + }, 30_000); + + it('starts normally when the connection is refused (nothing listening)', async () => { + const port = await refusedPort(); + + await towerStart({ port, wait: false }); + + expect(daemonSpawn).toHaveBeenCalledTimes(1); + const [, args] = vi.mocked(daemonSpawn).mock.calls[0]; + expect(args).toEqual(expect.arrayContaining([path.join(h.dir, 'tower-server.js'), String(port)])); + }, 30_000); +}); + +describe('afx tower stop against the same unresponsive holder (#1901)', () => { + it('still stops it: replacing a hung Tower stays the deliberate path', async () => { + const { child, port } = await startStalledServer(); + const exited = new Promise((resolve) => child.once('exit', resolve)); + + await towerStop({ port }); + await exited; + + expect(isAlive(child)).toBe(false); + }, 30_000); +}); diff --git a/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts b/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts index a682175ac..33f832d9d 100644 --- a/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts +++ b/packages/codev/src/agent-farm/__tests__/send-hold-warning.test.ts @@ -31,6 +31,7 @@ vi.mock('../lib/tower-client.js', async (importOriginal) => ({ ...(await importOriginal()), TowerClient: class { isRunning = isRunningMock; + probeHealth = async () => ((await isRunningMock()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = sendMessageMock; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/send.test.ts b/packages/codev/src/agent-farm/__tests__/send.test.ts index a1283499c..8152c51ab 100644 --- a/packages/codev/src/agent-farm/__tests__/send.test.ts +++ b/packages/codev/src/agent-farm/__tests__/send.test.ts @@ -18,6 +18,7 @@ const { mockIsRunning, mockSendMessage, mockLoadState } = vi.hoisted(() => ({ vi.mock('../lib/tower-client.js', () => ({ TowerClient: vi.fn().mockImplementation(function (this: any) { this.isRunning = mockIsRunning; + this.probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); this.sendMessage = mockSendMessage; }), })); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts index 69ed1c766..be3789eb1 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1057-status-owner.test.ts @@ -33,6 +33,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status now reads the overview for held-mail awareness. These suites diff --git a/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts index 22ba53a63..0733222a7 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1273-interrupt.test.ts @@ -110,6 +110,7 @@ const { mockSendMessage, mockIsRunning, mockDetectWorkspaceRoot, mockDetectCurre vi.mock('../lib/tower-client.js', () => ({ TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; }, })); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts index 8af01365b..eb15d02cf 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1273-reset-command.test.ts @@ -44,6 +44,7 @@ const { vi.mock('../lib/tower-client.js', () => ({ TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; getTerminal = mockGetTerminal; getTerminalOutput = mockGetTerminalOutput; diff --git a/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts index e75b149a3..721a8bc61 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1313-status-held.test.ts @@ -33,6 +33,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), getOverview: (...a: any[]) => mockGetOverview(...a), diff --git a/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts index b518a8728..5b85e5a5e 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1470-self-refresh-command.test.ts @@ -50,6 +50,7 @@ vi.mock('../lib/tower-client.js', async importOriginal => { ...actual, TowerClient: class { isRunning = mockIsRunning; + probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); sendMessage = mockSendMessage; }, }; diff --git a/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts b/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts index 18d97c350..755c3bd2c 100644 --- a/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts +++ b/packages/codev/src/agent-farm/__tests__/status-fleet-observability.test.ts @@ -25,6 +25,7 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status reads the overview for held-mail awareness; null → "no held info". diff --git a/packages/codev/src/agent-farm/__tests__/status-naming.test.ts b/packages/codev/src/agent-farm/__tests__/status-naming.test.ts index 4ac906200..d6d67e354 100644 --- a/packages/codev/src/agent-farm/__tests__/status-naming.test.ts +++ b/packages/codev/src/agent-farm/__tests__/status-naming.test.ts @@ -30,11 +30,13 @@ vi.mock('../state.js', () => ({ vi.mock('../lib/tower-client.js', () => ({ TowerClient: vi.fn().mockImplementation(function (this: any) { this.isRunning = (...a: any[]) => mockIsRunning(...a); + this.probeHealth = async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }); this.getHealth = (...a: any[]) => mockGetHealth(...a); this.getWorkspaceStatus = (...a: any[]) => mockGetWorkspaceStatus(...a); }), getTowerClient: () => ({ isRunning: (...a: any[]) => mockIsRunning(...a), + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), getHealth: (...a: any[]) => mockGetHealth(...a), getWorkspaceStatus: (...a: any[]) => mockGetWorkspaceStatus(...a), // Spec 1313 round 3: status reads the overview for held-mail awareness; null → "no held info". diff --git a/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts b/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts index 56184abbc..254c5311e 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-sweep-husks.test.ts @@ -12,6 +12,7 @@ const mockSweepHusks = vi.fn(); vi.mock('../lib/tower-client.js', () => ({ getTowerClient: () => ({ isRunning: mockIsRunning, + probeHealth: async () => ((await mockIsRunning()) ? { state: 'running' } : { state: 'not-running' }), findHuskCandidates: mockFindHuskCandidates, sweepHusks: mockSweepHusks, }), diff --git a/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts b/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts index ce87d3147..4191ac164 100644 --- a/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts +++ b/packages/codev/src/agent-farm/__tests__/tower-windows-launch.test.ts @@ -29,7 +29,16 @@ const h = vi.hoisted(() => { }; }); -vi.mock('../lib/tower-client.js', () => ({ DEFAULT_TOWER_PORT: 4100, AGENT_FARM_DIR: h.agentFarmDir })); +vi.mock('../lib/tower-client.js', () => ({ + DEFAULT_TOWER_PORT: 4100, + AGENT_FARM_DIR: h.agentFarmDir, + // towerStart's "is one already up?" probe (#1901): nothing is listening, so it launches. + TowerClient: class { + async probeHealth() { + return { state: 'not-running' }; + } + }, +})); vi.mock('../utils/config.js', () => ({ getConfig: () => ({ serversDir: h.agentFarmDir }) })); vi.mock('../utils/shell.js', () => ({ isPortAvailable: vi.fn(async () => true) })); vi.mock('node:http', () => { diff --git a/packages/sdk/src/__tests__/tower-client.test.ts b/packages/sdk/src/__tests__/tower-client.test.ts index c469f4636..0ef595b29 100644 --- a/packages/sdk/src/__tests__/tower-client.test.ts +++ b/packages/sdk/src/__tests__/tower-client.test.ts @@ -132,6 +132,49 @@ describe('TowerClient REST', () => { }); }); +describe('TowerClient.probeHealth (#1901)', () => { + const throwing = (err: unknown) => vi.fn(async () => { throw err; }) as unknown as typeof fetch; + const errno = (code: string) => Object.assign(new Error(`connect ${code}`), { code }); + /** Node's fetch over `localhost`: one attempt per address, the aggregate's code copied from the first. */ + const nodeFetchFailure = (...codes: string[]) => + Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new AggregateError(codes.map(errno), ''), { code: codes[0] }), + }); + + it('reports running with the health payload on a healthy answer', async () => { + const { impl } = jsonFetch(200, { status: 'healthy', uptime: 5 }); + expect(await new TowerClient(opts(impl)).probeHealth()).toMatchObject({ state: 'running', health: { uptime: 5 } }); + }); + + it('reports not-running only when every address refused the connection', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ECONNREFUSED', 'ECONNREFUSED')))); + expect(await client.probeHealth()).toEqual({ state: 'not-running' }); + }); + + it('does not let a refused ::1 mask a 127.0.0.1 that failed another way', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ECONNREFUSED', 'ECONNRESET')))); + expect((await client.probeHealth()).state).toBe('unresponsive'); + }); + + it('reports a timeout as unresponsive, not as not-running', async () => { + const timeout = Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); + const client = new TowerClient(opts(throwing(timeout))); + expect(await client.probeHealth()).toEqual({ state: 'unresponsive', error: 'Request timeout' }); + expect(await client.isRunning()).toBe(false); + }); + + it('keeps the reset reason Node puts on the cause', async () => { + const reset = Object.assign(new TypeError('fetch failed'), { cause: errno('ECONNRESET') }); + const client = new TowerClient(opts(throwing(reset))); + expect(await client.probeHealth()).toEqual({ state: 'unresponsive', error: 'fetch failed: ECONNRESET' }); + }); + + it('reports an error status as unresponsive with the status and body', async () => { + const { impl } = jsonFetch(503, { error: 'BUSY' }); + expect(await new TowerClient(opts(impl)).probeHealth()).toEqual({ state: 'unresponsive', error: 'HTTP 503: BUSY' }); + }); +}); + describe('parseSseText', () => { it('decodes one complete data: envelope and returns no tail', () => { const seen: SseEnvelope[] = []; From 9590bc6fa4076f22adda4724632ac093dcd64acb Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:14:27 -0800 Subject: [PATCH 08/18] chore(porch): bugfix-1901 pr phase-transition --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index 3369b8f10..839352f7d 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -1,7 +1,7 @@ id: bugfix-1901 title: afx-tower-is-not-running-repor protocol: bugfix -phase: fix +phase: pr plan_phases: [] current_plan_phase: null gates: @@ -11,4 +11,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-24T20:59:52.373Z' +updated_at: '2026-11-24T21:14:27.221Z' From 5fd81dcdf09673f00bde5fb14ee6f2df27fb4ac5 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:14:48 -0800 Subject: [PATCH 09/18] [Bugfix #1901] Thread: fix-phase notes --- codev/state/bugfix-1901_thread.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md index 2ec4d390c..a45782535 100644 --- a/codev/state/bugfix-1901_thread.md +++ b/codev/state/bugfix-1901_thread.md @@ -89,6 +89,26 @@ should do when the port is held but `/api/status` misses a 2 s probe. 5. The PRFT write-up gives the towerStart change its own paragraph, as a behaviour change: start no longer replaces a hung Tower by itself. +## 2026-11-24 — fix committed (98d72e49f fix, 5522a861e test) + +- AIR #1950 (merged to main mid-project) had already fixed the dead ECONNREFUSED check and added + `connectionRefused` to `request()`. I reused it rather than adding a parallel flag, and tightened + it: a localhost AggregateError counts as refused only when every attempt refused. +- The shared helper lives in its own module (`lib/tower-check.ts`), so the many tests that mock all + of `lib/tower-client.js` only needed a one-line `probeHealth` mapped from their `isRunning` mock. +- Hazard caught: the #1691 and windows-launch towerStart tests stubbed `node:http` to fake a + refusal. With the probe moved to fetch they would have hit the LIVE Tower on 4100, so both now + stub `TowerClient.probeHealth`. +- Fails-without-fix confirmed. Pre-fix `tower.ts` makes the stalled-holder test fail (it SIGTERMs + the holder). Removing the every-address rule fails the `::1` masking test. +- End to end, with the real built CLI, isolated HOME, a stalled holder on a spare port: + `afx tower start --port P` exits 1 after 21 s naming the PID and command line, and the holder + survives. `afx tower stop --port P` kills it. Stop needed the SIGKILL fallback there only because + the harness parent was blocked in `spawnSync` and could not reap its child (zombie answers + kill -0). +- `status --json` still reports `tower.running: false` for an unresponsive Tower; the human output + says "not answering" with the reason. Left as is (minimal). + ### Planned fix (per the issue's Fix section) One shared helper over the SDK probe that classifies the failure: - connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" From afaa76331ad1a98d92a2468b42ca658bbe0aaa36 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:15:26 -0800 Subject: [PATCH 10/18] chore(porch): bugfix-1901 record PR #1976 --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index 839352f7d..ea0387dad 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -11,4 +11,9 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-24T21:14:27.221Z' +updated_at: '2026-11-24T21:15:26.039Z' +pr_history: + - phase: pr + pr_number: 1976 + branch: builder/bugfix-1901 + created_at: '2026-11-24T21:15:26.038Z' From b2869baeca8e7b2343272f8f0ddbf86d3fb24924 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:23:11 -0800 Subject: [PATCH 11/18] [Bugfix #1901] Fix: workspace stop never clears state on an unanswered deactivation; IPv6-unreachable still reads as refused From PR review (CMAP round 1): - workspace stop guarded only the health probe. A healthy probe followed by a deactivation request Tower never answered fell into the legacy cleanup and clearRuntime(), wiping the registry of builders that may still be running. deactivateWorkspace() now passes status and connectionRefused through, and stop aborts with "nothing was cleared" when Tower took the request and never answered. Answered errors still fall back to local cleanup. - A localhost refusal counts when at least one attempt was refused and every attempt failed before reaching a server (EHOSTUNREACH, ENETUNREACH, EADDRNOTAVAIL). On a machine with broken IPv6, an unreachable ::1 plus a refused 127.0.0.1 is a down Tower, so workspace start starts one instead of exiting. A reached-then-reset 127.0.0.1 is still not masked. - open always reports the API error line instead of exiting silently when a failed request carries no error text. --- .../codev/src/agent-farm/commands/open.ts | 8 +++----- .../codev/src/agent-farm/commands/stop.ts | 6 ++++++ packages/sdk/src/tower-client.ts | 19 +++++++++++++------ 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/codev/src/agent-farm/commands/open.ts b/packages/codev/src/agent-farm/commands/open.ts index 6e7ceb8d0..b82b111c1 100644 --- a/packages/codev/src/agent-farm/commands/open.ts +++ b/packages/codev/src/agent-farm/commands/open.ts @@ -47,11 +47,9 @@ async function tryTowerApi( return { ok: false, refused: true }; } - if (result.error) { - logger.error(`Tower API error (HTTP ${result.status}): ${result.error}`); - logger.kv('Workspace', workspacePath); - logger.kv('File', filePath); - } + logger.error(`Tower API error (HTTP ${result.status}): ${result.error ?? 'no file tab in the response'}`); + logger.kv('Workspace', workspacePath); + logger.kv('File', filePath); return { ok: false, refused: false }; } diff --git a/packages/codev/src/agent-farm/commands/stop.ts b/packages/codev/src/agent-farm/commands/stop.ts index c67cf7c3c..0aa5d1eea 100644 --- a/packages/codev/src/agent-farm/commands/stop.ts +++ b/packages/codev/src/agent-farm/commands/stop.ts @@ -54,6 +54,12 @@ export async function stop(): Promise { return; } + // Tower took the request and never answered: it may or may not have deactivated, so nothing + // local is cleared on a guess (#1901). + if (result.status === 0 && !result.connectionRefused) { + fatal(`Tower did not answer the deactivation request (${result.error}); nothing was cleared. Retry afx workspace stop.`); + } + // If tower returned error (e.g., workspace not found), fall through to legacy cleanup logger.debug(`Tower deactivation failed: ${result.error}, trying legacy cleanup`); } diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index 6273ff5cd..071fc6a62 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -288,15 +288,20 @@ import { encodeWorkspacePath } from './workspace.js'; * `ECONNREFUSED` on `err.cause`, which a check of `err.message` alone never sees (#1950). * * `localhost` resolves to both `::1` and `127.0.0.1`, and when every address fails Node's cause - * is an AggregateError whose `code` is copied from the FIRST attempt only. Tower binds IPv4, so - * that first attempt is always a refused `::1`; the connection counts as refused only when every - * attempt was (#1901), or a refused `::1` would mask a `127.0.0.1` that failed some other way. + * is an AggregateError whose `code` is copied from the FIRST attempt only. So each attempt is + * judged (#1901): the connection counts as refused when at least one attempt was refused and + * every other one also failed before reaching a server (an unreachable `::1` on a machine with + * broken IPv6, say). A refused `::1` must not mask a `127.0.0.1` that was reached and then + * failed, such as a reset. */ +const NEVER_REACHED_CODES = new Set(['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EADDRNOTAVAIL']); + function isConnectionRefused(err: unknown): boolean { if (!(err instanceof Error)) return String(err).includes('ECONNREFUSED'); const cause = (err as { cause?: { code?: unknown; message?: unknown; errors?: unknown } }).cause; if (Array.isArray(cause?.errors) && cause.errors.length > 0) { - return cause.errors.every((attempt) => (attempt as { code?: unknown } | null)?.code === 'ECONNREFUSED'); + const codes = cause.errors.map((attempt) => (attempt as { code?: unknown } | null)?.code); + return codes.includes('ECONNREFUSED') && codes.every((code) => typeof code === 'string' && NEVER_REACHED_CODES.has(code)); } return ( err.message.includes('ECONNREFUSED') || @@ -555,7 +560,7 @@ export class TowerClient { async deactivateWorkspace( workspacePath: string - ): Promise<{ ok: boolean; stopped?: number[]; error?: string }> { + ): Promise<{ ok: boolean; stopped?: number[]; error?: string; status?: number; connectionRefused?: boolean }> { const encoded = encodeWorkspacePath(workspacePath); const result = await this.request<{ success: boolean; stopped?: number[]; error?: string }>( `/api/workspaces/${encoded}/deactivate`, @@ -563,7 +568,9 @@ export class TowerClient { ); if (!result.ok) { - return { ok: false, error: result.error }; + // `status` 0 without `connectionRefused` means Tower took the request and never answered, + // so the caller cannot know whether it deactivated (#1901). + return { ok: false, error: result.error, status: result.status, connectionRefused: result.connectionRefused }; } return { From e3c3939a132b76a600805945dc0e8a582572b871 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:23:11 -0800 Subject: [PATCH 12/18] [Bugfix #1901] Test: workspace start/stop never act on a busy Tower; broken-IPv6 refusal - bugfix-1901-workspace-start-stop: - start on an unresponsive Tower exits and never calls towerStart; - a refused connection still starts Tower; - stop aborts without clearRuntime() when /health is not answered and when the deactivation request is not answered; - an answered error still falls back to local cleanup. The start and stop guards each fail their test when removed. - sdk: an unreachable ::1 plus a refused 127.0.0.1 reads as not-running. - Thread: CMAP round 1 notes. --- codev/state/bugfix-1901_thread.md | 20 ++++ .../bugfix-1901-workspace-start-stop.test.ts | 101 ++++++++++++++++++ .../sdk/src/__tests__/tower-client.test.ts | 5 + 3 files changed, 126 insertions(+) create mode 100644 packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md index a45782535..1c0590ff9 100644 --- a/codev/state/bugfix-1901_thread.md +++ b/codev/state/bugfix-1901_thread.md @@ -109,6 +109,26 @@ should do when the port is held but `/api/status` misses a 2 s probe. - `status --json` still reports `tower.running: false` for an unresponsive Tower; the human output says "not answering" with the reason. Left as is (minimal). +## 2026-11-24 — PR #1976, CMAP round 1 + +- codex REQUEST_CHANGES (real): `workspace stop` guarded only the health probe. A healthy probe + followed by an unanswered `deactivateWorkspace()` still fell into legacy cleanup and + `clearRuntime()`. Fixed: the SDK passes through `status`/`connectionRefused`, and stop aborts + when Tower took the request but never answered. A test pins it (fails without the guard). +- claude APPROVE, non-blocking. Fixed in place: + - Broken-IPv6 regression: `ENETUNREACH` on `::1` plus a refused `127.0.0.1` read as unresponsive, + so `workspace start` would have exited instead of starting Tower. Refused now means "at least + one attempt refused and every attempt failed before reaching a server". + - `open` could exit 1 silently. + - The start/stop guards had no tests; added (start fails without its guard). +- Deferred, suggested as follow-ups: + - `/health` cost under load (`getInstances` plus a full `ps` census, probed up to twice per gate); + server-side. + - `send` stacking `--retry` over `checkTower`'s own retry. + - `status --json` not distinguishing busy from down. +- Owner ruling main-42: the 900000 ms tests timeout is now in the shared config.json, so I dropped + my local override. + ### Planned fix (per the issue's Fix section) One shared helper over the SDK probe that classifies the failure: - connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts new file mode 100644 index 000000000..9b3b59a7b --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-workspace-start-stop.test.ts @@ -0,0 +1,101 @@ +/** + * Issue #1901 — `afx workspace start` and `afx workspace stop` must not act on a Tower that is + * busy rather than down. + * + * Both used to treat any failed health probe as "Tower is not running". Start then started one, + * falling into `towerStart`'s old "zombie" branch that SIGTERMed the live Tower. Stop fell back + * to a local cleanup ending in `clearRuntime()`, wiping the registry of builders that were still + * running. That fallback is for a Tower that answered with an error or is not running. A Tower + * that took the request and never answered may still be running everything, so stop aborts and + * clears nothing: at the health probe, and again at the deactivation request itself. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockProbe = vi.fn(); +const mockDeactivate = vi.fn(); +const mockActivate = vi.fn(); +const mockClearRuntime = vi.fn(); +const mockTowerStart = vi.fn(); + +vi.mock('../lib/tower-client.js', () => ({ + DEFAULT_TOWER_PORT: 4100, + getTowerClient: () => ({ + probeHealth: (...a: unknown[]) => mockProbe(...a), + deactivateWorkspace: (...a: unknown[]) => mockDeactivate(...a), + activateWorkspace: (...a: unknown[]) => mockActivate(...a), + getWorkspaceUrl: () => 'http://localhost:4100/workspace/alpha/', + killTerminal: vi.fn(), + }), +})); +vi.mock('../commands/tower.js', () => ({ towerStart: (...a: unknown[]) => mockTowerStart(...a) })); +vi.mock('../state.js', () => ({ + loadState: () => ({ builders: [], utils: [], architects: [] }), + clearRuntime: (...a: unknown[]) => mockClearRuntime(...a), + getArchitects: () => [], +})); +vi.mock('../utils/config.js', () => ({ getConfig: () => ({ workspaceRoot: '/work/alpha' }) })); +vi.mock('../utils/index.js', () => ({ getConfig: () => ({ workspaceRoot: '/work/alpha' }) })); +vi.mock('../utils/shell.js', () => ({ openBrowser: vi.fn() })); +vi.mock('../utils/logger.js', () => ({ + logger: { header: vi.fn(), info: vi.fn(), success: vi.fn(), debug: vi.fn(), blank: vi.fn(), warn: vi.fn(), error: vi.fn(), kv: vi.fn() }, + fatal: (message: string) => { + throw new Error(`FATAL: ${message}`); + }, +})); + +const { start } = await import('../commands/start.js'); +const { stop } = await import('../commands/stop.js'); + +const unresponsive = { state: 'unresponsive', error: 'Request timeout' }; + +beforeEach(() => { + for (const mock of [mockProbe, mockDeactivate, mockActivate, mockClearRuntime, mockTowerStart]) mock.mockReset(); + mockActivate.mockResolvedValue({ ok: true }); +}); + +describe('afx workspace start against a busy Tower (#1901)', () => { + it('exits with the reason and never starts (or replaces) a Tower', async () => { + mockProbe.mockResolvedValue(unresponsive); + + await expect(start({ noBrowser: true })).rejects.toThrow(/FATAL: Tower did not answer \/health \(Request timeout\)/); + expect(mockTowerStart).not.toHaveBeenCalled(); + expect(mockActivate).not.toHaveBeenCalled(); + }); + + it('starts Tower when the connection is refused, as before', async () => { + mockProbe.mockResolvedValue({ state: 'not-running' }); + + await start({ noBrowser: true }); + expect(mockTowerStart).toHaveBeenCalledTimes(1); + expect(mockActivate).toHaveBeenCalledWith('/work/alpha'); + }); +}); + +describe('afx workspace stop against a busy Tower (#1901)', () => { + it('aborts without clearing anything when /health is not answered', async () => { + mockProbe.mockResolvedValue(unresponsive); + + await expect(stop()).rejects.toThrow(/FATAL: Tower did not answer \/health \(Request timeout\)/); + expect(mockDeactivate).not.toHaveBeenCalled(); + expect(mockClearRuntime).not.toHaveBeenCalled(); + }); + + it('aborts without clearing anything when the deactivation request is not answered', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + mockDeactivate.mockResolvedValue({ ok: false, status: 0, error: 'Request timeout' }); + + await expect(stop()).rejects.toThrow( + 'FATAL: Tower did not answer the deactivation request (Request timeout); nothing was cleared.', + ); + expect(mockClearRuntime).not.toHaveBeenCalled(); + }); + + it('still falls back to local cleanup when Tower answers with an error', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + mockDeactivate.mockResolvedValue({ ok: false, status: 404, error: 'Workspace not found' }); + + await stop(); + expect(mockClearRuntime).toHaveBeenCalledWith('/work/alpha'); + }); +}); diff --git a/packages/sdk/src/__tests__/tower-client.test.ts b/packages/sdk/src/__tests__/tower-client.test.ts index 0ef595b29..371052038 100644 --- a/packages/sdk/src/__tests__/tower-client.test.ts +++ b/packages/sdk/src/__tests__/tower-client.test.ts @@ -151,6 +151,11 @@ describe('TowerClient.probeHealth (#1901)', () => { expect(await client.probeHealth()).toEqual({ state: 'not-running' }); }); + it('still reports not-running when ::1 is unreachable and 127.0.0.1 refused (broken IPv6)', async () => { + const client = new TowerClient(opts(throwing(nodeFetchFailure('ENETUNREACH', 'ECONNREFUSED')))); + expect(await client.probeHealth()).toEqual({ state: 'not-running' }); + }); + it('does not let a refused ::1 mask a 127.0.0.1 that failed another way', async () => { const client = new TowerClient(opts(throwing(nodeFetchFailure('ECONNREFUSED', 'ECONNRESET')))); expect((await client.probeHealth()).state).toBe('unresponsive'); From 602c377bc2a94c6bc01dbea50499cd855e2f6abc Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:25:35 -0800 Subject: [PATCH 13/18] chore(porch): bugfix-1901 pr gate-requested --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index ea0387dad..87e437672 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -7,13 +7,15 @@ current_plan_phase: null gates: pr: status: pending + requested_at: '2026-11-24T21:25:35.735Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-24T21:15:26.039Z' +updated_at: '2026-11-24T21:25:35.738Z' pr_history: - phase: pr pr_number: 1976 branch: builder/bugfix-1901 created_at: '2026-11-24T21:15:26.038Z' +pr_ready_for_human: true From 86245db5be8526c5dcd051b2ad058fcbabc2f032 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:34:12 -0800 Subject: [PATCH 14/18] [Bugfix #1901] Fix: send never stacks retries or misreads a busy Tower as a not-found; status --json tells busy from down Architect round, after merging PR #1957 (Spec 1940, named architects): - A :architect: send that came back NOT_FOUND asks the address book, to tell an older Tower. When Tower did not answer that check at all, the bare not-found was reported, though nobody could judge it. getAddressBook() now marks a failure with no HTTP answer as unanswered, and send says the check went unanswered and to retry. An answered failure of the check still leaves the not-found. - checkTower() takes a retries option (default 1). send --retry N passes 0, so its budget owns the retrying: N + 1 health probes instead of 2(N + 1). Without --retry the gate's single retry still applies. - status --json: tower is {running, state, error}. running is unchanged for existing scripts; state is running, not-running or unresponsive; error is the reason when unresponsive, otherwise null. --- .../codev/src/agent-farm/commands/send.ts | 34 +++++++++++++------ .../codev/src/agent-farm/commands/status.ts | 16 ++++++--- .../codev/src/agent-farm/lib/tower-check.ts | 7 +++- packages/sdk/src/tower-client.ts | 6 ++-- 4 files changed, 44 insertions(+), 19 deletions(-) diff --git a/packages/codev/src/agent-farm/commands/send.ts b/packages/codev/src/agent-farm/commands/send.ts index 253cf75ab..c2576201a 100644 --- a/packages/codev/src/agent-farm/commands/send.ts +++ b/packages/codev/src/agent-farm/commands/send.ts @@ -354,16 +354,28 @@ function namesAnArchitectInAWorkspace(to: string): boolean { * is the older one; a Tower that answers knows the form, and its not-found stands. * * Only on that failure, so a send that succeeds, or fails any other way, costs nothing more. + * + * Returns what to report in place of the Tower's not-found, or null when it stands. A Tower + * that gives no answer to the question at all is busy, not older, and its not-found cannot be + * judged either way, so that is said instead (#1901). */ -async function failedForAnOlderTower( +async function explainNotFound( client: TowerClient, to: string, result: SendResult, caller: { workspace?: string; from: string }, -): Promise { - if (result.errorCode !== 'NOT_FOUND' || !namesAnArchitectInAWorkspace(to)) return false; +): Promise { + if (result.errorCode !== 'NOT_FOUND' || !namesAnArchitectInAWorkspace(to)) return null; const book = await client.getAddressBook(caller); - return !book.ok && book.unknownRoute === true; + if (book.ok) return null; + if (book.unknownRoute) return olderTowerError('does not know an address of the form :architect:'); + if (book.unanswered) { + return ( + `Tower did not answer the address-book check (${book.error}) needed to tell whether ${to} is ` + + `missing or this Tower predates that address form; it appears to be up, retry` + ); + } + return null; } /** @@ -536,16 +548,18 @@ export async function send(options: SendOptions): Promise { } // Ensure Tower is running. The health probe sends nothing, so under --retry every failure of - // it may be retried. + // it may be retried. One loop owns the retrying (#1901): with --retry it is that budget, and + // the gate probes once per attempt; without it, the gate's own single retry applies. const client = new TowerClient(); const retry = retryBudget(options.retry ?? 0); - let tower = await checkTower(client); + const gate = (options.retry ?? 0) > 0 ? { retries: 0 } : {}; + let tower = await checkTower(client, gate); while (tower.state !== 'running') { const why = tower.state === 'not-running' ? 'Tower is not running' : `Tower did not answer /health (${tower.error})`; if (!(await retry(`${why}; nothing has been sent.`))) { fatal(tower.message); } - tower = await checkTower(client); + tower = await checkTower(client, gate); } if (options.all) { @@ -588,10 +602,8 @@ export async function send(options: SendOptions): Promise { }, retry); if (!result.ok) { - if (await failedForAnOlderTower(client, target!, result, { workspace, from })) { - throw new Error(olderTowerError('does not know an address of the form :architect:')); - } - throw new Error(result.error || 'Unknown error'); + const explained = await explainNotFound(client, target!, result, { workspace, from }); + throw new Error(explained ?? (result.error || 'Unknown error')); } // Report the real first outcome (Spec 1307 `--delay` + Spec 1313 mailbox). A diff --git a/packages/codev/src/agent-farm/commands/status.ts b/packages/codev/src/agent-farm/commands/status.ts index 4500f6967..a2cce2cbf 100644 --- a/packages/codev/src/agent-farm/commands/status.ts +++ b/packages/codev/src/agent-farm/commands/status.ts @@ -8,7 +8,7 @@ import { loadState } from '../state.js'; import { logger } from '../utils/logger.js'; import { getConfig } from '../utils/config.js'; import { getTowerClient } from '../lib/tower-client.js'; -import { checkTower } from '../lib/tower-check.js'; +import { checkTower, type TowerCheck } from '../lib/tower-check.js'; import { getTypeColor } from '../utils/display.js'; import { currentArchitectName } from '../utils/architect-name.js'; import { discoverBuilders, type StoredBuilderIdentity } from '../servers/overview.js'; @@ -289,7 +289,7 @@ function renderActivity(visible: Builder[], views: Map) * stdout in `--json` mode — safe for tooling to `JSON.parse`. */ function emitStatusJson(params: { - towerRunning: boolean; + tower: TowerCheck; // `name` is explicitly nullable (not optional): an unregistered workspace // must still emit `"name": null` so the machine-readable contract is stable // for tooling — `JSON.stringify` would otherwise drop an `undefined` key. @@ -305,10 +305,16 @@ function emitStatusJson(params: { visible: Builder[]; views: Map; }): void { - const { towerRunning, workspace, architects, visible, views, ownerFilter, fleet, mailbox } = params; + const { tower, workspace, architects, visible, views, ownerFilter, fleet, mailbox } = params; const payload = { - tower: { running: towerRunning }, + // `running: false` covers both a Tower that is down and one that took the connection but did + // not answer; `state` tells them apart and `error` says why it did not answer (#1901). + tower: { + running: tower.state === 'running', + state: tower.state, + error: tower.state === 'unresponsive' ? tower.error : null, + }, workspace, fleet, mailbox, @@ -407,7 +413,7 @@ export async function status(options: StatusOptions = {}): Promise { } } emitStatusJson({ - towerRunning, + tower, workspace: { path: workspacePath, name: workspaceName ?? null, active: workspaceActive }, architects, visible, diff --git a/packages/codev/src/agent-farm/lib/tower-check.ts b/packages/codev/src/agent-farm/lib/tower-check.ts index c1acf79e4..192ce8be4 100644 --- a/packages/codev/src/agent-farm/lib/tower-check.ts +++ b/packages/codev/src/agent-farm/lib/tower-check.ts @@ -21,6 +21,11 @@ export type TowerCheck = export interface TowerCheckOptions { /** The command a "not running" message tells the reader to run. */ startCommand?: string; + /** + * Extra probes after an unresponsive one (default 1). A caller with its own retry loop passes + * 0, so the two do not stack. + */ + retries?: number; retryDelayMs?: number; } @@ -30,7 +35,7 @@ export async function checkTower( ): Promise { const startedAt = Date.now(); let probe = await client.probeHealth(); - if (probe.state === 'unresponsive') { + for (let left = options.retries ?? 1; probe.state === 'unresponsive' && left > 0; left--) { await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? TOWER_RETRY_DELAY_MS)); probe = await client.probeHealth(); } diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index 97937cc7f..74d1c9404 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -645,7 +645,7 @@ export class TowerClient { */ async getAddressBook( caller: { workspace?: string; from?: string } = {}, - ): Promise<{ ok: true; result: AddressBookResponse } | { ok: false; error: string; unknownRoute?: true }> { + ): Promise<{ ok: true; result: AddressBookResponse } | { ok: false; error: string; unknownRoute?: true; unanswered?: true }> { const query = new URLSearchParams(); if (caller.workspace !== undefined) query.set('workspace', caller.workspace); if (caller.from !== undefined) query.set('from', caller.from); @@ -653,7 +653,9 @@ export class TowerClient { const result = await this.request(`/api/address-book${text === '' ? '' : `?${text}`}`); if (!result.ok || result.data === undefined) { const failure = { ok: false as const, error: result.error ?? `Tower answered ${result.status}` }; - return isUnknownRoute(result) ? { ...failure, unknownRoute: true } : failure; + if (isUnknownRoute(result)) return { ...failure, unknownRoute: true }; + // No HTTP answer at all (timeout, reset, refused): says nothing about which Tower it is (#1901). + return result.status === 0 ? { ...failure, unanswered: true } : failure; } return { ok: true, result: result.data }; } From 77a2fcaa9c6c2886553d0c44f9034c493fdf9716 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:34:12 -0800 Subject: [PATCH 15/18] [Bugfix #1901] Test: send against a busy Tower after Spec 1940; retry ownership; status --json state - bugfix-1901-send-unresponsive: the real send command and SDK client over a scripted Tower. - A three-part address against an unanswered /health, an unanswered address-book check, and an unanswered send each read as unresponsive or a timeout, never "older Tower" and never a bare not-found. - Total probes pinned: 2 without --retry, N + 1 with --retry N. - bugfix-1901-status-json: tower is {running, state, error} for running, not-running and unresponsive. - Each fails without its change. - Thread: architect-round notes. --- codev/state/bugfix-1901_thread.md | 18 ++ .../bugfix-1901-send-unresponsive.test.ts | 161 ++++++++++++++++++ .../__tests__/bugfix-1901-status-json.test.ts | 73 ++++++++ 3 files changed, 252 insertions(+) create mode 100644 packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts create mode 100644 packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts diff --git a/codev/state/bugfix-1901_thread.md b/codev/state/bugfix-1901_thread.md index 1c0590ff9..5a38b2e64 100644 --- a/codev/state/bugfix-1901_thread.md +++ b/codev/state/bugfix-1901_thread.md @@ -129,6 +129,24 @@ should do when the port is held but `/api/status` misses a 2 s probe. - Owner ruling main-42: the 900000 ms tests timeout is now in the shared config.json, so I dropped my local override. +## 2026-11-24 — architect round: merge with Spec 1940, two follow-ups pulled in + +- Merged origin/main (merge 325ae5022), which brought PR #1957 (named architects). It also changes + `send.ts` and the SDK client. Read as one piece: + - an unresponsive `/health` stops at the gate, before any send or address-book question; + - an unanswered send is a timeout and never asks the address book, which only a NOT_FOUND triggers; + - **gap:** NOT_FOUND followed by an unanswered address-book check was reported as the bare + not-found. `getAddressBook()` now marks a failure with no HTTP answer as `unanswered`, and + send says the check went unanswered and to retry. An answered failure still leaves the + not-found, as Spec 1940's test pins. +- Retry ownership: `checkTower` takes `retries` (default 1). `send --retry N` passes 0, so the budget + owns the retrying: N + 1 probes, not 2(N + 1). Without `--retry` it stays at 2. +- `status --json`: `tower` is `{running, state, error}`. `running` is unchanged for existing + scripts, and `error` is null unless unresponsive. +- Follow-up (1), the cheap liveness route, was filed by the architect as #1977. +- Fails-without-change confirmed for each: retry-line revert → probe-count test fails; merged-head + send.ts/status.ts → address-book test and all 3 status-json tests fail. + ### Planned fix (per the issue's Fix section) One shared helper over the SDK probe that classifies the failure: - connect refused (nothing listening) → "Tower is not running. Start it with: afx tower start" diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts new file mode 100644 index 000000000..f8d3ebd46 --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-send-unresponsive.test.ts @@ -0,0 +1,161 @@ +/** + * Issue #1901 × Spec 1940 — `afx send` against a Tower that is up but not answering. + * + * Two changes meet in send's failure handling. Spec 1940 asks the address book when a + * `:architect:` send comes back not found, to tell an older Tower. #1901 tells a + * Tower that is not running from one that took the connection and did not answer. A busy Tower + * must read as busy at every step: not "not running", not "older Tower", and not a not-found + * that nobody could check. And `--retry` must not stack on the health gate's own retry: one loop + * owns the retrying, and the total number of probes is pinned here. + * + * Same harness as `spec-1940-older-tower-send.test.ts`: the real command and the real SDK client, + * over a transport that answers as the Tower under test does. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; +import { TowerClient as SdkTowerClient } from '@cluesmith/codev-sdk/tower-client'; + +const transport = vi.hoisted(() => ({ fetchFn: undefined as unknown as typeof fetch })); + +vi.mock('../lib/tower-client.js', () => ({ + TowerClient: class extends SdkTowerClient { + constructor() { + super({ fetchFn: (...args: Parameters) => transport.fetchFn(...args) }); + } + }, +})); + +const { send } = await import('../commands/send.js'); + +type Route = () => Response | Error; + +function json(status: number, payload: unknown): Response { + return new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json' } }); +} + +/** What Node's fetch throws when the 10 s abort fires before Tower answers. */ +const noAnswer = () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }); +const healthy = () => json(200, { status: 'healthy' }); +/** The not-found an older Tower gives `codev:architect:review` (it reads `architect:review` as a builder). */ +const olderNotFound = () => + json(404, { error: 'NOT_FOUND', message: "Agent 'architect:review' not found in workspace 'codev'." }); + +/** A Tower as a transport: each route answers, or throws to stand for no answer. Records the paths asked. */ +function tower(routes: { health: Route; send?: Route; addressBook?: Route }): string[] { + const asked: string[] = []; + transport.fetchFn = (async (input: Parameters[0]) => { + const { pathname } = new URL(String(input)); + asked.push(pathname); + const route = { '/health': routes.health, '/api/send': routes.send, '/api/address-book': routes.addressBook }[pathname]; + if (!route) throw new Error(`unexpected request: ${pathname}`); + const outcome = route(); + if (outcome instanceof Error) throw outcome; + return outcome; + }) as typeof fetch; + return asked; +} + +class Exit extends Error { + constructor(readonly code: number) { + super(`exit ${code}`); + } +} + +const UNANSWERED_HEALTH = /^\[error\] Tower did not answer \/health \(Request timeout\) after \d+ ms; it appears to be up, retry$/; + +describe('afx send against a busy Tower (#1901 × Spec 1940)', () => { + let workspace: string; + let errors: string[]; + const cwd = process.cwd(); + const architectName = process.env.CODEV_ARCHITECT_NAME; + + beforeEach(() => { + workspace = realpathSync(mkdtempSync(join(tmpdir(), 'bugfix-1901-send-'))); + mkdirSync(join(workspace, '.git')); + process.chdir(workspace); + process.env.CODEV_ARCHITECT_NAME = 'main'; + errors = []; + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation((...args) => void errors.push(stripVTControlCharacters(args.join(' ')))); + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Exit(code ?? 0); + }) as never); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + process.chdir(cwd); + if (architectName === undefined) delete process.env.CODEV_ARCHITECT_NAME; + else process.env.CODEV_ARCHITECT_NAME = architectName; + rmSync(workspace, { recursive: true, force: true }); + }); + + /** Run `send`, letting faked retry pauses elapse, and return how it exited. */ + async function sendExpectingExit(options: Parameters[0]): Promise { + vi.useFakeTimers(); + const settled = expect(send(options)).rejects.toMatchObject({ code: 1 }); + await vi.runAllTimersAsync(); + await settled; + } + + describe('a three-part address', () => { + it('reports an unanswered /health as unresponsive, before any send or address-book question', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toHaveLength(1); + expect(errors[0]).toMatch(UNANSWERED_HEALTH); + expect(asked).toEqual(['/health', '/health']); + }); + + it('reports an unanswered address-book check as unresponsive, not as an older Tower or a not-found', async () => { + const asked = tower({ health: healthy, send: olderNotFound, addressBook: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toEqual([ + '[error] Tower did not answer the address-book check (Request timeout) needed to tell whether ' + + 'codev:architect:review is missing or this Tower predates that address form; it appears to be up, retry', + ]); + expect(asked).toEqual(['/health', '/api/send', '/api/address-book']); + }); + + it('reports an unanswered send as a timeout, and asks the address book nothing', async () => { + const asked = tower({ health: healthy, send: noAnswer }); + + await sendExpectingExit({ builder: 'codev:architect:review', message: 'hello' }); + + expect(errors).toEqual(['[error] Request timeout']); + expect(asked).toEqual(['/health', '/api/send']); + }); + }); + + describe('who owns the retry', () => { + it('without --retry, the health gate retries once: two probes in all', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'spir-42', message: 'hello' }); + + expect(asked).toEqual(['/health', '/health']); + expect(errors.filter((line) => line.startsWith('[retry]'))).toEqual([]); + }); + + it('with --retry N, that budget owns the retrying and the gate probes once per attempt: N + 1 probes', async () => { + const asked = tower({ health: noAnswer }); + + await sendExpectingExit({ builder: 'spir-42', message: 'hello', retry: 2 }); + + expect(asked).toEqual(['/health', '/health', '/health']); + const retries = errors.filter((line) => line.startsWith('[retry]')); + expect(retries).toHaveLength(2); + expect(retries[0]).toContain('Tower did not answer /health (Request timeout); nothing has been sent. Retry 1/2'); + expect(errors.at(-1)).toMatch(UNANSWERED_HEALTH); + }); + }); +}); diff --git a/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts b/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts new file mode 100644 index 000000000..0205ac2d9 --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/bugfix-1901-status-json.test.ts @@ -0,0 +1,73 @@ +/** + * Issue #1901 — `afx status --json` tells a busy Tower from a down one. + * + * `tower.running` stays as it was (false for both, so existing scripts read the same). `state` + * says which (`running`, `not-running`, `unresponsive`), and `error` says why an unresponsive + * Tower did not answer, null otherwise: the file's nullable-not-optional contract. + * + * Mocking harness mirrors status-fleet-observability.test.ts. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +const mockProbe = vi.fn(); + +vi.mock('../utils/config.js', () => ({ + getConfig: vi.fn(() => ({ workspaceRoot: '/fake/workspace' })), +})); +vi.mock('../state.js', () => ({ + loadState: () => ({ architect: null, architects: [], builders: [], utils: [], annotations: [] }), +})); +vi.mock('../lib/tower-client.js', () => ({ + getTowerClient: () => ({ + probeHealth: (...a: unknown[]) => mockProbe(...a), + getHealth: async () => ({ status: 'healthy', uptime: 1, activeWorkspaces: 0, memoryUsage: 0 }), + getWorkspaceStatus: async () => null, + getOverview: async () => null, + }), +})); +vi.mock('../../lib/config.js', () => ({ loadConfig: vi.fn(() => ({})) })); +vi.mock('../utils/logger.js', () => ({ + logger: { header: vi.fn(), success: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn(), info: vi.fn(), kv: vi.fn(), blank: vi.fn(), row: vi.fn() }, + fatal: vi.fn((msg: string) => { + throw new Error(msg); + }), +})); + +import { status } from '../commands/status.js'; + +describe('afx status --json: busy apart from down (#1901)', () => { + let logSpy: ReturnType; + + beforeEach(() => { + mockProbe.mockReset(); + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + + afterEach(() => { + logSpy.mockRestore(); + }); + + async function towerField(): Promise { + await status({ json: true }); + expect(logSpy).toHaveBeenCalledTimes(1); + return JSON.parse(String(logSpy.mock.calls[0][0])).tower; + } + + it('reports an unresponsive Tower with its reason', async () => { + mockProbe.mockResolvedValue({ state: 'unresponsive', error: 'Request timeout' }); + expect(await towerField()).toEqual({ running: false, state: 'unresponsive', error: 'Request timeout' }); + }); + + it('reports a down Tower as not-running, error null (present, not omitted)', async () => { + mockProbe.mockResolvedValue({ state: 'not-running' }); + const tower = await towerField(); + expect(tower).toEqual({ running: false, state: 'not-running', error: null }); + expect(Object.prototype.hasOwnProperty.call(tower, 'error')).toBe(true); + }); + + it('reports a running Tower as before, with state running', async () => { + mockProbe.mockResolvedValue({ state: 'running' }); + expect(await towerField()).toEqual({ running: true, state: 'running', error: null }); + }); +}); From fed29326fb8f3504f570a22305dc3aa617140bee Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 16:38:15 -0800 Subject: [PATCH 16/18] [Bugfix #1901] Fix: the decisions image request honours the client's requestTimeoutMs PR #1971 (merged from main) added requestBinary() with the module's fixed REQUEST_TIMEOUT_MS. The requestTimeoutMs option this PR added is the timeout for every request, and the other three request paths use it. The default is unchanged (10 000 ms), so only a client that sets the option sees a difference. --- packages/sdk/src/tower-client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk/src/tower-client.ts b/packages/sdk/src/tower-client.ts index 273ec19c1..ac052e375 100644 --- a/packages/sdk/src/tower-client.ts +++ b/packages/sdk/src/tower-client.ts @@ -1268,7 +1268,7 @@ export class TowerClient { } const response = await this.fetchFn(`${this.baseUrl}${path}`, { headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal: AbortSignal.timeout(this.requestTimeoutMs), }); if (response.ok) { const bytes = new Uint8Array(await response.arrayBuffer()); From 365e44feb2088f6e9c6d48257dec81bbc340570f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 16:47:43 -0800 Subject: [PATCH 17/18] chore(porch): bugfix-1901 pr gate-approved --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index 87e437672..bae69e7c6 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -6,16 +6,17 @@ plan_phases: [] current_plan_phase: null gates: pr: - status: pending + status: approved requested_at: '2026-11-24T21:25:35.735Z' + approved_at: '2026-11-25T00:47:43.268Z' iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-24T21:25:35.738Z' +updated_at: '2026-11-25T00:47:43.280Z' pr_history: - phase: pr pr_number: 1976 branch: builder/bugfix-1901 created_at: '2026-11-24T21:15:26.038Z' -pr_ready_for_human: true +pr_ready_for_human: false From a487ae5d59de1bc2c8f5d04dd80a1b9517021d95 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 16:47:45 -0800 Subject: [PATCH 18/18] chore(porch): bugfix-1901 protocol complete --- .../bugfix-1901-afx-tower-is-not-running-repor/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml index bae69e7c6..a70437d44 100644 --- a/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml +++ b/codev/projects/bugfix-1901-afx-tower-is-not-running-repor/status.yaml @@ -1,7 +1,7 @@ id: bugfix-1901 title: afx-tower-is-not-running-repor protocol: bugfix -phase: pr +phase: verified plan_phases: [] current_plan_phase: null gates: @@ -13,7 +13,7 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-16T21:51:51.349Z' -updated_at: '2026-11-25T00:47:43.280Z' +updated_at: '2026-11-25T00:47:45.750Z' pr_history: - phase: pr pr_number: 1976