diff --git a/src/claude-usage-limit.ts b/src/claude-usage-limit.ts index 46c3309..b7bf3de 100644 --- a/src/claude-usage-limit.ts +++ b/src/claude-usage-limit.ts @@ -186,7 +186,7 @@ export function parseClaudeLimitResetTime( return candidates.find((date) => date && date.getTime() > nowMs) ?? null; } -function formatResetTime(resetAt: Date, nowMs: number): string { +export function formatResetTime(resetAt: Date, nowMs: number): string { const reset = zonedParts(resetAt.getTime(), TIMEZONE); const today = zonedParts(nowMs, TIMEZONE); const time = `${String(reset.hour).padStart(2, '0')}:${String( diff --git a/src/claude-usage-pause.test.ts b/src/claude-usage-pause.test.ts index 0c4d4de..83d2d1a 100644 --- a/src/claude-usage-pause.test.ts +++ b/src/claude-usage-pause.test.ts @@ -19,6 +19,7 @@ import { consumeRunPausedForClaudeUsage, getActiveClaudeUsagePause, isRoomPausedForClaudeUsage, + isRoomPausedOnlyForAlignment, markRunPausedForClaudeUsage, pauseRoomForClaudeUsage, releaseRoomFromClaudeUsagePause, @@ -124,6 +125,41 @@ describe('Claude usage pause', () => { expect(isRoomPausedForClaudeUsage('room-b')).toBe(true); }); + it('keeps an alignment-only pause out of the account-wide limit until a real limit joins', () => { + pauseRoomForClaudeUsage({ + chatJid: 'room-a', + resumeAt: RESET, + resetKnown: true, + alignment: true, + now: NOW, + }); + + expect(isRoomPausedForClaudeUsage('room-a')).toBe(true); + expect(isRoomPausedOnlyForAlignment('room-a')).toBe(true); + expect(getActiveClaudeUsagePause(NOW.getTime())).toBeNull(); + + pauseRoomForClaudeUsage({ + chatJid: 'room-b', + resumeAt: RESET, + resetKnown: true, + now: NOW, + }); + expect(isRoomPausedOnlyForAlignment('room-a')).toBe(false); + expect(getActiveClaudeUsagePause(NOW.getTime())).toEqual({ + until: RESET, + resetKnown: true, + }); + + pauseRoomForClaudeUsage({ + chatJid: 'room-c', + resumeAt: RESET, + resetKnown: true, + alignment: true, + now: NOW, + }); + expect(isRoomPausedOnlyForAlignment('room-c')).toBe(false); + }); + it('ignores an unreadable stored state', () => { routerState.set(CLAUDE_USAGE_PAUSE_KEY, '{not json'); expect(getActiveClaudeUsagePause(NOW.getTime())).toBeNull(); diff --git a/src/claude-usage-pause.ts b/src/claude-usage-pause.ts index cf5cb4a..79147a1 100644 --- a/src/claude-usage-pause.ts +++ b/src/claude-usage-pause.ts @@ -29,6 +29,12 @@ interface ClaudeUsagePauseState { resetKnown: boolean; /** chatJid -> ISO time the room was paused. */ rooms: Record; + /** + * Set while every room was paused only by the usage-alignment hold + * (usage-alignment-hold.ts), not by a real limit. Such a pause does not + * block other rooms; the hold itself is re-checked on every run. + */ + alignmentOnly?: boolean; } export interface ActiveClaudeUsagePause { @@ -61,6 +67,8 @@ export function pauseRoomForClaudeUsage(args: { chatJid: string; resumeAt: Date; resetKnown: boolean; + /** Paused by the usage-alignment hold, not by a usage limit. */ + alignment?: boolean; now?: Date; }): ActiveClaudeUsagePause { const now = args.now ?? new Date(); @@ -71,6 +79,9 @@ export function pauseRoomForClaudeUsage(args: { until: keepExisting ? state.until : args.resumeAt.toISOString(), resetKnown: keepExisting ? state.resetKnown : args.resetKnown, rooms: { ...(state?.rooms ?? {}) }, + alignmentOnly: + args.alignment === true && + (state === null || state.alignmentOnly === true), }; next.rooms[args.chatJid] ??= now.toISOString(); writeState(next); @@ -86,7 +97,7 @@ export function getActiveClaudeUsagePause( nowMs: number = Date.now(), ): ActiveClaudeUsagePause | null { const state = readState(); - if (!state) return null; + if (!state || state.alignmentOnly) return null; const until = new Date(state.until); return until.getTime() > nowMs ? { until, resetKnown: state.resetKnown } @@ -97,6 +108,12 @@ export function isRoomPausedForClaudeUsage(chatJid: string): boolean { return Boolean(readState()?.rooms[chatJid]); } +/** True when the room is paused and no usage limit is involved. */ +export function isRoomPausedOnlyForAlignment(chatJid: string): boolean { + const state = readState(); + return Boolean(state?.alignmentOnly && state.rooms[chatJid]); +} + /** Drop a room from the pause (the user stopped its work). */ export function releaseRoomFromClaudeUsagePause(chatJid: string): boolean { const state = readState(); diff --git a/src/db/router-state.ts b/src/db/router-state.ts index b40e51b..3fd1260 100644 --- a/src/db/router-state.ts +++ b/src/db/router-state.ts @@ -41,6 +41,8 @@ const SUPPORTED_ROUTER_STATE_KEYS = new Set([ 'last_agent_seq', // claude-usage-pause.ts 'claude_usage_pause', + // usage-alignment-hold.ts + 'usage_alignment_hold_until', ]); export const PAIRED_SESSION_TASK_KEY_PREFIX = 'paired_session_task:'; const SUPPORTED_ROUTER_STATE_KEY_PREFIXES = [PAIRED_SESSION_TASK_KEY_PREFIX]; diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index 3c890fe..4b32afd 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -226,6 +226,7 @@ import * as serviceRouting from './service-routing.js'; import * as tokenRefresh from './token-refresh.js'; import * as claudeOauthToken from './claude-oauth-token.js'; import { consumeRunPausedForClaudeUsage } from './claude-usage-pause.js'; +import * as usageAlignmentHold from './usage-alignment-hold.js'; import type { RegisteredGroup } from './types.js'; function makeGroup(): RegisteredGroup { @@ -2761,6 +2762,7 @@ describe('runAgentForGroup Claude failure recovery', () => { until: string; resetKnown: boolean; rooms: Record; + alignmentOnly?: boolean; } | null; beforeEach(() => { @@ -3242,6 +3244,63 @@ describe('runAgentForGroup Claude failure recovery', () => { expect(consumeRunPausedForClaudeUsage('run-after-usage-reset')).toBe(false); }); + it('pauses a Claude turn without running it during the usage alignment hold', async () => { + const outputs: string[] = []; + const until = new Date(Date.now() + 60 * 60_000); + vi.mocked(usageAlignmentHold.getUsageAlignmentHold).mockReturnValue({ + until, + }); + + const result = await runAgentForGroup(makeDeps(), { + group: makeGroup(), + prompt: 'hello', + chatJid: 'group@test', + runId: 'run-during-alignment-hold', + onOutput: async (output) => { + const text = + output.output && 'text' in output.output + ? output.output.text + : output.result; + if (typeof text === 'string') outputs.push(text); + }, + }); + + expect(result).toBe('success'); + expect(agentRunner.runAgentProcess).not.toHaveBeenCalled(); + expect(outputs).toEqual([ + expect.stringMatching(/사용량 초기화 시각.*보류합니다/), + ]); + const pause = readUsagePause(); + expect(pause?.until).toBe(until.toISOString()); + expect(pause?.alignmentOnly).toBe(true); + expect(Object.keys(pause?.rooms ?? {})).toEqual(['group@test']); + expect(consumeRunPausedForClaudeUsage('run-during-alignment-hold')).toBe( + true, + ); + }); + + it('runs a Claude turn during the alignment hold in a room with an urgent bypass', async () => { + const until = new Date(Date.now() + 60 * 60_000); + vi.mocked(usageAlignmentHold.getUsageAlignmentHold).mockReturnValue({ + until, + }); + usageAlignmentHold.grantUsageAlignmentBypass('bypass@test', until); + vi.mocked(agentRunner.runAgentProcess).mockResolvedValueOnce({ + status: 'success', + result: 'done', + }); + + await runAgentForGroup(makeDeps(), { + group: makeGroup(), + prompt: 'hello', + chatJid: 'bypass@test', + runId: 'run-alignment-bypass', + }); + + expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); + expect(readUsagePause()).toBeNull(); + }); + it('closes the task, clears the session and posts a notice on a safeguards refusal', async () => { const outputs: string[] = []; const refusal = diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index 3dfe107..109eea1 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -10,6 +10,7 @@ import { executeMessageAgentAttemptLifecycle } from './message-agent-executor-li import { runMessageAgentAttempt } from './message-agent-executor-attempt-runner.js'; import { formatClaudeUsagePauseMessage, + formatResetTime, isClaudeUsageLimitReason, resolveClaudeUsageResume, type ClaudeUsageResume, @@ -20,6 +21,11 @@ import { pauseRoomForClaudeUsage, } from './claude-usage-pause.js'; import { getPairedTaskById } from './db.js'; +import { + formatUsageAlignmentHoldMessage, + getUsageAlignmentHold, + isUsageAlignmentBypassed, +} from './usage-alignment-hold.js'; import { completePairedTaskWithReason } from './paired-task-status.js'; import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js'; import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js'; @@ -93,6 +99,8 @@ async function pauseRunForClaudeUsage(args: { chatJid: string; runId: string; resume: ClaudeUsageResume; + /** Paused by the usage-alignment hold instead of a usage limit. */ + alignment?: boolean; summary: string; pairedExecutionLifecycle: PauseLifecycle; onOutput?: (output: AgentOutput) => Promise; @@ -101,14 +109,17 @@ async function pauseRunForClaudeUsage(args: { chatJid: args.chatJid, resumeAt: args.resume.resumeAt, resetKnown: args.resume.resetKnown, + alignment: args.alignment, }); markRunPausedForClaudeUsage(args.runId); args.pairedExecutionLifecycle.updateSummary({ outputText: args.summary }); args.pairedExecutionLifecycle.releaseForClaudeUsagePause(); - const notice = formatClaudeUsagePauseMessage({ - resumeAt: pause.until, - resetKnown: pause.resetKnown, - }); + const notice = args.alignment + ? formatUsageAlignmentHoldMessage(formatResetTime(pause.until, Date.now())) + : formatClaudeUsagePauseMessage({ + resumeAt: pause.until, + resetKnown: pause.resetKnown, + }); await args.onOutput?.({ status: 'success', result: null, @@ -132,20 +143,39 @@ async function pauseWhileClaudeUsageLimited(args: { log: { warn: (obj: Record, msg: string) => void }; }): Promise { const pause = getActiveClaudeUsagePause(); - if (!pause) return false; - args.log.warn( - { until: pause.until.toISOString(), role: args.activeRole }, - 'Claude usage limit still in effect; pausing the room without starting a run', - ); + const hold = isUsageAlignmentBypassed(args.chatJid) + ? null + : getUsageAlignmentHold(); + if (!pause && !hold) return false; try { - await pauseRunForClaudeUsage({ - chatJid: args.chatJid, - runId: args.runId, - resume: { resumeAt: pause.until, resetKnown: pause.resetKnown }, - summary: 'Claude usage limit still in effect', - pairedExecutionLifecycle: args.pairedExecutionLifecycle, - onOutput: args.onOutput, - }); + if (pause && (!hold || pause.until >= hold.until)) { + args.log.warn( + { until: pause.until.toISOString(), role: args.activeRole }, + 'Claude usage limit still in effect; pausing the room without starting a run', + ); + await pauseRunForClaudeUsage({ + chatJid: args.chatJid, + runId: args.runId, + resume: { resumeAt: pause.until, resetKnown: pause.resetKnown }, + summary: 'Claude usage limit still in effect', + pairedExecutionLifecycle: args.pairedExecutionLifecycle, + onOutput: args.onOutput, + }); + } else if (hold) { + args.log.warn( + { until: hold.until.toISOString(), role: args.activeRole }, + 'Usage alignment hold in effect; pausing the room without starting a run', + ); + await pauseRunForClaudeUsage({ + chatJid: args.chatJid, + runId: args.runId, + resume: { resumeAt: hold.until, resetKnown: true }, + alignment: true, + summary: 'Usage alignment hold in effect', + pairedExecutionLifecycle: args.pairedExecutionLifecycle, + onOutput: args.onOutput, + }); + } } finally { await args.pairedExecutionLifecycle.asyncFinalize(); } diff --git a/src/message-runtime-group-processing.ts b/src/message-runtime-group-processing.ts index 2a4a61d..1f4d525 100644 --- a/src/message-runtime-group-processing.ts +++ b/src/message-runtime-group-processing.ts @@ -41,7 +41,16 @@ import { stopRoomWorkIfRequested, type RoomStopResult, } from './room-stop.js'; -import { isRoomPausedForClaudeUsage } from './claude-usage-pause.js'; +import { + isRoomPausedForClaudeUsage, + isRoomPausedOnlyForAlignment, + releaseRoomFromClaudeUsagePause, +} from './claude-usage-pause.js'; +import { + getUsageAlignmentHold, + grantUsageAlignmentBypass, + hasUrgentMention, +} from './usage-alignment-hold.js'; import { reopenReviewSkippedTaskForReview } from './review-request-gate.js'; import { createScopedLogger, logger } from './logger.js'; import type { GroupQueue, GroupRunContext } from './group-queue.js'; @@ -274,6 +283,20 @@ async function processMissedMessages( args.failureFinalText, ); + // Urgent bypass of the usage-alignment hold: an @-mention lets this room + // run until the hold ends. + const alignmentHold = getUsageAlignmentHold(); + if (alignmentHold && hasUrgentMention(missedMessages)) { + grantUsageAlignmentBypass(runtime.chatJid, alignmentHold.until); + if (isRoomPausedOnlyForAlignment(runtime.chatJid)) { + releaseRoomFromClaudeUsagePause(runtime.chatJid); + } + runtime.log.info( + { until: alignmentHold.until.toISOString() }, + 'Urgent mention; room bypasses the usage alignment hold', + ); + } + // A stop request still goes through, so the user can drop paused work. if ( isRoomPausedForClaudeUsage(runtime.chatJid) && diff --git a/src/message-runtime.test.ts b/src/message-runtime.test.ts index c231b32..f35b028 100644 --- a/src/message-runtime.test.ts +++ b/src/message-runtime.test.ts @@ -276,6 +276,7 @@ import { resolveBotOnlyPairedFollowUpAction, } from './message-runtime-flow.js'; import * as config from './config.js'; +import * as usageAlignmentHold from './usage-alignment-hold.js'; import { logger } from './logger.js'; import { resetPairedFollowUpScheduleState, @@ -439,6 +440,75 @@ describe('createMessageRuntime', () => { expect(saveState).not.toHaveBeenCalled(); }); + it('lets an @-mention run a room held only by the usage alignment hold', async () => { + const chatJid = 'group@test'; + const group = makeGroup('claude-code'); + const channel = makeChannel(chatJid); + const until = new Date(Date.now() + 60 * 60_000); + let pauseState: string | undefined = JSON.stringify({ + until: until.toISOString(), + resetKnown: true, + rooms: { [chatJid]: new Date().toISOString() }, + alignmentOnly: true, + }); + + vi.mocked(usageAlignmentHold.getUsageAlignmentHold).mockReturnValue({ + until, + }); + vi.mocked(db.getRouterState).mockImplementation((key) => + key === 'claude_usage_pause' ? pauseState : undefined, + ); + vi.mocked(db.setRouterState).mockImplementation((key, value) => { + if (key === 'claude_usage_pause') pauseState = value; + }); + vi.mocked(db.getMessagesSince).mockReturnValue([ + { + id: 'msg-urgent-1', + chat_jid: chatJid, + sender: 'user@test', + sender_name: 'User', + content: '<@1234567890> 급한 건이에요', + timestamp: '2026-10-16T21:00:00.000Z', + is_bot_message: false, + }, + ]); + vi.mocked(agentRunner.runAgentProcess).mockResolvedValue({ + status: 'success', + result: '처리했습니다.', + }); + + const runtime = createMessageRuntime({ + assistantName: 'Andy', + idleTimeout: 1_000, + pollInterval: 1_000, + timezone: 'UTC', + channels: [channel], + queue: { + enqueueMessageCheck: vi.fn(), + registerProcess: vi.fn(), + closeStdin: vi.fn(), + notifyIdle: vi.fn(), + } as any, + getRoomBindings: () => ({ [chatJid]: group }), + getSessions: () => ({}), + getLastTimestamp: () => '', + setLastTimestamp: vi.fn(), + getLastAgentTimestamps: () => ({}), + saveState: vi.fn(), + persistSession: vi.fn(), + clearSession: vi.fn(), + }); + + await runtime.processGroupMessages(chatJid, { + runId: 'run-alignment-urgent', + reason: 'messages', + }); + + expect(usageAlignmentHold.isUsageAlignmentBypassed(chatJid)).toBe(true); + expect(JSON.parse(pauseState ?? 'null')?.rooms).toEqual({}); + expect(agentRunner.runAgentProcess).toHaveBeenCalled(); + }); + it('keeps mentionless substantive bot messages in paired rooms', async () => { const chatJid = 'group@test'; const group = makeGroup('codex'); diff --git a/src/task-scheduler.test.ts b/src/task-scheduler.test.ts index a2b08b2..1b9d87d 100644 --- a/src/task-scheduler.test.ts +++ b/src/task-scheduler.test.ts @@ -134,6 +134,7 @@ import { pauseRoomForClaudeUsage, } from './claude-usage-pause.js'; import { TIMEZONE } from './config.js'; +import * as usageAlignmentHold from './usage-alignment-hold.js'; import * as serviceRouting from './service-routing.js'; import * as tokenRefresh from './token-refresh.js'; import { createTaskStatusTracker } from './task-status-tracker.js'; @@ -381,6 +382,58 @@ describe('task scheduler', () => { expect(enqueueMessageCheck).toHaveBeenCalledTimes(1); }); + it('holds due Claude tasks, not Codex tasks, until the usage alignment hold ends', async () => { + const dueAt = new Date(Date.now() - 60_000).toISOString(); + for (const [id, agentType] of [ + ['task-claude-held', 'claude-code'], + ['task-codex-not-held', 'codex'], + ] as const) { + createTask({ + id, + group_folder: 'shared-group', + chat_jid: 'shared@g.us', + agent_type: agentType, + prompt: id, + schedule_type: 'once', + schedule_value: dueAt, + context_mode: 'isolated', + next_run: dueAt, + status: 'active', + created_at: '2026-02-22T00:00:00.000Z', + }); + } + const enqueueTask = vi.fn(); + const deps = { + serviceAgentType: 'claude-code' as const, + roomBindings: () => ({ + 'shared@g.us': { + name: 'Shared', + folder: 'shared-group', + trigger: '@Andy', + added_at: '2026-02-22T00:00:00.000Z', + }, + }), + getSessions: () => ({}), + queue: { enqueueTask, enqueueMessageCheck: vi.fn() } as any, + onProcess: () => {}, + sendMessage: async () => {}, + }; + + vi.mocked(usageAlignmentHold.getUsageAlignmentHold).mockReturnValueOnce({ + until: new Date(Date.now() + 60 * 60_000), + }); + await runSchedulerTickOnce(deps); + expect(enqueueTask.mock.calls.map((call) => call[1])).toEqual([ + 'task-codex-not-held', + ]); + + enqueueTask.mockClear(); + await runSchedulerTickOnce(deps); + expect(enqueueTask.mock.calls.map((call) => call[1])).toContain( + 'task-claude-held', + ); + }); + it('can execute one scheduler tick without starting the timer loop', async () => { const dueAt = new Date(Date.now() - 60_000).toISOString(); createTask({ diff --git a/src/task-scheduler.ts b/src/task-scheduler.ts index 94d0959..c771882 100644 --- a/src/task-scheduler.ts +++ b/src/task-scheduler.ts @@ -45,6 +45,7 @@ import { writeTaskSnapshotForGroup, } from './task-scheduler-runtime.js'; import { runGithubCiTask } from './task-scheduler-github.js'; +import { getUsageAlignmentHold } from './usage-alignment-hold.js'; import type { SchedulerDependencies, TaskExecutionContext, @@ -460,8 +461,15 @@ export async function runSchedulerTickOnce( } const dueTasks = getDueTasks(); + const alignmentHold = getUsageAlignmentHold(nowMs); if (dueTasks.length > 0) { - logger.info({ count: dueTasks.length }, 'Found due tasks'); + logger.info( + { + count: dueTasks.length, + alignmentHoldUntil: alignmentHold?.until.toISOString(), + }, + 'Found due tasks', + ); } for (const task of dueTasks) { @@ -471,6 +479,21 @@ export async function runSchedulerTickOnce( continue; } + // A Claude task during the usage-alignment hold would open an off-slot + // usage window; leave it due so it runs once the hold ends. + if ( + alignmentHold && + !isGitHubCiTask(currentTask) && + (currentTask.agent_type || deps.serviceAgentType || 'claude-code') === + 'claude-code' + ) { + logger.debug( + { taskId: currentTask.id, until: alignmentHold.until.toISOString() }, + 'Holding a due Claude task until the usage alignment hold ends', + ); + continue; + } + deps.queue.enqueueTask(getTaskQueueJid(currentTask), currentTask.id, () => isGitHubCiTask(currentTask) ? runGithubCiTask(currentTask, deps) diff --git a/src/usage-alignment-hold.test.ts b/src/usage-alignment-hold.test.ts new file mode 100644 index 0000000..c2447e1 --- /dev/null +++ b/src/usage-alignment-hold.test.ts @@ -0,0 +1,107 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { routerState } = vi.hoisted(() => ({ + routerState: new Map(), +})); +vi.mock('./db.js', () => ({ + getRouterState: (key: string) => routerState.get(key), +})); + +import type { NewMessage } from './types.js'; +import { isSupportedRouterStateKey } from './db/router-state.js'; + +// test/vitest-env.ts stubs getUsageAlignmentHold for every other test file. +const { + USAGE_ALIGNMENT_HOLD_UNTIL_KEY, + getUsageAlignmentHold, + grantUsageAlignmentBypass, + hasUrgentMention, + isUsageAlignmentBypassed, +} = await vi.importActual( + './usage-alignment-hold.js', +); + +const kst = (iso: string): number => Date.parse(`${iso}+09:00`); +const holdUntil = (iso: string): string | undefined => + getUsageAlignmentHold(kst(iso))?.until.toISOString(); + +function message(content: string, extra: Partial = {}): NewMessage { + return { + id: 'm1', + chat_jid: 'room@test', + sender: 'u1', + sender_name: 'user', + content, + timestamp: '2026-10-16T00:00:00.000Z', + ...extra, + }; +} + +beforeEach(() => { + routerState.clear(); +}); + +describe('usage alignment hold', () => { + it('uses a router_state key that startup accepts', () => { + expect(isSupportedRouterStateKey(USAGE_ALIGNMENT_HOLD_UNTIL_KEY)).toBe( + true, + ); + }); + + it('holds 04:00-08:00 KST only', () => { + expect(holdUntil('2026-10-16T03:59:59')).toBeUndefined(); + expect(holdUntil('2026-10-16T04:00:00')).toBe('2026-10-15T23:00:00.000Z'); + expect(holdUntil('2026-10-16T07:59:59')).toBe('2026-10-15T23:00:00.000Z'); + expect(holdUntil('2026-10-16T08:00:00')).toBeUndefined(); + expect(holdUntil('2026-10-16T23:30:00')).toBeUndefined(); + }); + + it('extends the hold to a one-off end, then falls back to the daily gap', () => { + routerState.set( + USAGE_ALIGNMENT_HOLD_UNTIL_KEY, + '2026-10-16T13:00:00+09:00', + ); + expect(holdUntil('2026-10-16T05:47:00')).toBe('2026-10-16T04:00:00.000Z'); + expect(holdUntil('2026-10-16T09:00:00')).toBe('2026-10-16T04:00:00.000Z'); + expect(holdUntil('2026-10-16T13:00:00')).toBeUndefined(); + expect(holdUntil('2026-10-17T05:00:00')).toBe('2026-10-16T23:00:00.000Z'); + }); + + it('runs a one-off hold that ends inside the gap on to 08:00', () => { + routerState.set( + USAGE_ALIGNMENT_HOLD_UNTIL_KEY, + '2026-10-17T05:00:00+09:00', + ); + expect(holdUntil('2026-10-17T02:00:00')).toBe('2026-10-16T23:00:00.000Z'); + }); + + it('ignores an unreadable one-off value', () => { + routerState.set(USAGE_ALIGNMENT_HOLD_UNTIL_KEY, 'not a date'); + expect(holdUntil('2026-10-16T10:00:00')).toBeUndefined(); + }); + + it('treats a human @-mention as urgent', () => { + expect(hasUrgentMention([message('<@1234567890> 급해요')])).toBe(true); + expect(hasUrgentMention([message('<@!1234567890> 급해요')])).toBe(true); + expect(hasUrgentMention([message('@claude 지금 봐줘')])).toBe(true); + expect(hasUrgentMention([message('메일은 a@b.com 입니다')])).toBe(false); + expect(hasUrgentMention([message('그냥 질문')])).toBe(false); + expect( + hasUrgentMention([message('<@1> 리뷰', { is_bot_message: true })]), + ).toBe(false); + }); + + it('lets a bypassed room run until the hold ends', () => { + const until = new Date(kst('2026-10-16T13:00:00')); + grantUsageAlignmentBypass('room@test', until); + expect( + isUsageAlignmentBypassed('room@test', kst('2026-10-16T12:59:00')), + ).toBe(true); + expect( + isUsageAlignmentBypassed('other@test', kst('2026-10-16T12:59:00')), + ).toBe(false); + expect( + isUsageAlignmentBypassed('room@test', kst('2026-10-16T13:00:00')), + ).toBe(false); + }); +}); diff --git a/src/usage-alignment-hold.ts b/src/usage-alignment-hold.ts new file mode 100644 index 0000000..1fe113e --- /dev/null +++ b/src/usage-alignment-hold.ts @@ -0,0 +1,96 @@ +/** + * Usage-window alignment hold. + * + * The Claude 5h usage window opens with the first request after the previous + * one closed. The primer (usage-primer.ts) fires at 08/13/18/23 KST so the + * windows run 08-13, 13-18, 18-23 and 23-04. That only works if nothing calls + * Claude between 04:00 and 08:00 KST: a request in that gap opens an off-slot + * window and every later reset of the day drifts. + * + * While a hold is in effect, Claude work pauses (claude-usage-pause.ts keeps + * the messages and resumes the rooms when it ends) and due Claude scheduled + * tasks wait. Holds: + * - daily 04:00-08:00 KST; + * - a one-off hold until the time stored in router_state + * `usage_alignment_hold_until` (ISO). It is ignored once that time passes, + * so the daily gap is the only hold again afterwards. + * + * Urgent bypass: a human message that @-mentions someone lets that room run + * until the hold ends (the user accepts the drift). + */ + +import { getRouterState } from './db.js'; +import type { NewMessage } from './types.js'; + +export const USAGE_ALIGNMENT_HOLD_UNTIL_KEY = 'usage_alignment_hold_until'; + +const GAP_START_HOUR_KST = 4; +const GAP_END_HOUR_KST = 8; +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; + +export interface UsageAlignmentHold { + until: Date; +} + +function dailyGapEnd(nowMs: number): number | null { + const kst = new Date(nowMs + KST_OFFSET_MS); + const hour = kst.getUTCHours(); + if (hour < GAP_START_HOUR_KST || hour >= GAP_END_HOUR_KST) return null; + kst.setUTCHours(GAP_END_HOUR_KST, 0, 0, 0); + return kst.getTime() - KST_OFFSET_MS; +} + +function oneOffHoldEnd(nowMs: number): number | null { + const raw = getRouterState(USAGE_ALIGNMENT_HOLD_UNTIL_KEY); + if (!raw) return null; + const until = Date.parse(raw); + return Number.isFinite(until) && until > nowMs ? until : null; +} + +/** The hold in effect now (the later end when both apply), or null. */ +export function getUsageAlignmentHold( + nowMs: number = Date.now(), +): UsageAlignmentHold | null { + const ends = [dailyGapEnd(nowMs), oneOffHoldEnd(nowMs)].filter( + (end): end is number => end !== null, + ); + if (ends.length === 0) return null; + let until = Math.max(...ends); + // A one-off hold ending inside the daily gap runs on to the gap's end. + until = Math.max(until, dailyGapEnd(until) ?? until); + return { until: new Date(until) }; +} + +const MENTION_PATTERN = /<@!?\d+>|(^|\s)@\S/; + +/** True when a human message @-mentions someone (urgent bypass). */ +export function hasUrgentMention(messages: NewMessage[]): boolean { + return messages.some( + (message) => + !message.is_from_me && + !message.is_bot_message && + MENTION_PATTERN.test(message.content), + ); +} + +// chatJid -> epoch ms the bypass lasts until (the hold end when granted). +const bypassedRooms = new Map(); + +export function grantUsageAlignmentBypass(chatJid: string, until: Date): void { + bypassedRooms.set(chatJid, until.getTime()); +} + +export function isUsageAlignmentBypassed( + chatJid: string, + nowMs: number = Date.now(), +): boolean { + const until = bypassedRooms.get(chatJid); + if (until === undefined) return false; + if (until > nowMs) return true; + bypassedRooms.delete(chatJid); + return false; +} + +export function formatUsageAlignmentHoldMessage(at: string): string { + return `사용량 초기화 시각(08·13·18·23시)을 맞추려고 ${at}까지 이 방의 Claude 작업을 보류합니다. ${at} 이후 자동으로 이어서 진행합니다. 급하면 @태그해서 보내 주시고, 멈추려면 "중단"이라고 보내 주세요.`; +} diff --git a/test/vitest-env.ts b/test/vitest-env.ts index 408433d..b7af302 100644 --- a/test/vitest-env.ts +++ b/test/vitest-env.ts @@ -1,3 +1,5 @@ +import { vi } from 'vitest'; + const CANONICAL_DISCORD_KEYS = new Set([ 'DISCORD_OWNER_BOT_TOKEN', 'DISCORD_REVIEWER_BOT_TOKEN', @@ -11,3 +13,11 @@ for (const key of Object.keys(process.env)) { } } } + +// The usage-alignment hold depends on the wall clock (04:00-08:00 KST) and +// would pause every Claude turn in tests run during that window. Tests that +// cover the hold set it explicitly (or use vi.importActual). +vi.mock('../src/usage-alignment-hold.js', async (importOriginal) => ({ + ...(await importOriginal()), + getUsageAlignmentHold: vi.fn(() => null), +}));