Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
1bd1b9f
fix(daemon): report a failed close-time script write instead of a qui…
claude Nov 10, 2026
de30049
fix(cli): report a failed lease release on disconnect
claude Nov 10, 2026
1dd949b
fix(daemon): cancel shutdown deadline timers when the work settles first
claude Nov 10, 2026
043e88f
fix(daemon): dispose an ordinary binding that publishes after request…
claude Nov 10, 2026
8147527
fix(daemon): release a suite test session's provider lease through th…
claude Nov 10, 2026
8b7c1aa
fix(daemon): record daemon-level diagnostics that run outside a request
claude Nov 10, 2026
d4c59a8
fix(cli): make connect limrun idempotent per session and remove unuse…
claude Nov 10, 2026
13a0609
fix(app-log): rotate app.log while a sink is open and read network du…
claude Nov 10, 2026
169473e
test: move new connection and suite lease cases into focused files
claude Nov 10, 2026
b8cf1bb
test: name the moved lease and connection cases for the modules they …
claude Nov 10, 2026
f5ec71d
fix(daemon): pin script-write failure handling for close and teardown
claude Nov 10, 2026
5d3e795
fix(daemon): report a failed provider lease timer run instead of reje…
claude Nov 10, 2026
722ecd0
fix(app-log): size the rotation check from the descriptor and rotate …
claude Nov 10, 2026
b8a777f
fix(cli): keep generated profiles unless provably unused, and give un…
claude Nov 10, 2026
dd8e698
fix(daemon): record a lease-expiry sweep failure instead of rejecting…
claude Nov 10, 2026
3afe76c
fix(app-log): leave an empty current app.log after a disposal rotation
claude Nov 10, 2026
8197957
test: pin profile references and the teardown write failure
claude Nov 10, 2026
e954fe4
test(daemon): close the runtime in finally in the lease sweep failure…
claude Nov 10, 2026
d2689cb
fix(daemon): keep the inner hint for close save-script failures close…
claude Nov 10, 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
9 changes: 7 additions & 2 deletions packages/capture-kit/src/capture-admission/app-log-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ export function ensureAppLogPath(outPath: string, env: NodeJS.ProcessEnv): void
const directory = path.dirname(outPath);
if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true });
assertAppLogFileIsNotSymbolicLink(outPath);
rotateAppLogIfNeeded(outPath, {
rotateAppLogIfNeeded(outPath, resolveAppLogRotationConfig(env));
}

/** The size cap and rotated-file count `app.log` writers apply. */
export function resolveAppLogRotationConfig(env: NodeJS.ProcessEnv): AppLogRotationConfig {
return {
maxBytes: positiveIntEnv(env.AGENT_DEVICE_APP_LOG_MAX_BYTES, DEFAULT_MAX_APP_LOG_BYTES),
maxRotatedFiles: positiveIntEnv(env.AGENT_DEVICE_APP_LOG_MAX_FILES, DEFAULT_MAX_ROTATED_FILES),
});
};
}

export function rotateAppLogIfNeeded(outPath: string, config: AppLogRotationConfig): void {
Expand Down
35 changes: 35 additions & 0 deletions packages/daemon/src/core/__tests__/request-runtime-binding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,41 @@ test('late exact-owner binding is rolled back when request cleanup already began
expect(disposePublished).toHaveBeenCalledOnce();
});

test('late ordinary binding is disposed when request cleanup already began', async () => {
const runtime = makeGateway();
const selected = device('late-ordinary');
const published = await runtime.gateway.bind({
device: selected,
intent: { kind: 'ordinary' },
scope,
});
const disposePublished = vi.fn(async () => {});
const lateBinding = { ...published, [Symbol.asyncDispose]: disposePublished };
let publish: (binding: DeviceBinding<PlatformRuntimeOperations>) => void = () => {};
const gateway: DeviceRuntimeGateway<PlatformRuntimeOperations> = {
inspectFacts: async () => runtime.gateway.inspectFacts(selected),
bind: vi.fn(
async () =>
await new Promise<DeviceBinding<PlatformRuntimeOperations>>((resolve) => {
publish = resolve;
}),
),
shutdown: async () => {},
};
const bindings = createRequestRuntimeBindings({
gateway,
scope,
admitDeviceClaim,
dispatchLedger: createRequestDispatchLedger(),
});
const binding = bindings.bindDevice(selected, appLogInspectUse);
await bindings[Symbol.asyncDispose]();
publish(lateBinding);

await expect(binding).rejects.toThrow('Cannot register cleanup after disposal has begun');
expect(disposePublished).toHaveBeenCalledOnce();
});

