Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions packages/channels/base/src/ChannelBase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5792,6 +5792,27 @@ describe('ChannelBase', () => {
expect(promptText).not.toContain('\u202E');
});

it('truncates long channel memory before injecting it into the prompt', async () => {
const channelMemory = {
readChannelMemory: vi
.fn()
.mockResolvedValue(`${'a'.repeat(11_999)}\u{1f389}TAIL`),
appendChannelMemory: vi.fn().mockResolvedValue({ changed: true }),
clearChannelMemory: vi.fn().mockResolvedValue({ changed: true }),
};
const ch = createChannel({ allowedUsers: ['alice'] }, { channelMemory });

await ch.handleInbound(envelope({ text: 'ship it', senderId: 'alice' }));

const promptText = (bridge.prompt as ReturnType<typeof vi.fn>).mock
.calls[0][1] as string;
expect(promptText).toContain('Channel memory for this chat (truncated):');
expect(promptText).toContain('[Channel memory truncated]');
expect(promptText).toContain('\u{1f389}');
expect(promptText).not.toContain('TAIL');
expect(promptText.length).toBeLessThan(12_500);
});

it('does not read or inject memory again in the same session', async () => {
let reads = 0;
const channelMemory = {
Expand Down Expand Up @@ -10144,6 +10165,48 @@ describe('ChannelBase', () => {
);
});

it('truncates long channel memory before injecting it into a loop prompt', async () => {
const channelMemory = {
readChannelMemory: vi
.fn()
.mockResolvedValue(`${'a'.repeat(13_000)}TAIL`),
appendChannelMemory: vi.fn().mockResolvedValue({ changed: true }),
clearChannelMemory: vi.fn().mockResolvedValue({ changed: true }),
};
const ch = createChannel(
{ instructions: 'Use repo conventions.', allowedUsers: ['alice'] },
{ channelMemory },
);
ch.proactiveSupported = true;

await ch.runLoopPrompt({
id: 'job-1',
channelName: 'test-chan',
target: {
channelName: 'test-chan',
senderId: 'alice',
chatId: 'chat1',
isGroup: false,
},
cwd: '/tmp',
cron: '0 9 * * *',
prompt: 'post summary',
label: 'daily summary',
recurring: true,
enabled: true,
createdBy: 'Alice',
createdAt: '2026-06-30T01:00:00.000Z',
consecutiveFailures: 0,
runCount: 0,
});

const promptText = (bridge.prompt as ReturnType<typeof vi.fn>).mock
.calls[0]![1] as string;
expect(promptText).toContain('Channel memory for this chat (truncated):');
expect(promptText).toContain('[Channel memory truncated]');
expect(promptText).not.toContain('TAIL');
});

it('retries loop channel memory injection after a transient read failure', async () => {
const stderr = vi
.spyOn(process.stderr, 'write')
Expand Down
33 changes: 25 additions & 8 deletions packages/channels/base/src/ChannelBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
sanitizePromptText,
sanitizePromptPath,
sanitizeLogText,
truncateCodePoints,
PROMPT_UNSAFE_INVISIBLES,
} from './sanitize.js';
import type {
Expand Down Expand Up @@ -63,6 +64,7 @@ const CURRENT_MESSAGE_MARKER = '[Current message - respond to this]';
const GROUP_HISTORY_ENTRY_TEXT_LIMIT = 1000;
const GROUP_HISTORY_ENTRY_METADATA_LIMIT = 256;
const LOOP_CANCEL_GRACE_MS = 5000;
const CHANNEL_MEMORY_PROMPT_CHAR_LIMIT = 12_000;
const CHANNEL_MEMORY_CLASSIFIER_MIN_CONFIDENCE = 0.7;
const CHANNEL_MEMORY_CLASSIFIER_TRIGGER_RE =
/(记住|记得|记一下|记忆|忘掉|忘记|清空|清除|删除|保存|remember|memory|forget)/iu;
Expand Down Expand Up @@ -97,6 +99,21 @@ const SENSITIVE_PAYLOAD_KEY_PATTERN = new RegExp(
'i',
);

function formatChannelMemoryPrompt(memoryText: string): string | undefined {
const sanitized = sanitizePromptText(memoryText).trim();
if (!sanitized) {
return undefined;
}
if (sanitized.length <= CHANNEL_MEMORY_PROMPT_CHAR_LIMIT) {
return `Channel memory for this chat:\n${sanitized}`;
}
const truncated = truncateCodePoints(
sanitized,
CHANNEL_MEMORY_PROMPT_CHAR_LIMIT,
).trimEnd();
return `Channel memory for this chat (truncated):\n${truncated}\n[Channel memory truncated]`;
}

export interface ChannelBaseOptions {
router?: SessionRouter;
proxy?: string;
Expand Down Expand Up @@ -696,10 +713,9 @@ export abstract class ChannelBase {
threadId: job.target.threadId,
})
).trim();
if (memoryText) {
context.push(
`Channel memory for this chat:\n${sanitizePromptText(memoryText)}`,
);
const memoryPrompt = formatChannelMemoryPrompt(memoryText);
if (memoryPrompt) {
context.push(memoryPrompt);
}
} catch (error) {
process.stderr.write(
Expand Down Expand Up @@ -3447,10 +3463,11 @@ export abstract class ChannelBase {
this.instructedSessions.delete(sessionId);
}
}
if (memoryText) {
sessionContext.push(
`Channel memory for this chat:\n${sanitizePromptText(memoryText)}`,
);
const memoryPrompt = memoryText
? formatChannelMemoryPrompt(memoryText)
: undefined;
if (memoryPrompt) {
sessionContext.push(memoryPrompt);
}
if (this.config.instructions) {
sessionContext.push(this.config.instructions);
Expand Down
2 changes: 1 addition & 1 deletion packages/channels/base/src/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const PROMPT_UNSAFE_INVISIBLES =
* (e.g. an emoji \ud83c\udf89 = 2 units) leaves a lone surrogate that renders as `\ufffd`.
* `Array.from` iterates by code point, so slicing it never splits a pair.
*/
function truncateCodePoints(str: string, max: number): string {
export function truncateCodePoints(str: string, max: number): string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Array.from(str) iterates by code point, not grapheme cluster. If the 12,000th code point lands mid-ZWJ-sequence (e.g., family emoji 👨‍👩‍👧‍👧), the output will contain a broken partial glyph before the [Channel memory truncated] marker. This is a pre-existing limitation, but the new call site on channel memory (which plausibly contains emoji) is the most likely to hit it. Consider Intl.Segmenter for grapheme-safe splitting when available.

— qwen3.7-max via Qwen Code /review

const cp = Array.from(str);
return cp.length > max ? cp.slice(0, max).join('') : str;
}
Expand Down
9 changes: 7 additions & 2 deletions scripts/tests/qwen-autofix-workflow.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,9 @@ describe('qwen-autofix workflow', () => {
expect(workflow).toContain('trigger_label=${label_is_trigger}');
expect(workflow).toContain('trigger_label=false label=');
expect(workflow).toContain('sender_trusted=${sender_is_trusted}');
expect(workflow).toContain("group: 'qwen-autofix-issue'");
expect(workflow).toContain(
"group: 'qwen-autofix-issue-${{ needs.route.outputs.issue_number || github.run_id }}'",
);
expect(workflow).toContain(
'(.labels // []) | map(.name) as $labels | ($labels | index($ready))',
);
Expand Down Expand Up @@ -361,7 +363,10 @@ describe('qwen-autofix workflow', () => {
expect(routeStep).not.toContain('comment command accepted');
expect(routeStep).not.toContain('address-review command accepted');
expect(routeStep).not.toContain('ROUTE_PR="${ISSUE_NUMBER}"');
expect(routeStep).not.toContain('ROUTE_ISSUE="${ISSUE_NUMBER}"');
expect(routeStep).toContain('ROUTE_ISSUE="${ISSUE_NUMBER}"');
expect(routeStep).toContain(
'issue #${ISSUE_NUMBER} assigned to ${AUTOFIX_BOT} → issue phase',
);
});

it('gates real-time review triggers on bot author, trusted sender, and in-repo PR', () => {
Expand Down
Loading