Compare commits
4 Commits
c6afd7ccb8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae4b21e245 | ||
|
|
0f0f698fb4 | ||
|
|
043e9e71c5 | ||
|
|
5c5942ae21 |
@@ -74,7 +74,8 @@ If the first visible line is not one of these statuses, the output is invalid; d
|
|||||||
- **DONE** — Legacy alias for **TASK_DONE**. Prefer **TASK_DONE** for new turns
|
- **DONE** — Legacy alias for **TASK_DONE**. Prefer **TASK_DONE** for new turns
|
||||||
- **DONE_WITH_CONCERNS** — Changes required: at least one unresolved P0-P2 finding. List each finding with its severity and the exact fix. This is not an approval
|
- **DONE_WITH_CONCERNS** — Changes required: at least one unresolved P0-P2 finding. List each finding with its severity and the exact fix. This is not an approval
|
||||||
- **BLOCKED** — Cannot proceed without user decision
|
- **BLOCKED** — Cannot proceed without user decision
|
||||||
- **NEEDS_CONTEXT** — Missing information from user
|
- **NEEDS_CONTEXT** — Missing information that only the user can provide. This ends the task and hands it to the user, so never use it to ask the owner for anything
|
||||||
|
- To get test output, evidence, or a fix from the owner, use **DONE_WITH_CONCERNS** and name exactly what the owner must provide; that sends the task back to the owner
|
||||||
|
|
||||||
Do not start with non-status review labels like **APPROVE** or **REVISE**. Use **TASK_DONE** for approval and **DONE_WITH_CONCERNS** for change requests.
|
Do not start with non-status review labels like **APPROVE** or **REVISE**. Use **TASK_DONE** for approval and **DONE_WITH_CONCERNS** for change requests.
|
||||||
|
|
||||||
@@ -87,7 +88,7 @@ Do not start with non-status review labels like **APPROVE** or **REVISE**. Use *
|
|||||||
- Treat `EJCLAW_WORK_DIR` as the canonical verification root for this turn. You may inspect other local paths for context, but final review findings must be re-checked against `EJCLAW_WORK_DIR`
|
- Treat `EJCLAW_WORK_DIR` as the canonical verification root for this turn. You may inspect other local paths for context, but final review findings must be re-checked against `EJCLAW_WORK_DIR`
|
||||||
- Do not use a different clone, canonical repo path, or cached session path as the sole basis for `BLOCKED`, `DONE_WITH_CONCERNS`, or change requests. If another path disagrees with `EJCLAW_WORK_DIR`, prefer `EJCLAW_WORK_DIR` and explicitly call out the mismatch
|
- Do not use a different clone, canonical repo path, or cached session path as the sole basis for `BLOCKED`, `DONE_WITH_CONCERNS`, or change requests. If another path disagrees with `EJCLAW_WORK_DIR`, prefer `EJCLAW_WORK_DIR` and explicitly call out the mismatch
|
||||||
- When test/typecheck/build/lint evidence is needed, prefer the dedicated verification path (`run_verification`) over assuming the reviewer workspace should execute the full project locally
|
- When test/typecheck/build/lint evidence is needed, prefer the dedicated verification path (`run_verification`) over assuming the reviewer workspace should execute the full project locally
|
||||||
- If direct execution is unavailable, request `run_verification` or owner-provided evidence. Do not present static analysis as completed verification
|
- If direct execution is unavailable, request `run_verification` or owner-provided evidence (via DONE_WITH_CONCERNS). Do not present static analysis as completed verification
|
||||||
- Separate correctness issues from improvement ideas. If something is only a better alternative, label it P3 instead of blocking the owner unnecessarily
|
- Separate correctness issues from improvement ideas. If something is only a better alternative, label it P3 instead of blocking the owner unnecessarily
|
||||||
- Stagnation: **Spinning** (same error 3+), **Oscillation** (alternating approaches), **Diminishing returns** (shrinking improvement), **No progress** (discussion without change) — name the pattern and report: **Status**, **Attempted**, **Recommendation**
|
- Stagnation: **Spinning** (same error 3+), **Oscillation** (alternating approaches), **Diminishing returns** (shrinking improvement), **No progress** (discussion without change) — name the pattern and report: **Status**, **Attempted**, **Recommendation**
|
||||||
- Implementation, commits, and pushes require agreement from both sides. Either can veto
|
- Implementation, commits, and pushes require agreement from both sides. Either can veto
|
||||||
|
|||||||
@@ -25,6 +25,15 @@ Therefore:
|
|||||||
- If something genuinely cannot complete within one turn, do not pretend a notification is coming. Finish with a concrete status and explicitly ask the user to send a follow-up message to continue. For recurring polling of CI/scheduled work, use the `schedule_task` / `watch_ci` tools, which DO re-invoke you.
|
- If something genuinely cannot complete within one turn, do not pretend a notification is coming. Finish with a concrete status and explicitly ask the user to send a follow-up message to continue. For recurring polling of CI/scheduled work, use the `schedule_task` / `watch_ci` tools, which DO re-invoke you.
|
||||||
- Never leave an intermediate "I'll wait … I'll be notified" planning sentence as your final answer.
|
- Never leave an intermediate "I'll wait … I'll be notified" planning sentence as your final answer.
|
||||||
|
|
||||||
|
### Wait on a PID, not on `pgrep -f`
|
||||||
|
|
||||||
|
A wait loop like `while pgrep -f "pytest evals"; do sleep 10; done` matches its own shell, whose command line contains the same text. It never sees the job exit and runs until its timeout (2026-11-11: an eval finished at 16:47 but the loop only ended at 16:53, and every later wait lost minutes the same way).
|
||||||
|
|
||||||
|
- Save the PID when you start the job: `nohup <cmd> > "$HOME/.tmp/job.log" 2>&1 & echo $! > "$HOME/.tmp/job.pid"`
|
||||||
|
- Wait on that PID: `pid=$(cat "$HOME/.tmp/job.pid"); while kill -0 "$pid" 2>/dev/null; do sleep 10; done` (in the same shell, `wait "$pid"` is enough)
|
||||||
|
- If you can only match by name, use a pattern that cannot match itself: `pgrep -f "[p]ytest evals"`. This only works if the plain text (`pytest evals`) appears nowhere else in that same command, so do not launch and wait in one command this way
|
||||||
|
- When the loop ends, check the log tail or exit status to make sure the job finished and the loop did not just hit its timeout
|
||||||
|
|
||||||
## Media attachments
|
## Media attachments
|
||||||
|
|
||||||
When a locally generated image, screenshot, video, audio, or document should appear in Discord, include a `MEDIA:` directive on its own line with an absolute local path:
|
When a locally generated image, screenshot, video, audio, or document should appear in Discord, include a `MEDIA:` directive on its own line with an absolute local path:
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ Your output is sent directly to the Discord group.
|
|||||||
- Prefer reading the current workspace before making assumptions
|
- Prefer reading the current workspace before making assumptions
|
||||||
- Modify only what is needed for the task
|
- Modify only what is needed for the task
|
||||||
- Verify changes when you can instead of claiming they should work
|
- Verify changes when you can instead of claiming they should work
|
||||||
|
- When waiting for a long job, save its PID at launch and poll with `kill -0 "$pid"`. Do not poll with `pgrep -f "<text>"` from a shell whose own command line contains that text: it matches itself and only exits at its timeout. If you must match by name, use `pgrep -f "[p]ytest evals"`
|
||||||
- For CI/status/watch requests that require future follow-up, schedule `watch_ci`
|
- For CI/status/watch requests that require future follow-up, schedule `watch_ci`
|
||||||
- Do not use generic recurring task registration from Codex
|
- Do not use generic recurring task registration from Codex
|
||||||
- If the user wants a reminder or other non-CI recurring task, tell them to ask Claude/클코 to schedule it
|
- If the user wants a reminder or other non-CI recurring task, tell them to ask Claude/클코 to schedule it
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { execFile } from 'child_process';
|
import { execFile } from 'child_process';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { pathToFileURL } from 'url';
|
import { fileURLToPath, pathToFileURL } from 'url';
|
||||||
export { computeVerificationSnapshotId } from '../../../shared/verification-snapshot.js';
|
export { computeVerificationSnapshotId } from '../../../shared/verification-snapshot.js';
|
||||||
|
|
||||||
export const VERIFICATION_PROFILES = [
|
export const VERIFICATION_PROFILES = [
|
||||||
@@ -130,17 +130,19 @@ export async function runVerificationRequestDirect(
|
|||||||
repoRoot: string,
|
repoRoot: string,
|
||||||
request: VerificationRequest,
|
request: VerificationRequest,
|
||||||
): Promise<VerificationResponse> {
|
): Promise<VerificationResponse> {
|
||||||
const helperPath = path.join(
|
// The helper ships with the EJClaw install, not with the repo under review
|
||||||
repoRoot,
|
// (src/ and dist/ both sit three levels below the install root).
|
||||||
'shared',
|
const helperPath = fileURLToPath(
|
||||||
'verification-request-runner.js',
|
new URL('../../../shared/verification-request-runner.js', import.meta.url),
|
||||||
);
|
);
|
||||||
const helperEnv = buildVerificationHelperEnv();
|
const helperEnv = buildVerificationHelperEnv();
|
||||||
const { stdout, stderr } = await execFileCapture(
|
const { stdout, stderr } = await execFileCapture(
|
||||||
'bun',
|
'bun',
|
||||||
[helperPath, repoRoot, JSON.stringify(request)],
|
[helperPath, repoRoot, JSON.stringify(request)],
|
||||||
{
|
{
|
||||||
cwd: repoRoot,
|
// Not repoRoot: EJClaw's config loader reads `.env` from the cwd, and the
|
||||||
|
// repo under review may have its own `.env`. Commands still run in repoRoot.
|
||||||
|
cwd: path.dirname(helperPath),
|
||||||
env: helperEnv,
|
env: helperEnv,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
import path from 'path';
|
|
||||||
import { pathToFileURL } from 'url';
|
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const [repoDir, requestJson] = process.argv.slice(2);
|
const [repoDir, requestJson] = process.argv.slice(2);
|
||||||
|
|
||||||
@@ -10,8 +7,11 @@ async function main() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const verificationModuleUrl = pathToFileURL(
|
// Load the verifier from the EJClaw install this helper ships with; repoDir
|
||||||
path.join(repoDir, 'src', 'verification.ts'),
|
// is only the workspace being verified and need not be an EJClaw checkout.
|
||||||
|
const verificationModuleUrl = new URL(
|
||||||
|
'../src/verification.ts',
|
||||||
|
import.meta.url,
|
||||||
).href;
|
).href;
|
||||||
const verificationModule = await import(verificationModuleUrl);
|
const verificationModule = await import(verificationModuleUrl);
|
||||||
const request = JSON.parse(requestJson);
|
const request = JSON.parse(requestJson);
|
||||||
|
|||||||
@@ -62,6 +62,12 @@ export interface AgentOutput {
|
|||||||
};
|
};
|
||||||
/** Tool calls of the run, reported with the terminal output (Claude runner). */
|
/** Tool calls of the run, reported with the terminal output (Claude runner). */
|
||||||
toolUsage?: import('./review-skip.js').AgentToolUsage;
|
toolUsage?: import('./review-skip.js').AgentToolUsage;
|
||||||
|
/**
|
||||||
|
* Host notice emitted after the paired task state changed (e.g. escalated to
|
||||||
|
* the user). Sent as a separate message even after the turn's final, which
|
||||||
|
* would otherwise drop it.
|
||||||
|
*/
|
||||||
|
postCompletionNotice?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readRoomSkillOverridesForRunner(
|
function readRoomSkillOverridesForRunner(
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ const loginShouldRejectRef = vi.hoisted(() => ({ value: false }));
|
|||||||
vi.mock('discord.js', () => {
|
vi.mock('discord.js', () => {
|
||||||
const Events = {
|
const Events = {
|
||||||
MessageCreate: 'messageCreate',
|
MessageCreate: 'messageCreate',
|
||||||
|
MessageUpdate: 'messageUpdate',
|
||||||
ClientReady: 'ready',
|
ClientReady: 'ready',
|
||||||
Error: 'error',
|
Error: 'error',
|
||||||
};
|
};
|
||||||
@@ -231,6 +232,25 @@ async function triggerMessage(message: any) {
|
|||||||
for (const h of handlers) await h(message);
|
for (const h of handlers) await h(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function triggerMessageUpdate(oldMessage: any, newMessage: any) {
|
||||||
|
const handlers = currentClient().eventHandlers.get('messageUpdate') || [];
|
||||||
|
for (const h of handlers) await h(oldMessage, newMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEditPair(
|
||||||
|
before: string,
|
||||||
|
after: string,
|
||||||
|
overrides: Parameters<typeof createMessage>[0] = {},
|
||||||
|
) {
|
||||||
|
const editedAt = new Date('2024-01-01T00:05:00.000Z');
|
||||||
|
const oldMessage = { ...createMessage({ ...overrides, content: before }) };
|
||||||
|
const newMessage = {
|
||||||
|
...createMessage({ ...overrides, content: after }),
|
||||||
|
editedAt,
|
||||||
|
};
|
||||||
|
return { oldMessage, newMessage, editedAt };
|
||||||
|
}
|
||||||
|
|
||||||
// --- Tests ---
|
// --- Tests ---
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -1309,3 +1329,161 @@ describe('channel properties', () => {
|
|||||||
expect(metadata.get('dc:222')?.name).toBe('second-chat');
|
expect(metadata.get('dc:222')?.name).toBe('second-chat');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Message edits ---
|
||||||
|
|
||||||
|
describe('message edit handling', () => {
|
||||||
|
it('delivers a human edit as a new message with the original and edited text', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const { oldMessage, newMessage, editedAt } = createEditPair(
|
||||||
|
'오늘 날씨 알려줘',
|
||||||
|
'내일 날씨 알려줘',
|
||||||
|
{ messageId: 'msg_042', memberDisplayName: '승한' },
|
||||||
|
);
|
||||||
|
await triggerMessageUpdate(oldMessage, newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).toHaveBeenCalledTimes(1);
|
||||||
|
expect(opts.onMessage).toHaveBeenCalledWith('dc:1234567890123456', {
|
||||||
|
id: `msg_042:edit:${editedAt.getTime()}`,
|
||||||
|
chat_jid: 'dc:1234567890123456',
|
||||||
|
sender: '55512345',
|
||||||
|
sender_name: '승한',
|
||||||
|
content:
|
||||||
|
'[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: 오늘 날씨 알려줘\n수정: 내일 날씨 알려줘',
|
||||||
|
timestamp: editedAt.toISOString(),
|
||||||
|
is_from_me: false,
|
||||||
|
is_bot_message: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives each successive edit of one message its own id', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const first = createEditPair('a', 'b');
|
||||||
|
await triggerMessageUpdate(first.oldMessage, first.newMessage);
|
||||||
|
const second = createEditPair('b', 'c');
|
||||||
|
second.newMessage.editedAt = new Date('2024-01-01T00:06:00.000Z');
|
||||||
|
await triggerMessageUpdate(second.oldMessage, second.newMessage);
|
||||||
|
|
||||||
|
const ids = vi.mocked(opts.onMessage).mock.calls.map(([, msg]) => msg.id);
|
||||||
|
expect(ids).toHaveLength(2);
|
||||||
|
expect(new Set(ids).size).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores updates whose text did not change (link preview / embed)', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const { oldMessage, newMessage } = createEditPair(
|
||||||
|
'https://example.com',
|
||||||
|
'https://example.com',
|
||||||
|
);
|
||||||
|
await triggerMessageUpdate(oldMessage, newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores an embed being generated for a link (edit time unchanged)', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
// Unfurl: Discord adds the embed but leaves edited_timestamp null.
|
||||||
|
const oldMessage = {
|
||||||
|
...createMessage({ content: '이거 봐 https://example.com' }),
|
||||||
|
editedAt: null,
|
||||||
|
embeds: [],
|
||||||
|
};
|
||||||
|
const newMessage = {
|
||||||
|
...createMessage({ content: '이거 봐 https://example.com' }),
|
||||||
|
editedAt: null,
|
||||||
|
embeds: [{ url: 'https://example.com', title: 'Example' }],
|
||||||
|
};
|
||||||
|
await triggerMessageUpdate(oldMessage, newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores "Remove Embeds" even on a message that was edited before', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
// SUPPRESS_EMBEDS keeps the earlier edited_timestamp. The cached old text
|
||||||
|
// is deliberately different so only the edit-time check can reject it.
|
||||||
|
const editedAt = new Date('2024-01-01T00:05:00.000Z');
|
||||||
|
const oldMessage = {
|
||||||
|
...createMessage({ content: '수정 전 https://example.com' }),
|
||||||
|
editedAt: new Date(editedAt),
|
||||||
|
embeds: [{ url: 'https://example.com' }],
|
||||||
|
};
|
||||||
|
const newMessage = {
|
||||||
|
...createMessage({ content: '수정 후 https://example.com' }),
|
||||||
|
editedAt: new Date(editedAt),
|
||||||
|
embeds: [],
|
||||||
|
flags: { has: (flag: number) => flag === 1 << 2 },
|
||||||
|
};
|
||||||
|
await triggerMessageUpdate(oldMessage, newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores edits by bots, including its own messages', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const own = createEditPair('진행 중', '완료', {
|
||||||
|
authorId: '999888777',
|
||||||
|
isBot: true,
|
||||||
|
});
|
||||||
|
await triggerMessageUpdate(own.oldMessage, own.newMessage);
|
||||||
|
hasReviewerLeaseMock.mockReturnValue(true);
|
||||||
|
const other = createEditPair('a', 'b', { authorId: '111', isBot: true });
|
||||||
|
await triggerMessageUpdate(other.oldMessage, other.newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores uncached (partial) messages and unregistered channels', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel('test-token', opts);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const partial = createEditPair('a', 'b');
|
||||||
|
await triggerMessageUpdate(
|
||||||
|
{ ...partial.oldMessage, partial: true, content: null },
|
||||||
|
partial.newMessage,
|
||||||
|
);
|
||||||
|
const unregistered = createEditPair('a', 'b', { channelId: '999' });
|
||||||
|
await triggerMessageUpdate(
|
||||||
|
unregistered.oldMessage,
|
||||||
|
unregistered.newMessage,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not deliver edits on outbound-only bots', async () => {
|
||||||
|
const opts = createTestOpts();
|
||||||
|
const channel = new DiscordChannel(
|
||||||
|
'test-token',
|
||||||
|
opts,
|
||||||
|
undefined,
|
||||||
|
'discord-review',
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
await channel.connect();
|
||||||
|
|
||||||
|
const { oldMessage, newMessage } = createEditPair('a', 'b');
|
||||||
|
await triggerMessageUpdate(oldMessage, newMessage);
|
||||||
|
|
||||||
|
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
GatewayIntentBits,
|
GatewayIntentBits,
|
||||||
Message,
|
Message,
|
||||||
MessageFlags,
|
MessageFlags,
|
||||||
|
PartialMessage,
|
||||||
TextChannel,
|
TextChannel,
|
||||||
} from 'discord.js';
|
} from 'discord.js';
|
||||||
|
|
||||||
@@ -170,6 +171,16 @@ export interface DiscordChannelOpts {
|
|||||||
roomBindings: () => Record<string, RegisteredGroup>;
|
roomBindings: () => Record<string, RegisteredGroup>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An edited message is stored as a new message (own id, new seq) so it is
|
||||||
|
// processed exactly like a freshly sent one; the prefix tells the agent it
|
||||||
|
// replaces an earlier message rather than being a new request.
|
||||||
|
export function formatEditedMessageContent(
|
||||||
|
before: string,
|
||||||
|
after: string,
|
||||||
|
): string {
|
||||||
|
return `[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: ${before || '(내용 없음)'}\n수정: ${after}`;
|
||||||
|
}
|
||||||
|
|
||||||
function finishDiscordOutboundText(cleanText: string): string {
|
function finishDiscordOutboundText(cleanText: string): string {
|
||||||
const cleaned = cleanText
|
const cleaned = cleanText
|
||||||
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
||||||
@@ -237,6 +248,10 @@ export class DiscordChannel implements Channel {
|
|||||||
await this.handleMessageCreate(message);
|
await this.handleMessageCreate(message);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.client.on(Events.MessageUpdate, async (oldMessage, newMessage) => {
|
||||||
|
await this.handleMessageUpdate(oldMessage, newMessage);
|
||||||
|
});
|
||||||
|
|
||||||
// Handle errors gracefully
|
// Handle errors gracefully
|
||||||
this.client.on(Events.Error, (err) => {
|
this.client.on(Events.Error, (err) => {
|
||||||
logger.error({ err: err.message }, 'Discord client error');
|
logger.error({ err: err.message }, 'Discord client error');
|
||||||
@@ -389,6 +404,60 @@ export class DiscordChannel implements Channel {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async handleMessageUpdate(
|
||||||
|
oldMessage: Message | PartialMessage,
|
||||||
|
newMessage: Message | PartialMessage,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!this.receivesInbound) return;
|
||||||
|
// Partial = not in the cache (e.g. sent before the bot started): the
|
||||||
|
// original text is unknown, so skip it.
|
||||||
|
if (oldMessage.partial || newMessage.partial) return;
|
||||||
|
// Human edits only: own/other bot edits (streaming progress, reviewer bot)
|
||||||
|
// are not user input.
|
||||||
|
if (newMessage.author.bot) return;
|
||||||
|
// Discord sets a new edited_timestamp only when the author edits the
|
||||||
|
// message. Embed/link-preview generation and "Remove Embeds" (the
|
||||||
|
// SUPPRESS_EMBEDS flag) also fire MessageUpdate but leave it unchanged.
|
||||||
|
const editedAt = newMessage.editedAt;
|
||||||
|
if (!editedAt || editedAt.getTime() === oldMessage.editedAt?.getTime()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const before = oldMessage.content;
|
||||||
|
const after = newMessage.content;
|
||||||
|
// Same text = not a text edit.
|
||||||
|
if (before === after) return;
|
||||||
|
|
||||||
|
const chatJid = `dc:${newMessage.channelId}`;
|
||||||
|
const group = this.opts.roomBindings()[chatJid];
|
||||||
|
if (!group) return;
|
||||||
|
if (
|
||||||
|
this.agentTypeFilter &&
|
||||||
|
(group.agentType || 'claude-code') !== this.agentTypeFilter
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const senderName =
|
||||||
|
newMessage.member?.displayName ||
|
||||||
|
newMessage.author.displayName ||
|
||||||
|
newMessage.author.username;
|
||||||
|
this.opts.onMessage(chatJid, {
|
||||||
|
id: `${newMessage.id}:edit:${editedAt.getTime()}`,
|
||||||
|
chat_jid: chatJid,
|
||||||
|
sender: newMessage.author.id,
|
||||||
|
sender_name: senderName,
|
||||||
|
content: formatEditedMessageContent(before, after),
|
||||||
|
timestamp: editedAt.toISOString(),
|
||||||
|
is_from_me: false,
|
||||||
|
is_bot_message: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
{ chatJid, sender: senderName, messageId: newMessage.id },
|
||||||
|
'Discord message edit stored',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async sendMessage(
|
async sendMessage(
|
||||||
jid: string,
|
jid: string,
|
||||||
text: string,
|
text: string,
|
||||||
|
|||||||
@@ -328,6 +328,76 @@ describe('createPairedExecutionLifecycle completion handling', () => {
|
|||||||
'원하시던 .env 위치는 여기에 있습니다.',
|
'원하시던 .env 위치는 여기에 있습니다.',
|
||||||
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
||||||
]);
|
]);
|
||||||
|
expect(outputs.every((o) => o.postCompletionNotice === true)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flags the escalation notice so it is sent after the reviewer final', async () => {
|
||||||
|
const outputs: AgentOutput[] = [];
|
||||||
|
const base = {
|
||||||
|
id: 'paired-task-reviewer-escalated',
|
||||||
|
chat_jid: 'group@test',
|
||||||
|
group_folder: 'test-group',
|
||||||
|
owner_service_id: 'claude',
|
||||||
|
reviewer_service_id: 'codex-main',
|
||||||
|
title: null,
|
||||||
|
source_ref: 'HEAD',
|
||||||
|
plan_notes: null,
|
||||||
|
round_trip_count: 1,
|
||||||
|
review_requested_at: '2026-04-09T00:00:00.000Z',
|
||||||
|
arbiter_requested_at: null,
|
||||||
|
created_at: '2026-04-09T00:00:00.000Z',
|
||||||
|
};
|
||||||
|
vi.mocked(db.getPairedTaskById).mockReturnValue({
|
||||||
|
...base,
|
||||||
|
status: 'completed',
|
||||||
|
arbiter_verdict: 'escalate',
|
||||||
|
completion_reason: 'escalated',
|
||||||
|
updated_at: '2026-04-09T00:00:01.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
const lifecycle = createPairedExecutionLifecycle({
|
||||||
|
pairedExecutionContext: {
|
||||||
|
task: {
|
||||||
|
...base,
|
||||||
|
status: 'in_review',
|
||||||
|
arbiter_verdict: null,
|
||||||
|
completion_reason: null,
|
||||||
|
updated_at: '2026-04-09T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
workspace: null,
|
||||||
|
envOverrides: {},
|
||||||
|
},
|
||||||
|
pairedTurnIdentity: {
|
||||||
|
turnId:
|
||||||
|
'paired-task-reviewer-escalated:2026-04-09T00:00:00.000Z:reviewer-turn',
|
||||||
|
taskId: 'paired-task-reviewer-escalated',
|
||||||
|
taskUpdatedAt: '2026-04-09T00:00:00.000Z',
|
||||||
|
intentKind: 'reviewer-turn',
|
||||||
|
role: 'reviewer',
|
||||||
|
},
|
||||||
|
completedRole: 'reviewer',
|
||||||
|
chatJid: 'group@test',
|
||||||
|
runId: 'run-reviewer-escalated',
|
||||||
|
enqueueMessageCheck: vi.fn(),
|
||||||
|
onOutput: async (output) => {
|
||||||
|
outputs.push(output);
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
});
|
||||||
|
|
||||||
|
lifecycle.recordFinalOutputBeforeDelivery(
|
||||||
|
'NEEDS_CONTEXT\n배포 대상을 알려 주세요.',
|
||||||
|
);
|
||||||
|
lifecycle.markStatus('succeeded');
|
||||||
|
lifecycle.markSawOutput(true);
|
||||||
|
await lifecycle.asyncFinalize();
|
||||||
|
|
||||||
|
expect(outputs).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
result: '<@216851709744513024> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
postCompletionNotice: true,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('releases an owner turn interrupted by a human message without counting an owner failure', async () => {
|
it('releases an owner turn interrupted by a human message without counting an owner failure', async () => {
|
||||||
|
|||||||
@@ -125,19 +125,27 @@ async function notifyPairedCompletionIfNeeded(args: {
|
|||||||
const task = args.task;
|
const task = args.task;
|
||||||
if (!task) return;
|
if (!task) return;
|
||||||
|
|
||||||
const emit = (text: string): Promise<void> | undefined =>
|
const emit = (
|
||||||
|
text: string,
|
||||||
|
options?: { postCompletionNotice?: boolean },
|
||||||
|
): Promise<void> | undefined =>
|
||||||
args.onOutput?.({
|
args.onOutput?.({
|
||||||
status: 'success',
|
status: 'success',
|
||||||
result: text,
|
result: text,
|
||||||
output: { visibility: 'public', text },
|
output: { visibility: 'public', text },
|
||||||
phase: 'final',
|
phase: 'final',
|
||||||
|
...(options?.postCompletionNotice ? { postCompletionNotice: true } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Escalation notice fires for any role's completion that escalated to the user.
|
// Escalation notice fires for any role's completion that escalated to the user.
|
||||||
if (task.status === 'completed' && task.completion_reason === 'escalated') {
|
if (task.status === 'completed' && task.completion_reason === 'escalated') {
|
||||||
const sender = getLastHumanMessageSender(args.chatJid);
|
const sender = getLastHumanMessageSender(args.chatJid);
|
||||||
const mention = sender ? `<@${sender}> ` : '';
|
const mention = sender ? `<@${sender}> ` : '';
|
||||||
await emit(`${mention}⚠️ 자동 해결 불가 — 확인이 필요합니다.`);
|
// The turn already published its final and released its attempt, so this
|
||||||
|
// must bypass those guards or the user is left with a silent stop.
|
||||||
|
await emit(`${mention}⚠️ 자동 해결 불가 — 확인이 필요합니다.`, {
|
||||||
|
postCompletionNotice: true,
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,10 +159,11 @@ async function notifyPairedCompletionIfNeeded(args: {
|
|||||||
) {
|
) {
|
||||||
const ownerAnswer = getLatestOwnerAnswer(task.id);
|
const ownerAnswer = getLatestOwnerAnswer(task.id);
|
||||||
if (ownerAnswer) {
|
if (ownerAnswer) {
|
||||||
await emit(ownerAnswer);
|
await emit(ownerAnswer, { postCompletionNotice: true });
|
||||||
}
|
}
|
||||||
await emit(
|
await emit(
|
||||||
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
||||||
|
{ postCompletionNotice: true },
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,6 +105,32 @@ describe('message-runtime-final-delivery', () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it('still delivers a post-completion notice after direct terminal IPC delivery', async () => {
|
||||||
|
const result = await deliverMessageRuntimeFinalText({
|
||||||
|
text: '⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
chatJid: 'chat-1',
|
||||||
|
runId: 'run-1',
|
||||||
|
channel: makeChannel(),
|
||||||
|
group: makeGroup(),
|
||||||
|
startSeq: 10,
|
||||||
|
endSeq: 11,
|
||||||
|
deliveryRole: 'reviewer',
|
||||||
|
deliveryServiceId: 'codex-main',
|
||||||
|
notice: true,
|
||||||
|
hasDirectTerminalDeliveryForRun: vi.fn(() => true),
|
||||||
|
isDuplicateOfLastBotFinal: vi.fn(() => false),
|
||||||
|
openContinuation: vi.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(createProducedWorkItem).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
result_payload: '⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(deliverOpenWorkItem).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('creates and delivers a produced work item with default agent type and attachment roots', async () => {
|
it('creates and delivers a produced work item with default agent type and attachment roots', async () => {
|
||||||
const channel = makeChannel();
|
const channel = makeChannel();
|
||||||
const isDuplicateOfLastBotFinal = vi.fn(() => false);
|
const isDuplicateOfLastBotFinal = vi.fn(() => false);
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ export async function deliverMessageRuntimeFinalText(args: {
|
|||||||
deliveryRole: PairedRoomRole | null;
|
deliveryRole: PairedRoomRole | null;
|
||||||
deliveryServiceId: string | null;
|
deliveryServiceId: string | null;
|
||||||
replaceMessageId?: string | null;
|
replaceMessageId?: string | null;
|
||||||
|
/** Post-completion host notice: sent even when the run's terminal went via IPC. */
|
||||||
|
notice?: boolean;
|
||||||
hasDirectTerminalDeliveryForRun?: (
|
hasDirectTerminalDeliveryForRun?: (
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
runId: string,
|
runId: string,
|
||||||
@@ -32,6 +34,7 @@ export async function deliverMessageRuntimeFinalText(args: {
|
|||||||
openContinuation: (chatJid: string) => void;
|
openContinuation: (chatJid: string) => void;
|
||||||
}): Promise<boolean> {
|
}): Promise<boolean> {
|
||||||
if (
|
if (
|
||||||
|
!args.notice &&
|
||||||
(args.deliveryRole === 'reviewer' || args.deliveryRole === 'arbiter') &&
|
(args.deliveryRole === 'reviewer' || args.deliveryRole === 'arbiter') &&
|
||||||
args.hasDirectTerminalDeliveryForRun?.(
|
args.hasDirectTerminalDeliveryForRun?.(
|
||||||
args.chatJid,
|
args.chatJid,
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ interface CreateExecuteTurnDeps {
|
|||||||
deliveryRole: PairedRoomRole | null;
|
deliveryRole: PairedRoomRole | null;
|
||||||
deliveryServiceId: string | null;
|
deliveryServiceId: string | null;
|
||||||
replaceMessageId?: string | null;
|
replaceMessageId?: string | null;
|
||||||
|
notice?: boolean;
|
||||||
}) => Promise<boolean>;
|
}) => Promise<boolean>;
|
||||||
afterDeliverySuccess?: (args: {
|
afterDeliverySuccess?: (args: {
|
||||||
chatJid: string;
|
chatJid: string;
|
||||||
@@ -247,6 +248,7 @@ export function createExecuteTurn(deps: CreateExecuteTurnDeps): ExecuteTurnFn {
|
|||||||
deliveryRole: resolvedDeliveryRole,
|
deliveryRole: resolvedDeliveryRole,
|
||||||
deliveryServiceId: resolvedDeliveryServiceId,
|
deliveryServiceId: resolvedDeliveryServiceId,
|
||||||
replaceMessageId: options?.replaceMessageId ?? null,
|
replaceMessageId: options?.replaceMessageId ?? null,
|
||||||
|
...(options?.notice ? { notice: true } : {}),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
|
|||||||
@@ -150,6 +150,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
|||||||
deliveryRole,
|
deliveryRole,
|
||||||
deliveryServiceId,
|
deliveryServiceId,
|
||||||
replaceMessageId,
|
replaceMessageId,
|
||||||
|
notice,
|
||||||
}) => {
|
}) => {
|
||||||
return deliverMessageRuntimeFinalText({
|
return deliverMessageRuntimeFinalText({
|
||||||
text,
|
text,
|
||||||
@@ -164,6 +165,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
|||||||
deliveryRole,
|
deliveryRole,
|
||||||
deliveryServiceId,
|
deliveryServiceId,
|
||||||
replaceMessageId,
|
replaceMessageId,
|
||||||
|
notice,
|
||||||
hasDirectTerminalDeliveryForRun:
|
hasDirectTerminalDeliveryForRun:
|
||||||
deps.queue.hasDirectTerminalDeliveryForRun?.bind(deps.queue),
|
deps.queue.hasDirectTerminalDeliveryForRun?.bind(deps.queue),
|
||||||
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
||||||
|
|||||||
@@ -1017,3 +1017,72 @@ describe('MessageTurnController human interruptions', () => {
|
|||||||
expect(deliverFinalText).not.toHaveBeenCalled();
|
expect(deliverFinalText).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('MessageTurnController post-completion notices', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delivers an escalation notice after the reviewer final even though the attempt was released', async () => {
|
||||||
|
const channel = makeChannel();
|
||||||
|
const deliverFinalText = vi.fn().mockResolvedValue(true);
|
||||||
|
let ownsAttempt = true;
|
||||||
|
const controller = new MessageTurnController({
|
||||||
|
chatJid: 'dc:test-room',
|
||||||
|
group: makeGroup(),
|
||||||
|
runId: 'run-reviewer-escalated',
|
||||||
|
channel,
|
||||||
|
idleTimeout: 1_000,
|
||||||
|
failureFinalText: '실패',
|
||||||
|
isClaudeCodeAgent: false,
|
||||||
|
clearSession: vi.fn(),
|
||||||
|
requestClose: vi.fn(),
|
||||||
|
deliverFinalText,
|
||||||
|
canDeliverFinalText: () => ownsAttempt,
|
||||||
|
allowProgressReplayWithoutFinal: false,
|
||||||
|
deliveryRole: 'reviewer',
|
||||||
|
pairedTurnIdentity: makeTurnIdentity(),
|
||||||
|
});
|
||||||
|
|
||||||
|
await controller.start();
|
||||||
|
await controller.handleOutput({
|
||||||
|
status: 'success',
|
||||||
|
phase: 'final',
|
||||||
|
result: 'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||||
|
output: {
|
||||||
|
visibility: 'public',
|
||||||
|
text: 'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Completing the paired execution escalates the task and releases the
|
||||||
|
// attempt before the host emits its notice.
|
||||||
|
ownsAttempt = false;
|
||||||
|
// A late runner output must still be dropped.
|
||||||
|
await controller.handleOutput({
|
||||||
|
status: 'success',
|
||||||
|
phase: 'final',
|
||||||
|
result: '늦은 출력',
|
||||||
|
output: { visibility: 'public', text: '늦은 출력' },
|
||||||
|
});
|
||||||
|
await controller.handleOutput({
|
||||||
|
status: 'success',
|
||||||
|
phase: 'final',
|
||||||
|
result: '<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
output: {
|
||||||
|
visibility: 'public',
|
||||||
|
text: '<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
},
|
||||||
|
postCompletionNotice: true,
|
||||||
|
});
|
||||||
|
await controller.finish('success');
|
||||||
|
|
||||||
|
expect(deliverFinalText.mock.calls.map(([text]) => text)).toEqual([
|
||||||
|
'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||||
|
'<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
]);
|
||||||
|
expect(deliverFinalText).toHaveBeenLastCalledWith(
|
||||||
|
'<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||||
|
{ replaceMessageId: null, notice: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -66,6 +66,8 @@ interface MessageTurnControllerOptions {
|
|||||||
options?: {
|
options?: {
|
||||||
attachments?: OutboundAttachment[];
|
attachments?: OutboundAttachment[];
|
||||||
replaceMessageId?: string | null;
|
replaceMessageId?: string | null;
|
||||||
|
/** A post-completion host notice, not the run's own terminal output. */
|
||||||
|
notice?: boolean;
|
||||||
},
|
},
|
||||||
) => Promise<boolean>;
|
) => Promise<boolean>;
|
||||||
canDeliverFinalText?: () => boolean;
|
canDeliverFinalText?: () => boolean;
|
||||||
@@ -173,6 +175,11 @@ export class MessageTurnController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleOutput(result: AgentOutput): Promise<void> {
|
async handleOutput(result: AgentOutput): Promise<void> {
|
||||||
|
if (result.postCompletionNotice) {
|
||||||
|
await this.deliverPostCompletionNotice(result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.terminalObserved()) {
|
if (this.terminalObserved()) {
|
||||||
this.log.info(
|
this.log.info(
|
||||||
{
|
{
|
||||||
@@ -871,6 +878,28 @@ export class MessageTurnController {
|
|||||||
this.latestProgressTextForFinal = null;
|
this.latestProgressTextForFinal = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Host notices about the paired task's next state (e.g. escalated to the
|
||||||
|
* user) are produced after this run already completed its paired turn
|
||||||
|
* attempt, so the terminal-final and turn-ownership guards would always drop
|
||||||
|
* them. Send them as a fresh message; the progress state is left untouched.
|
||||||
|
*/
|
||||||
|
private async deliverPostCompletionNotice(
|
||||||
|
result: AgentOutput,
|
||||||
|
): Promise<void> {
|
||||||
|
const raw = getAgentOutputText(result);
|
||||||
|
const text = raw ? sanitizeForOutbound(raw) : null;
|
||||||
|
if (!text) return;
|
||||||
|
const delivered = await this.options.deliverFinalText(text, {
|
||||||
|
replaceMessageId: null,
|
||||||
|
notice: true,
|
||||||
|
});
|
||||||
|
this.logOutboundAudit('post-completion-notice', {
|
||||||
|
textLength: text.length,
|
||||||
|
delivered,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async publishFailureFinal(): Promise<void> {
|
private async publishFailureFinal(): Promise<void> {
|
||||||
if (this.terminalObserved()) {
|
if (this.terminalObserved()) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
Reference in New Issue
Block a user