test('late exact-owner rollback failure is secondary diagnostic evidence', async () => {
const runtime = makeGateway();
const selected = device('late-cleanup-failure');
Expand Down
35 changes: 28 additions & 7 deletions packages/daemon/src/core/__tests__/session-script-writer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,10 @@ test('write(session) without { force: true } still refuses, even when a prior wr
});

// Default (no options / force omitted): refuse-on-exist, unchanged.
expect(() => writer.write(session)).toThrow(/already exists/);
expect(writer.write(session)).toMatchObject({
written: false,
error: { details: { reason: 'script_target_exists' } },
});
expect(fs.readFileSync(outPath, 'utf8')).toBe(before);
});

Expand Down Expand Up @@ -606,17 +609,35 @@ test('an ordinary (non-repair) recording now refuses an existing target too (beh
actions: [action({ command: 'click', positionals: ['id="new"'] })],
});

// Unlike a repair-armed write (which returns `{written:false, error}`), an
// ordinary (non-repair-armed) write's catch block RETHROWS an AppError
// (`write()`: `if (repairArmed) return {...}; if (error instanceof
// AppError) throw error;`) — so refusal here surfaces as a thrown error,
// not a returned result.
expect(() => writer.write(session)).toThrow(/already exists/);
expect(writer.write(session)).toMatchObject({
written: false,
error: { message: expect.stringMatching(/already exists/) },
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
});
// The pre-existing target is left byte-for-byte unchanged — refused, not
// clobbered.
expect(fs.readFileSync(outPath, 'utf8')).toBe(before);
});

test('an ordinary recording returns a filesystem write failure as a typed error, never a quiet skip', () => {
const root = mkdtempForTestSync('agent-device-script-writer-ordinary-fs-failure-');
const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd);
const blocker = path.join(root, 'blocker');
fs.writeFileSync(blocker, '');
const outPath = path.join(blocker, 'flow.ad');
const session = makeAuthoringSession('default', {
scriptPublication: authoringPublication('armed', { path: outPath }),
actions: [action({ command: 'click', positionals: ['id="new"'] })],
});

expect(writer.write(session)).toMatchObject({
written: false,
error: {
code: 'COMMAND_FAILED',
details: { reason: 'script_write_failed', path: outPath },
},
});
});

