Skip to content

Commit 64f40ac

Browse files
committed
refactor: resolve session artifact paths without a store
1 parent 5411c0b commit 64f40ac

10 files changed

Lines changed: 106 additions & 85 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
// oxlint-disable-next-line no-restricted-imports -- asserts a path under os.homedir
4+
import os from 'node:os';
5+
import path from 'node:path';
6+
import { expandSessionPath } from './session-paths.ts';
7+
8+
test('expandSessionPath resolves tilde, relative-with-cwd, and absolute paths', () => {
9+
const homePath = expandSessionPath('~/flows/replay.ad');
10+
assert.equal(homePath.startsWith(os.homedir()), true);
11+
assert.equal(homePath.endsWith(path.join('flows', 'replay.ad')), true);
12+
13+
const relativePath = expandSessionPath('workflows/replay.ad', '/tmp/agent-device-cwd');
14+
assert.equal(relativePath, path.resolve('/tmp/agent-device-cwd', 'workflows/replay.ad'));
15+
16+
const absoluteInput = path.resolve('/tmp', 'agent-device-absolute.ad');
17+
const absolutePath = expandSessionPath(absoluteInput, '/tmp/ignored-cwd');
18+
assert.equal(absolutePath, absoluteInput);
19+
});
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import path from 'node:path';
4+
import { AppError } from '@agent-device/kernel/errors';
5+
import { resolveSessionDir } from '../session-artifact-paths.ts';
6+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
7+
8+
test('resolveSessionDir keeps every session dir beneath the sessions dir', () => {
9+
const sessionsDir = path.join(
10+
mkdtempForTestSync('agent-device-tests'),
11+
'agent-device-tests',
12+
'sessions',
13+
);
14+
assert.equal(resolveSessionDir(sessionsDir, 'a/b:c d'), path.join(sessionsDir, 'a_b_c_d'));
15+
// `.` and `..` survive `safeSessionName` unchanged, so without an explicit
16+
// refusal `path.join` resolves them to the sessions dir itself and its parent
17+
// (the daemon state dir): a remote caller's `--session ..` would then land
18+
// app.log / runner.log / requests/*.ndjson outside the sessions tree.
19+
for (const name of ['.', '..', '']) {
20+
assert.throws(
21+
() => resolveSessionDir(sessionsDir, name),
22+
(error: unknown) =>
23+
error instanceof AppError &&
24+
error.code === 'INVALID_ARGS' &&
25+
/session name/i.test(error.message),
26+
`expected resolveSessionDir(${JSON.stringify(name)}) to reject`,
27+
);
28+
}
29+
});

‎src/daemon/__tests__/session-store.test.ts‎

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import fs from 'node:fs';
4-
// oxlint-disable-next-line no-restricted-imports -- asserts a path under os.homedir
5-
import os from 'node:os';
64
import path from 'node:path';
7-
import { AppError } from '@agent-device/kernel/errors';
85
import { SessionStore } from '../session-store.ts';
96
import type { SessionState } from '../session-state.ts';
107
import { buildRequestFinishedEvent } from '@agent-device/session-journal/session-event-log';
@@ -96,19 +93,6 @@ function assertScriptMatches(script: string, patterns: RegExp[]): void {
9693
}
9794
}
9895

