Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Native evidence: 3 s for every lookup, and look again when only an ancestor moved (#1192)

Deeecf8097ac995
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 2fef6df9e..bd86e933a 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -13,6 +13,7 @@ import { setUpWithin } from '../../lib/setUpWithin.js'
import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
import type { GridLaunchAnswer, GridLaunchRequest } from '../../lib/gridLaunchWire.js'
import { engineHooks } from '../../engines/hooks.js'
+import { ENUMERATION_ATTEMPTS } from '../../engines/kit/nativeFiles.js'
import { loadEngine } from '../../engines/inProcess.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'
@@ -179,10 +180,13 @@ describe('creating an agent', () => {
}
if (mode === 'redirected during enumeration') {
const actual = await vi.importActual<typeof import('node:fs')>('node:fs')
- vi.mocked(opendirSync).mockImplementationOnce((path, options) => {
+ // Redirected during every look (`ENUMERATION_ATTEMPTS`): one redirect alone is looked at again.
+ let redirects = 0
+ vi.mocked(opendirSync).mockImplementation((path, options) => {
+ if (++redirects > ENUMERATION_ATTEMPTS) return actual.opendirSync(path, options)
renameSync(parent, parent + '-original'); mkdirSync(cwd, { recursive: true })
try { return actual.opendirSync(path, options) }
- finally { renameSync(parent, parent + '-redirected'); renameSync(parent + '-original', parent) }
+ finally { renameSync(parent, `${parent}-redirected-${redirects}`); renameSync(parent + '-original', parent) }
})
}
if (mode === 'error' || mode === 'thrown text') preTrustCodexProject.mockImplementationOnce(() => { throw mode === 'error' ? Error('fixture denied') : 'fixture denied' })
diff --git a/cli/src/engines/kit/homeAdoption.spec.ts b/cli/src/engines/kit/homeAdoption.spec.ts
index aa687df46..e6c5949ee 100644
--- a/cli/src/engines/kit/homeAdoption.spec.ts
+++ b/cli/src/engines/kit/homeAdoption.spec.ts
@@ -3,9 +3,10 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createHomeAdopter, readAdoptedHomes } from './homeAdoption.js'
+import { NATIVE_EVIDENCE_MS } from './nativeEvidence.js'
const clock = vi.hoisted(() => ({ now: 0, remaining: Infinity }))
-vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => --clock.remaining < 0 ? 251 : clock.now } }))
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => --clock.remaining < 0 ? 3_001 : clock.now } })) // past NATIVE_EVIDENCE_MS
vi.mock('node:fs', async original => {
const actual = await original<typeof fs>()
@@ -305,7 +306,7 @@ describe('durable monotone home adoption', () => {
})
it('holds when an I/O call exhausts the shared work deadline', () => {
- vi.mocked(fs.fsyncSync).mockImplementation(fd => { actual.fsyncSync(fd); clock.now += 251 })
+ vi.mocked(fs.fsyncSync).mockImplementation(fd => { actual.fsyncSync(fd); clock.now += NATIVE_EVIDENCE_MS + 1 })
expect(() => adopter.adopt(add('/held'))).toThrow('work deadline')
expect(actual.existsSync(record(0))).toBe(false)
})
diff --git a/cli/src/engines/kit/homeAdoption.ts b/cli/src/engines/kit/homeAdoption.ts
index e16a9b783..eef52e234 100644
--- a/cli/src/engines/kit/homeAdoption.ts
+++ b/cli/src/engines/kit/homeAdoption.ts
@@ -6,6 +6,7 @@ import { dirname, join } from 'node:path'
import { performance } from 'node:perf_hooks'
import { MAX_CATALOG_HOMES, readHomeCatalog, type HomeCatalog, type HomeCatalogRead } from './homeCatalog.js'
import { IdentityReadUnavailable } from './identityScan.js'
+import { NATIVE_EVIDENCE_MS } from './nativeEvidence.js'
const MAX_RECORDS = MAX_CATALOG_HOMES * 2 + 2
const MAX_BYTES = 64 * 1024
@@ -20,7 +21,7 @@ const digest = (text: string) => createHash('sha256').update(text).digest('hex')
const stamp = (info: BigIntStats) => [info.dev, info.ino, info.mode, info.uid, info.size, info.mtimeNs, info.ctimeNs].join(':')
const empty = (): HomeCatalog => ({ claude: [], codex: [] })
const deadline = () => {
- const until = performance.now() + 250
+ const until = performance.now() + NATIVE_EVIDENCE_MS
return () => { if (performance.now() > until) throw unavailable('exceeded its work deadline') }
}
function inspect(info: BigIntStats, directory = false): void {
diff --git a/cli/src/engines/kit/homeCatalog.spec.ts b/cli/src/engines/kit/homeCatalog.spec.ts
index 9a2f25783..38cfa6651 100644
--- a/cli/src/engines/kit/homeCatalog.spec.ts
+++ b/cli/src/engines/kit/homeCatalog.spec.ts
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readHomeCatalog } from './homeCatalog.js'
+import { NATIVE_EVIDENCE_MS } from './nativeEvidence.js'
const clock = vi.hoisted(() => ({ now: 0 }))
vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => clock.now } }))
@@ -213,7 +214,7 @@ describe('fresh complete native home evidence', () => {
it.each(['operations', 'deadline'])('bounds an unfinished read by %s', limit => {
write({ codex: [path('a'.repeat(200))] })
vi.mocked(fs.readSync).mockImplementation((fd, buffer, options = {}) => {
- if (limit === 'deadline') clock.now = 251
+ if (limit === 'deadline') clock.now = NATIVE_EVIDENCE_MS + 1
return actual.readSync(fd, buffer, limit === 'deadline' ? options : { ...options, length: 1 })
})
expect(() => readHomeCatalog(catalog())).toThrow(limit === 'deadline' ? 'read deadline' : 'read-operation limit')
diff --git a/cli/src/engines/kit/homeCatalog.ts b/cli/src/engines/kit/homeCatalog.ts
index ec1d5c20b..7ff164aa5 100644
--- a/cli/src/engines/kit/homeCatalog.ts
+++ b/cli/src/engines/kit/homeCatalog.ts
@@ -3,6 +3,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type St
import { dirname, isAbsolute } from 'node:path'
import { performance } from 'node:perf_hooks'
import { IdentityReadUnavailable } from './identityScan.js'
+import { NATIVE_EVIDENCE_MS } from './nativeEvidence.js'
export type HomeCatalog = { claude: string[]; codex: string[] }
export type HomeCatalogRead = { homes: HomeCatalog; text: string | null; version: string | null }
@@ -75,7 +76,7 @@ function parse(text: string): HomeCatalog {
/** Fresh, bounded bytes tied to their opened descriptor and current pathname. No stamp cache. */
export function readHomeCatalog(file: string): HomeCatalogRead {
const started = performance.now()
- const deadline = () => { if (performance.now() - started > 250) throw unavailable('exceeded its read deadline') }
+ const deadline = () => { if (performance.now() - started > NATIVE_EVIDENCE_MS) throw unavailable('exceeded its read deadline') }
let info: Stats
try { info = lstatSync(file) }
catch (error) {
diff --git a/cli/src/engines/kit/launchExecutable.ts b/cli/src/engines/kit/launchExecutable.ts
index 14e3bbe38..f69dbd8bf 100644
--- a/cli/src/engines/kit/launchExecutable.ts
+++ b/cli/src/engines/kit/launchExecutable.ts
@@ -76,7 +76,7 @@ export async function captureLaunchExecutable(engine: AgentEngine, shell?: strin
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
try {
- const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const paths = new NativePaths(new NativeEvidenceBudget())
if (paths.resolveSync(path, true)) return held('Waiting for the engine search path to stop changing.')
// A dangling executable/ancestor alias is an existing user choice,
// not evidence that installation is safe. Ordinary missing folders
diff --git a/cli/src/engines/kit/nativeEvidence.ts b/cli/src/engines/kit/nativeEvidence.ts
index aff1471ee..5cb471d4f 100644
--- a/cli/src/engines/kit/nativeEvidence.ts
+++ b/cli/src/engines/kit/nativeEvidence.ts
@@ -8,12 +8,20 @@ import { IdentityReadUnavailable } from './identityScan.js'
export const nativeUnavailable = (reason: string): never => { throw new IdentityReadUnavailable(reason) }
+/**
+ * How long one native lookup may take on the wall clock: 3 s, for every lookup. It caps a stuck disk, not a
+ * healthy one, which answers in milliseconds. Path, hook-file, installation and engine-home lookups had
+ * 250 ms, and on a loaded machine the event loop alone took longer: CI runners and a Mac at load 40 held
+ * healthy installations and handoffs as unavailable (2026-10-11).
+ */
+export const NATIVE_EVIDENCE_MS = 3_000
+
export class NativeEvidenceBudget {
private readonly deadline: number
private operations = 32_768
private bytes = 16 * 1024 * 1024
private probes = 64
- constructor(timeoutMs = 3_000) { this.deadline = performance.now() + timeoutMs }
+ constructor(timeoutMs = NATIVE_EVIDENCE_MS) { this.deadline = performance.now() + timeoutMs }
remaining(): number {
const left = Math.floor(this.deadline - performance.now())
if (left <= 0) nativeUnavailable('the native process evidence deadline was reached')
diff --git a/cli/src/engines/kit/nativeFiles.ts b/cli/src/engines/kit/nativeFiles.ts
index 7ab730d45..a6bf71217 100644
--- a/cli/src/engines/kit/nativeFiles.ts
+++ b/cli/src/engines/kit/nativeFiles.ts
@@ -9,6 +9,8 @@ import { controlIdentity, type ControlIdentityRule } from './controlIdentity.js'
const stamp = (info: BigIntStats) => `${nativeFileKey(info)}:${info.mode}:${info.uid}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
type Location = { path: string; info: BigIntStats }
+/** Listings of one directory before a route that keeps changing is called unavailable (`entries`). */
+export const ENUMERATION_ATTEMPTS = 4
type Read = { location: Location; limit: number; line?: string; prefix?: Buffer }
export class NativeFiles {
@@ -16,7 +18,7 @@ export class NativeFiles {
private readonly reads = new Map<string, Read>()
private readonly directories = new Map<string, string>()
private entriesLeft = 4096
- constructor(readonly budget = new NativeEvidenceBudget(250)) { this.paths = new NativePaths(budget) }
+ constructor(readonly budget = new NativeEvidenceBudget()) { this.paths = new NativePaths(budget) }
locate(path: string, missingOkay = false): Location | null {
return this.paths.resolveSync(path, missingOkay)
@@ -106,34 +108,43 @@ export class NativeFiles {
const location = this.locate(path, missingOkay)
if (!location) return []
if (!location.info.isDirectory()) return nativeUnavailable('a binding session directory is not a directory')
- const route = this.directoryRoute(location.path)
- let before: BigIntStats
- try { before = lstatSync(location.path, { bigint: true }) }
- catch { return nativeUnavailable('a binding session directory became unreadable') }
- if (nativeFileKey(before) !== nativeFileKey(location.info)) return nativeUnavailable('a binding session directory was replaced')
- let directory
- const names: string[] = []
- try {
- directory = opendirSync(location.path, { bufferSize: 32 })
- for (;;) {
- this.budget.step()
- const entry = directory.readSync()
- if (!entry) break
- if (--this.entriesLeft < 0) return nativeUnavailable('the binding directory entry limit was reached')
- names.push(entry.name)
+ // A busy ancestor (the temporary folder, ~/.harness) changes its stamps whenever anything else creates a
+ // file in it, which says nothing about this directory. Only a listing whose whole route held still counts,
+ // so look again a few times before calling the evidence unavailable: on CI and on a Mac at load 40 one
+ // look was not enough, and healthy installations and handoffs were held (2026-10-11). A route that keeps
+ // moving is still refused.
+ const left = this.entriesLeft
+ for (let attempt = 1; ; attempt++) {
+ this.entriesLeft = left
+ const route = this.directoryRoute(location.path)
+ let before: BigIntStats
+ try { before = lstatSync(location.path, { bigint: true }) }
+ catch { return nativeUnavailable('a binding session directory became unreadable') }
+ if (nativeFileKey(before) !== nativeFileKey(location.info)) return nativeUnavailable('a binding session directory was replaced')
+ let directory
+ const names: string[] = []
+ try {
+ directory = opendirSync(location.path, { bufferSize: 32 })
+ for (;;) {
+ this.budget.step()
+ const entry = directory.readSync()
+ if (!entry) break
+ if (--this.entriesLeft < 0) return nativeUnavailable('the binding directory entry limit was reached')
+ names.push(entry.name)
+ }
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ return nativeUnavailable('a binding session directory could not be read completely')
+ } finally {
+ if (directory) { try { directory.closeSync() } catch { nativeUnavailable('a binding session directory could not be closed') } }
}
- } catch (error) {
- if (error instanceof IdentityReadUnavailable) throw error
- return nativeUnavailable('a binding session directory could not be read completely')
- } finally {
- if (directory) { try { directory.closeSync() } catch { nativeUnavailable('a binding session directory could not be closed') } }
- }
- const after = this.directoryRoute(location.path)
- if (route.size !== after.size || [...route].some(([part, version]) => after.get(part) !== version)) {
- return nativeUnavailable('a binding directory or ancestor changed during enumeration')
+ const after = this.directoryRoute(location.path)
+ if (route.size === after.size && [...route].every(([part, version]) => after.get(part) === version)) {
+ this.directories.set(location.path, stamp(before))
+ return names
+ }
+ if (attempt >= ENUMERATION_ATTEMPTS) return nativeUnavailable('a binding directory or ancestor changed during enumeration')
}
- this.directories.set(location.path, stamp(before))
- return names
}
/** Selected identity is checked last. Appended body text does not change a complete header. */
diff --git a/cli/src/engines/kit/nativeHookFiles.ts b/cli/src/engines/kit/nativeHookFiles.ts
index 8aa33fec3..63297e70a 100644
--- a/cli/src/engines/kit/nativeHookFiles.ts
+++ b/cli/src/engines/kit/nativeHookFiles.ts
@@ -59,7 +59,7 @@ function ensureDirectory(path: string, attempt: HookPreparationAttempt): void {
function directoryPath(path: string): string {
const suffix: string[] = []
for (let depth = 0; depth < 256; depth++) {
- const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(path, true)
+ const route = new NativePaths(new NativeEvidenceBudget()).resolveSync(path, true)
if (route) {
if (!route.info.isDirectory()) throw new HookPreparationHeld('the configuration parent is not a directory')
return join(route.path, ...suffix)
@@ -72,7 +72,7 @@ function directoryPath(path: string): string {
/** The result is local to one preparation attempt, not a settings cache.
* A changed alias, owner, file or contents invalidates the whole observation. */
export function inspectHookFile(file: string, defaultMode = 0o666) {
- const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const paths = new NativePaths(new NativeEvidenceBudget())
const located = paths.resolveSync(file, true)
const facts = paths.snapshot()
const directory = directoryPath(dirname(file))
@@ -104,7 +104,7 @@ export function inspectHookFile(file: string, defaultMode = 0o666) {
// Another destination in the same preparation may have created a shared
// absent directory. New ordinary directories are fine; a newly inserted
// alias is not authority to write at a different location.
- const fresh = new NativePaths(new NativeEvidenceBudget(250))
+ const fresh = new NativePaths(new NativeEvidenceBudget())
fresh.resolveSync(file, true)
const knownAliases = new Set(facts.filter(fact => fact.alias).map(fact => fact.path))
if (fresh.snapshot().some(fact => fact.alias && !knownAliases.has(fact.path))) {
@@ -122,7 +122,7 @@ export function inspectHookFile(file: string, defaultMode = 0o666) {
if (content !== null && next !== null && (mode & 0o200) === 0) throw new HookPreparationHeld('the settings file is read-only')
let parent = dirname(target)
for (let depth = 0; depth < 256; depth++) {
- const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(parent, true)
+ const route = new NativePaths(new NativeEvidenceBudget()).resolveSync(parent, true)
if (route) { accessSync(route.path, constants.W_OK | constants.X_OK); return }
parent = dirname(parent)
}
@@ -209,7 +209,7 @@ export function inspectHookFile(file: string, defaultMode = 0o666) {
attempt.observe(file, inspectHookFile(file).verify)
let parent = dirname(target)
for (let depth = 0; depth < 256; depth++) {
- const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(parent, true)
+ const route = new NativePaths(new NativeEvidenceBudget()).resolveSync(parent, true)
if (route) { await syncDirectoryChain(route.path, attempt); break }
parent = dirname(parent)
}
@@ -245,7 +245,7 @@ interface PendingPreparation { identity?: string; keys: string[]; revoke(): void
function preparationProof(files: readonly string[], verifyRoutes: () => void): HookPreparationProof {
verifyRoutes()
const confirmed = files.map(file => {
- const paths = new NativePaths(new NativeEvidenceBudget(250)), located = paths.resolveSync(file, true)
+ const paths = new NativePaths(new NativeEvidenceBudget()), located = paths.resolveSync(file, true)
const observed = inspectHookFile(file)
return { file, target: located?.path ?? join(directoryPath(dirname(file)), basename(file)), stamp: observed.stamp, facts: paths.snapshot(), verify: observed.verify }
})
@@ -300,7 +300,7 @@ function dispatchFlushes(): void {
export function hookPreparationRoutes(files: readonly string[]): { verify(): void; keys: string[]; facts: ReturnType<NativePaths['snapshot']> } {
if (!files.length || files.length > 32) throw new HookPreparationHeld('the destination set exceeds its limit')
const reservations = files.map(file => {
- const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const paths = new NativePaths(new NativeEvidenceBudget())
const located = paths.resolveSync(file, true), facts = paths.snapshot()
const key = located?.path ?? join(directoryPath(dirname(file)), basename(file))
return { file, key, facts: facts.filter(fact => fact.identity !== null && fact.path !== located?.path),
@@ -309,7 +309,7 @@ export function hookPreparationRoutes(files: readonly string[]): { verify(): voi
const verifyRoutes = () => {
for (const { file, key, facts, aliases } of reservations) {
if (facts.length) verifyNativePathFacts(facts)
- const fresh = new NativePaths(new NativeEvidenceBudget(250)), located = fresh.resolveSync(file, true)
+ const fresh = new NativePaths(new NativeEvidenceBudget()), located = fresh.resolveSync(file, true)
const target = located?.path ?? join(directoryPath(dirname(file)), basename(file))
if (target !== key || fresh.snapshot().some(fact => fact.alias && !aliases.has(fact.path))) {
throw new HookPreparationHeld('the reserved destination route changed')
diff --git a/cli/src/engines/kit/nativeHookYaml.ts b/cli/src/engines/kit/nativeHookYaml.ts
index 6e718ec9f..32dfe84ed 100644
--- a/cli/src/engines/kit/nativeHookYaml.ts
+++ b/cli/src/engines/kit/nativeHookYaml.ts
@@ -139,7 +139,7 @@ async function installIn(rule: NativeYamlHooks, cmd: string, home: string, optio
// first settings file. A background catalog scan never creates a profile.
const config = observed.content ?? ''
- const budget = new NativeEvidenceBudget(250)
+ const budget = new NativeEvidenceBudget()
let tokens = 0
for (const _token of new Lexer().lex(config)) {
budget.step()
diff --git a/cli/src/engines/kit/nativeInstall.spec.ts b/cli/src/engines/kit/nativeInstall.spec.ts
index 3b802e850..3c74b21b7 100644
--- a/cli/src/engines/kit/nativeInstall.spec.ts
+++ b/cli/src/engines/kit/nativeInstall.spec.ts
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { EngineInstallRecipe } from '../../lib/engineInstall.js'
+import { ENUMERATION_ATTEMPTS } from './nativeFiles.js'
import { createNativeInstallations, NATIVE_INSTALL_WORKER } from './nativeInstall.js'
const fixture = vi.hoisted(() => ({ failSync: false, argv: [] as string[], onSync: undefined as undefined | (() => number | void), onDirectoryOpen: undefined as undefined | (() => void) }))
@@ -36,12 +37,28 @@ beforeEach(() => {
fixture.argv = [process.execPath, '-e', `require('node:fs').appendFileSync(${JSON.stringify(join(root, 'installed'))}, 'one\\n')`]
})
afterEach(() => { rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks() })
+/** An ancestor of the claims that changes during every listing attempt (`ENUMERATION_ATTEMPTS`), then stops. */
+function keepChanging(times = ENUMERATION_ATTEMPTS): () => void {
+ return () => {
+ if (--times === 0) fixture.onDirectoryOpen = undefined
+ writeFileSync(join(root, `sibling-${times}`), 'changed during enumeration')
+ }
+}
const controller = (dispatch = vi.fn()) => ({ dispatch, ...createNativeInstallations({ directory, node: () => process.execPath, dispatch }) })
function complete(file = join(directory, '00000000.json'), code = 0): void {
const text = readFileSync(file, 'utf8'), claim = JSON.parse(text)
writeFileSync(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash(text), code, signal: null }), { mode: 0o600 })
}
+it('looks again when an ancestor changes once during a listing, as a busy temporary folder does', async () => {
+ const install = controller()
+ fixture.onDirectoryOpen = keepChanging(1)
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(fixture.onDirectoryOpen).toBeUndefined()
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ expect(existsSync(join(directory, '00000000.json'))).toBe(true)
+})
+
it('does not reserve or dispatch after cancellation', async () => {
const install = controller()
expect(await install.ensure('opencode', recipe, environment, 'request', () => false)).toMatchObject({ complete: false })
@@ -151,12 +168,9 @@ it('settles a durable non-dispatch cancellation through the ready-executable sta
const witness = `${directory}.00000000.dispatch`
fixture.onSync = () => { if (existsSync(witness)) fixture.failSync = true }
const other = controller()
- // Linux CI's parallel fixtures can change an ancestor during enumeration.
- // That is a real hold; keep each disk fault armed until its stage is reached.
- fixture.onDirectoryOpen = () => {
- fixture.onDirectoryOpen = undefined
- writeFileSync(join(root, 'sibling'), 'changed during inspection')
- }
+ // An ancestor that changes during every look is a real hold; keep each disk fault armed until its
+ // stage is reached.
+ fixture.onDirectoryOpen = keepChanging()
expect(await other.ensure('codex', recipe, environment, 'other', () => true)).toMatchObject({ complete: false })
expect(fixture.onDirectoryOpen).toBeUndefined()
expect(existsSync(witness)).toBe(false)
@@ -194,10 +208,7 @@ it('does not replay a dispatch whose reply was lost', async () => {
it.each(['changed owner', 'foreign result', 'failed installer', 'unsafe result', 'orphan result', 'malformed result', 'contradictory result'])('holds %s without dispatch or a false completion', async kind => {
const install = controller()
- if (kind === 'failed installer') fixture.onDirectoryOpen = () => {
- fixture.onDirectoryOpen = undefined
- writeFileSync(join(root, 'sibling'), 'changed during enumeration')
- }
+ if (kind === 'failed installer') fixture.onDirectoryOpen = keepChanging()
if (kind === 'failed installer') {
expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({
complete: false, detail: 'Waiting to confirm durable engine installation ownership.',
diff --git a/cli/src/engines/kit/nativeInstall.ts b/cli/src/engines/kit/nativeInstall.ts
index 6633d675a..da20f4ed8 100644
--- a/cli/src/engines/kit/nativeInstall.ts
+++ b/cli/src/engines/kit/nativeInstall.ts
@@ -38,7 +38,7 @@ const hold = (detail: string): NativeInstallation => ({ complete: false, detail
/** Never read a growing journal file without a bound, or tighten foreign permissions to trust it. */
function readRecord(file: string): { text: string; file: string; stamp: string; facts: NativePathFact[]; verify(): void } {
- const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const paths = new NativePaths(new NativeEvidenceBudget())
const location = paths.resolveSync(file, true), facts = paths.snapshot()
if (!location) {
// An ancestor may be an ordinary alias, such as macOS /var. Absence
@@ -161,7 +161,7 @@ export function createNativeInstallations({ directory, node = managedNodePath, d
return null
}
secureStateDirectory(directory, !authority)
- const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const paths = new NativePaths(new NativeEvidenceBudget())
paths.resolveSync(directory)
const directoryFacts = paths.snapshot(), directoryId = identity(lstatSync(directory, { bigint: true }))
const physical = () => { try { verifyNativePathFacts(directoryFacts); return true } catch { return false } }
@@ -287,7 +287,7 @@ export function createNativeInstallations({ directory, node = managedNodePath, d
: complete ? { complete: true } : null
if (!pending && names.length >= MAX_INSTALLATIONS) return hold('The engine installation history is full. Its saved records need review before another installation.')
// HOME gets a fresh budget after history enumeration and yields.
- const homes = new NativePaths(new NativeEvidenceBudget(250)), home = homes.resolveSync(environment.HOME)
+ const homes = new NativePaths(new NativeEvidenceBudget()), home = homes.resolveSync(environment.HOME)
if (!home?.info.isDirectory()) return hold('Waiting to confirm the native installation home.')
const routes = [...directoryFacts, ...homes.snapshot()]
const file = pending?.file ?? join(directory, `${String(names.length).padStart(8, '0')}.json`)
diff --git a/cli/src/engines/kit/nativePaths.ts b/cli/src/engines/kit/nativePaths.ts
index 033bf91bf..160aed03b 100644
--- a/cli/src/engines/kit/nativePaths.ts
+++ b/cli/src/engines/kit/nativePaths.ts
@@ -12,7 +12,7 @@ type Location = { path: string; info: BigIntStats } | null
/** Immutable route facts can cross a service boundary; timestamps matter for aliases, not sibling churn. */
export type NativePathFact = { path: string; identity: string | null; alias?: { target: string; version: string } }
export function verifyNativePathFacts(facts: readonly NativePathFact[]): void {
- const budget = new NativeEvidenceBudget(250)
+ const budget = new NativeEvidenceBudget()
if (!facts.length || facts.length > 256) return nativeUnavailable('the retained route exceeds its limit')
for (const fact of facts) {
budget.step()
@@ -88,7 +88,7 @@ export class NativePaths {
this.budget.step()
const retained = [...this.parts].filter(([path]) => path !== removedPath && !path.startsWith(removedPath + '/'))
return () => {
- const fresh = new NativePaths(new NativeEvidenceBudget(250))
+ const fresh = new NativePaths(new NativeEvidenceBudget())
for (const [path, part] of retained) fresh.parts.set(path, part)
fresh.verify()
}
diff --git a/cli/src/engines/transcriptBindings.spec.ts b/cli/src/engines/transcriptBindings.spec.ts
index 34febfffd..7f3999aaf 100644
--- a/cli/src/engines/transcriptBindings.spec.ts
+++ b/cli/src/engines/transcriptBindings.spec.ts
@@ -229,11 +229,13 @@ it('retains an unreadable competing directory even after the parent was found',
it('does not infer an empty directory from an iterator acquired during an ancestor round trip', () => {
const path = child(), sessions = join(home, 'sessions'), elsewhere = join(root, 'empty')
fs.mkdirSync(elsewhere)
+ // Every look makes its own round trip, so the route never holds still.
+ let trips = 0
vi.mocked(fs.opendirSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) => {
if (String(path) !== sessions) return Reflect.apply(actual.opendirSync, actual, [path, ...args])
fs.renameSync(home, home + '-aside'); fs.mkdirSync(home); fs.mkdirSync(sessions)
const result = Reflect.apply(actual.opendirSync, actual, [sessions, ...args])
- fs.renameSync(home, home + '-temporary'); fs.renameSync(home + '-aside', home)
+ fs.renameSync(home, `${home}-temporary-${++trips}`); fs.renameSync(home + '-aside', home)
return result
}) as typeof fs.opendirSync)
expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('ancestor changed')
diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.ts
index 7e72cf69c..a0521dfa5 100644
--- a/cli/src/lib/engineHomes.spec.ts
+++ b/cli/src/lib/engineHomes.spec.ts
@@ -14,7 +14,7 @@ import {
const shell = vi.hoisted(() => ({ env: {} as NodeJS.ProcessEnv }))
vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.env }))
const clock = vi.hoisted(() => ({ remaining: Infinity }))
-vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => --clock.remaining < 0 ? 251 : 0 } }))
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => --clock.remaining < 0 ? 3_001 : 0 } })) // past NATIVE_EVIDENCE_MS
vi.mock('node:fs', async original => {
const actual = await original<typeof fs>()
return { ...actual, linkSync: vi.fn(actual.linkSync), lstatSync: vi.fn(actual.lstatSync) }
diff --git a/cli/src/lib/handoffFiles.ts b/cli/src/lib/handoffFiles.ts
index f695a7f3c..f0d7f8654 100644
--- a/cli/src/lib/handoffFiles.ts
+++ b/cli/src/lib/handoffFiles.ts
@@ -29,7 +29,7 @@ export function readHandoffFile(path: string, limit: number, privateMode = false
|| typeof process.getuid === 'function' && before.uid !== BigInt(process.getuid())
|| before.size > BigInt(limit) || before.nlink < 1n
|| (before.mode & (privateMode ? 0o077n : 0o022n)) !== 0n) return hold()
- const bytes = Buffer.alloc(Number(before.size)), budget = new NativeEvidenceBudget(250)
+ const bytes = Buffer.alloc(Number(before.size)), budget = new NativeEvidenceBudget()
for (let at = 0, calls = 0; at < bytes.length; calls++) {
budget.step()
if (calls >= 128) return hold()
diff --git a/cli/src/lib/publishedGridConfig.ts b/cli/src/lib/publishedGridConfig.ts
index f75821f52..88aaacd39 100644
--- a/cli/src/lib/publishedGridConfig.ts
+++ b/cli/src/lib/publishedGridConfig.ts
@@ -71,7 +71,7 @@ export async function publishGridConfigDir(key: string, inputFiles: readonly Gri
mkdirSync(directory, { mode: 0o700 })
}
privateDirectory(directory, false)
- const directoryPaths = new NativePaths(new NativeEvidenceBudget(250)), selectedDirectory = directoryPaths.resolveSync(directory)!
+ const directoryPaths = new NativePaths(new NativeEvidenceBudget()), selectedDirectory = directoryPaths.resolveSync(directory)!
const directoryFacts = directoryPaths.snapshot()
attempt.observe(directory, () => verifyNativePathFacts(directoryFacts))
const ownerBytes = JSON.stringify({ digest, directory: identity(selectedDirectory.info) })
@@ -104,7 +104,7 @@ export async function publishGridConfigDir(key: string, inputFiles: readonly Gri
mkdirSync(link.target, { recursive: true, mode: 0o700 })
route.verify()
// The borrowed native directory may be an existing, verified alias.
- const targetPaths = new NativePaths(new NativeEvidenceBudget(250)), target = targetPaths.resolveSync(link.target)
+ const targetPaths = new NativePaths(new NativeEvidenceBudget()), target = targetPaths.resolveSync(link.target)
if (!target?.info.isDirectory()) throw new HookPreparationHeld('the borrowed native location is not a directory')
const retained = targetPaths.snapshot()
const authorityBytes = JSON.stringify({ version: 1, target: link.target, facts: retained })
@@ -125,7 +125,7 @@ export async function publishGridConfigDir(key: string, inputFiles: readonly Gri
if (settled.content !== null || completedBefore.content !== null) throw new HookPreparationHeld('a published native link was removed')
symlinkSync(link.target, path, 'dir')
}
- const selected = new NativePaths(new NativeEvidenceBudget(250))
+ const selected = new NativePaths(new NativeEvidenceBudget())
selected.resolveSync(path)
const facts = selected.snapshot()
linkFacts.push(...facts)
@@ -148,7 +148,7 @@ export async function publishGridConfigDir(key: string, inputFiles: readonly Gri
}
// Joined publishers still retain their own link routes, not a peer's closure.
for (const link of links) {
- const paths = new NativePaths(new NativeEvidenceBudget(250)); paths.resolveSync(join(directory, link.name)); linkFacts.push(...paths.snapshot())
+ const paths = new NativePaths(new NativeEvidenceBudget()); paths.resolveSync(join(directory, link.name)); linkFacts.push(...paths.snapshot())
}
const retained = new Map<string, NativePathFact>()
for (const fact of [...linkFacts, ...targetRoutes?.facts ?? []]) {
diff --git a/cli/src/lib/registry.homes.spec.ts b/cli/src/lib/registry.homes.spec.ts
index 3419e6418..238b34798 100644
--- a/cli/src/lib/registry.homes.spec.ts
+++ b/cli/src/lib/registry.homes.spec.ts
@@ -2,6 +2,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
+import { ENUMERATION_ATTEMPTS } from '../engines/kit/nativeFiles.js'
const fault = vi.hoisted(() => ({ beforeVerify: undefined as (() => void) | undefined, captures: 0,
onDirectoryOpen: undefined as (() => void) | undefined }))
@@ -52,9 +53,11 @@ it('repairs a child-overwritten parent from an adopted Codex home before the log
}]), { mode: 0o600 })
vi.resetModules()
const { registry } = await import('./registry.js')
+ // An ancestor that changes during every look (`ENUMERATION_ATTEMPTS`); one change alone is looked at again.
+ let looks = ENUMERATION_ATTEMPTS
fault.onDirectoryOpen = () => {
- fault.onDirectoryOpen = undefined
- writeFileSync(join(root!, 'sibling'), 'changed during enumeration')
+ if (--looks === 0) fault.onDirectoryOpen = undefined
+ writeFileSync(join(root!, `sibling-${looks}`), 'changed during enumeration')
}
registry.load()
expect(fault.onDirectoryOpen).toBeUndefined()