// (f) confirm the absent-target case still succeeds for ordinary recording —
// the refusal is scoped to an EXISTING target, not a blanket block.
test('an ordinary (non-repair) recording still publishes cleanly when its target does not exist yet', () => {
Expand Down
7 changes: 4 additions & 3 deletions packages/daemon/src/core/request-runtime-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function createRequestRuntimeBindings(params: {
const intent: DeviceBindingIntent = { kind: 'ordinary' };
bindingPromise = params.gateway
.bind({ device, intent, scope: params.scope })
.then((binding) => cleanups.use(binding))
.then(async (binding) => await adoptBinding(cleanups, binding, params.scope))
.then(admitBinding);
bindings.set(key, bindingPromise);
void bindingPromise.catch(() => {
Expand All @@ -149,7 +149,7 @@ export function createRequestRuntimeBindings(params: {
params.admitDevice?.(device);
const intent: DeviceBindingIntent = { kind: 'exact-owner', owner, fence };
const published = await params.gateway.bind({ device, intent, scope });
const adopted = await adoptExactBinding(cleanups, published, scope);
const adopted = await adoptBinding(cleanups, published, scope);
const binding = await admitBinding(adopted);
return recordBoundMutations(narrowDeviceBinding(binding, use), params.dispatchLedger);
};
Expand All @@ -167,7 +167,8 @@ export function createRequestRuntimeBindings(params: {
};
}

async function adoptExactBinding(
/** Adopts a published binding into the request cleanups, or disposes it when cleanup already began. */
async function adoptBinding(
cleanups: AsyncCleanupStack,
binding: DeviceBinding<PlatformRuntimeOperations>,
scope: PlatformRequestScope,
Expand Down
37 changes: 20 additions & 17 deletions packages/daemon/src/core/session-script-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,50 +183,53 @@
};
}

/**
* `write()`'s catch-block classifier, extracted verbatim (no behavior change):
* diagnose, then route by whether the session is repair-armed.
* `write()`'s catch-block classifier: diagnose, then return the failure as a typed error.
*
* ADR 0012 decision 6, R4 + BLOCKER 2: a repair COMMIT failure must be
* SURFACED (no-clobber refusal, bare-`@ref`, or a filesystem error alike) so
* close/teardown can report it and keep the session for retry — never
* swallowed into a silent `{written:false}`. Ordinary (non-repair) recording
* keeps its existing SHAPE of behavior: an AppError still fails loud (thrown,
* not swallowed into `{written:false}`) and any other fs error is a quiet
* skip — but an AppError is no longer only theoretical here. Since
* `publishHealedScriptAtomically` refuses ANY pre-existing target uniformly
* (maintainer-approved: refuse-on-exist applies to ordinary recording too, not
* just repair heals), an ordinary `open`/`close --save-script` write against
* an existing target now throws that same no-clobber AppError, surfacing here
* as a genuine "fails loud" case rather than the "none is raised on that path"
* it was before that change.
* ADR 0012 decision 6, R4 + BLOCKER 2: every armed write failure (no-clobber refusal, bare-`@ref`,
* or a filesystem error alike) is returned as `{ written: false, error }`, never thrown and never
* swallowed, so close can report it and teardown can continue to retire the session.
*/
function handleSessionScriptWriteFailure(params: {
session: SessionState;
Comment thread
thymikee marked this conversation as resolved.
Resolved
error: unknown;
scriptPath: string | undefined;
repairArmed: boolean;
activePublication: boolean;
}): SessionScriptWriteResult {
const { session, error, scriptPath, repairArmed, activePublication } = params;
emitDiagnostic({
level: 'warn',
phase: 'session_script_write_failed',
data: {
session: session.name,
path: scriptPath,
error: error instanceof Error ? error.message : String(error),
},
});
if (repairArmed) {
return { written: false, error: toRepairCommitFailure(error, scriptPath) };
}
if (activePublication) {
return { written: false, error: toActivePublicationFailure(error, scriptPath) };
}
if (error instanceof AppError) throw error;
return { written: false };
return { written: false, error: toOrdinaryWriteFailure(error, scriptPath) };
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}

function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError {
if (error instanceof AppError) return error;
const detail = error instanceof Error ? error.message : String(error);
return new AppError(
'COMMAND_FAILED',
`Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`,
{
reason: 'script_write_failed',
...(scriptPath ? { path: scriptPath } : {}),
hint: 'Check the target path and its permissions, then re-record with open --save-script.',
},
error,
);
}

Check warning on line 232 in packages/daemon/src/core/session-script-writer.ts

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Ordinary close no longer fails loud: callers that ignore result.error report success

`handleSessionScriptWriteFailure` now returns `{ written:false, error }` instead of throwing, but per-action/active publication in `session-script-publication.ts` and `finalizeRepairTeardown` (non-repair sessions) only inspect `written`, so a no-clobber refusal or fs error is silently recorded as a successful close. No test pins this behavior for those paths. ### Also raised here Also raised at this location by persona `javascript`: Ordinary script-write failures are now returned, so callers that check only `written` swallow them — `handleSessionScriptWriteFailure` used to rethrow an `AppError` and, for a non-AppError filesystem error, return a bare `{ written: false }`; every non-repair, non-active-publication failure now comes back as `{ written: false, error }` instead of throwing. That is correct only for callers that read `result.error`: `SessionStore.writeSessionLog` has at least one internal call site (packages/daemon/src/core/session-store.ts:307) that I could not confirm inspects `result.error`, and any such caller now turns a refused or failed `.ad` write into a silent skip where the base aborted the caller with a thrown error. The PR description already flags this as a risk on the teardown path.

/**
* ADR 0012 decision 6 (BLOCKER 2c): normalizes a repair-commit failure into a
Expand Down
58 changes: 58 additions & 0 deletions packages/daemon/src/server/__tests__/provider-lease-expiry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts';
import { leaseReleaseRequestFor } from '../../resources/lease-registry-scope.ts';
import type { DeviceLease } from '@agent-device/contracts/device';
import { mkdtempForTestSync } from '@agent-device/test-kit';
import path from 'node:path';
import { withDaemonDiagnosticsScope } from '@agent-device/daemon-contracts/daemon-diagnostics-scope';

test('retries an expired live-only provider lease release after a transient failure', async () => {
vi.useFakeTimers();
Expand Down Expand Up @@ -46,6 +48,41 @@ test('retries an expired live-only provider lease release after a transient fail
}
});

test('a timer-driven release retry records its diagnostics in the daemon scope', async () => {
vi.useFakeTimers();
const logPath = path.join(mkdtempForTestSync('agent-device-expiry-retry-scope-'), 'daemon.log');
const lease = new LeaseRegistry().allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
leaseProvider: 'browserstack',
});
const release = vi
.fn<(lease: DeviceLease) => Promise<Record<string, unknown>>>()
.mockRejectedValue(new Error('provider outage'));
const releaser = createExpiredProviderLeaseReleaser({
leaseLifecycleProvider: { release },
providerRuntimeIds: ['browserstack'],
retryDelayMs: 10,
withinDiagnosticsScope: async (run) => await withDaemonDiagnosticsScope({ logPath }, run),
});

try {
// The first attempt runs outside any scope, as an expiry sweep did before it had one.
await releaser.release(lease);
expect(fs.existsSync(logPath)).toBe(false);

await vi.advanceTimersByTimeAsync(10);

expect(release).toHaveBeenCalledTimes(2);
expect(fs.readFileSync(logPath, 'utf8')).toMatch(
/"phase":"provider_lease_expiry_retry_scheduled"/,
);
} finally {
releaser.shutdown();
vi.useRealTimers();
}
});

test('retries a persisted expired provider lease after daemon restart', async () => {
const stateDir = mkdtempForTestSync('agent-device-expired-provider-lease-');
const lease = new LeaseRegistry().allocateLease({
Expand Down Expand Up @@ -167,6 +204,27 @@ test('shutdown drain reports releases completed before and during its final retr
}
});

test('a shutdown drain that settles inside its budget leaves no deadline timer behind', async () => {
vi.useFakeTimers();
const releaser = createExpiredProviderLeaseReleaser({
leaseLifecycleProvider: { release: vi.fn().mockResolvedValue({}) },
providerRuntimeIds: ['browserstack'],
});

try {
releaser.beginShutdown();
await expect(releaser.drain(2_000)).resolves.toEqual({
pending: [],
unknown: [],
released: [],
});
expect(vi.getTimerCount()).toBe(0);
} finally {
releaser.shutdown();
vi.useRealTimers();
}
});

test('a daemon killed while holding a provider lease recovers it on restart', async () => {
const stateDir = mkdtempForTestSync('agent-device-live-provider-lease-');
const recoverExpiredLease = vi.fn(async (_lease: DeviceLease) => undefined);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ test('a SIGTERM shutdown gives the handoff a diagnostics scope to write its reas
const daemonLog = fs.readFileSync(path.join(stateDir, 'daemon.log'), 'utf8');
expect(daemonLog).toMatch(/"phase":"detach_scope_probe"/);
expect(daemonLog).toMatch(/"lane":"physical_coredevice"/);
// The shutdown's one lease and claim summary also runs outside any request.
expect(daemonLog).toMatch(/"phase":"daemon_shutdown_provider_release_drain"/);
} finally {
fs.rmSync(stateDir, { recursive: true, force: true });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device
import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts';
import { SessionStore } from '../../core/session-store.ts';
import { makeRecordingSession } from '../../__tests__/support/session-teardown.fixtures.ts';
import { makeIosSession } from '../../__tests__/support/session-factories.ts';

afterEach(() => {
vi.useRealTimers();
Expand Down Expand Up @@ -89,3 +90,28 @@ test('daemon shutdown resolves durable recording resources through the effective
expect(stderrChunks.join('')).not.toMatch(/resource record is missing/);
expect(sessionStore.get(effectiveSessionName)).toBeUndefined();
});

test('a session teardown that finishes inside its budget cancels its deadline timer', async () => {
vi.useFakeTimers();
const root = mkdtempForTestSync('agent-device-shutdown-deadline-');
const sessionStore = new SessionStore(
path.join(root, 'sessions'),
createLiveTestHostEnvironment(),
);
const session = makeIosSession('shutdown-fast');
sessionStore.publish(session.name, session);
const stderrChunks: string[] = [];

const teardown = teardownDaemonSessionForShutdown({
ref: sessionStore.lookup(session.name)!,
sessionStore,
stderr: { write: (chunk) => stderrChunks.push(chunk) },
platformCleanup: platformResourceCleanupFixture(),
});
await vi.advanceTimersByTimeAsync(0);
expect(await teardown).toBe(true);

expect(vi.getTimerCount()).toBe(0);
await vi.advanceTimersByTimeAsync(60_000);
expect(stderrChunks.join('')).not.toMatch(/timed out/);
});
Loading
Loading