aft icon indicating copy to clipboard operation
aft copied to clipboard

Repeat breaker counts internal permission retries as agent calls (two searches escalate as six)

Open chpock opened this issue 1 month ago • 1 comments

Summary

The repeat breaker counts adapter-internal permission_required retries as additional agent tool calls. One external-file search can contribute three observations: ask for the file, ask for its containing external search root, then return the result. Two logical searches can therefore reach count six and trigger:

The turn must end now with no further tool call.

This is independent of the omitted aft_search.pattern bug in #1367: it reproduces with two completely identical logical inputs, where no distinction between patterns is involved. Adding pattern to the repeat identity does not fix this overcount.

Reproduced on the released AFT 0.63.5 executable, not just inferred from source. The observation path remains unconditional on main at 7ca30b526163a62bc0756e49238ab689eb46969f; that main build was inspected, not executed.

Expected versus actual

Expected: one agent-level tool invocation contributes one repetition observation, regardless of the internal authorization exchange needed to execute it. After two identical logical searches, the breaker should not report a sixth agent call or escalate at a six-call threshold. Permission enforcement and capability scope must remain intact.

Actual: the Pi adapter consumes intermediate permission responses and retries internally, while the shared native runner observes every attempt. The model sees two tool invocations; the breaker sees six. It also compares permission-response text with final search-result text and diagnoses misleading “output drift,” even with unchanged source and identical final results.

Minimal reproduction, independent of #1367

Configure a small project root and a separate external directory, each containing:

export const alphaOne = 1;

Keep these fixtures outside AFT's automatically allowed temporary roots (/tmp, /var/tmp, the daemon's TMPDIR, etc.; see v0.63.5 access_policy_temp.rs:53–84). A fixture under an automatically allowed temp root does not exercise permission negotiation.

Use a fresh session, harness: "pi", restrict_to_project_root: false, and no initial outside-access grants. Indexes can be disabled: the bounded external scan is sufficient. Use the ordinary permission-continuation protocol, preserving returned permissions_continuation tokens and adding the next ask's grant token.

Make the following same logical search twice, at least 31 seconds apart, using the same session:

{"pattern":"alphaOne","path":"/outside/index.ts"}

For each logical invocation, the native sequence is:

Attempt Presented grants Response Requested scope
1 0 success: false, code: "permission_required" /outside/index.ts
2 1 success: false, code: "permission_required" /outside (the resolved external root)
3 2 successful search result none

Start the second logical invocation without reusing consumed one-use tokens from the previous invocation, just as the adapter does. During that second invocation, the three rendered repeat ordinals are 4 → 5 → 6. Its final successful result carries:

This is the 6th call with the same arguments in 31s. The call is being repeated
with the same arguments while its output is drifting (for example, because it
includes a timestamp). The turn must end now with no further tool call.

The actual reminder also includes background-task/watch advice. Neither background polling nor changes to the fixture are involved in this reproduction. The 31-second delay satisfies the real breaker's observation-span gate; the proof is explicit request/response counts, not timing performance.

Controls and captured-input replay

These cases were executed with the installed binary and separate session IDs:

Case Logical searches Native attempts Final end-turn instruction
External file, identical inputs 2 6 Yes, final count 6; isolates this issue
External file, different patterns only 2 6 Yes, this issue plus #1367
External file, different patterns and different query 2 6 No; different repeat identities
Internal file, different patterns 2 2 No; no outside-permission exchange
Replay of the two original external-file arguments from #1367 2 6 Yes; counts 4/5/6 and the historical refused-root hash reproduced

A standalone portable reproduction below additionally checks identical internal-file inputs: two logical calls, two native attempts, no end-turn instruction. It asserts the observed 0.63.5 bug as a diagnostic; it is not a passing regression test for a repair.

Source mechanism

1. Permission negotiation is inside one Pi invocation

In the installed @cortexkit/[email protected]/dist/index.js, withOutsidePermissions at 32058–32121 loops on permission_required, combines continuation grants with the next ask's grant, and invokes the native call again. callToolCall uses that wrapper at 32162–32175. The search handler at 38086–38118 calls it once per Pi tool invocation; intermediate permission responses are not separate model tool calls.

