Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(scheduler): 保留托管目标生命周期并在恢复前检查投递资格

Dashb5d8a29bf9d2
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
index 04c71c6a8d..1aa831252a 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
@@ -407,10 +407,17 @@ describe('MakerScheduleRunner model selection', () => {
// device, with different effort/Fast support. Tier: unit (in-memory host).
// Windows standalone: 14.30s (collection 10.08s, 72 tests 3.85s). Reuses the
// existing file-level imports/fixture; no module resets or new real I/O.
- it.each([undefined, 'studio'])('re-resolves a deleted relocated target at %s', async (agentDeviceId) => {
+ it.each([
+ { agentDeviceId: undefined, target: { status: 'deleted' } },
+ { agentDeviceId: 'studio', target: { status: 'deleted' } },
+ { agentDeviceId: undefined, target: { status: 'archived', source: 'bot' } },
+ { agentDeviceId: undefined, target: { status: 'archived', orcaRole: 'worker' as const } },
+ { agentDeviceId: undefined, target: { status: 'archived', orcaRemoteLead: '{"leadSessionId":"lead"}' } },
+ { agentDeviceId: undefined, target: { status: 'archived', source: 'review' } },
+ ])('preserves persistent replacement routing for an unavailable managed/deleted target: %j', async ({ agentDeviceId, target }) => {
const h = createSessionHarness();
Object.assign(h.session, { agentKind: 'codex', model: 'gpt-5.5' });
- mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'deleted', agentDeviceId: 'relocated' });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ ...target, agentDeviceId: 'relocated' });
const resolveModelSelection = vi.fn(async (choice) => ({ ...choice, effort: 'high' as const }));
const harness = createRunnerHarness(h, null, {
acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
index ebdfaeaf97..5a5965127b 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
@@ -172,6 +172,28 @@ describe('MakerScheduleRunner pre-run hook cwd 解析', () => {
expect(maker.createSession).not.toHaveBeenCalled();
});
+ // PR #6864: source=user schedules can target managed sessions too. The target's
+ // lifecycle, not just the schedule source, must keep archive retirement intact.
+ it.each([
+ { source: 'bot' },
+ { orcaRole: 'worker' },
+ { orcaRemoteLead: '{"leadSessionId":"lead"}' },
+ { source: 'review' },
+ ])('retires an archived managed target before hooks: %j', async (managed) => {
+ const target = { status: 'archived', ...managed };
+ mocks.getSessionRowSnapshot.mockResolvedValue(target);
+ const { runner, maker } = createRunner(vi.fn() as never);
+ const pause = vi.fn();
+ runner.attachScheduler({ pause } as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: 'owner' }), createFireContext()))
+ .resolves.toMatchObject({ skipped: true });
+ expect(pause).toHaveBeenCalledWith('schedule-1', { exemptRunId: 'run-1' });
+ expect(target.status).toBe('archived');
+ expect(mocks.restoreArchivedSessionForSend).not.toHaveBeenCalled();
+ expect(mocks.executePreRunHook).not.toHaveBeenCalled();
+ expect(maker.createSession).not.toHaveBeenCalled();
+ });
+
it('does not run the hook with an unrestored worktree snapshot', async () => {
const target = { status: 'archived', workingDir: '/repo/.cindy-worktrees/task' };
mocks.getSessionRowSnapshot.mockImplementation(async () => ({ ...target }));
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
index 92505a9bf4..c50ef607b4 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
@@ -423,7 +423,12 @@ describe('MakerScheduleRunner send outcome policy', () => {
expect(h.send).not.toHaveBeenCalled();
});
- it.each([false, true])('retires a deleted target and releases an acquired lock (racing=%s)', async (racing) => {
+ it.each([
+ { racing: false, target: { status: 'deleted' } },
+ { racing: true, target: { status: 'deleted' } },
+ { racing: false, target: { status: 'archived', orcaRole: 'worker' } },
+ { racing: true, target: { status: 'archived', orcaRole: 'worker' } },
+ ])('retires an unavailable managed/deleted target and releases its lock: %j', async ({ racing, target }) => {
const order: string[] = [];
const h = createSessionHarness(async () => ({ accepted: true }));
const releaseAgentSwitchLock = vi.fn(() => {
@@ -435,7 +440,7 @@ describe('MakerScheduleRunner send outcome policy', () => {
order.push('notify');
});
mocks.getSessionRowSnapshot.mockResolvedValue({
- status: 'deleted',
+ ...target,
userSendAt: null,
providerId: null,
});
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
index 6ea5a0b1ba..9f113df964 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
@@ -15,7 +15,8 @@ import { SchedulerScriptCapabilityBroker } from '../script-capability-broker';
const sendToSessionMock = vi.hoisted(() => vi.fn());
const restoreArchivedSessionForSend = vi.hoisted(() => vi.fn());
-vi.mock('../../localDb/ipc/sessions', () => ({ restoreArchivedSessionForSend }));
+const getSessionRowSnapshotStrict = vi.hoisted(() => vi.fn());
+vi.mock('../../localDb/ipc/sessions', () => ({ restoreArchivedSessionForSend, getSessionRowSnapshotStrict }));
// ghost pipe 统一入口:缺省回显请求(jira/feishu 用例断言请求形状),
// 单个用例可 mockResolvedValueOnce 覆盖返回(断言 data 解包 / 错误映射)。
const callGhostToolMock = vi.hoisted(() =>
@@ -82,6 +83,7 @@ describe('SchedulerScriptCapabilityBroker', () => {
beforeEach(() => {
sendToSessionMock.mockReset();
restoreArchivedSessionForSend.mockReset();
+ getSessionRowSnapshotStrict.mockReset().mockResolvedValue({ status: 'active', source: 'user' });
callGhostToolMock.mockReset();
callGhostToolMock.mockImplementation(async (request: unknown) => ({ ok: true, result: request }));
registerCallMock.mockReset();
@@ -524,6 +526,38 @@ describe('SchedulerScriptCapabilityBroker', () => {
expect(status).toBe('active');
});
+ // PR #6864: rejected Review input must not reactivate an archived audit task.
+ // Exercise the real broker/policy boundary; previous happy-path mocks missed it.
+ it.each(['active', 'archived'])('rejects a %s Review target without changing its lifecycle', async (status) => {
+ const target = { status, source: 'review' };
+ getSessionRowSnapshotStrict.mockResolvedValue(target);
+ restoreArchivedSessionForSend.mockImplementation(async () => { target.status = 'active'; });
+ sendToSessionMock.mockResolvedValue({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Review input rejected' });
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'sessions.dispatch', params: { target_session_id: 'review', message: 'update' } },
+ new Set(['sessions.dispatch']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ expect(target.status).toBe(status);
+ expect(restoreArchivedSessionForSend).not.toHaveBeenCalled();
+ expect(sendToSessionMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { source: 'bot' },
+ { orcaRole: 'worker' },
+ { orcaRemoteLead: '{"leadSessionId":"lead"}' },
+ ])('leaves an archived managed dispatch target to its service lifecycle: %j', async (managed) => {
+ const target = { status: 'archived', ...managed };
+ getSessionRowSnapshotStrict.mockResolvedValue(target);
+ sendToSessionMock.mockResolvedValue({ ok: false, errorCode: 'ARCHIVED', message: 'Target archived' });
+ await expect(new SchedulerScriptCapabilityBroker().call(
+ { method: 'sessions.dispatch', params: { target_session_id: 'owner', message: 'update' } },
+ new Set(['sessions.dispatch']), { schedule: schedule() },
+ )).rejects.toMatchObject({ code: 'ARCHIVED' });
+ expect(target.status).toBe('archived');
+ expect(restoreArchivedSessionForSend).not.toHaveBeenCalled();
+ });
+
it('dispatches sessions with host-owned create defaults from the schedule', async () => {
sendToSessionMock.mockResolvedValue({
ok: true,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
index bbf0bd640c..9acca95085 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
@@ -119,6 +119,29 @@ describe('ScriptScheduleRunner', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
+ // Same lifecycle boundary as the Agent runner: archived managed owners retain
+ // their previous pause behavior, including remote workers without orcaRole.
+ it.each([
+ { source: 'bot' },
+ { orcaRole: 'worker' },
+ { orcaRemoteLead: '{"leadSessionId":"lead"}' },
+ { source: 'review' },
+ ])('pauses an archived managed script owner before hooks: %j', async (managed) => {
+ const owner = { status: 'archived', ...managed };
+ const db = { select: () => ({ from: () => ({ where: () => ({ limit: async () => [owner] }) }) }) };
+ const pause = vi.fn();
+ const runner = new ScriptScheduleRunner({ broker: { call: vi.fn() }, logger: {},
+ getDb: () => db as never, scheduler: { pause } as never });
+ await expect(runner.fire({ ...schedule(), targetSessionId: 'owner', preRunHook: { command: 'check' } }, {
+ runId: 'run-owner', firedAt: 1, signal: new AbortController().signal,
+ })).resolves.toMatchObject({ skipped: true });
+ expect(pause).toHaveBeenCalledWith('script-schedule', { exemptRunId: 'run-owner' });
+ expect(owner.status).toBe('archived');
+ expect(restoreArchivedSessionForSend).not.toHaveBeenCalled();
+ expect(executePreRunHookMock).not.toHaveBeenCalled();
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
it('does not retire a live owner or treat a database outage as a missing owner', async () => {
const pause = vi.fn();
const limit = vi.fn().mockResolvedValue([{ status: 'active' }]);
diff --git a/apps/desktop/src/main/scheduler-host/restore-target.ts b/apps/desktop/src/main/scheduler-host/restore-target.ts
index cb67e4167f..0d06332d9a 100644
--- a/apps/desktop/src/main/scheduler-host/restore-target.ts
+++ b/apps/desktop/src/main/scheduler-host/restore-target.ts
@@ -8,14 +8,23 @@ import {
} from '../localDb/ipc/sessions';
import { withSessionRouteLock } from '../localDb/sessionRouteLock';
+type ScheduledTargetLifecycle = Pick<SessionRowSnapshot, 'source' | 'orcaRole' | 'orcaRemoteLead'>;
+
+/** Service-owned tasks keep their existing archive/retirement lifecycle. */
+export function isManagedScheduledTarget(target: ScheduledTargetLifecycle): boolean {
+ return target.source === 'bot' || target.source === 'review'
+ || target.orcaRole === 'worker' || !!target.orcaRemoteLead;
+}
+
/** Scheduled input uses the ordinary restore boundary, including its managed-task
* exclusions and multi-device status broadcast. Never archive again after a run. */
export async function restoreScheduledTarget(
sessionId: string,
- target: Pick<SessionRowSnapshot, 'status' | 'workingDir' | 'remoteHostId'>,
+ target: Pick<SessionRowSnapshot, 'status' | 'workingDir' | 'remoteHostId'> & ScheduledTargetLifecycle,
signal?: AbortSignal,
): Promise<void> {
signal?.throwIfAborted();
+ if (isManagedScheduledTarget(target)) return;
const dir = target.workingDir;
const managed = !target.remoteHostId && dir && getManagedWorktreeBasePath(path.resolve(dir).replace(/\\/g, '/'));
if (target.status !== 'archived' && !managed) return;
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index a970f445a1..8d6ec267c9 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -118,7 +118,7 @@ import { backfillSessionMeta } from './runners/_shared';
import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';
import { beginHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInteractionSurface.js';
import { terminalErrorText } from '../im/shared/turnRetryNotice.js';
-import { restoreScheduledTarget } from './restore-target';
+import { isManagedScheduledTarget, restoreScheduledTarget } from './restore-target';
const ALLOWED_EFFORT = new Set<string>([
'minimal',
@@ -809,7 +809,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
// and service-owned Bot lifecycle separate.
if (schedule.source !== 'bot' && schedule.targetSessionId) {
const target = await getSessionRowSnapshot(schedule.targetSessionId);
- if (target?.status === 'deleted' && !schedule.persistentSession) {
+ if (target && !schedule.persistentSession && (target.status === 'deleted'
+ || (target.status === 'archived' && isManagedScheduledTarget(target)))) {
return this.retireHeartbeat(schedule, ctx, target.status);
}
if (target && target.status !== 'deleted') {
@@ -996,7 +997,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
holder.releaseAgentSwitchLock = undefined;
// The user archived again during preparation. Consume this occurrence;
// do not undo that newer action or pause the recurring automation.
- if (row?.status === 'archived' && schedule.source !== 'bot') {
+ if (row?.status === 'archived' && schedule.source !== 'bot' && !isManagedScheduledTarget(row)) {
return { sessionId, skipped: true, resultText: 'Scheduled target archived during preparation' };
}
// 持续任务的目标已删除/丢失时重新绑定;Bot 保留原有服务侧生命周期。
diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
index ea98b40235..38bdc6e87f 100644
--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
@@ -13,7 +13,9 @@ import {
} from '../cindy-brain/index.js';
import { validateFsRelPath } from '../cindy-brain/fsSlot.js';
import { tryGetOrcaCollabService } from '../maker-ipc/register.js';
-import { restoreArchivedSessionForSend } from '../localDb/ipc/sessions';
+import { getSessionRowSnapshotStrict, restoreArchivedSessionForSend } from '../localDb/ipc/sessions';
+import { assertReviewSessionExternalInputAllowed } from '../reviewer/reviewSessionInputPolicy';
+import { isManagedScheduledTarget } from './restore-target';
import type { ScriptCapabilityBroker, ScriptCapabilityCall } from './script-runner';
// model 兜底与 runner 同源(2026-06 曾因多份拷贝不同步导致 UI 显示与实跑模型不一致)
@@ -401,7 +403,12 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
// Bound owners are restored once at fire admission. A later archive must
// not be undone by the same run. Unbound scripts first choose their target here.
if (targetSessionId && !schedule.targetSessionId) {
- await restoreArchivedSessionForSend(targetSessionId);
+ const target = await getSessionRowSnapshotStrict(targetSessionId);
+ // Use the dispatcher's Review policy before any lifecycle mutation.
+ await assertReviewSessionExternalInputAllowed(targetSessionId, () => target?.source ?? null);
+ if (target && !isManagedScheduledTarget(target)) {
+ await restoreArchivedSessionForSend(targetSessionId);
+ }
}
const result = await service.sendToSession({
targetSessionId,
diff --git a/apps/desktop/src/main/scheduler-host/script-runner.ts b/apps/desktop/src/main/scheduler-host/script-runner.ts
index b95296d3fc..66a66ddf99 100644
--- a/apps/desktop/src/main/scheduler-host/script-runner.ts
+++ b/apps/desktop/src/main/scheduler-host/script-runner.ts
@@ -18,7 +18,7 @@ import { sessions } from '../localDb/schema';
import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';
import { capAppend, killProcessTree } from './proc-util';
import type { SchedulerDrizzleDb } from './storage';
-import { restoreScheduledTarget } from './restore-target';
+import { isManagedScheduledTarget, restoreScheduledTarget } from './restore-target';
const PROTOCOL = 'cindy-script/1' as const;
const LEGACY_PROTOCOL = 'xdt-maker-script/1' as const;
@@ -172,9 +172,10 @@ export class ScriptScheduleRunner {
throw new Error('bound script execution requires session storage and scheduler');
}
const [owner] = await this.deps.getDb()
- .select({ status: sessions.status, workingDir: sessions.workingDir, remoteHostId: sessions.remoteHostId }).from(sessions)
+ .select({ status: sessions.status, workingDir: sessions.workingDir, remoteHostId: sessions.remoteHostId,
+ source: sessions.source, orcaRole: sessions.orcaRole, orcaRemoteLead: sessions.orcaRemoteLead }).from(sessions)
.where(eq(sessions.id, schedule.targetSessionId)).limit(1);
- if (!owner || owner.status === 'deleted') {
+ if (!owner || owner.status === 'deleted' || (owner.status === 'archived' && isManagedScheduledTarget(owner))) {
await this.deps.scheduler.pause(schedule.id, { exemptRunId: ctx.runId });
return { sessionId: '', skipped: true,
resultText: `Script stopped: target session ${owner?.status ?? 'missing'}` };
@@ -390,9 +391,9 @@ export class ScriptScheduleRunner {
: result;
writeFrame({ type: 'call_result', id: frame.id, ok: true, result: responseResult });
} catch (error) {
- // Recheck typed owner rejections after preparation. Only deleted/missing
- // owners retire the schedule; archiving and transient dispatch failures
- // leave the automation active for its next occurrence.
+ // Recheck typed owner rejections after preparation. Deleted/missing or
+ // archived managed owners retire the schedule; ordinary archives and
+ // transient dispatch failures keep it active for its next occurrence.
const failure = safeError(error);
if (schedule.targetSessionId && frame.method === 'sessions.dispatch'
&& (!frame.params?.target_session_id || frame.params.target_session_id === schedule.targetSessionId)