99-
test('expandHome resolves tilde, relative-with-cwd, and absolute paths', () => {
100-
const homePath = SessionStore.expandHome('~/flows/replay.ad');
101-
assert.equal(homePath.startsWith(os.homedir()), true);
102-
assert.equal(homePath.endsWith(path.join('flows', 'replay.ad')), true);
103-
104-
const relativePath = SessionStore.expandHome('workflows/replay.ad', '/tmp/agent-device-cwd');
105-
assert.equal(relativePath, path.resolve('/tmp/agent-device-cwd', 'workflows/replay.ad'));
106-
107-
const absoluteInput = path.resolve('/tmp', 'agent-device-absolute.ad');
108-
const absolutePath = SessionStore.expandHome(absoluteInput, '/tmp/ignored-cwd');
109-
assert.equal(absolutePath, absoluteInput);
110-
});
111-
11296
test('defaultTracePath sanitizes session name', () => {
11397
const store = new SessionStore(
11498
path.join(mkdtempForTestSync('agent-device-tests'), 'agent-device-tests'),
@@ -119,30 +103,6 @@ test('defaultTracePath sanitizes session name', () => {
119103
assert.match(tracePath, /\.trace\.log$/);
120104
});
121105

122-
test('resolveSessionDir keeps every session dir beneath the sessions dir', () => {
123-
const sessionsDir = path.join(
124-
mkdtempForTestSync('agent-device-tests'),
125-
'agent-device-tests',
126-
'sessions',
127-
);
128-
const store = new SessionStore(sessionsDir);
129-
assert.equal(store.resolveSessionDir('a/b:c d'), path.join(sessionsDir, 'a_b_c_d'));
130-
// `.` and `..` survive `safeSessionName` unchanged, so without an explicit
131-
// refusal `path.join` resolves them to the sessions dir itself and its parent
132-
// (the daemon state dir): a remote caller's `--session ..` would then land
133-
// app.log / runner.log / requests/*.ndjson outside the sessions tree.
134-
for (const name of ['.', '..', '']) {
135-
assert.throws(
136-
() => store.resolveSessionDir(name),
137-
(error: unknown) =>
138-
error instanceof AppError &&
139-
error.code === 'INVALID_ARGS' &&
140-
/session name/i.test(error.message),
141-
`expected resolveSessionDir(${JSON.stringify(name)}) to reject`,
142-
);
143-
}
144-
});
145-
146106
test('session lease metadata round-trips through the store', () => {
147107
const { store, session } = makeFixture('agent-device-session-lease-');
148108
session.lease = {

‎src/daemon/device/device-claim-owner-recovery.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import { createPlatformRuntimeGateway } from '../../platform-runtime.ts';
44
import { resolveDaemonPaths } from '../../daemon-resolution.ts';
55
import { createDeviceClaimReconciler } from './device-claim-reconciliation.ts';
66
import type { DeviceClaimReconciler } from './device-claims.ts';
7-
import { SessionStore } from '../session-store.ts';
7+
import {
8+
resolveSessionDir,
9+
resolveSessionAppLogPath,
10+
resolveSessionAppLogPidPath,
11+
} from '../session-artifact-paths.ts';
812

913
export type OwnerScopedClaimRecovery = {
1014
reconcile: DeviceClaimReconciler;
@@ -49,17 +53,16 @@ function composeOwnerScopedClaimRecovery(
4953
scope: PlatformRequestScope,
5054
): OwnerScopedClaimRecovery {
5155
const daemonPaths = resolveDaemonPaths(stateDir);
52-
const sessionStore = new SessionStore(daemonPaths.sessionsDir);
5356
const gateway = createPlatformRuntimeGateway({
5457
sessionsDir: daemonPaths.sessionsDir,
5558
ownedProcesses: createOwnedProcessRecordStore({
5659
stateDir: daemonPaths.baseDir,
5760
sessionsDir: daemonPaths.sessionsDir,
58-
resolveSessionDir: (sessionId) => sessionStore.resolveSessionDir(sessionId),
61+
resolveSessionDir: (sessionId) => resolveSessionDir(daemonPaths.sessionsDir, sessionId),
5962
}),
6063
resolveSessionArtifacts: (sessionId) => ({
61-
outputPath: sessionStore.resolveAppLogPath(sessionId),
62-
pidPath: sessionStore.resolveAppLogPidPath(sessionId),
64+
outputPath: resolveSessionAppLogPath(daemonPaths.sessionsDir, sessionId),
65+
pidPath: resolveSessionAppLogPidPath(daemonPaths.sessionsDir, sessionId),
6366
}),
6467
});
6568
return {

‎src/daemon/handlers/session-app-deployment.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { expandSessionPath } from '@agent-device/host-kit/session-paths';
12
import fs from 'node:fs';
23
import type { AppDeploymentResult } from '@agent-device/contracts/app-deployment-runtime';
34
import {
@@ -9,7 +10,7 @@ import { readNotificationPayload } from '../dispatch-payload.ts';
910
import { cleanupUploadedArtifact, prepareUploadedArtifact } from '../artifact-tracking.ts';
1011
import { expireRefFrame } from '../ref-frame.ts';
1112
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from '../request-runtime-binding.ts';
12-
import { SessionStore } from '../session-store.ts';
13+
import type { SessionStore } from '../session-store.ts';
1314
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
1415
import type { SessionState } from '../session-state.ts';
1516
import { resolvePayloadInput } from '../payload-input.ts';
@@ -62,7 +63,7 @@ export async function handleAppDeploymentCommand(params: {
6263
try {
6364
const appPath = uploadedArtifactId
6465
? prepareUploadedArtifact(uploadedArtifactId, req.meta?.tenantId)
65-
: SessionStore.expandHome(target.appPathInput);
66+
: expandSessionPath(target.appPathInput);
6667
if (!fs.existsSync(appPath)) {
6768
return errorResponse('INVALID_ARGS', `App binary not found: ${appPath}`);
6869
}
@@ -242,7 +243,7 @@ function resolvePushPayload(payloadArg: string, cwd?: string): string {
242243
const resolved = resolvePayloadInput(payloadArg, {
243244
subject: 'Push payload',
244245
cwd,
245-
expandPath: (value, currentCwd) => SessionStore.expandHome(value, currentCwd),
246+
expandPath: (value, currentCwd) => expandSessionPath(value, currentCwd),
246247
});
247248
return resolved.kind === 'file' ? resolved.path : resolved.text;
248249
}

‎src/daemon/handlers/trace-runtime.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
import { expandSessionPath } from '@agent-device/host-kit/session-paths';
12
import fs from 'node:fs';
23
import path from 'node:path';
34
import type { TraceCommandResult } from '@agent-device/contracts/recording';
4-
import { SessionStore } from '../session-store.ts';
5+
import type { SessionStore } from '../session-store.ts';
56
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
67
import type { SessionState } from '../session-state.ts';
78
import { recordSessionAction } from '../session-action-recorder.ts';
@@ -29,9 +30,7 @@ function startTrace(
2930
session: SessionState,
3031
): DaemonResponse {
3132
if (session.trace) return errorResponse('INVALID_ARGS', 'trace already in progress');
32-
const outPath = SessionStore.expandHome(
33-
req.positionals?.[1] ?? sessionStore.defaultTracePath(session),
34-
);
33+
const outPath = expandSessionPath(req.positionals?.[1] ?? sessionStore.defaultTracePath(session));
3534
fs.mkdirSync(path.dirname(outPath), { recursive: true });
3635
fs.appendFileSync(outPath, '');
3736
session.trace = { outPath, startedAt: Date.now() };
@@ -72,7 +71,7 @@ function stopTrace(
7271

7372
function relocateTraceOutput(currentPath: string, requestedPath: string | undefined): string {
7473
if (!requestedPath) return currentPath;
75-
const resolved = SessionStore.expandHome(requestedPath);
74+
const resolved = expandSessionPath(requestedPath);
7675
fs.mkdirSync(path.dirname(resolved), { recursive: true });
7776
if (fs.existsSync(currentPath)) fs.renameSync(currentPath, resolved);
7877
else fs.appendFileSync(resolved, '');

‎src/daemon/screenshot-runtime.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { expandSessionPath } from '@agent-device/host-kit/session-paths';
12
import type { CommandFlags } from '@agent-device/contracts/command';
23
import {
34
retiredScreenshotMaxSizeFlagError,
@@ -38,7 +39,6 @@ import {
3839
type ScreenshotRuntimeBindings,
3940
} from './screenshot-runtime-binding.ts';
4041
import { setSessionSnapshot } from './session-snapshot.ts';
41-
import { SessionStore } from './session-store.ts';
4242
import type { DaemonRequest } from './daemon-request.ts';
4343
import type { SessionState } from './session-state.ts';
4444

@@ -321,7 +321,7 @@ function readScreenshotRequest(
321321
const positionals = req.positionals ?? [];
322322
const flags = req.flags ?? {};
323323
const expand = (value: string | undefined) =>
324-
value === undefined ? undefined : SessionStore.expandHome(value, req.meta?.cwd);
324+
value === undefined ? undefined : expandSessionPath(value, req.meta?.cwd);
325325
const positionalPath = expand(positionals[0]);
326326
const outFlag = expand(flags.out);
327327
return {

‎src/daemon/session-artifact-paths.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import path from 'node:path';
22
import type { DiagnosticsRecordRef } from '@agent-device/kernel/errors';
3-
import { safeSessionName } from '@agent-device/host-kit/session-paths';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths';
45

56
/** Path to session-scoped platform subprocess output, such as Apple runner xcodebuild logs. */
67
export function resolveSessionRunnerLogPath(sessionDir: string): string {
@@ -49,3 +50,27 @@ export function resolveRemoteRequestDiagnosticsPath(
4950
ref.requestId,
5051
);
5152
}
53+
54+
/**
55+
* The one place a session name becomes a directory, so the invariant that every
56+
* session dir lies beneath `sessionsDir` is enforced here rather than by each
57+
* caller: `.` and `..` survive `safeSessionName` and would resolve to the
58+
* sessions dir itself or the daemon state dir above it.
59+
*/
60+
export function resolveSessionDir(sessionsDir: string, sessionName: string): string {
61+
if (!isSafeSessionSegment(sessionName)) {
62+
throw new AppError(
63+
'INVALID_ARGS',
64+
`Invalid session name ${JSON.stringify(sessionName)}: a session name cannot be empty, ".", or "..".`,
65+
);
66+
}
67+
return path.join(sessionsDir, safeSessionName(sessionName));
68+
}
69+
70+
export function resolveSessionAppLogPath(sessionsDir: string, address: string): string {
71+
return path.join(resolveSessionDir(sessionsDir, address), 'app.log');
72+
}
73+
74+
export function resolveSessionAppLogPidPath(sessionsDir: string, address: string): string {
75+
return path.join(resolveSessionDir(sessionsDir, address), 'app-log.pid');
76+
}

‎src/daemon/session-observability/internal/session-perf-runtime.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { expandSessionPath } from '@agent-device/host-kit/session-paths';
12
import path from 'node:path';
23
import { type PerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf-capture-admission-ledger';
34
import {
@@ -28,7 +29,7 @@ import type {
2829
BindDeviceRuntime,
2930
InspectDeviceRuntimeFacts,
3031
} from '../../request-runtime-binding.ts';
31-
import { SessionStore } from '../../session-store.ts';
32+
import type { SessionStore } from '../../session-store.ts';
3233
import type { DaemonRequest, DaemonResponse } from '../../daemon-request.ts';
3334
import type { SessionState } from '../../session-state.ts';
3435
import { recordSessionAction } from '../../session-action-recorder.ts';
@@ -138,7 +139,7 @@ async function executeAdmittedPerfPlan(
138139
appId: session.appBundleId,
139140
kind: plan.request.kind,
140141
outPath: plan.request.outPath
141-
? SessionStore.expandHome(plan.request.outPath, params.req.meta?.cwd)
142+
? expandSessionPath(plan.request.outPath, params.req.meta?.cwd)
142143
: undefined,
143144
artifactsDir: path.join(
144145
params.sessionStore.ensureSessionDir(params.sessionName),
@@ -171,7 +172,7 @@ async function executeAdmittedPerfPlan(
171172
const data = await runtime.operations.perfProfileReport({
172173
appId: session.appBundleId,
173174
kind: plan.request.kind,
174-
tracePath: SessionStore.expandHome(tracePath, params.req.meta?.cwd),
175+
tracePath: expandSessionPath(tracePath, params.req.meta?.cwd),
175176
outPath,
176177
template: plan.request.template ?? (last?.kind === 'xctrace' ? last.template : undefined),
177178
profile: last,
@@ -257,7 +258,7 @@ async function stopPerfCapture(
257258
const mismatchMessage = perfCaptureStopMismatch(snapshot, request);
258259
if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage);
259260
if (request.outPath) {
260-
capture.handle.setOutputPath(SessionStore.expandHome(request.outPath, params.req.meta?.cwd));
261+
capture.handle.setOutputPath(expandSessionPath(request.outPath, params.req.meta?.cwd));
261262
}
262263
const completion = await finishLivePerfCapture({
263264
intent: 'capture',
@@ -395,7 +396,7 @@ function resolveNativeOutPath(
395396
requestedPath: string | undefined,
396397
fallbackFileName: string,
397398
): string {
398-
if (requestedPath) return SessionStore.expandHome(requestedPath, params.req.meta?.cwd);
399+
if (requestedPath) return expandSessionPath(requestedPath, params.req.meta?.cwd);
399400
return path.join(
400401
params.sessionStore.ensureSessionDir(params.sessionName),
401402
`${timestampToken()}-${fallbackFileName}`,

‎src/daemon/session-store.ts‎

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import path from 'node:path';
22
import fs from 'node:fs';
3-
import { AppError } from '@agent-device/kernel/errors';
43
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
54
import type { SessionRef, SessionRuntimeHints, SessionState } from './session-state.ts';
65
import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts';
6+
import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths';
77
import {
8-
expandSessionPath,
9-
isSafeSessionSegment,
10-
safeSessionName,
11-
} from '@agent-device/host-kit/session-paths';
8+
resolveSessionDir,
9+
resolveSessionAppLogPath,
10+
resolveSessionAppLogPidPath,
11+
} from './session-artifact-paths.ts';
1212
import {
1313
readRepairTombstoneFile,
1414
resolveRepairTombstonePath,
@@ -380,20 +380,8 @@ export class SessionStore {
380380
return path.join(this.sessionsDir, `${safeName}-${timestamp}.trace.log`);
381381
}
382382

383-
/**
384-
* The one place a session name becomes a directory, so the invariant that every
385-
* session dir lies beneath `sessionsDir` is enforced here rather than by each
386-
* caller: `.` and `..` survive `safeSessionName` and would resolve to the
387-
* sessions dir itself or the daemon state dir above it.
388-
*/
389383
resolveSessionDir(sessionName: string): string {
390-
if (!isSafeSessionSegment(sessionName)) {
391-
throw new AppError(
392-
'INVALID_ARGS',
393-
`Invalid session name ${JSON.stringify(sessionName)}: a session name cannot be empty, ".", or "..".`,
394-
);
395-
}
396-
return path.join(this.sessionsDir, safeSessionName(sessionName));
384+
return resolveSessionDir(this.sessionsDir, sessionName);
397385
}
398386

399387
// Daemon state dir (parent of the `sessions/` dir), matching daemonPaths.baseDir. Called via
@@ -411,21 +399,17 @@ export class SessionStore {
411399

412400
/** Path to session-scoped app log file. Agent can grep this for token-efficient debugging. */
413401
resolveAppLogPath(sessionName: string): string {
414-
return path.join(this.resolveSessionDir(sessionName), 'app.log');
402+
return resolveSessionAppLogPath(this.sessionsDir, sessionName);
415403
}
416404

417405
resolveAppLogPidPath(sessionName: string): string {
418-
return path.join(this.resolveSessionDir(sessionName), 'app-log.pid');
406+
return resolveSessionAppLogPidPath(this.sessionsDir, sessionName);
419407
}
420408

421409
resolveEventLogPath(sessionName: string): string {
422410
return resolveSessionEventLogPath(this.resolveSessionDir(sessionName));
423411
}
424412

425-
static expandHome(filePath: string, cwd?: string): string {
426-
return expandSessionPath(filePath, cwd);
427-
}
428-
429413
/**
430414
* Resolve the map key for a live session object. SessionState.name is the
431415
* public session name, while the map key may include cwd/tenant isolation.

0 commit comments

Comments
 (0)