fix(cases): bounded path probe landing fixes (#516)

- hooks-config: a probe the bulk cap refused gets ONE bounded re-probe past the
  cap (probeBeforeTouching), and whatever is still unknown is skipped. The
  per-spawn hook and statusLine helpers used to fall back to an unbounded
  lstat/readFile there, which on a dead workspace never settled and could take
  the last threadpool workers (and hang the boot hook sweep). New test: cap
  engaged, stat/lstat/readFile hanging on two more paths; both helpers return.
- describeUnknownPath()/unknownPathReason(): POST /api/sessions, quick-start and
  GET /api/cases/:name now say a folder was not checked (other mounts are still
  not answering) instead of blaming a healthy folder at the stall ceiling.
  errorCodes unchanged.
- #535 x #516: Create in a custom folder probes the parent through the bounded
  probe before realpath/stat/lstat/readdir touch it; an unknown parent is 422
  OPERATION_FAILED (UNREACHABLE) within the probe timeout. New test.
- Docs: MAX_STALLED default is 2 (follows UV_THREADPOOL_SIZE), CaseInfo
  .unreachable covers a refused probe, the boot sweep skips an unanswering
  workspace, a CLAUDE.md gotcha for bounded probes, verbs.md documents the 422
  (plugin mirror synced), api-reference documents the custom-folder 422.
- Tests: the launcher case-lookup describe is no longer nested in the Grok
  block, and the cap-below-ceiling test no longer depends on an inherited
  UV_THREADPOOL_SIZE / CODEMAN_PATH_PROBE_MAX_STALLED.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-10-05 20:00:30 +02:00
parent aca23aa404
commit 88f5a43a9f
17 changed files with 335 additions and 101 deletions
+48 -3
View File
@@ -37,7 +37,14 @@ vi.mock('node:fs', async (importOriginal) => {
});
import fs from 'node:fs/promises';
import { boundedPathExists, isNearStalledPath, probePath, probePathKind } from '../src/utils/bounded-path-probe.js';
import {
boundedPathExists,
describeUnknownPath,
isNearStalledPath,
probePath,
probePathKind,
unknownPathReason,
} from '../src/utils/bounded-path-probe.js';
import { MAX_STALLED_PATH_PROBES, PATH_PROBE_STALL_CEILING, PATH_PROBE_TIMEOUT_MS } from '../src/config/path-probe.js';
const stat = vi.mocked(fs.stat);
@@ -100,6 +107,9 @@ describe('probePath', () => {
expect(await boundedPathExists('/present')).toBe(true);
expect(await boundedPathExists('/missing')).toBe(false);
expect(await boundedPathExists('/eio')).toBe(false);
// An error answer is neither a stall nor a refusal.
expect(unknownPathReason('/eio')).toBe('unreadable');
expect(describeUnknownPath('Case folder', '/eio')).toBe('Case folder is not responding or not readable: /eio');
});
it('reports whether a present path is a directory', async () => {
@@ -291,6 +301,15 @@ describe('probePath', () => {
expect(stat).not.toHaveBeenCalled();
expect(await probePath('/healthy/explicit', { pastCap: true })).toBe('unknown');
expect(stat).not.toHaveBeenCalled();
// ...and the message says the folder was never checked, rather than blaming it.
expect(unknownPathReason('/healthy/explicit', { pastCap: true })).toBe('refused');
expect(unknownPathReason(dead[0], { pastCap: true })).toBe('stalled');
expect(describeUnknownPath('workingDir', '/healthy/explicit', { pastCap: true })).toMatch(
/^workingDir was not checked: .*not answering.*: \/healthy\/explicit$/
);
expect(describeUnknownPath('workingDir', dead[0], { pastCap: true })).toBe(
`workingDir is not responding or not readable: ${dead[0]}`
);
// Once one stalled stat settles, an explicit request is probed again.
releases.get(dead[0])!();
@@ -298,8 +317,34 @@ describe('probePath', () => {
expect(await probePath('/healthy/explicit', { pastCap: true })).toBe('present');
});
it('keeps the bulk cap below the ceiling, so a pastCap probe has room', () => {
expect(MAX_STALLED_PATH_PROBES).toBeLessThan(PATH_PROBE_STALL_CEILING);
it('keeps the bulk cap below the ceiling, so a pastCap probe has room', async () => {
// Read under a controlled environment: the limits are computed at import from
// UV_THREADPOOL_SIZE and CODEMAN_PATH_PROBE_MAX_STALLED, which the test process
// could otherwise inherit.
const saved = { uv: process.env.UV_THREADPOOL_SIZE, max: process.env.CODEMAN_PATH_PROBE_MAX_STALLED };
const limitsUnder = async (uv: string | undefined, max: string | undefined) => {
if (uv === undefined) delete process.env.UV_THREADPOOL_SIZE;
else process.env.UV_THREADPOOL_SIZE = uv;
if (max === undefined) delete process.env.CODEMAN_PATH_PROBE_MAX_STALLED;
else process.env.CODEMAN_PATH_PROBE_MAX_STALLED = max;
vi.resetModules();
return import('../src/config/path-probe.js');
};
try {
const defaults = await limitsUnder(undefined, undefined);
expect([defaults.MAX_STALLED_PATH_PROBES, defaults.PATH_PROBE_STALL_CEILING]).toEqual([2, 3]);
const bigPool = await limitsUnder('8', undefined);
expect([bigPool.MAX_STALLED_PATH_PROBES, bigPool.PATH_PROBE_STALL_CEILING]).toEqual([6, 7]);
// An override may reach the ceiling but never pass it.
const overridden = await limitsUnder(undefined, '64');
expect(overridden.MAX_STALLED_PATH_PROBES).toBe(overridden.PATH_PROBE_STALL_CEILING);
} finally {
if (saved.uv === undefined) delete process.env.UV_THREADPOOL_SIZE;
else process.env.UV_THREADPOOL_SIZE = saved.uv;
if (saved.max === undefined) delete process.env.CODEMAN_PATH_PROBE_MAX_STALLED;
else process.env.CODEMAN_PATH_PROBE_MAX_STALLED = saved.max;
vi.resetModules();
}
});
it('warns once when a path first stalls and once when the cap engages', async () => {
+91
View File
@@ -0,0 +1,91 @@
/**
* @fileoverview "Create in a custom folder" (#535) on a parent folder that does not
* answer (#516): `prepareNewCasePath` must ask the bounded path probe first, and give
* up with UNREACHABLE within the probe timeout instead of reaching the realpath / stat /
* lstat / readdir calls that would wait on a hard mount forever.
*
* Only the chosen dead paths hang; everything else is the real filesystem.
* Port: none.
*/
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, realpathSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const probe = vi.hoisted(() => {
// Short probe timeout so a stall costs ~100 ms, read at import.
process.env.CODEMAN_PATH_PROBE_TIMEOUT_MS = '100';
return { dead: '/mnt/dead-nas-case-parent', releases: [] as Array<() => void>, touched: [] as string[] };
});
/** A call on the dead path never settles (a hard mount), until afterEach releases it. */
function hangOnDead<F extends (...a: never[]) => unknown>(name: string, real: F): F {
return ((path: string, ...rest: unknown[]) => {
if (String(path) === probe.dead || String(path).startsWith(probe.dead + '/')) {
probe.touched.push(`${name} ${String(path)}`);
return new Promise((_resolve, reject) => {
probe.releases.push(() => reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })));
});
}
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
}) as unknown as F;
}
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
const stat = hangOnDead('stat', actual.stat);
return { ...actual, stat, default: { ...actual, stat } };
});
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
const promises = {
...actual.promises,
realpath: hangOnDead('realpath', actual.promises.realpath),
stat: hangOnDead('stat', actual.promises.stat),
lstat: hangOnDead('lstat', actual.promises.lstat),
readdir: hangOnDead('readdir', actual.promises.readdir),
};
return { ...actual, promises, default: { ...actual, promises } };
});
import { prepareNewCasePath } from '../src/web/case-path.js';
const root = realpathSync(mkdtempSync(join(tmpdir(), 'case-path-unreachable-')));
const ctx = { home: join(root, 'home'), dataDir: join(root, 'home', '.codeman'), casesDirs: [join(root, 'cases')] };
afterEach(async () => {
probe.releases.splice(0).forEach((release) => release());
probe.touched.length = 0;
await new Promise((r) => setTimeout(r, 0));
});
afterAll(() => {
rmSync(root, { recursive: true, force: true });
delete process.env.CODEMAN_PATH_PROBE_TIMEOUT_MS;
});
describe('prepareNewCasePath on a parent folder that does not answer', () => {
it('answers UNREACHABLE within the probe timeout and never touches the path unbounded', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const result = await Promise.race([
prepareNewCasePath(`${probe.dead}/new-case`, ctx),
new Promise<'hung'>((resolve) => setTimeout(() => resolve('hung'), 2_000)),
]);
warn.mockRestore();
expect(result).toMatchObject({ ok: false, code: 'UNREACHABLE' });
expect((result as { reason: string }).reason).toBe(
`The parent folder is not responding or not readable: ${probe.dead}`
);
// Only the bounded probe's own stat reached the dead mount.
expect(probe.touched).toEqual([`stat ${probe.dead}`]);
});
it('still reports a parent that definitely does not exist as NOT_FOUND', async () => {
expect(await prepareNewCasePath(join(root, 'no-such-parent', 'new-case'), ctx)).toMatchObject({
ok: false,
code: 'NOT_FOUND',
});
});
});
+58 -58
View File
@@ -1227,66 +1227,66 @@ describe('Grok quick start', () => {
expect(names).toEqual(['w1-grok-case', 'w2-grok-case', 'w3-grok-case']);
expect(selected).toEqual(['sess-gk-0']);
});
});
describe('case lookup before a local launch', () => {
function loadLaunchHarness(caseAnswer: Record<string, unknown>) {
const elements: Record<string, any> = {
quickStartCase: { value: 'nas-case' },
shellCount: { value: '1' },
tabCount: { value: '1' },
};
const requests: Array<{ url: string; method?: string }> = [];
const written: string[] = [];
const CodemanApp = function CodemanApp(this: any) {};
const context = vm.createContext({
CodemanApp,
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: (id: string) => elements[id] ?? null },
fetch: async (url: string, init?: { method?: string }) => {
requests.push({ url, method: init?.method });
if (url === '/api/cases/nas-case') return { json: async () => caseAnswer };
if (url === '/api/cases' && init?.method === 'POST') {
return {
json: async () => ({
success: true,
data: { case: { name: 'nas-case', path: '/home/u/codeman-cases/nas-case' } },
}),
};
}
// Anything past the case lookup is out of scope here: stop the launch.
throw new Error(`stop: ${url}`);
},
console,
});
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
const app = new (CodemanApp as any)();
app.terminal = { clear: () => {}, writeln: (line: string) => written.push(line), focus: () => {} };
app.sessions = new Map();
app.cases = [];
app.getTerminalDimensions = () => null;
app._readTabCount = () => 1;
app.loadAppSettingsFromStorage = () => ({});
app.getCaseSettings = () => ({});
return { app, requests, written };
}
describe('case lookup before a local launch', () => {
function loadLaunchHarness(caseAnswer: Record<string, unknown>) {
const elements: Record<string, any> = {
quickStartCase: { value: 'nas-case' },
shellCount: { value: '1' },
tabCount: { value: '1' },
};
const requests: Array<{ url: string; method?: string }> = [];
const written: string[] = [];
const CodemanApp = function CodemanApp(this: any) {};
const context = vm.createContext({
CodemanApp,
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: (id: string) => elements[id] ?? null },
fetch: async (url: string, init?: { method?: string }) => {
requests.push({ url, method: init?.method });
if (url === '/api/cases/nas-case') return { json: async () => caseAnswer };
if (url === '/api/cases' && init?.method === 'POST') {
return {
json: async () => ({
success: true,
data: { case: { name: 'nas-case', path: '/home/u/codeman-cases/nas-case' } },
}),
};
}
// Anything past the case lookup is out of scope here: stop the launch.
throw new Error(`stop: ${url}`);
},
console,
});
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
const app = new (CodemanApp as any)();
app.terminal = { clear: () => {}, writeln: (line: string) => written.push(line), focus: () => {} };
app.sessions = new Map();
app.cases = [];
app.getTerminalDimensions = () => null;
app._readTabCount = () => 1;
app.loadAppSettingsFromStorage = () => ({});
app.getCaseSettings = () => ({});
return { app, requests, written };
}
const unreachable = { success: false, error: 'Case folder is not responding', errorCode: 'OPERATION_FAILED' };
const missing = { success: false, error: 'Case not found', errorCode: 'NOT_FOUND' };
const unreachable = { success: false, error: 'Case folder is not responding', errorCode: 'OPERATION_FAILED' };
const missing = { success: false, error: 'Case not found', errorCode: 'NOT_FOUND' };
for (const launcher of ['runClaude', 'runShell'] as const) {
it(`${launcher} never creates a case when the lookup could not tell whether it exists`, async () => {
const { app, requests, written } = loadLaunchHarness(unreachable);
await app[launcher]();
expect(requests.some((r) => r.url === '/api/cases' && r.method === 'POST')).toBe(false);
expect(written.join('\n')).toContain('Case folder is not responding');
});
for (const launcher of ['runClaude', 'runShell'] as const) {
it(`${launcher} never creates a case when the lookup could not tell whether it exists`, async () => {
const { app, requests, written } = loadLaunchHarness(unreachable);
await app[launcher]();
expect(requests.some((r) => r.url === '/api/cases' && r.method === 'POST')).toBe(false);
expect(written.join('\n')).toContain('Case folder is not responding');
});
it(`${launcher} creates the case when the lookup says it does not exist`, async () => {
const { app, requests } = loadLaunchHarness(missing);
await app[launcher]();
expect(requests.some((r) => r.url === '/api/cases' && r.method === 'POST')).toBe(true);
});
}
});
it(`${launcher} creates the case when the lookup says it does not exist`, async () => {
const { app, requests } = loadLaunchHarness(missing);
await app[launcher]();
expect(requests.some((r) => r.url === '/api/cases' && r.method === 'POST')).toBe(true);
});
}
});
+34 -11
View File
@@ -22,18 +22,26 @@ const probe = vi.hoisted(() => {
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
const stat = ((path: string, ...rest: unknown[]) => {
for (const dead of probe.dead) {
if (String(path) === dead || String(path).startsWith(dead + '/')) {
return new Promise((resolve, reject) => {
probe.releases.push(() => reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })));
void resolve;
});
/** A call on a dead path never settles (a hard mount), until afterEach releases it. */
const hangOnDead = <F extends (...a: never[]) => unknown>(real: F): F =>
((path: string, ...rest: unknown[]) => {
for (const dead of probe.dead) {
if (String(path) === dead || String(path).startsWith(dead + '/')) {
return new Promise((resolve, reject) => {
probe.releases.push(() => reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })));
void resolve;
});
}
}
}
return (actual.stat as (...a: unknown[]) => unknown)(path, ...rest);
}) as typeof actual.stat;
return { ...actual, stat, default: { ...actual, stat } };
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
}) as unknown as F;
const hung = {
stat: hangOnDead(actual.stat),
lstat: hangOnDead(actual.lstat),
readFile: hangOnDead(actual.readFile),
realpath: hangOnDead(actual.realpath),
};
return { ...actual, ...hung, default: { ...actual, ...hung } };
});
import { applyWorkspaceHooks, resolveStatusLineCliCommand, stripCaseEnvKeys } from '../src/hooks-config.js';
@@ -149,6 +157,21 @@ describe('workspace helpers while other mounts are unreachable', () => {
expect(await resolveStatusLineCliCommand(workspace, true)).toMatch(/statusline-exporter\.sh$/);
});
it('skips, within the probe timeout, dead workspaces whose probes the bulk cap refused', async () => {
// Two unrelated stalls engage the bulk cap, so probes of these two paths are
// refused without a stat. Their lstat and readFile hang too: a helper that
// touched them directly would never return and would hold a threadpool worker.
await stallUnrelatedMounts(MAX_STALLED_PATH_PROBES);
probe.dead.add('/mnt/dead-nas-c');
probe.dead.add('/mnt/dead-nas-d');
const within = <T>(work: Promise<T>) =>
Promise.race([work, new Promise<'hung'>((resolve) => setTimeout(() => resolve('hung'), 2_000))]);
expect(await within(applyWorkspaceHooks('/mnt/dead-nas-c/project', true))).toBeUndefined();
expect(await within(resolveStatusLineCliCommand('/mnt/dead-nas-d/project', true))).toBeUndefined();
expect(existsSync('/mnt/dead-nas-c/project')).toBe(false);
});
it('does not inject the exporter into a workspace on the dead mount', async () => {
probe.dead.add('/mnt/dead-nas-y');
expect(await probePath('/mnt/dead-nas-y/project')).toBe('unknown');