The portable reproduction uses that same grant/continuation exchange explicitly, making every native response observable without calling a model.

2. External-file search legitimately checks two scopes

In v0.63.5 semantic_search/mod.rs:896–945:

  • :896–923 validates the exact requested file, initially requiring file permission.
  • :924 resolves the external root.
  • :936–945 separately validates that root, which is not authorized by an exact-file grant.
  • With the file capability continued and the root capability added, the third attempt succeeds.

The two authorization boundaries are not themselves reported as a bug. The defect is treating their internal retries as further agent decisions. approval_not_covered at the second boundary is consistent with a valid file capability that does not cover the root; it need not mean expiry or a transport reconnect.

3. Every attempt is observed, including permission_required

The contract above RepeatObservation, main run_tool_call.rs:628–647 describes one agent call, observed exactly once. for_agent_call:650–685 already excludes native plumbing and preview calls, but not permission-negotiation attempts.

The shared runner constructs the observation before preparation/dispatch and then executes this after obtaining the result, without excluding permission_required:

if let Some(repeat) = repeat {
    repeat.observe(app_ctx, &mut result.text);
}

Permission tokens do not turn these attempts into distinct semantic searches. They should not: adding ephemeral grant IDs to the repeat identity would avoid the symptom by defeating useful repetition detection, rather than counting the logical call correctly.

4. Inflation reaches the existing escalation threshold early

response_finalize.rs:22–72 produces the observed text. The non-worker escalated branch is the explicit instruction to end the turn. Worker-session branches use different wording but still receive the inflated count; their broader runtime behavior was not separately tested here.

Original incident and resolution of #1367's open question

When #1367 was filed, it explicitly left “six observations versus two visible searches” unresolved. The follow-up explains that discrepancy:

2026-11-03T18:25:56.236Z outside-access retry refused reason=approval_not_covered operation=read path_hash=<same-root-hash>
2026-11-03T18:25:56.898Z successful external-file search response

2026-11-03T18:28:20.456Z repeat_breaker fired session=<session> tool=aft_search count=4 span_ms=144405
2026-11-03T18:28:20.600Z outside-access retry refused reason=approval_not_covered operation=read path_hash=<same-root-hash>
2026-11-03T18:28:20.600Z repeat_breaker fired session=<session> tool=aft_search count=5 span_ms=144550
2026-11-03T18:28:21.248Z repeat_breaker fired session=<session> tool=aft_search count=6 span_ms=145198
2026-11-03T18:28:21.249Z successful external-file search response with the end-turn reminder
2026-11-03T18:28:37Z ordinary agent turn completion with unfinished/unverified work

This is a sanitized, shortened extraction: local paths, session IDs and their path hash are replaced; successful-response lines summarize the native log's recorded successful search responses. Counts and timestamps are retained.

Replaying the original file path in an isolated process reproduced the exact historical BLAKE3 refusal hash while the response explicitly asked for the containing external project root. This attributes the intermediate refusal to scope expansion rather than merely proposing a generic retry explanation. That replay used the current read-only source file, not a recovered byte-for-byte historical checkout. The first two historical permission-response bodies were consumed by the adapter and were not recovered from the Pi transcript; the current real-binary replay exposes both scopes directly.

The last tool result's stop instruction survived Magic Context transformation into its retained outgoing-message snapshot. About 16 seconds later, the independent Pi peer ended normally without sending its expected intercom checkpoint. Its coordinating peer received no message to resume from. This is a plausible consequence of the instruction, not proof of the model's internal reason for stopping, and AFT did not forcibly kill the process. The outgoing snapshot is not a raw provider-wire capture. The peer's local name “Worker” did not make it a managed/headless worker session, so the non-worker wording was expected under AFT's detection rules.

