Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(maker-core): 改为只按同一调用自身的重复间隔识别脚本突发重复

Dashe6fca5862f81
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index dad47fc750..bf641ec6aa 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -51,12 +51,15 @@ Claude Code 在原有 per-sidechain 回调里检测所有模型;Pi / Codex 在
这仍是有界启发式,不是任意长度循环的证明,也不以没有文件改动作为失败依据。
Codex code mode 下脚本在后台运行,模型同时继续回应;app-server 只逐个上报脚本内部的工具调用,
-不标注调用属于哪段脚本,用量通知与思考 item 也会落在同一段脚本的调用之间,所以不能按“模型回应”
-分组。Codex 的 Guard 改用调用节奏区分:本次调用开始距上一次普通结果到达不足 2 秒
-(`CODEX_SCRIPT_CHAINED_CALL_GAP_MS`,一次模型采样不可能这么快)视为脚本连发,按节奏轮询处理——
-不推进完全相同、窗口、轮转判据,也不取消进行中的复核,只续接完全相同结果的 60 分钟上限;
-模型逐次重复同一调用,每次间隔都有采样时间,照常计数。代价:脚本自身的无界死循环只会被
-60 分钟上限抓到(2026-10-18 脚本点保存后连续截快照等页面更新被误判)。Pi 与 Claude Code 不启用。
+不标注调用属于哪段脚本,用量通知与思考 item 也会落在同一段脚本的调用之间,后台脚本与模型采样
+还会交叠,所以不能按“模型回应”分组,也不能凭全局最近一次结果推断调用归属。Codex 的 Guard 只用
+同一调用(name+input 相同)自己的开始时间判断:距它上一次开始不足 2 秒
+(`CODEX_BURST_REPEAT_GAP_MS`,两次模型回应之间必有数秒采样)是一阵突发重复,不推进完全相同、
+窗口、轮转判据,不算参与判定(因此不会取消进行中的复核),只续接完全相同结果的 60 分钟上限;
+写入或命令照常打断长只读窗口,其余调用走原有判据。模型逐次重复同一调用,每次间隔都有采样时间,
+照常计数。判据与其它调用、完成顺序、并发无关;每种调用最多记 256 种的开始时间。代价:脚本自身的
+无界快速死循环只会被 60 分钟上限抓到;循环周期含多种调用且脚本每种间隔都小于 2 秒时,不被判为突发
+(2026-10-18 脚本点保存后连续截快照等页面更新被误判)。Pi 与 Claude Code 不启用。
节奏与复核:一次普通调用若距上一次普通调用开始已有至少 30 秒(`sleep` 后再查 CI、
命令内自带等待或慢推理),或其结果距上一次普通结果到达已有至少 30 秒(模型一次发出
diff --git a/packages/maker-core/src/agents/shared/loop-guard.test.ts b/packages/maker-core/src/agents/shared/loop-guard.test.ts
index 5fd256fc2e..1d4fde91e7 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.test.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.test.ts
@@ -788,39 +788,39 @@ describe('ToolLoopGuard pacing and final limits', () => {
expect(captured).not.toBe(input);
});
- // codex P1(#6388):后台脚本调用在模型调用发出之后才完成时,间隔不能按「最新结果」算(为负),
- // 否则间隔很长的真实重复会被误判为脚本连发而永远不计数。
- it('measures the chained gap from results that arrived before the call started', () => {
- const { guard, advance } = clockGuard({ chainedCallGapMs: 2_000 });
+ // 2026-10-18 误报:脚本里同一调用在突发里重复(0.8s 一次)不是模型逐次重复;
+ // 隔着采样时间的重复仍须计数。
+ it('ignores a call repeated in a burst but counts it once sampling gaps separate it', () => {
+ const { guard, advance } = clockGuard({ burstRepeatGapMs: 2_000 });
+ for (let i = 0; i < 30; i++) {
+ expect(feed(guard, `burst-${i}`, 'browser', { action: 'snapshot' }, 'saving').kind).toBe('ok');
+ advance(800);
+ }
let last: ToolLoopGuardVerdict = { kind: 'ok' };
- for (let round = 0; round < 6; round++) {
- guard.onToolUse(`model-${round}`, 'read', { path: 'a' });
- advance(500);
- guard.onToolUse(`script-${round}`, 'read', { path: 'b' });
- advance(500);
- guard.onToolResult(`script-${round}`, 'same');
- advance(500);
- last = guard.onToolResult(`model-${round}`, 'same');
- advance(8_500);
+ for (let i = 0; i < 4; i++) {
+ advance(3_000);
+ last = feed(guard, `model-${i}`, 'browser', { action: 'snapshot' }, 'saving');
}
- expect(last).toMatchObject({ kind: 'hard', reason: 'pingpong', count: 12 });
+ expect(last).toMatchObject({ kind: 'hard', reason: 'consecutive' });
});
- // codex P1(#6388):夹在模型重复调用之间的脚本连发调用不能清零模型的连续计数。
- it('keeps the model streak when different chained script calls run between its repeats', () => {
- const { guard, advance } = clockGuard({ chainedCallGapMs: 2_000 });
+ // codex P1(#6388):判据只看该调用自己的开始时间。后台脚本以其它调用持续快速返回结果,
+ // 不能让隔着采样时间的模型重复被当作突发而永远不计数;完成顺序、并发也不影响。
+ it('counts model repeats even while a script keeps returning unrelated results quickly', () => {
+ const { guard, advance } = clockGuard({ burstRepeatGapMs: 2_000 });
let last: ToolLoopGuardVerdict = { kind: 'ok' };
- for (let round = 0; round < 4; round++) {
+ for (let round = 0; round < 6; round++) {
guard.onToolUse(`model-${round}`, 'read', { path: 'a' });
+ guard.onToolUse(`script-a-${round}`, 'read', { path: 'b' });
advance(500);
- last = guard.onToolResult(`model-${round}`, 'same');
+ guard.onToolResult(`script-a-${round}`, 'same');
+ guard.onToolUse(`script-b-${round}`, 'read', { path: 'b' });
advance(500);
- guard.onToolUse(`script-${round}`, 'read', { path: `other-${round}` });
- advance(500);
- guard.onToolResult(`script-${round}`, `other-${round}`);
+ last = guard.onToolResult(`model-${round}`, 'same');
+ guard.onToolResult(`script-b-${round}`, 'same');
advance(8_500);
}
- expect(last).toMatchObject({ kind: 'hard', reason: 'consecutive', count: 4 });
+ expect(last).toMatchObject({ kind: 'hard', reason: 'pingpong', count: 12 });
});
});
diff --git a/packages/maker-core/src/agents/shared/loop-guard.ts b/packages/maker-core/src/agents/shared/loop-guard.ts
index f96f4f8c0c..aef28d181c 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.ts
@@ -34,6 +34,8 @@ const DEFAULT_ROTATION_DISTINCT_LIMIT = 4;
const STABLE_READ_WINDOW_SIZE = 128;
const STABLE_READ_DISTINCT_LIMIT = 32;
const STABLE_READ_MIN_REPEATS = 4;
+/** 突发重复判据最多记住多少种调用的开始时间。 */
+const MAX_TRACKED_CALL_STARTS = 256;
const READ_ONLY_TOOL_NAMES = new Set(['Read', 'Grep', 'Glob', 'read', 'grep', 'find', 'ls']);
/**
* 节奏判据:本次普通调用距上一次普通调用开始至少这么久,或本次结果距上一次普通结果
@@ -179,8 +181,6 @@ interface PendingToolUse {
name: string;
input: unknown;
startedAt: number;
- /** 本调用发出时,此前最近一次普通结果到达的时刻(没有则 null);连发判据用它算间隔。 */
- precedingFinishedAt: number | null;
}
/**
@@ -217,12 +217,13 @@ export interface ToolLoopGuardOptions {
/** 两次普通调用开始间隔或结果到达间隔达到此值即视为节奏轮询,不计入重复判据。 */
pacedIntervalMs?: number;
/**
- * 连发判据(缺省关闭):本次调用开始距上一次普通调用结果到达不足此值,说明两次调用之间
- * 没有模型采样,是同一段脚本在连着发起。Codex code mode 下脚本在后台运行,app-server 只上报
- * 脚本内部的调用,不标注归属,脚本里点保存后反复截快照等页面更新的有界轮询
- * (2026-10-18 误报)与模型逐次重复同一调用只能靠这个间隔区分。连发结果按节奏轮询处理。
+ * 突发重复判据(缺省关闭):同一调用(name+input 相同)距它上一次开始不足此值,是一阵突发,
+ * 不是一次新的模型回应——两次模型回应之间必有数秒采样。Codex code mode 下脚本在后台运行,
+ * app-server 只上报脚本内部的调用,不标注归属,脚本里点保存后反复截快照等页面更新的有界轮询
+ * (2026-10-18 误报)只能靠这个间隔与模型逐次重复区分。只看该调用自己的开始时间,
+ * 与其它调用、完成顺序、并发无关。突发重复不计入重复判据,也不取消进行中的复核。
*/
- chainedCallGapMs?: number;
+ burstRepeatGapMs?: number;
/** 快速完全相同调用的最终上限(不经复核)。 */
finalConsecutiveLimit?: number;
/** 完全相同结果持续时长的最终上限(不经复核)。 */
@@ -280,7 +281,7 @@ export class ToolLoopGuard {
readonly rotationDistinctLimit: number;
readonly contractConsecutiveLimit: number;
readonly pacedIntervalMs: number;
- readonly chainedCallGapMs: number | undefined;
+ readonly burstRepeatGapMs: number | undefined;
readonly finalConsecutiveLimit: number;
readonly finalStreakMs: number;
private readonly now: () => number;
@@ -309,6 +310,8 @@ export class ToolLoopGuard {
// 第 2/3 层共用状态: 最近 max(windowSize, rotationWindowSize) 个 name+input 指纹
private callWindow: string[] = [];
private stableReadWindow: string[] = [];
+ // 每种调用(name+input)最近一次开始的时间,供突发重复判据使用;有界,淘汰最久未出现的。
+ private lastStartByCall = new Map<string, number>();
// 第 4 层无批次兼容状态: 最近一次契约错误的 name+类别键与连续计数
private lastContractKey: string | null = null;
@@ -330,7 +333,7 @@ export class ToolLoopGuard {
this.rotationDistinctLimit = options.rotationDistinctLimit ?? DEFAULT_ROTATION_DISTINCT_LIMIT;
this.contractConsecutiveLimit = options.contractConsecutiveLimit ?? DEFAULT_CONTRACT_CONSECUTIVE_LIMIT;
this.pacedIntervalMs = options.pacedIntervalMs ?? DEFAULT_PACED_INTERVAL_MS;
- this.chainedCallGapMs = options.chainedCallGapMs;
+ this.burstRepeatGapMs = options.burstRepeatGapMs;
this.finalConsecutiveLimit = options.finalConsecutiveLimit ?? DEFAULT_FINAL_CONSECUTIVE_LIMIT;
this.finalStreakMs = options.finalStreakMs ?? DEFAULT_FINAL_STREAK_MS;
this.now = options.now ?? Date.now;
@@ -344,13 +347,8 @@ export class ToolLoopGuard {
onToolUse(toolUseId: string, toolName: unknown, input: unknown): void {
if (toolUseId.length === 0) return;
if (typeof toolName !== 'string' || toolName.length === 0) return;
- const previous = this.pendingToolUses.get(toolUseId);
- this.pendingToolUses.set(toolUseId, {
- name: toolName,
- input,
- startedAt: previous?.startedAt ?? this.now(),
- precedingFinishedAt: previous ? previous.precedingFinishedAt : this.lastOrdinaryFinishedAt,
- });
+ const startedAt = this.pendingToolUses.get(toolUseId)?.startedAt ?? this.now();
+ this.pendingToolUses.set(toolUseId, { name: toolName, input, startedAt });
}
/** 最近一次结果是否被纳入判定;为 true 且判定为 ok 说明此前的疑似模式已被打破。 */
@@ -413,12 +411,7 @@ export class ToolLoopGuard {
this.lastResultObservedValue = true;
const finishedAt = this.now();
- // 连发:发出时距此前最近一次结果到达不足 chainedCallGapMs,中间没有模型采样的时间。
- // 用发出当时已到达的结果而不是现在最新的:后台调用可能在本调用发出之后才完成,
- // 那样算出的间隔为负,会把间隔很长的真实重复误判为连发。
- const chained = this.chainedCallGapMs !== undefined && toolUse.precedingFinishedAt !== null
- && toolUse.startedAt - toolUse.precedingFinishedAt < this.chainedCallGapMs;
- const paced = chained || (this.lastOrdinaryStartedAt !== null
+ const paced = (this.lastOrdinaryStartedAt !== null
&& toolUse.startedAt - this.lastOrdinaryStartedAt >= this.pacedIntervalMs)
|| (this.lastOrdinaryFinishedAt !== null
&& finishedAt - this.lastOrdinaryFinishedAt >= this.pacedIntervalMs);
@@ -428,24 +421,25 @@ export class ToolLoopGuard {
const fullFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, output);
const callFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, null);
this.lastResultCallFingerprintValue = callFingerprint;
+ const burstRepeat = this.noteCallStart(callFingerprint, toolUse.startedAt);
// 复核放行额度按普通结果计,节奏轮询同样消耗。
const inGrace = this.suspicionGraceResults > 0;
if (inGrace) this.suspicionGraceResults -= 1;
// 节奏轮询只参与完全相同 streak 的续接与最终时长上限,不计入任何疑似判据。
if (paced) {
- // 连发不算参与判定:既不推进也不打破模式,进行中的复核因此不会被它取消。
- if (chained) this.lastResultObservedValue = false;
- if (chained) {
- // 连发既不推进也不打破已有计数:夹在模型重复调用之间的脚本调用不能清零连续段,
- // 只有与当前连续段完全相同时才续接时长上限。
- if (fullFingerprint === this.lastFullFingerprint) this.observeStreak(fullFingerprint, false);
- return this.finalVerdict(toolUse.name);
- }
// 写入或命令照常打断长只读窗口,节奏本身不改变这一点。
if (!READ_ONLY_TOOL_NAMES.has(toolUse.name)) this.stableReadWindow = [];
this.observeStreak(fullFingerprint, false);
return this.finalVerdict(toolUse.name);
}
+ // 突发重复:不计入任何疑似判据,也不算参与判定(不打破模式,进行中的复核不被它取消)。
+ // 只续接完全相同结果的时长上限;写入或命令照常打断长只读窗口,其余调用走原有判据。
+ if (burstRepeat) {
+ this.lastResultObservedValue = false;
+ if (!READ_ONLY_TOOL_NAMES.has(toolUse.name)) this.stableReadWindow = [];
+ if (fullFingerprint === this.lastFullFingerprint) this.observeStreak(fullFingerprint, false);
+ return this.finalVerdict(toolUse.name);
+ }
const suspect = (verdict: ToolLoopGuardVerdict, pattern: Iterable<string>): ToolLoopGuardVerdict => {
if (inGrace) return { kind: 'ok' };
this.lastSuspectPatternValue = new Set(pattern);
@@ -586,6 +580,19 @@ export class ToolLoopGuard {
this.resetPatternState();
}
+ /** 记录该调用本次开始时间,返回它是否是距上一次同一调用不足 burstRepeatGapMs 的突发重复。 */
+ private noteCallStart(callFingerprint: string, startedAt: number): boolean {
+ const previous = this.lastStartByCall.get(callFingerprint);
+ this.lastStartByCall.delete(callFingerprint);
+ this.lastStartByCall.set(callFingerprint, startedAt);
+ if (this.lastStartByCall.size > MAX_TRACKED_CALL_STARTS) {
+ const oldest = this.lastStartByCall.keys().next().value;
+ if (oldest !== undefined) this.lastStartByCall.delete(oldest);
+ }
+ return this.burstRepeatGapMs !== undefined && previous !== undefined
+ && startedAt - previous < this.burstRepeatGapMs;
+ }
+
/** 续接或重开完全相同 streak;counted=false 的节奏结果只续接不计数。 */
private observeStreak(fingerprint: string, counted: boolean): void {
if (fingerprint === this.lastFullFingerprint) {
@@ -633,6 +640,7 @@ export class ToolLoopGuard {
this.suspicionGraceResults = 0;
this.callWindow = [];
this.stableReadWindow = [];
+ this.lastStartByCall.clear();
this.lastContractKey = null;
this.contractStreak = 0;
this.resetContractBatchState();
diff --git a/packages/maker-core/src/agents/shared/tool-loop-review.test.ts b/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
index 5c2967766e..6cd676c7a8 100644
--- a/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
+++ b/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
@@ -134,12 +134,12 @@ describe('ToolLoopMonitor', () => {
expect(t.stops).toEqual([]);
});
- // greptile P1(#6388):连发调用不计数,但也不能当作「模式已打破」取消进行中的复核。
- it('keeps a pending review when a chained script call is ignored', async () => {
+ // greptile P1(#6388):突发重复不计数,但也不能当作「模式已打破」取消进行中的复核。
+ it('keeps a pending review when a burst repeat is ignored', async () => {
vi.useFakeTimers();
const { reviewer, pending } = deferredReviewer();
const stops: HardToolLoopVerdict[] = [];
- const monitor = new ToolLoopMonitor(new ToolLoopGuard({ chainedCallGapMs: 2_000 }), {
+ const monitor = new ToolLoopMonitor(new ToolLoopGuard({ burstRepeatGapMs: 2_000 }), {
reviewer, context: () => ({ sessionId: 's1', agentKind: 'codex', model: 'm1' }),
onReviewedStop: (verdict) => stops.push(verdict), logger,
});
@@ -149,8 +149,8 @@ describe('ToolLoopMonitor', () => {
expect(monitor.onToolResult(`r${i}`, `changed ${i}`).kind).toBe('ok');
}
expect(reviewer).toHaveBeenCalledTimes(1);
- monitor.onToolUse('chained', 'read', { path: 'same.ts' });
- expect(monitor.onToolResult('chained', 'changed again').kind).toBe('ok');
+ monitor.onToolUse('burst', 'read', { path: 'same.ts' });
+ expect(monitor.onToolResult('burst', 'changed again').kind).toBe('ok');
expect(pending[0]?.signal.aborted).toBe(false);
pending[0]?.resolve('stop');
await vi.advanceTimersByTimeAsync(0);
diff --git a/packages/maker-core/src/session.tool-loop.test.ts b/packages/maker-core/src/session.tool-loop.test.ts
index 4b5b6367b1..cff411d8ea 100644
--- a/packages/maker-core/src/session.tool-loop.test.ts
+++ b/packages/maker-core/src/session.tool-loop.test.ts
@@ -311,15 +311,15 @@ describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentK
});
// 2026-10-18 误报:code mode 脚本在后台连着发起调用(点保存后反复截快照等页面更新),
-// app-server 不标注调用属于哪段脚本。连发(无模型采样间隔)不计数,模型逐次重复仍须中断。
-it('does not count Codex calls chained back to back by a script, but still stops a model repeating itself', async () => {
+// app-server 不标注调用属于哪段脚本。同一调用的突发重复(无模型采样间隔)不计数,模型逐次重复仍须中断。
+it('does not count a Codex call repeated in a script burst, but still stops a model repeating itself', async () => {
const t = setup('codex');
const context = { rt: newCodexRuntimeState(), log: { info() {}, warn() {}, error() {}, debug() {} } };
let n = 0;
- const call = async (action: string, text: string) => {
+ const call = async (action: string, text: string, ref?: string) => {
const item = {
type: 'mcpToolCall', id: `exec-${n++}`, server: 'cindy_browser', tool: 'call_tool',
- arguments: { name: 'browser', args: { action } }, status: 'completed',
+ arguments: { name: 'browser', args: { action, ...(ref ? { ref } : {}) } }, status: 'completed',
result: { content: [{ type: 'text', text }] },
};
translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item }, t.queue, context);
@@ -329,7 +329,7 @@ it('does not count Codex calls chained back to back by a script, but still stops
await t.session.send('upload the icons');
await vi.advanceTimersByTimeAsync(3_000);
for (let i = 0; i < 30; i++) {
- await call(i % 7 === 0 ? 'click' : 'snapshot', i % 7 === 0 ? 'clicked' : 'saving');
+ await call(i % 7 === 0 ? 'click' : 'snapshot', i % 7 === 0 ? `clicked e${i}` : 'saving', i % 7 === 0 ? `e${i}` : undefined);
await vi.advanceTimersByTimeAsync(800);
}
expect(t.errors()).toHaveLength(0);
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index e149489731..5b7f605139 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -134,11 +134,10 @@ export const STALL_ABORT_RECOVERY_GRACE_MS = 10_000;
*/
export const MANUAL_ABORT_RECOVERY_GRACE_MS = 15_000;
/**
- * Codex tool calls arriving sooner than this after the previous result cannot have
- * had a model sampling in between (one sampling takes seconds), so they come from a
- * script issuing them in sequence rather than from the model repeating itself.
+ * The same Codex tool call starting again sooner than this cannot be a new model
+ * response (one sampling takes seconds): it is a script repeating it in a burst.
*/
-const CODEX_SCRIPT_CHAINED_CALL_GAP_MS = 2_000;
+const CODEX_BURST_REPEAT_GAP_MS = 2_000;
/** Shared confirmation budget for provider interrupt ACK and send acceptance. */
const GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS = 5_000;
@@ -2337,9 +2336,9 @@ export class Session {
// not enable the retry-count rule without that evidence. Claude also
// disables category-only retries; repetition rules stay active.
contractConsecutiveLimit: Number.POSITIVE_INFINITY,
- // Codex code mode: calls issued back-to-back by one background script
- // carry no ownership marker; see ToolLoopGuardOptions.chainedCallGapMs.
- ...(this.agentKind === 'codex' ? { chainedCallGapMs: CODEX_SCRIPT_CHAINED_CALL_GAP_MS } : {}),
+ // Codex code mode: a background script's calls carry no ownership marker;
+ // see ToolLoopGuardOptions.burstRepeatGapMs.
+ ...(this.agentKind === 'codex' ? { burstRepeatGapMs: CODEX_BURST_REPEAT_GAP_MS } : {}),
}), {
reviewer: this.toolLoopReviewer,
context: () => ({ sessionId: this.id, agentKind: this.agentKind, model: this.handle.model }),