refactor(session): route construction through Session.create

This commit is contained in:
imccyu
2026-08-04 18:41:07 +08:00
parent c7f693aa40
commit 8cbdd5b9d0
61 changed files with 305 additions and 292 deletions

View File

@@ -639,7 +639,7 @@ describe('session reference discovery and preparation', () => {
expect(JSON.stringify(before)).toContain('durable referenced fact')
expect(JSON.stringify(before)).toContain('use @source')
expect(JSON.stringify(before)).not.toContain('later source mutation')
expect(new Session(SessionId('replayed-target'), target.events).deriveMessages()).toEqual(before)
expect(Session.create(SessionId('replayed-target'), target.events).deriveMessages()).toEqual(before)
})
it('rejects direct invalid configuration before service publication', async () => {

View File

@@ -44,7 +44,7 @@ function reading(
}
function preparing(turn: number, step: number): Session {
const session = new Session(SessionId(`time-invariant-${turn}-${step}`))
const session = Session.create(SessionId(`time-invariant-${turn}-${step}`))
for (let priorTurn = 1; priorTurn < turn; priorTurn += 1) {
session.append('turn/start', { turn: priorTurn, trigger: { kind: 'message', source: { kind: 'user' } } })
session.append('turn/end', { turn: priorTurn, reason: { kind: 'completed' } })
@@ -136,7 +136,7 @@ describe('time-context invariants', () => {
started.append('step/start', { turn: 1, step: 1 })
expect(() => { ctx.emit('session/event', started, event(reading())) }).toThrow(/must precede step\/start/)
expect(() => {
ctx.emit('session/event', new Session(SessionId('time-invariant-empty')), event(reading()))
ctx.emit('session/event', Session.create(SessionId('time-invariant-empty')), event(reading()))
}).toThrow(/inside an open turn/)
})

View File

@@ -141,7 +141,7 @@ function requestText(request: GenerateOptions): string {
describe('durable step context', () => {
it('records turn, step, zoned time, and the preceding model-visible message baseline', async () => {
const { ctx } = await mount({ timeZone: 'Asia/Shanghai' })
const session = new Session(SessionId('first'))
const session = Session.create(SessionId('first'))
openMessageTurn(session, 1)
vi.setSystemTime(BASE + 90_061_000)
@@ -160,7 +160,7 @@ describe('durable step context', () => {
it('reports an unavailable first-step baseline when no model-visible message precedes it', async () => {
const { ctx } = await mount()
const session = new Session(SessionId('unavailable'))
const session = Session.create(SessionId('unavailable'))
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
await fire(ctx, sessionAgent(session), 1, 1)
@@ -175,7 +175,7 @@ describe('durable step context', () => {
['zero interval', { refreshIntervalMs: 0 }],
] as const)('uses the preceding durable step-context timestamp after step one with %s', async (_label, config) => {
const { ctx } = await mount(config)
const session = new Session(SessionId('later-step'))
const session = Session.create(SessionId('later-step'))
const agent = sessionAgent(session)
openMessageTurn(session, 3)
await fire(ctx, agent, 3, 1)
@@ -191,7 +191,7 @@ describe('durable step context', () => {
it('reports an unavailable later-step baseline at the matching turn boundary', async () => {
const { ctx } = await mount()
const session = new Session(SessionId('later-step-boundary'))
const session = Session.create(SessionId('later-step-boundary'))
openMessageTurn(session, 4)
await fire(ctx, sessionAgent(session), 4, 2)
@@ -203,7 +203,7 @@ describe('durable step context', () => {
it('reports an unavailable later-step baseline when event lookup is exhausted', async () => {
const { ctx } = await mount()
const session = new Session(SessionId('later-step-exhausted'))
const session = Session.create(SessionId('later-step-exhausted'))
await fire(ctx, sessionAgent(session), 1, 2)
@@ -214,7 +214,7 @@ describe('durable step context', () => {
it('injects after backward wall-clock movement and clamps elapsed time to zero', async () => {
const { ctx } = await mount({ refreshIntervalMs: 60_000 })
const session = new Session(SessionId('backward'))
const session = Session.create(SessionId('backward'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
await fire(ctx, agent, 1, 1)
@@ -228,7 +228,7 @@ describe('durable step context', () => {
it('uses a shadowed durable injection after resume and injects at the exact threshold', async () => {
const { ctx } = await mount({ refreshIntervalMs: 1_000 })
const original = new Session(SessionId('seed-source'))
const original = Session.create(SessionId('seed-source'))
openMessageTurn(original, 1)
await fire(ctx, sessionAgent(original), 1, 1)
const user = original.events.find(event => event.type === 'user/message' && event.data.source.kind === 'user')
@@ -244,7 +244,7 @@ describe('durable step context', () => {
original.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
expect(JSON.stringify(original.deriveMessages())).not.toContain('Time sampled while preparing')
const resumed = new Session(SessionId('resumed'), [...original.events])
const resumed = Session.create(SessionId('resumed'), [...original.events])
const resumedAgent = sessionAgent(resumed)
vi.setSystemTime(BASE + 999)
openMessageTurn(resumed, 2)
@@ -266,7 +266,7 @@ describe('durable step context', () => {
it('applies a positive interval across turns without sharing state between sessions', async () => {
const { ctx } = await mount({ refreshIntervalMs: 1_000 })
const first = new Session(SessionId('interval-first'))
const first = Session.create(SessionId('interval-first'))
const firstAgent = sessionAgent(first, 'first-agent')
openMessageTurn(first, 1)
await fire(ctx, firstAgent, 1, 1)
@@ -277,7 +277,7 @@ describe('durable step context', () => {
const beforeSkip = first.events.length
await fire(ctx, firstAgent, 2, 1)
const independent = new Session(SessionId('interval-independent'))
const independent = Session.create(SessionId('interval-independent'))
openMessageTurn(independent, 1)
await fire(ctx, sessionAgent(independent, 'independent-agent'), 1, 1)
@@ -288,7 +288,7 @@ describe('durable step context', () => {
it('runs before ordinary pre-step listeners and skips an already-aborted step', async () => {
const { ctx } = await mount()
const session = new Session(SessionId('ordering'))
const session = Session.create(SessionId('ordering'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
let ordinarySawContext = false
@@ -311,7 +311,7 @@ describe('configuration and lifecycle', () => {
process.env['TZ'] = 'Asia/Shanghai'
const { ctx } = await mount()
process.env['TZ'] = 'America/New_York'
const session = new Session(SessionId('system-zone'))
const session = Session.create(SessionId('system-zone'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -345,7 +345,7 @@ describe('configuration and lifecycle', () => {
it('removes its listener when the plugin fiber disposes', async () => {
const { ctx, fiber } = await mount()
const session = new Session(SessionId('dispose'))
const session = Session.create(SessionId('dispose'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
await fire(ctx, agent, 1, 1)
@@ -445,7 +445,7 @@ describe('real Loader export path', () => {
await ctx.plugin(AgentRegistry)
const plugin = loader.unwrapExports(timeContext) as Parameters<Context['plugin']>[0]
await ctx.plugin(plugin)
const session = new Session(SessionId('loader'))
const session = Session.create(SessionId('loader'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
expect(contextTexts(session)[0]).toContain('Time sampled while preparing turn 1, step 1:')

View File

@@ -150,7 +150,7 @@ afterEach(() => {
describe('tmux-context injection', () => {
it('injects the tmux location on the first step of a turn', async () => {
const { ctx } = await mount({}, true)
const session = new Session(SessionId('first'))
const session = Session.create(SessionId('first'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -169,7 +169,7 @@ describe('tmux-context injection', () => {
it('queries the pane this process runs in and matches its controlling tty', async () => {
const { ctx, bash } = await mount({}, true)
const session = new Session(SessionId('command'))
const session = Session.create(SessionId('command'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -187,7 +187,7 @@ describe('tmux-context injection', () => {
it('does not run on later steps of a turn', async () => {
const { ctx, bash } = await mount({}, true)
const session = new Session(SessionId('later-step'))
const session = Session.create(SessionId('later-step'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 2)
@@ -198,7 +198,7 @@ describe('tmux-context injection', () => {
it('re-injects a new turn only when tmux state changed', async () => {
const { ctx, bash } = await mount({}, true)
const session = new Session(SessionId('change'))
const session = Session.create(SessionId('change'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
@@ -226,7 +226,7 @@ describe('tmux-context injection', () => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
const { ctx, bash } = await mount({ refreshIntervalMs: 10_000 }, true)
const session = new Session(SessionId('interval'))
const session = Session.create(SessionId('interval'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
@@ -253,7 +253,7 @@ describe('tmux-context injection', () => {
describe('tmux-context prior-reading resilience', () => {
it('treats a prior non-text plugin reading as absent and injects afresh', async () => {
const { ctx, bash } = await mount({}, true)
const session = new Session(SessionId('prior-non-text'))
const session = Session.create(SessionId('prior-non-text'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
session.append('user/message', createUserMessage({
@@ -269,7 +269,7 @@ describe('tmux-context prior-reading resilience', () => {
it('treats a prior single-line plugin reading (no newline) as empty state', async () => {
const { ctx, bash } = await mount({}, true)
const session = new Session(SessionId('prior-single-line'))
const session = Session.create(SessionId('prior-single-line'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
session.append('user/message', createUserMessage({
@@ -288,7 +288,7 @@ describe('tmux-context prior-reading resilience', () => {
describe('tmux-context no-op paths', () => {
it('is a no-op when no bash executor is mounted', async () => {
const { ctx } = await mount()
const session = new Session(SessionId('no-bash'))
const session = Session.create(SessionId('no-bash'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -299,7 +299,7 @@ describe('tmux-context no-op paths', () => {
it('is a no-op when the tmux query exits nonzero (outside tmux, or an inherited env whose tty does not match the pane)', async () => {
const { ctx, bash } = await mount({}, true)
bash.result = runResult('', { exitCode: 1 })
const session = new Session(SessionId('outside-tmux'))
const session = Session.create(SessionId('outside-tmux'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -310,7 +310,7 @@ describe('tmux-context no-op paths', () => {
it('is a no-op when the reading has the wrong field count', async () => {
const { ctx, bash } = await mount({}, true)
bash.result = runResult('0\\t1\\tnode\n')
const session = new Session(SessionId('malformed'))
const session = Session.create(SessionId('malformed'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -321,7 +321,7 @@ describe('tmux-context no-op paths', () => {
it('is a no-op when the pane id is empty', async () => {
const { ctx, bash } = await mount({}, true)
bash.result = runResult(`${tmuxLine({ paneId: '' })}\n`)
const session = new Session(SessionId('empty-pane'))
const session = Session.create(SessionId('empty-pane'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -333,7 +333,7 @@ describe('tmux-context no-op paths', () => {
const { ctx, bash } = await mount({}, true)
bash.runError = new Error('bash executor unavailable')
const warn = vi.spyOn(ctx.logger, 'warn')
const session = new Session(SessionId('run-rejected'))
const session = Session.create(SessionId('run-rejected'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -346,7 +346,7 @@ describe('tmux-context no-op paths', () => {
const { ctx, bash } = await mount({}, true)
bash.resolveError = new Error('command denied by policy')
const warn = vi.spyOn(ctx.logger, 'warn')
const session = new Session(SessionId('resolve-rejected'))
const session = Session.create(SessionId('resolve-rejected'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -360,7 +360,7 @@ describe('tmux-context no-op paths', () => {
// Non-Error throw: the executor seam is typed, but a bad impl can reject with anything.
bash.runError = 'spawn refused' as unknown as Error
const warn = vi.spyOn(ctx.logger, 'warn')
const session = new Session(SessionId('non-error-rejection'))
const session = Session.create(SessionId('non-error-rejection'))
openMessageTurn(session, 1)
await fire(ctx, sessionAgent(session), 1, 1)
@@ -371,7 +371,7 @@ describe('tmux-context no-op paths', () => {
it('skips an already-aborted step and runs before ordinary agent/step listeners', async () => {
const { ctx } = await mount({}, true)
const session = new Session(SessionId('ordering'))
const session = Session.create(SessionId('ordering'))
const agent = sessionAgent(session)
openMessageTurn(session, 1)
let ordinarySawContext = false

View File

@@ -170,7 +170,7 @@ async function mountFileToolsAndWorkspaceContext(ctx: Context, config: workspace
function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent {
const id = SessionId('s1')
const session = new Session(id, seed, cwd === undefined ? undefined : { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd })
const session = Session.create(id, seed, cwd === undefined ? undefined : { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd })
return {
ctx: new Context(),
id: SessionId('a1'),