Environment and provenance

  • AFT executable, @cortexkit/aft-pi, @cortexkit/aft-bridge: 0.63.5; this was also the latest published release when checked.
  • Linux x64, Node 26.12.1, Pi 1.4.0.
  • Historical requests used the subc daemon. Controlled reproduction uses standalone NDJSON transport for isolation; source inspection establishes the shared native permission/repeat runner, and the historical subc log independently records 4/5/6.
  • The historical daemon was still alive for follow-up identification. SHA-256 of its /proc/<pid>/exe matched both the active ck-aft file and installed platform-package binary: 3070b151a33dfb2730d8ec82b277a53cef97eb97bf8949e3546ad2701b80ec4e.
  • Relevant installed adapter/bridge file modification and change times predated both Pi hosts' startup. This supports the inspected implementation but is not a reproducible source-to-binary build attestation.
  • Fixtures, HOME/XDG paths, cache and sessions were isolated. No live target-session prompts, model replay, code fixes, package installation, debugger attachment or target-project writes were needed.
  • The five-case result set and source explanation received independent read-only review. The reviewer inspected the retained results rather than rerunning them.

Portable executable reproduction

Requires an existing Linux x64 installation of the 0.63.5 bridge and platform packages. Save as repro.mjs and run with Node:

AFT_REPRO_PARENT="$HOME" AFT_NODE_MODULES=/absolute/path/to/node_modules node repro.mjs

The script creates uniquely named fixtures/state under AFT_REPRO_PARENT (which must already exist and lie outside automatically allowed temp roots), sends no model requests and retains no grant tokens in its output. It gives the child a separate TMPDIR so the fixtures do not become automatically approved through an inherited temporary-root setting. It takes a little over 31 seconds. Assertions intentionally recognize the buggy released behavior; a repair should make that positive assertion fail until the diagnostic is converted into an expected-correctness regression test.

Full reproducer, including internal-file control
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { pathToFileURL } from "node:url";

const modules = process.env.AFT_NODE_MODULES;
if (!modules || !path.isAbsolute(modules)) {
  throw new Error("Set AFT_NODE_MODULES to the absolute node_modules directory containing the AFT packages");
}
const { BinaryBridge } = await import(pathToFileURL(path.join(modules, "@cortexkit/aft-bridge/dist/bridge.js")));
const { inlineUserConfigTier } = await import(pathToFileURL(path.join(modules, "@cortexkit/aft-bridge/dist/config-tiers.js")));
const parent = process.env.AFT_REPRO_PARENT;
if (!parent || !path.isAbsolute(parent)) {
  throw new Error("Set AFT_REPRO_PARENT to an existing absolute directory outside AFT's automatically allowed temp roots");
}
const run = await mkdtemp(path.join(parent, "aft-permission-counter-"));
const root = path.join(run, "root");
const outside = path.join(run, "outside");
const home = path.join(run, "home");
for (const directory of [root, outside, home, path.join(run, "native-tmp")]) await mkdir(directory);
for (const directory of [root, outside]) {
  await writeFile(path.join(directory, "index.ts"), "export const alphaOne = 1;\n");
}
const bridge = new BinaryBridge(
  path.join(modules, "@cortexkit/aft-linux-x64/bin/aft"),
  root,
  {
    maxRestarts: 0,
    timeoutMs: 20_000,
    childEnv: {
      HOME: home,
      TMPDIR: path.join(run, "native-tmp"),
      XDG_CONFIG_HOME: path.join(run, "config"),
      XDG_DATA_HOME: path.join(run, "data"),
      XDG_CACHE_HOME: path.join(run, "cache"),
      AFT_CACHE_DIR: path.join(run, "cache"),
    },
  },
  {
    harness: "pi",
    cortexkit_user_config_path: path.join(run, "config", "aft.jsonc"),
    config: inlineUserConfigTier({
      indexes: { trigram: false, semantic: false },
      restrict_to_project_root: false,
    }),
  },
);
const cases = [
  { name: "outside-identical-input", file: path.join(outside, "index.ts") },
  { name: "inside-identical-input", file: path.join(root, "index.ts") },
].map((item) => ({ ...item, session: randomUUID(), logicalCalls: [] }));

