Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d2f4417
chore(porch): bugfix-1901 init bugfix
waleedkadous Nov 16, 2026
ca64179
[Bugfix #1901] WIP: investigate notes before reboot (no code yet)
waleedkadous Nov 17, 2026
06ee5a0
[Bugfix #1901] Investigate: root cause and scope
waleedkadous Nov 24, 2026
e7675a8
Merge remote-tracking branch 'origin/main' into builder/bugfix-1901
waleedkadous Nov 24, 2026
5667ade
[Bugfix #1901] Record architect ruling: towerStart in scope
waleedkadous Nov 24, 2026
7b10def
chore(porch): bugfix-1901 fix phase-transition
waleedkadous Nov 24, 2026
98d72e4
[Bugfix #1901] Fix: tell "Tower not running" from "Tower not answering"
waleedkadous Nov 24, 2026
5522a86
[Bugfix #1901] Test: only a refused connection reads as "Tower not ru…
waleedkadous Nov 24, 2026
9590bc6
chore(porch): bugfix-1901 pr phase-transition
waleedkadous Nov 24, 2026
5fd81dc
[Bugfix #1901] Thread: fix-phase notes
waleedkadous Nov 24, 2026
afaa763
chore(porch): bugfix-1901 record PR #1976
waleedkadous Nov 24, 2026
b2869ba
[Bugfix #1901] Fix: workspace stop never clears state on an unanswere…
waleedkadous Nov 24, 2026
e3c3939
[Bugfix #1901] Test: workspace start/stop never act on a busy Tower; …
waleedkadous Nov 24, 2026
602c377
chore(porch): bugfix-1901 pr gate-requested
waleedkadous Nov 24, 2026
325ae50
Merge remote-tracking branch 'origin/main' into builder/bugfix-1901
waleedkadous Nov 24, 2026
86245db
[Bugfix #1901] Fix: send never stacks retries or misreads a busy Towe…
waleedkadous Nov 24, 2026
77a2fca
[Bugfix #1901] Test: send against a busy Tower after Spec 1940; retry…
waleedkadous Nov 24, 2026
620f0ae
Merge remote-tracking branch 'origin/main' into builder/bugfix-1901
waleedkadous Nov 25, 2026
fed2932
[Bugfix #1901] Fix: the decisions image request honours the client's …
waleedkadous Nov 25, 2026
365e44f
chore(porch): bugfix-1901 pr gate-approved
waleedkadous Nov 25, 2026
a487ae5
chore(porch): bugfix-1901 protocol complete
waleedkadous Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
id: bugfix-1901
title: afx-tower-is-not-running-repor
protocol: bugfix
phase: verified
plan_phases: []
current_plan_phase: null
gates:
pr:
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-25T00:47:45.750Z'
pr_history:
- phase: pr
pr_number: 1976
branch: builder/bugfix-1901
created_at: '2026-11-24T21:15:26.038Z'
pr_ready_for_human: false
159 changes: 159 additions & 0 deletions codev/state/bugfix-1901_thread.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# 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.

## 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.

### 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.

## 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).

## 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.

## 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"
- timeout / reset / bad response → retry once after a short pause; if that also fails, report
"Tower did not answer /health (<error>) 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.
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ vi.mock('../lib/tower-client.js', async (importOriginal) => ({
...(await importOriginal<typeof import('../lib/tower-client.js')>()),
TowerClient: class {
isRunning = isRunningMock;
probeHealth = async () => ((await isRunningMock()) ? { state: 'running' } : { state: 'not-running' });
sendMessage = sendMessageMock;
},
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -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
* `<workspace>:architect:<name>` 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<typeof fetch>) => 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<typeof fetch>[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<typeof send>[0]): Promise<void> {
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);
});
});
});
Loading
Loading