import { inspectionStatus } from '../src/engine/safety.ts' import { test } from 'node:test' import assert from 'node:assert/strict' import * as binding from '../src/plugin/turnbind.ts' import { makeSubagentHost, type HostAdapters } from '../src/plugin/host.ts' import { inject } from '../src/index.ts' import { testParticipants } from './helpers/participants.ts' import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' function makeSafetyHost(ctx: Context, manager: Agent) { // #99:观察引用/祖先/orphan 证据由参与者索引持有,host 只做转发。 const participants = testParticipants(ctx) const host = makeSubagentHost({ ctx, managerAgentOf: () => manager, registerJudgeSession() {}, revokeJudgeSession() {}, registerRoleActorSession() {} } satisfies HostAdapters, participants) return Object.assign(host, { participants }) } test('plugin injects the standard Web services but never compaction (preset-plane since dsh rc.7)', () => { // compaction 由每个会话的 preset 在 isolate 域挂载(web-app bundle 禁用了 // 宿主平面副本),宿主行 inject 只会永久 pending 并卡死 boot;运行期按 // agent 解析(host.ts compactionFor)。 assert.deepEqual(inject, ['commands', 'tools', 'subagents', 'agents', 'sessions', 'jobs', 'llm']) }) test('turn/end binds its exact completed turn, never a later dispatch', () => { const end = { seq: 3, type: 'turn/end', data: { turn: 1 } } const events = [ { seq: 0, type: 'turn/start', data: { turn: 1 } }, { seq: 1, type: 'user/message', data: { id: 'dispatch-old' } }, { seq: 2, type: 'user/message', data: { id: 'steer' } }, end, { seq: 4, type: 'turn/start', data: { turn: 2 } }, { seq: 5, type: 'user/message', data: { id: 'dispatch-new' } }, ] assert.deepEqual(binding.endedTurnUserMessageIds(events, end), new Set(['steer', 'dispatch-old'])) assert.equal(binding.endedTurnUserMessageIds(events, { ...end, data: { turn: 9 } }), undefined) }) test('safe inspection rejects a different live Activation for the observed Session', async () => { const oldActor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const replacement = { ...oldActor, whenIdle: async () => {} } as unknown as Agent let current: Agent | undefined = oldActor const ctx = { jobs: { list: () => [], events: { subscribe: () => () => {} } }, effect: () => {}, agents: { get: () => current, list: () => current ? [current] : [] }, subagents: { listDescendants: async () => [] }, } as unknown as Context const host = makeSafetyHost(ctx, oldActor) host.participants.observeTurnEnd('actor') current = replacement assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe') }) test('safe inspection rejects a descendant that appears while idle checks await', async () => { let checks = 0 let child: Agent | undefined const actor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => { if (++checks === 2) child = { id: 'child', status: 'running', session: { id: 'child', header: { parentSession: 'actor' } }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent }, } as unknown as Agent const ctx = { jobs: { list: () => [], events: { subscribe: () => () => {} } }, effect: () => {}, agents: { get: (id: unknown) => id === 'actor' ? actor : child, list: () => child ? [actor, child] : [actor] }, subagents: { listDescendants: async () => [] }, } as unknown as Context const host = makeSafetyHost(ctx, actor) assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe') }) test('safe inspection requires observable idle descendants, empty inboxes, and terminal non-orphan jobs', async () => { const actor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const child = { id: 'child', status: 'idle', session: { id: 'child', header: { parentSession: 'actor' } }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent let descendants: unknown[] = [] let live: Agent[] = [actor] let jobs: Array<{ status: string; owner?: string; detail?: string }> = [] const ctx = { jobs: { list: () => jobs, events: { subscribe: () => () => {} } }, effect: () => {}, agents: { get: (id: unknown) => live.find(agent => agent.id === id), list: () => live }, subagents: { listDescendants: async () => descendants }, } as unknown as Context const host = makeSafetyHost(ctx, actor) descendants = [{ kind: 'diagnostic', id: 'child', reason: 'corrupt', parentId: 'actor', depth: 1 }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe') descendants = [{ kind: 'child', id: 'child', activity: 'inactive', hasChildren: false, mode: 'continuable', label: 'child', parentId: 'actor', depth: 1 }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe', 'durably inactive descendant has no live Activation') descendants = [{ kind: 'child', id: 'child', activity: 'running', hasChildren: false, mode: 'continuable', label: 'child', parentId: 'actor', depth: 1 }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'running descriptor without an Agent is unknown') live = [actor, { ...child, status: 'running' } as unknown as Agent] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'waiting', '#54 只有"仍在跑的已知后代"这一唯一阻碍 = 等待,不是收口未知') live = [actor, { ...child, inbox: { nextTurn: [{}], nextStep: [] } } as unknown as Agent] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'waiting') live = [actor, child] jobs = [{ status: 'running' }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe', 'unowned jobs do not belong to the Role tree') jobs = [{ status: 'stopping', owner: 'actor' }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe') jobs = [{ status: 'completed', owner: 'actor' }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe') jobs = [{ status: 'failed', owner: 'actor', detail: 'work may be orphaned after teardown' }] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe') }) test('safe inspection keeps failing closed when a non-waitable member of the closure is busy', async () => { // #54 r001-F1:只有 `kind: 'child'` 的 durable 后代才可算"等待并行子代理"; // 其余 busy 成员(会话自身、tree/observed 补齐的 live 后代)保持 fail-closed。 const actor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const neverInDescendants = { id: 'absent', status: 'running', session: { id: 'absent', header: { parentSession: 'actor' } }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent let live: Agent[] = [actor, neverInDescendants] const ctx = { jobs: { list: () => [], events: { subscribe: () => () => {} } }, effect: () => {}, agents: { get: (id: unknown) => live.find(agent => agent.id === id), list: () => live }, subagents: { listDescendants: async () => [] }, } as unknown as Context const host = makeSafetyHost(ctx, actor) assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'busy live descendant outside the durable descriptor list is not a waitable parallel subagent') live = [{ ...actor, status: 'running' } as unknown as Agent, neverInDescendants] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'the inspected Session itself is never waitable') }) test('orphan evidence follows its exact nested Session across descriptor removal without tainting a new Session', async () => { const actor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const branch = { id: 'branch-old', status: 'idle', session: { id: 'branch-old', header: { parentSession: 'actor' } }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const leaf = { id: 'leaf-old', status: 'idle', session: { id: 'leaf-old', header: { parentSession: 'branch-old' } }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent const fresh = { id: 'fresh', status: 'idle', session: { id: 'fresh', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: async () => {} } as unknown as Agent let descendants: unknown[] = [ { kind: 'child', id: 'branch-old', activity: 'running', hasChildren: true, mode: 'continuable', label: 'branch', parentId: 'actor', depth: 1 }, { kind: 'child', id: 'leaf-old', activity: 'inactive', hasChildren: false, mode: 'continuable', label: 'leaf', parentId: 'branch-old', depth: 2 }, ] let branchLive = true type SettledEvent = { type: 'settled'; job: { owner?: string; detail?: string }; cause: string } let done: ((event: SettledEvent) => void) | undefined const ctx = { jobs: { list: () => [], events: { subscribe: (_filter: unknown, listener: typeof done) => { done = listener; return () => {} } } }, effect: () => {}, agents: { get: (id: unknown) => id === 'actor' ? actor : id === 'branch-old' && branchLive ? branch : id === 'fresh' ? fresh : undefined, list: () => branchLive ? [actor, branch, fresh] : [actor, fresh], }, subagents: { listDescendants: async (id: unknown) => id === 'actor' ? descendants : [] }, } as unknown as Context const host = makeSafetyHost(ctx, actor) assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe') branchLive = false done?.({ type: 'settled', job: { owner: String(leaf.id), detail: 'cancel threw during teardown; work may be orphaned: cleanup failed' }, cause: 'teardown' }) descendants = [] assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'known ancestry survives an unavailable middle Agent and descriptor removal') assert.equal(inspectionStatus(await host.safeToInspect('fresh')), 'safe') }) test('safe inspection waits exact Agent, rejects job tail and retains cold/orphan evidence', async () => { const idle = Promise.withResolvers() let live = true let jobs: Array<{ status: string; owner?: string; detail?: string }> = [] type SettledEvent = { type: 'settled'; job: { owner?: string; detail?: string }; cause: string } let done: ((event: SettledEvent) => void) | undefined let dispose: (() => void) | undefined let unsubscribed = false const actor = { id: 'actor', status: 'idle', session: { id: 'actor', header: {} }, inbox: { nextTurn: [], nextStep: [] }, whenIdle: () => idle.promise } as unknown as Agent const ctx = { get: () => { throw new Error('required services must use direct Context properties') }, jobs: { list: () => jobs, events: { subscribe: (_filter: unknown, listener: typeof done) => { done = listener; return () => { unsubscribed = true; done = undefined } } } }, effect: (factory: () => () => void) => { dispose = factory() }, agents: { get: () => live ? actor : undefined, list: () => live ? [actor] : [] }, subagents: { listDescendants: async () => [] }, } as unknown as Context const host = makeSafetyHost(ctx, actor) host.participants.observeTurnEnd('actor') let settled = false const checking = host.safeToInspect('actor').then(result => { settled = true; return result }) await Promise.resolve() assert.equal(settled, false, 'public idle does not prove maintenance/driver quiescence') jobs = [{ status: 'stopping', owner: 'actor' }] idle.resolve() assert.equal(inspectionStatus(await checking), 'unsafe') jobs = [] live = false assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe', 'recorded exact Agent survives cold release') done?.({ type: 'settled', job: { owner: String(actor.id), detail: 'cancel threw during teardown; work may be orphaned: boom' }, cause: 'teardown' }) assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'removing job snapshots cannot erase orphan evidence') dispose?.() assert.equal(unsubscribed, true) assert.equal(done, undefined) live = true assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'safe', 'disposal clears old orphan evidence') live = false assert.equal(inspectionStatus(await host.safeToInspect('actor')), 'unsafe', 'disposal releases retained Agent references') })