async function logicalSearch(item) {
  let grants = [];
  const attempts = [];
  for (let round = 0; round < 8; round++) {
    const response = await bridge.toolCall(item.session, "search", {
      pattern: "alphaOne",
      path: item.file,
      ...(grants.length ? { permissions_granted: grants } : {}),
    });
    const text = response.text ?? "";
    attempts.push({
      success: response.success,
      code: response.code ?? null,
      grantedCount: grants.length,
      askedPaths: (response.asks ?? []).map((ask) => ask.path),
      emittedRepeatCount: Number(text.match(/This is the (\d+)(?:st|nd|rd|th)/)?.[1]) || null,
      endTurn: text.includes("The turn must end now with no further tool call"),
    });
    if (response.code !== "permission_required") {
      assert.equal(response.success, true, JSON.stringify(response));
      item.logicalCalls.push(attempts);
      return;
    }
    assert.ok(response.asks?.length);
    assert.ok(response.asks.every((ask) => ask.kind === "external_directory" && ask.grant_id?.startsWith("outside:")));
    grants = (response.permissions_continuation ?? []).filter((id) => typeof id === "string" && id.startsWith("outside:"));
    for (const ask of response.asks) {
      if (!grants.includes(ask.grant_id)) grants.push(ask.grant_id);
    }
  }
  throw new Error("Permission negotiation did not settle within eight attempts");
}

try {
  for (const item of cases) await logicalSearch(item);
  await delay(31_000);
  for (const item of cases) await logicalSearch(item);
  const [external, internal] = cases;
  assert.deepEqual(external.logicalCalls.map((call) => call.length), [3, 3]);
  assert.deepEqual(external.logicalCalls[1].map((attempt) => attempt.emittedRepeatCount), [4, 5, 6]);
  assert.equal(external.logicalCalls[1].at(-1).endTurn, true);
  assert.deepEqual(internal.logicalCalls.map((call) => call.length), [1, 1]);
  assert.equal(internal.logicalCalls[1].at(-1).endTurn, false);
  console.log(JSON.stringify(cases.map(({ name, logicalCalls }) => ({
    name,
    logicalSearches: logicalCalls.length,
    nativeAttempts: logicalCalls.reduce((n, call) => n + call.length, 0),
    attempts: logicalCalls,
  })), null, 2));
} finally {
  await bridge.shutdown();
}

emittedRepeatCount: null means no reminder was rendered at that attempt, not that the daemon had zero observations. The first invocation completes before the span gate, so its initial three observations do not yet render reminders. The same script was syntax-checked and executed against the installed release, with the external positive case and internal negative control passing its diagnostic assertions.

Suggested correction and regression coverage

Count logical agent invocations, not intermediate host authorization exchanges. The repair must preserve access enforcement and valid repeated-call detection; do not make grant IDs part of the semantic identity or disable the breaker wholesale. Simply ignoring every unsuccessful tool response would be broader than this bug: genuine failed agent calls may still be meaningful repetitions.

Suggested coverage:

  1. One external-file invocation with file ask → root ask → success contributes one observation, not three.
  2. Two identical external-file invocations separated beyond the span gate do not report a sixth agent call or escalate at the six-call threshold.
  3. Truly repeated logical calls still warn and escalate at the configured logical-call thresholds, in both worker/head wording modes.
  4. Continuation capabilities still preserve the first approval while obtaining the second; no permission enforcement is bypassed.
  5. Intermediate permission text does not become spurious final-output “drift.”
  6. Keep the existing preview/native-plumbing exclusions working. Exercise the common runner via standalone and subc paths where practical.

Related issues checked

  • #1367: different defect, omitted pattern. This report resolves its explicitly open six-versus-two question and demonstrates independent permission-attempt inflation.
  • #347: same class of accounting mistake, but preview/apply mutation double-counting; fixed in 0.58.0. This is a read-only permission-negotiation path in 0.63.5, not evidence that the preview fix regressed.
  • #1258: missing permission continuation for deferred multi-file inspect, fixed in 0.63.5. Here the continuation exchange completes successfully; its attempts are counted as model repetition.

Checked all 409 open/closed non-PR issue titles/bodies plus targeted comment searches before filing; no existing report for this permission-retry counting path was found.

chpock avatar Nov 03 '26 19:11 chpock

Confirmed: Pi retries permission negotiation within one tool invocation, but the shared native runner observes each attempt. That can inflate the repetition count and compare permission prompts with final result text. This is separate from the missing-pattern identity in #1367 and remains open.

aft-alfonso[bot] avatar Nov 11 '26 19:11 aft-alfonso[bot]