Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
433 changes: 433 additions & 0 deletions docs/design/skill-nudge/skill-nudge.md

Large diffs are not rendered by default.

22 changes: 15 additions & 7 deletions packages/cli/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
NativeLspService,
isBareMode,
isToolEnabled,
type ConfigParameters,
type MCPServerConfig,
} from '@qwen-code/qwen-code-core';
import { extensionsCommand } from '../commands/extensions.js';
Expand Down Expand Up @@ -1170,7 +1171,7 @@ export async function loadCliConfig(

const modelProvidersConfig = settings.modelProviders;

const config = new Config({
const configParams: ConfigParameters = {
sessionId,
sessionData,
embeddingModel: DEFAULT_QWEN_EMBEDDING_MODEL,
Expand Down Expand Up @@ -1220,11 +1221,13 @@ export async function loadCliConfig(
: settings.tools?.discoveryCommand,
toolCallCommand: bareMode ? undefined : settings.tools?.callCommand,
mcpServerCommand: bareMode ? undefined : settings.mcp?.serverCommand,
mcpServers: bareMode ? {} : (() => {
const base = settings.mcpServers || {};
const cliMcpServers = parseMcpConfig(argv.mcpConfig);
return cliMcpServers ? { ...base, ...cliMcpServers } : base;
})(),
mcpServers: bareMode
? {}
: (() => {
const base = settings.mcpServers || {};
const cliMcpServers = parseMcpConfig(argv.mcpConfig);
return cliMcpServers ? { ...base, ...cliMcpServers } : base;
})(),
allowedMcpServers: allowedMcpServers
? Array.from(allowedMcpServers)
: undefined,
Expand Down Expand Up @@ -1297,6 +1300,9 @@ export async function loadCliConfig(
? false
: (settings.memory?.enableManagedAutoMemory ?? true),
enableManagedAutoDream: settings.memory?.enableManagedAutoDream ?? false,
enableAutoSkill: bareMode
? false
: (settings.memory?.enableAutoSkill ?? false),
fastModel: settings.fastModel || undefined,
// Use separated hooks if provided, otherwise fall back to merged hooks
userHooks: bareMode
Expand Down Expand Up @@ -1334,7 +1340,9 @@ export async function loadCliConfig(
: undefined,
}
: undefined,
});
};

const config = new Config(configParams);

if (lspEnabled) {
try {
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/config/settingsSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,16 @@ const SETTINGS_SCHEMA = {
'Enable automatic consolidation (dream) of collected memories.',
showInDialog: false,
},
enableAutoSkill: {
type: 'boolean',
label: 'Enable Auto Skill',
category: 'Memory',
requiresRestart: false,
default: false,
description:
'Enable background review for reusable project skills after tool-heavy sessions.',
showInDialog: false,
},
},
},

Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/nonInteractiveCli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ describe('runNonInteractive', () => {

mockGeminiClient = {

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.

[Critical] TS2353: consumePendingMemoryTaskPromises 在 mock 对象类型中不存在。GeminiClient 新增了此方法(第 762 行),但 mock 类型未包含它,导致 tsc --noEmit 编译失败。

Suggested change
mockGeminiClient = {
consumePendingMemoryTaskPromises: vi.fn().mockReturnValue([]),
recordCompletedToolCall: vi.fn(),

— DeepSeek/deepseek-v4-pro via Qwen Code /review

sendMessageStream: vi.fn(),
consumePendingMemoryTaskPromises: vi.fn().mockReturnValue([]),
recordCompletedToolCall: vi.fn(),
getChatRecordingService: vi.fn(() => ({
initialize: vi.fn(),
recordMessage: vi.fn(),
Expand Down Expand Up @@ -162,6 +164,7 @@ describe('runNonInteractive', () => {
getCronScheduler: vi.fn().mockReturnValue(null),
setModelInvocableCommandsProvider: vi.fn(),
setModelInvocableCommandsExecutor: vi.fn(),
getAutoSkillEnabled: vi.fn().mockReturnValue(false),
getDisabledSlashCommands: vi.fn().mockReturnValue([]),
getBackgroundTaskRegistry: vi.fn().mockReturnValue({
setNotificationCallback: vi.fn(),
Expand Down
23 changes: 23 additions & 0 deletions packages/cli/src/nonInteractiveCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,14 @@ export async function runNonInteractive(
}

adapter.emitToolResult(finalRequestInfo, toolResponse);
config
.getGeminiClient()
.recordCompletedToolCall(
finalRequestInfo.name,
typeof finalRequestInfo.args['file_path'] === 'string'
? finalRequestInfo.args['file_path']
: undefined,
);

if (toolResponse.responseParts) {
toolResponseParts.push(...toolResponse.responseParts);
Expand Down Expand Up @@ -605,6 +613,14 @@ export async function runNonInteractive(
}

adapter.emitToolResult(requestInfo, toolResponse);
config
.getGeminiClient()
.recordCompletedToolCall(
requestInfo.name,
typeof requestInfo.args['file_path'] === 'string'
? requestInfo.args['file_path']
: undefined,
);

if (toolResponse.responseParts) {
itemToolResponseParts.push(...toolResponse.responseParts);
Expand Down Expand Up @@ -723,6 +739,13 @@ export async function runNonInteractive(
await new Promise((r) => setTimeout(r, 100));
}

const memoryTaskPromises = config
.getGeminiClient()
.consumePendingMemoryTaskPromises();
if (memoryTaskPromises.length > 0) {
await Promise.allSettled(memoryTaskPromises);
}

const metrics = uiTelemetryService.getMetrics();
const usage = computeUsageFromMetrics(metrics);
// Get stats for JSON format output
Expand Down
5 changes: 1 addition & 4 deletions packages/cli/src/ui/commands/tasksCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ export const tasksCommand: SlashCommand = {
}

const now = Date.now();
const lines: string[] = [
`Background shells (${entries.length} total)`,
'',
];
const lines: string[] = [`Background shells (${entries.length} total)`, ''];
for (const entry of entries) {
const endTime = entry.endTime ?? now;
const runtime = formatDuration(endTime - entry.startTime, {
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/ui/hooks/useGeminiStream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const MockedGeminiClientClass = vi.hoisted(() =>
this.sendMessageStream = mockSendMessageStream;
this.addHistory = vi.fn();
this.consumePendingMemoryTaskPromises = vi.fn().mockReturnValue([]);
this.recordCompletedToolCall = vi.fn();
this.getChatRecordingService = vi.fn().mockReturnValue({
recordThought: vi.fn(),
initialize: vi.fn(),
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/ui/hooks/useGeminiStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1882,6 +1882,15 @@ export const useGeminiStream = (
(t) => !t.request.isClientInitiated,
);

for (const toolCall of geminiTools) {
geminiClient?.recordCompletedToolCall(

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] geminiTools 遍历中调用 recordCompletedToolCall 时未过滤已取消(cancelled)的工具调用。已取消的工具从未执行任何实际工作,但会计入 toolCallCount,人工降低技能提炼阈值。且 cancelled 的 write_file/edit 也会设置 skillsModifiedInSession = true,即使用户从未实际提交写入。

Suggested change
geminiClient?.recordCompletedToolCall(
for (const toolCall of geminiTools.filter(tc => tc.status !== 'cancelled')) {
geminiClient?.recordCompletedToolCall(
toolCall.request.name,
toolCall.request.args as Record<string, unknown>,
);
}

— DeepSeek/deepseek-v4-pro via Qwen Code /review

toolCall.request.name,
typeof toolCall.request.args['file_path'] === 'string'
? toolCall.request.args['file_path']
: undefined,
);
}

if (geminiTools.length === 0) {
return;
}
Expand Down
13 changes: 11 additions & 2 deletions packages/core/src/agents/runtime/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,9 @@ export class AgentCore {
const toolsList: FunctionDeclaration[] = [];

const excludedFromSubagents = EXCLUDED_TOOLS_FOR_SUBAGENTS;
// When a subagent has an explicit tools list (not wildcard), only the

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] recursionGuardOnly 的注释与实际逻辑矛盾。顶部注释说「When a subagent has an explicit tools list...only the recursive-spawn guard is enforced」,但 else 分支内部却写着「Wildcard tool list...only block recursive spawning」——而这段代码实际执行的是显式工具列表路径。两个注释互相矛盾,会误导未来的维护者。

Suggested change
// When a subagent has an explicit tools list (not wildcard), only the
// Explicit tool list: only block recursive agent spawning.
// Other control-plane tools (cron, task, send_message) are
// allowed since the explicit list already bounds the agent.
const recursionGuardOnly = new Set<string>([ToolNames.AGENT]);

— DeepSeek/deepseek-v4-pro via Qwen Code /review

// recursive-spawn guard (AgentTool) is enforced.
const recursionGuardOnly = new Set<string>([ToolNames.AGENT]);

if (this.toolConfig) {
const asStrings = this.toolConfig.tools.filter(
Expand All @@ -367,13 +370,19 @@ export class AgentCore {
.filter((t) => !(t.name && excludedFromSubagents.has(t.name))),
);
} else {
// Explicit tool list: only prevent recursive agent spawning.
toolsList.push(

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] For subagents with explicit tool lists, the exclusion set was narrowed from EXCLUDED_TOOLS_FOR_SUBAGENTS (blocks AGENT, CRON_CREATE, CRON_LIST, CRON_DELETE, TASK_STOP, SEND_MESSAGE) to just recursionGuardOnly (only AGENT). This means control-plane tools like TASK_STOP and CRON_CREATE could leak to explicitly-configured subagents. While the skill review agent doesn't declare these, this weakens the safety net for future subagent configs.

Consider restoring the full exclusion or documenting the rationale.

— deepseek-v4-pro via Qwen Code /review

...toolRegistry.getFunctionDeclarationsFiltered(
asStrings.filter((name) => !excludedFromSubagents.has(name)),
asStrings.filter((name) => !recursionGuardOnly.has(name)),
),
);
}
toolsList.push(...onlyInlineDecls);
// Also filter inline FunctionDeclaration[] passed directly in toolConfig.
toolsList.push(

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] 内联 FunctionDeclaration[](onlyInlineDecls)仅按 recursionGuardOnly(只含 AGENT)过滤,而显式字符串工具列表按完整的 excludedFromSubagents(含 CRON_CREATE、TASK_STOP、SEND_MESSAGE 等)过滤。如果通过内联方式传入控制面工具,将绕过子 agent 排除过滤器。建议对 onlyInlineDecls 使用相同的 excludedFromSubagents 集合,保持一致性。

— DeepSeek/deepseek-v4-pro via Qwen Code /review

...onlyInlineDecls.filter(
(d) => !(d.name && recursionGuardOnly.has(d.name)),
),
);
} else {
// Inherit all available tools by default when not specified.
toolsList.push(
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,8 @@ export interface ConfigParameters {
enableManagedAutoMemory?: boolean;
/** Enable managed auto-dream consolidation separately from extraction. Defaults to true. */
enableManagedAutoDream?: boolean;
/** Enable automatic project skill review after tool-heavy sessions. Defaults to true. */

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.

[Critical] JSDoc says Defaults to true. but the Config constructor (this.enableAutoSkill = params.enableAutoSkill ?? false), settingsSchema.ts (default: false), and loadCliConfig all default to false. The PR description also says「默认关闭」. The JSDoc is misleading.

Suggested change
/** Enable automatic project skill review after tool-heavy sessions. Defaults to true. */
/** Enable automatic project skill review after tool-heavy sessions. Defaults to false. */
enableAutoSkill?: boolean;

— deepseek-v4-pro via Qwen Code /review

enableAutoSkill?: boolean;
/**
* Lightweight model for background tasks (memory extraction, dream, /btw side questions).
* When set and valid for the current auth type, forked agents use this model instead of
Expand Down Expand Up @@ -675,6 +677,7 @@ export class Config {
private readonly defaultFileEncoding: FileEncodingType | undefined;
private readonly enableManagedAutoMemory: boolean;
private readonly enableManagedAutoDream: boolean;
private readonly enableAutoSkill: boolean;
private fastModel?: string;
private readonly disableAllHooks: boolean;
/** User-level hooks (always loaded regardless of trust) */
Expand Down Expand Up @@ -870,6 +873,7 @@ export class Config {
});
this.enableManagedAutoMemory = params.enableManagedAutoMemory ?? true;
this.enableManagedAutoDream = params.enableManagedAutoDream ?? false;
this.enableAutoSkill = params.enableAutoSkill ?? false;
this.fastModel = params.fastModel || undefined;
this.disableAllHooks = params.disableAllHooks ?? false;
// Store user and project hooks separately for proper source attribution
Expand Down Expand Up @@ -2150,6 +2154,10 @@ export class Config {
return this.enableManagedAutoDream && !this.getBareMode();
}

getAutoSkillEnabled(): boolean {
return this.enableAutoSkill && !this.getBareMode();
}

/**
* Return the MemoryManager instance created for this Config.
* Use this to share background-task state (registry, drainer) with memory
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/core/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ describe('Gemini Client (client.ts)', () => {
getArenaAgentClient: vi.fn().mockReturnValue(null),
getManagedAutoMemoryEnabled: vi.fn().mockReturnValue(true),
getMemoryManager: vi.fn().mockReturnValue(mockMemoryManager),
getAutoSkillEnabled: vi.fn().mockReturnValue(false),
getDisableAllHooks: vi.fn().mockReturnValue(true),
getArenaManager: vi.fn().mockReturnValue(null),
getMessageBus: vi.fn().mockReturnValue(undefined),
Expand Down
53 changes: 48 additions & 5 deletions packages/core/src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { LoopDetectionService } from '../services/loopDetectionService.js';

// Tools
import type { RelevantAutoMemoryPromptResult } from '../memory/manager.js';
import { isProjectSkillPath } from '../skills/skill-paths.js';
import { ToolNames } from '../tools/tool-names.js';

// Telemetry
Expand Down Expand Up @@ -128,6 +129,8 @@ const EMPTY_RELEVANT_AUTO_MEMORY_RESULT: RelevantAutoMemoryPromptResult = {
export class GeminiClient {
private chat?: GeminiChat;
private sessionTurnCount = 0;
private toolCallCount = 0;
private skillsModifiedInSession = false;
private readonly surfacedRelevantAutoMemoryPaths = new Set<string>();

private readonly loopDetector: LoopDetectionService;
Expand Down Expand Up @@ -505,18 +508,47 @@ export class GeminiClient {
private runManagedAutoMemoryBackgroundTasks(
messageType: SendMessageType,
): void {
if (messageType !== SendMessageType.UserQuery) {
return;
}

if (!this.config.getManagedAutoMemoryEnabled()) {
if (
messageType !== SendMessageType.UserQuery &&

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.

[Critical] runManagedAutoMemoryBackgroundTasks gate expanded from UserQuery-only to UserQuery || ToolResult, but the gate change applies to the entire method — not just the autoSkill block. This causes scheduleExtract() and scheduleDream() to fire on every tool result submission, not just on user-initiated turns.

Each call triggers getHistory() (deep clone of entire conversation) and file I/O checks. A session with 20 tool calls now triggers 20 extract+dream attempts instead of 1.

Suggested change
messageType !== SendMessageType.UserQuery &&
private runManagedAutoMemoryBackgroundTasks(
messageType: SendMessageType,
): void {
// autoSkill: can trigger on UserQuery or ToolResult
if (
messageType === SendMessageType.UserQuery ||
messageType === SendMessageType.ToolResult
) {
if (this.config.getAutoSkillEnabled()) {
// ... scheduleSkillReview logic (existing)
}
}
// extract/dream: keep UserQuery-only to preserve existing behavior
if (messageType !== SendMessageType.UserQuery) return;
if (!this.config.getManagedAutoMemoryEnabled()) return;
// ... scheduleExtract, scheduleDream (existing)
}

— deepseek-v4-pro via Qwen Code /review

messageType !== SendMessageType.ToolResult
) {
return;
}

const projectRoot = this.config.getProjectRoot();
const sessionId = this.config.getSessionId();
const history = this.getHistory();
const mgr = this.config.getMemoryManager();
const autoSkillEnabled = this.config.getAutoSkillEnabled();

if (autoSkillEnabled) {
const skillReviewResult = mgr.scheduleSkillReview({
projectRoot,
sessionId,
history,
config: this.config,
toolCallCount: this.toolCallCount,
skillsModified: this.skillsModifiedInSession,
enabled: autoSkillEnabled,
threshold: 20,

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] threshold: 20, maxTurns: 8, timeoutMs: 120_000 are hardcoded literals at this call site, shadowing the named constants that are exported from manager.ts:187 (AUTO_SKILL_THRESHOLD) and skillReviewAgentPlanner.ts:26-27 (DEFAULT_AUTO_SKILL_MAX_TURNS, DEFAULT_AUTO_SKILL_TIMEOUT_MS). A maintainer who tunes AUTO_SKILL_THRESHOLD and runs the test suite (which uses the constant directly) sees green tests but ships a behavior bug because production reads the literal here.

Also enabled: autoSkillEnabled is dead — the call site is already inside if (autoSkillEnabled) { ... } two lines above, so this field is always true at this point.

Fix: Drop the four explicit fields and let scheduleSkillReview use its built-in defaults; or import the constants and pass them by reference. Either way, do not mix.

— claude-opus-4-7 via Qwen Code /review

maxTurns: 8,
timeoutMs: 120_000,
});
if (skillReviewResult.promise) {
this.pendingMemoryTaskPromises.push(
skillReviewResult.promise.then((record) => {
const touched = record.metadata?.['touchedSkillFiles'];
return Array.isArray(touched) ? touched.length : 0;
}),
);
}
}
this.toolCallCount = 0;

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] toolCallCount = 0 and skillsModifiedInSession = false are reset every turn (at the end of runManagedAutoMemoryBackgroundTasks, which fires per UserQuery/ToolResult). The PR description and design doc (docs/design/skill-nudge/skill-nudge.md) explicitly say the counter is session-scoped and only resets at session start. The implementation makes it turn-scoped.

Two observable consequences:

  1. A single 20-tool-call turn fires immediately (matches the threshold, but feels surprising while the user is still in the session).
  2. A multi-turn session totaling 200 tool calls (none ≥ 20 in a single turn) never fires — contrary to the design intent.

Also, skillsModifiedInSession reset semantics: if the user edits a skill file in turn N (the gate at runManagedAutoMemoryBackgroundTasks skips that turn but then resets the flag), then turn N+1 with 20 unrelated tool calls will fire a review even though the user just hand-modified a skill.

Fix: Either (a) move the reset to a real session-end / /clear hook to match the design, or (b) update the design doc to per-turn semantics and rename the field to skillsModifiedThisTurn. Whichever the team picks, pin it in a test.

— claude-opus-4-7 via Qwen Code /review

this.skillsModifiedInSession = false;

if (!this.config.getManagedAutoMemoryEnabled()) {
return;
}

const extractPromise = mgr
.scheduleExtract({
Expand Down Expand Up @@ -573,6 +605,17 @@ export class GeminiClient {
return promises;
}

recordCompletedToolCall(toolName: string, filePath?: string): void {

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.

[Critical] recordCompletedToolCall recognizes only 'write_file'/'edit' and only inspects args.file_path. The sibling partWritesToMemory in manager.ts:195-200,237-248 (used to gate the extract task) recognizes 4 tool names (write_file, edit, replace, create_file) and 3 arg keys (file_path, path, target_file). The two sit ~370 lines apart in the same conceptual subsystem.

Concrete failure: A replace tool call (legacy alias for edit per tool-names.ts) that writes to .qwen/skills/foo/SKILL.md will not flip skillsModifiedInSession. The session's auto-skill agent then runs over a session that just wrote skills — exactly the scenario the flag was designed to suppress. Same for any future tool that uses path or target_file (e.g., MCP file-write servers).

This is also a test-coverage gap: no client.test.ts case asserts that recordCompletedToolCall('write_file', '<projectRoot>/.qwen/skills/foo.md') flips the flag.

Fix: Extract a shared extractWrittenFilePath(toolName, args): string | undefined helper used by both call sites. Use the ToolNames.WRITE_FILE/ToolNames.EDIT constants instead of raw strings (the file already imports ToolNames).

— claude-opus-4-7 via Qwen Code /review

if (
filePath &&
(toolName === 'write_file' || toolName === 'edit') &&
isProjectSkillPath(filePath, this.config.getProjectRoot())
) {
this.skillsModifiedInSession = true;
}
this.toolCallCount += 1;
}

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] toolCallCount increments for all completed tool calls, including read-only operations (list_directory, read_file, grep_search). A simple "read one file and edit one line" task can produce 5-10 tool calls. In practice, the threshold of 20 is reached much sooner than the design doc's intended "tool-heavy session" semantics suggest.

Consider weighting write operations higher, or counting only non-read-only tools.

— deepseek-v4-pro via Qwen Code /review

async *sendMessageStream(
request: PartListUnion,
signal: AbortSignal,
Expand Down
Loading
Loading