fix(schedule): reconcile latest master contracts

This commit is contained in:
Tianyi Cui
2026-08-08 22:39:07 +08:00
parent 31e83f8ee7
commit 1f88085b53
35 changed files with 260 additions and 141 deletions
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/schedule/tool-schedule/README.md
README.md: 55842c3cb49c43b5c577835a26ef43e6ad452dfd
README.zh.md: 8738ac6b4516a1933b206b6baee5bb3d7d77d23a
README.md: 8068e649d2116da628af1436e1e3cc71b09dcaa0
README.zh.md: 72367b421a8b8dbf5ac866933684740be82157bf
+1 -1
View File
@@ -32,7 +32,7 @@ The closed v1 domain error codes are `invalid_prompt`, `invalid_selector`, `inva
The live owner derives the earliest target from the durable fold. It splits waits longer than the Node timer range and rereads the wall clock after every wake, so a rollback cannot fire early and a forward jump makes the record overdue.
An overdue reminder first checkpoints persistence. If `reserveTurnAdmission()` returns `undefined`, the record stays active and the owner retries after `whenIdle()`. A successful reservation samples one decision time, builds the complete framing, synchronously queues `followup()`, appends an id-only dispatch, releases in `finally`, and then checkpoints the dispatch. Framing or synchronous followup failure writes no dispatch. An append failure faults that owner because the message may already be queued; a barrier rejection leaves the dispatch pending for a later ordinary preflight and does not start a private retry timer.
An overdue reminder first checkpoints persistence. If a turn or another maintenance task already owns the Agent, `runMaintenance()` rejects the idle-phase claim; the record stays active and the owner retries after `whenIdle()`. A successful maintenance task samples one decision time, builds the complete framing, synchronously queues `followup()`, and appends an id-only dispatch before releasing the phase. Waking input remains parked until that release, after which the owner checkpoints dispatch. Framing or synchronous followup failure writes no dispatch. An append failure faults that owner because the message may already be queued; a barrier rejection leaves the dispatch pending for a later ordinary preflight and does not start a private retry timer.
Agent or plugin disposal cancels timers, stops new work, and awaits in-flight preflights and idle waits. It never appends delete records during teardown.
+1 -1
View File
@@ -32,7 +32,7 @@
live owner 从持久折叠结果派生最早的目标。它会拆分超过 Node timer 范围的等待,并在每次唤醒后重新读取墙钟,因此时钟回拨不会提前触发,时钟前跳则会使记录进入 overdue 状态。
overdue 提醒首先为持久化建立检查点。如果 `reserveTurnAdmission()` 返回 `undefined`,记录会保持活动,并在 `whenIdle()` 后重试。reservation 成功后,owner 会采样一次决策时间,构造完整 framing,同步将 `followup()` 入队,追加只含 id 的 dispatch,在 `finally` 中释放 reservation,随后为 dispatch 建立检查点。framing 构造或同步 `followup` 失败不会写入 dispatch。追加失败会使该 owner 进入故障状态,因为消息可能已经入队;barrier 拒绝会把 dispatch 留给后续普通 preflight 处理,而不会启动私有重试 timer。
overdue 提醒首先为持久化建立检查点。如果 agent 已被某个轮次或另一项 maintenance task 占用,`runMaintenance()` 会拒绝对 idle phase 的认领;记录会保持活动,owner 会在 `whenIdle()` 后重试。获准执行的 maintenance task 会采样一次决策时间,构造完整 framing,同步将 `followup()` 入队,并在释放 phase 前追加只含 id 的 dispatch。触发唤醒的 input 会保持 parked,直到该 phase 释放;随后 owner 为 dispatch 建立检查点。framing 构造或同步 `followup` 失败不会写入 dispatch。追加失败会使该 owner 进入故障状态,因为消息可能已经入队;barrier 拒绝会把 dispatch 留给后续普通 preflight 处理,而不会启动私有重试 timer。
agent 或插件执行 dispose(资源释放)时,会取消 timer、停止新工作,并等待进行中的 preflight 和 idle wait。清理期间绝不会追加 delete 记录。
+1 -3
View File
@@ -21,9 +21,7 @@
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"src"
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"peerDependencies": {
@@ -328,7 +328,6 @@ export function scheduleReminderPresentation(
scheduleId: change.schedule.id,
prompt: change.schedule.prompt,
occurrenceAt: change.schedule.scheduledAt,
deliveryMode: 'session-local',
})
case 'delete':
case 'dispatch':
+3 -3
View File
@@ -38,13 +38,13 @@ export function apply(ctx: Context): void {
let stopping = false
ctx.effect(() => {
const stopCreated = ctx.on('agent/created', (agent) => {
const stopCreated = ctx.on('agent/created', ({ agent }) => {
if (stopping || owners.has(agent) || !ctx.agents.roots().includes(agent)) return
const owner = new ScheduleOwner(ctx, agent)
const cleanup: OwnerCleanup = agent.ctx.effect(() => {
const disposeTools = registerScheduleTools(ctx, agent.ctx, agent, () => { owner.requestDrive() })
const stopStatus = agent.ctx.on('agent/status', (subject, status) => {
if (subject === agent && status === 'idle') owner.requestDrive()
const stopStatus = agent.ctx.on('agent/status', ({ status }) => {
if (status === 'idle') owner.requestDrive()
})
owner.start()
return async () => {
@@ -72,8 +72,6 @@ export interface ScheduleReminderPresentation {
readonly prompt: string
/** Scheduled one-shot occurrence represented by the dispatch. */
readonly occurrenceAt: string
/** Fixed delivery boundary rendered by the client plugin. */
readonly deliveryMode: ScheduleDeliveryMode
}
/** Management operations whose persistence barrier may be uncertain. */
@@ -101,13 +101,11 @@ describe('version-1 Schedule decoding and folding', () => {
scheduleId: 'same-id',
prompt: 'parent prompt',
occurrenceAt: '2026-08-05T12:00:00.000Z',
deliveryMode: 'session-local',
})
expect(scheduleReminderPresentation(events, 3, 2)).toEqual({
scheduleId: 'same-id',
prompt: 'child prompt',
occurrenceAt: '2026-08-05T12:00:00.000Z',
deliveryMode: 'session-local',
})
const nested = [
scheduleEvent(createData('same-id', 'grandparent prompt'), 0),
@@ -120,7 +118,6 @@ describe('version-1 Schedule decoding and folding', () => {
scheduleId: 'same-id',
prompt: 'parent prompt',
occurrenceAt: '2026-08-05T12:00:00.000Z',
deliveryMode: 'session-local',
})
const resumedThenForked = [
scheduleEvent(createData('resumed-id', 'resumed prompt'), 0),
@@ -131,7 +128,6 @@ describe('version-1 Schedule decoding and folding', () => {
scheduleId: 'resumed-id',
prompt: 'resumed prompt',
occurrenceAt: '2026-08-05T12:00:00.000Z',
deliveryMode: 'session-local',
})
expect(() => scheduleReminderPresentation([
scheduleEvent(createData('parent-only'), 0),
@@ -37,7 +37,7 @@ describe('Schedule package invariant', () => {
it('accepts valid candidates and rejects invalid transitions before append', async () => {
const { ctx } = await harness()
const session = ctx.sessions.create(SessionId('schedule-invariant'))
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
session.append('turn/start', { turn: 1 })
session.append('schedule/change', create('schedule-1'))
expect(session.events).toHaveLength(2)
@@ -124,7 +124,6 @@ describe('Schedule production JSONL restart', () => {
scheduleId: 'schedule-1',
prompt: 'restart reminder',
occurrenceAt: pendingRecord.scheduledAt,
deliveryMode: 'session-local',
})
expect(dispatchingAdapter.requests).toHaveLength(1)
await handle.dispose()
@@ -55,8 +55,8 @@ describe('Schedule plugin composition', () => {
expect(created.isError).toBe(false)
if (created.isError) throw new Error('expected Schedule create value')
expect(created.value).toMatchObject({ id: 'schedule-1', deliveryMode: 'session-local' })
agentEvents(ctx, root.agent).emit('agent/status', 'running')
agentEvents(ctx, root.agent).emit('agent/status', 'idle')
agentEvents(ctx, root.agent).emit('agent/status', { status: 'running' })
agentEvents(ctx, root.agent).emit('agent/status', { status: 'idle' })
const child = await root.agent.ctx.agents.create({ sessionId: SessionId('schedule-child') })
expect(ctx.agents.roots()).toEqual([existing.agent, root.agent])
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent, AgentCancelCause, SendOptions } from '@deepseek-ai/dsh-agent'
import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import {
@@ -26,6 +26,7 @@ interface RuntimeHarness {
flushCount: number
flushOutcomes: Array<'resolve' | 'reject'>
flushHandler: (() => Promise<void> | undefined) | undefined
onBusy: (() => void) | undefined
onReserve: (() => void) | undefined
onFollowup: (() => void) | undefined
idle: PromiseWithResolvers<undefined>
@@ -49,30 +50,35 @@ async function harness(): Promise<RuntimeHarness> {
flushCount: 0,
flushOutcomes: [] as Array<'resolve' | 'reject'>,
flushHandler: undefined as (() => Promise<void> | undefined) | undefined,
onBusy: undefined as (() => void) | undefined,
onReserve: undefined as (() => void) | undefined,
onFollowup: undefined as (() => void) | undefined,
idle: Promise.withResolvers<undefined>(),
}
const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
const agent: Agent = {
id: session.id,
options: {},
session,
inbox,
status: 'idle',
acceptsNextStep: false,
ctx: new Context(),
send(_message: UserMessage, _options: SendOptions) {},
updateInbox: () => 'not-found',
reserveTurnAdmission() {
order.push('reserve')
if (!controls.canReserve) return undefined
controls.onReserve?.()
let active = true
return () => {
if (!active) return
active = false
controls.releaseCount += 1
order.push('release')
send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {},
runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> {
order.push('maintenance')
if (!controls.canReserve) {
controls.onBusy?.()
throw new Error('agent busy')
}
controls.onReserve?.()
return (async () => {
try {
return await task(new AbortController().signal)
} finally {
controls.releaseCount += 1
order.push('release')
}
})()
},
cancel(_cause: AgentCancelCause) {},
whenIdle() {
@@ -86,7 +92,7 @@ async function harness(): Promise<RuntimeHarness> {
if (controls.throwFollowup) throw new Error('queue unavailable')
followed.push(message)
},
steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
steer(_message: UserMessage) {},
inject(_message: UserMessage) {},
}
const disposeAgent = ctx.agents.register(agent)
@@ -195,7 +201,7 @@ describe('Schedule timer and admission runtime', () => {
await owner.dispose()
})
it('keeps an overdue record active until whenIdle permits reservation', async () => {
it('keeps an overdue record active until whenIdle permits maintenance', async () => {
const test = await harness()
appendAfter(test, 'schedule-1', 1, Date.now() - 1_000)
test.controls.canReserve = false
@@ -219,7 +225,7 @@ describe('Schedule timer and admission runtime', () => {
await owner.dispose()
})
it('orders preflight, reservation, framing followup, dispatch, release, and barrier', async () => {
it('orders preflight, maintenance, framing followup, dispatch, release, and barrier', async () => {
const test = await harness()
appendAfter(test, 'schedule-"1', 1, Date.now() - 1_000, 'line\noccurrence_at: forged')
test.order.length = 0
@@ -227,7 +233,7 @@ describe('Schedule timer and admission runtime', () => {
owner.start()
await settle()
expect(test.order.slice(0, 6)).toEqual(['flush', 'reserve', 'followup', 'dispatch', 'release', 'flush'])
expect(test.order.slice(0, 6)).toEqual(['flush', 'maintenance', 'followup', 'dispatch', 'release', 'flush'])
expect(test.followed[0]?.content).toEqual([{
type: 'text',
text: [
@@ -259,7 +265,7 @@ describe('Schedule timer and admission runtime', () => {
await owner.dispose()
})
it('rechecks the wall clock after reservation before queuing', async () => {
it('rechecks the wall clock after claiming maintenance before queuing', async () => {
const test = await harness()
appendAfter(test, 'schedule-1', 1, Date.now() - 1_000)
test.controls.onReserve = () => {
@@ -548,7 +554,7 @@ describe('Schedule runtime failure and teardown boundaries', () => {
expect(departedRun.followed).toEqual([])
})
it('releases admission without work when liveness changes during reservation', async () => {
it('releases maintenance without work when liveness changes during its claim', async () => {
const test = await harness()
appendAfter(test, 'schedule-1', 1, Date.now() - 1_000)
test.controls.onReserve = test.disposeAgent
@@ -558,6 +564,17 @@ describe('Schedule runtime failure and teardown boundaries', () => {
expect(test.controls.releaseCount).toBe(1)
expect(test.followed).toEqual([])
await owner.dispose()
const busy = await harness()
appendAfter(busy, 'schedule-1', 1, Date.now() - 1_000)
busy.controls.canReserve = false
busy.controls.onBusy = busy.disposeAgent
const busyOwner = ownerFor(busy)
busyOwner.start()
await settle()
expect(busy.controls.whenIdleCount).toBe(0)
expect(busy.followed).toEqual([])
await busyOwner.dispose()
})
it('waits for in-flight preflight during dispose and does no post-dispose work', async () => {
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent, AgentCancelCause, SendOptions } from '@deepseek-ai/dsh-agent'
import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent'
import { CallId } from '@deepseek-ai/dsh-llm'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
@@ -24,20 +24,20 @@ interface ToolHarness {
function stubAgent(ctx: Context, id: string): Agent {
const session = ctx.sessions.create(SessionId(id))
const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
return {
id: session.id,
options: {},
session,
inbox,
status: 'idle',
acceptsNextStep: false,
ctx: new Context(),
send(_message: UserMessage, _options: SendOptions) {},
updateInbox: () => 'not-found',
reserveTurnAdmission: () => undefined,
send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {},
runMaintenance: task => task(signal),
cancel(_cause: AgentCancelCause) {},
whenIdle: () => Promise.resolve(),
followup(_message: UserMessage) {},
steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
steer(_message: UserMessage) {},
inject(_message: UserMessage) {},
}
}