Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
feat(eval-bank-v2): 新增 7 道纯 Node 跨平台实战题(4 道连续数值结果题 + 3 道复杂根因题)
- 全部提取自开源 makecindy/cindy (Apache-2.0),纯 Node.js >= 18 ESM,零外部 npm 依赖,platform: "any"(压缩包总计 ~192 KiB,展开 ~600 KiB)。
- 4 道连续数值结果优化题(mode: "metric",前置硬性正确性门禁 + 真实物理指标):
  - perf-jsonl-hotpaths@v1 (PR #15565):大帧 JSONL 分帧与工具负载热路径加速比
  - perf-mobile-home-heat@v1 (PR #15544):手机首页排序加速比 + 写盘/RPC/Widget 唤醒次数
  - perf-mcp-hosttools-churn@v1 (PR #15602):MCP 宿主工具每调用堆分配(KB/call) + Schema 重建数 + 加速比
  - perf-github-api-budget@v1 (PR #14157):48h 虚拟时钟 50-PR 确定性 API 配额点数 + 无效调用 + 429 限流次数
- 3 道复杂协议与路由根因题(精确有理数 ratio/all):
  - mcp-apps-exact-origin@v1 (PR #15220):CSP origin 精确匹配与 :* 通配端口绕过防护
  - codex-namespace-tool-collision@v1 (PR #14563):Responses API 命名空间工具碰撞与别名往返还原
  - smart-routing-three-tiers@v1 (PR #15050):智能路由三档默认、5h 紧张态 6 级排序与多源穿透隔离
- 附 suites/cindy-eval-v2-20261205.json、scripts/build-v2-bank.py 与 scripts/verify-v2-suite.mjs;7/7 通过 eval-lab 真实三控制组校准、冻结与防篡改门禁验证。

Assisted-by: Cindy (https://cindy.app)
Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com>
  • Loading branch information
dashhuang committed Dec 5, 2026
commit f9ef53e15b5fdf05bf03ee9d7f007c739a70d822
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["src/"]
577 changes: 577 additions & 0 deletions questions/codex-namespace-tool-collision/v1/author/evaluator.mjs

Large diffs are not rendered by default.

48 changes: 48 additions & 0 deletions questions/codex-namespace-tool-collision/v1/author/grade.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Trusted submission gate: protected inputs/tests cannot be altered."""
from pathlib import Path
import sys, json, filecmp, subprocess, os

Q = Path(__file__).resolve().parent.parent
root = Path(sys.argv[1]).resolve()
output = Path(sys.argv[2]).resolve()
allowed = json.loads((Q / 'author/editable.json').read_text())

def editable(rel):
return any(rel == p or (p.endswith('/') and rel.startswith(p)) for p in allowed) and '/__tests__/' not in '/' + rel and '.test.' not in rel

errors = []
if not root.is_dir():
errors.append('source root missing')
else:
for base in (Q / 'candidate').rglob('*'):
if not base.is_file():
continue
rel = base.relative_to(Q / 'candidate').as_posix()
if editable(rel):
continue
if rel.startswith(('.build/', '.work/')):
continue
other = root / rel
if not other.is_file() or other.is_symlink() or not filecmp.cmp(base, other, shallow=False):
errors.append(rel)

if errors:
result = {'status': 'environment_invalid', 'reason': 'submission changed protected inputs or package incomplete', 'files': errors}
else:
try:
p = subprocess.run(
[sys.executable, '-B', str(Q / 'author/grade_impl.py'), str(root), str(output)],
env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'),
capture_output=True, text=True, timeout=180
)
if p.returncode or not output.exists():
result = {'status': 'environment_invalid', 'reason': 'grader could not complete', 'stdout': p.stdout[-4000:], 'stderr': p.stderr[-4000:]}
else:
result = json.loads(output.read_text())
result['submissionGate'] = 'passed'
except subprocess.TimeoutExpired:
result = {'status': 'environment_invalid', 'reason': 'grader safety timeout'}

output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print(json.dumps({k: v for k, v in result.items() if k not in ['details', 'raw']}, ensure_ascii=False))
28 changes: 28 additions & 0 deletions questions/codex-namespace-tool-collision/v1/author/grade_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Isolated pure-Node capability grader for codex-namespace-tool-collision."""
import pathlib, shutil, tempfile, subprocess, json, sys

HERE = pathlib.Path(__file__).resolve().parent

def grade(submission_root):
submission_root = pathlib.Path(submission_root).resolve()
with tempfile.TemporaryDirectory(prefix='eval-codex-ns-') as td:
tmp = pathlib.Path(td)
sub_src = tmp / 'sub_src'
shutil.copytree(submission_root / 'src', sub_src)
p = subprocess.run(
['node', str(HERE / 'evaluator.mjs'), str(sub_src)],
capture_output=True, text=True, timeout=120
)
if p.returncode != 0:
return {'status': 'environment_invalid', 'reason': (p.stderr or p.stdout)[-2000:] or 'evaluator exited nonzero'}
lines = [line for line in p.stdout.splitlines() if line.strip()]
if not lines:
return {'status': 'environment_invalid', 'reason': 'evaluator produced no output'}
return json.loads(lines[-1])

if __name__ == '__main__':
try:
res = grade(sys.argv[1])
except Exception as exc:
res = {'status': 'environment_invalid', 'reason': str(exc)}
pathlib.Path(sys.argv[2]).write_text(json.dumps(res, ensure_ascii=False, indent=2) + '\n')
87 changes: 87 additions & 0 deletions questions/codex-namespace-tool-collision/v1/candidate/CONTRACT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Product & Protocol Contract

## 1. Public Entrypoints (`src/responses.mjs`)

- `prepareResponsesCompatibility(body, policy)`:
- `policy`:
- `namespaceTools?: 'native' | 'functions'`
- `customTools?: 'native' | 'functions' | 'preserve-apply-patch'`
- `repairFunctionArguments?: boolean`
- Returns `{ body, needsResponseTransform, restoreJson(text), createStreamRewrite() }`.
- `createResponsesCompatibilityAdapter(policy)`:
- Returns `{ adaptRequest(body, requestId, overrides?), releaseResponse(requestId), createResponseTransform(requestId, { contentType, contentEncoding }) }`.
- Supports `application/json` and `text/event-stream` response transforms.

## 2. Namespace Lowering & Wire-Name Collision Disambiguation

When `policy.namespaceTools === 'functions'`:

1. **Canonical bare ownership**:
- Top-level non-namespace declarations (both flat `{ type, name }` and Chat-shaped nested `{ type: 'function', function: { name } }`) and children of the reserved `functions` namespace represent bare tools and claim their literal bare wire name regardless of declaration order across `tools` and `input[].additional_tools`.
- Duplicate declarations of the same logical tool (e.g., both bare and inside `functions`, or repeated in `additional_tools`) are deduplicated cleanly.
2. **Whole-catalog reservation before disambiguation**:
- Before allocating any disambiguated suffix, reserve across all tool groups (`tools` and `input[].additional_tools`):
- every non-namespace tool's wire name (including nested `tool.function.name`),
- every namespace child's logical `child.name` (so a generated suffix cannot hijack a bare `tool_choice` selector naming another namespace child),
- every namespace child's default flattened wire name (`<namespace>__<child.name>`, or `<child.name>` for `functions`).
3. **Deterministic collision disambiguation**:
- A non-`functions` namespace child `(ns, name)` defaults to wire name `<ns>__<name>`.
- If that wire name is already owned by a distinct logical identity, `prepareResponsesCompatibility` MUST disambiguate instead of throwing `NamespaceToolCollisionError`: allocate `_2`, `_3`, ... with `wireName = prefix.slice(0, 64 - tail.length) + tail`, skipping any already-reserved name and adding the allocated name to the reserved set.
- Calling `rewriteRoutedNamespaceToolsForUpstream(body)` directly with default `disambiguate = false` retains throwing `NamespaceToolCollisionError` on collisions; passing `disambiguate = true` enables suffix allocation.
4. **Selector & replay consistency**:
- Bare declarations keep ownership of their literal bare selector even if a namespace child has the same default flattened spelling or same logical name.
- `tool_choice` (direct `{ type, name, namespace? }` and `{ type: 'allowed_tools', tools: [...] }`) and replayed `input` `function_call`/`custom_tool_call` items rewrite to the allocated wire name and drop the private `namespace` key.
- `tool_choice` authorization checks the **original declared tool kind** (`'function'` vs `'custom'`) before custom-to-function conversion: a `function` selector never authorizes a `custom` namespace tool and vice versa.
5. **Original `apply_patch` passthrough policy**:
- Under `customTools: 'preserve-apply-patch'`, a custom tool whose original logical name is `apply_patch` (including a namespaced `custom` child such as `editor.apply_patch` whose wire name was disambiguated to `editor__apply_patch_2`) stays `type: 'custom'` and is NOT converted to a `function` tool.
- Under `customTools: 'functions'`, all custom tools (including `apply_patch`) convert to `type: 'function'`.
6. **Canonical-only tool field stripping**:
- When `namespaceTools === 'functions'`, strips canonical-only fields (`defer_loading`) from tools in `body.tools` and `body.input[].additional_tools`.

## 3. Custom Tool & Dotted/Qualified Alias Round-Trip Restoration

Applies consistently to both JSON (`restoreJson`) and incremental SSE (`createStreamRewrite` / `createResponseTransform`):

1. **Order of operations**:
- Outbound: namespace identity allocation runs while original declaration and selector kinds are intact, before custom-tool conversion.
- Inbound: self-named namespace scrub → custom identity normalization → custom tool restoration (`function_call` → `custom_tool_call`, `fc_` → `ctc_`, `{ "input": "..." }` unwrapped) → namespace coordinate restoration → function argument schema repair.
2. **Dotted aliases**:
- For an authorized non-`functions` namespace tool `(ns, name)`, `<ns>.<name>` is also accepted for restoration ONLY when:
- neither `ns` nor `name` contains `__` (`dottedAliasIsUnambiguous`),
- `<ns>.<name>` is not ambiguous across the whole original catalog,
- `<ns>.<name>` is not declared as a bare wire tool name (so a bare `mcp.run` is never stolen),
- the tool was authorized by `tool_choice` with matching kind.
- Converted custom tools MUST recognize both their allocated wire name and their authorized dotted alias.
3. **Namespace-qualified provider echoes for converted custom tools**:
- Providers may emit `function_call` items carrying an explicit `namespace` alongside:
- the original tool name (`{ name: 'b', namespace: 'a' }`),
- the allocated wire name (`{ name: 'a__b_2', namespace: 'a' }`), or
- the dotted alias (`{ name: 'a.b', namespace: 'a' }`).
- When `namespace` matches the tool's authorized original namespace, normalize and restore to `{ type: 'custom_tool_call', namespace: 'a', name: 'b', input: ... }` (deleting `arguments`).
- Calls carrying a non-matching `namespace` (e.g., `namespace: 'other'`) or unrelated bare function names (e.g., `a__a__b_2` without `namespace`) MUST remain untouched.
4. **Explicit declared coordinate precedence**:
- If a call carries an explicit `(namespace, name)` coordinate that matches an authorized declared namespace tool (for example `{ type: 'function_call', namespace: 'a', name: 'a__b_2' }` when `a` declares both custom `b` and function `a__b_2`), that explicit coordinate takes precedence over another tool's allocated alias spelling and MUST NOT be mis-restored.
5. **Incremental SSE streams**:
- Across `response.output_item.added`, `response.function_call_arguments.delta`, `response.function_call_arguments.done`, and `response.output_item.done`, converted custom calls across wire, dotted, wire-qualified, dotted-qualified, and original-qualified spellings restore to `custom_tool_call` with `custom_tool_call_input` events (no raw `function_call_arguments.delta` leaks).

## 4. Logical-Name Conflict Guards

1. **Code Mode helper normalization guard**:
- When bare `exec` (custom) is declared, helper names such as `apply_patch` normalize to `exec` ONLY when not declared in the catalog.
- Declared-name guards MUST include BOTH original logical names (from the unlowered body) and lowered wire names (from the lowered body). Thus declaring `{ type: 'namespace', name: 'mcp', tools: [{ type: 'custom', name: 'apply_patch' }] }` (including inside `additional_tools`) retains `apply_patch` as a conflict guard and prevents a bare `apply_patch` call from being rerouted to `exec`.
2. **Same-name namespace conflict guard across lowered & original catalogs**:
- Self-named namespace scrubbing checks BOTH the lowered catalog and the original catalog so lowering cannot erase a genuine same-name namespace conflict (e.g., `foo` + `{ type: 'namespace', name: 'foo', tools: [{ type: 'function', name: 'foo' }] }`).
- Because custom tools may be lowered to `function_call` upstream, a same-name namespaced `custom` tool (e.g., `x__y.x__y` alongside lowered `x.y` -> `x__y`) blocks self-named scrubbing for `function_call` items as well as `custom_tool_call` items.

## 5. Selected-Tools-Only Self-Named Namespace Scrubbing

- Self-named echo repair strips `namespace` from `{ type: 'function_call' | 'custom_tool_call', name: x, namespace: x }` when bare `x` is authorized for that call kind and no active same-name namespace tool `(x, x)` conflicts.
- When `policy.namespaceTools === 'functions'`, same-name declarations coming from `type: 'namespace'` groups count as conflicts ONLY if `(namespace, name, kind)` is selected/authorized by the turn's namespace plan (`tool_choice` allows it, e.g., `'auto'`, `'required'`, or explicitly selects `{ namespace: 'x', name: 'x' }`). An unselected `namespace: x / x` MUST NOT block scrubbing of a selected bare `x`.
- Declarations carrying an inline `namespace` property directly on the tool spec (`{ type: 'custom', name: 'x', namespace: 'x' }`) are outside the namespace-group lowering plan and retain the conservative conflict guard.

## 6. Native-Namespace Schema Repair (`namespaceTools: 'native'`)

- When `namespaceTools === 'native'` and `repairFunctionArguments === true`:
- Tool declarations are NOT flattened (the request body passes through unchanged).
- Function argument repair schemas key on exact `(namespace, name)` coordinates rather than concatenated `ns__name` strings, so bare `files__read` (e.g., `value: number`) and namespaced `(files, read)` (e.g., `value: string`) each apply their own schema independently.
- Integral floats (`2.0`) in `integer` fields coerce to integers (`2`); safe bare integers (`3`) in `string`-only fields coerce to strings (`"3"`); non-integral floats (`1.5`) remain untouched.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Environment

- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline.
- Platform: Cross-platform (`platform: "any"` — macOS, Linux, Windows).
- Public checks:
- `npm test` — baseline smoke tests covering non-colliding tool lowering, restoration, and argument repair
22 changes: 22 additions & 0 deletions questions/codex-namespace-tool-collision/v1/candidate/TASK.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Task

You are investigating production compatibility failures in Cindy's Responses API tool-lowering and response-restoration pipeline (`src/`).

## Observed Production Symptoms

1. **Requests fail when bare and namespaced tools flatten to the same wire name**: Codex sessions frequently advertise both top-level tools (or tools inside the reserved `functions` group) and MCP/namespaced tools whose default flattened `<namespace>__<name>` spelling collides (for example, a top-level `collaboration__followup_task` alongside a `collaboration` namespace containing `followup_task`). Requests fail during outbound adaptation instead of disambiguating wire identities cleanly across declarations, replayed `input` items, `tool_choice`, and responses.
2. **Custom namespaced tools fail to round-trip across provider spellings**: When a colliding namespaced `custom` tool is lowered to a function tool for upstream gateways, providers may echo the call using the allocated wire name, a dotted alias (`<namespace>.<name>`), or a call retaining the original `namespace` field — in either JSON responses or incremental SSE streams. Several of these valid echoes are either dropped, left un-restored as `function_call`, or misattributed to another tool.
3. **Self-named namespace echo repair and helper normalization misbehave around colliding or unselected tools**:
- When `tool_choice` restricts a turn to a bare tool `x`, the mere declaration of an unselected namespace tool `x.x` prevents provider self-named echo repair (`{ name: "x", namespace: "x" }`).
- Conversely, genuine same-name namespaced custom tools or namespaced `apply_patch` declarations can lose their conflict protection during response repair, causing calls to be scrubbed or rerouted to the wrong tool.
4. **Native-namespace argument repair confuses colliding identities**: Even when namespaces are passed through natively (`namespaceTools: 'native'`), argument schema coercion can mix up a bare tool named `ns__name` with a namespaced tool `(ns, name)`.

## Requirements

- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes.
- Fix all protocol compatibility defects in `src/` so every invariant in `CONTRACT.md` holds across both JSON responses (`restoreJson`) and SSE streams (`createStreamRewrite` / `createResponseTransform`).
- Preserve full compatibility for ordinary non-colliding tools, argument coercion, and `apply_patch` policies.
- Run `npm test` and add your own verification tests as needed (do not edit existing tests).
- Summarize your findings, root causes, and verification results in `BUGS_FOUND.md`.

允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、运行环境和题面。
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "cindy-codex-namespace-tool-collision",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "node --test tests/smoke.test.mjs"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const PATCH_BEGIN = '*** Begin Patch';
const PATCH_END = '*** End Patch';
const TOP_LEVEL_PATCH_ENVELOPE = /^(\*\*\* Begin Patch(?: \*\*\*)?)(\r?\n)([\s\S]*)(\r?\n)(\*\*\* End Patch(?: \*\*\*)?)(\r?\n)?$/;
const PATCH_OPERATION_LINE = /^\*\*\* (?:Add|Update|Delete) File: .+$/m;

export function unwrapFreeformToolInput(argumentsText) {
if (typeof argumentsText !== 'string') return '';
try {
const parsed = JSON.parse(argumentsText);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
if (typeof parsed.input === 'string') return parsed.input;
}
} catch {
// The string is the freeform body, not nested JSON.
}
return argumentsText;
}

export function normalizeApplyPatchDelimiters(text) {
const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text);
if (!match) return text;
const [, begin, beginBreak, body, endBreak, end, trailingBreak = ''] = match;
if (!PATCH_OPERATION_LINE.test(body)) return text;
if (begin === PATCH_BEGIN && end === PATCH_END) return text;
return `${PATCH_BEGIN}${beginBreak}${body}${endBreak}${PATCH_END}${trailingBreak}`;
}

export function isCompletePatchEnvelope(text) {
const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text);
if (!match) return false;
return PATCH_OPERATION_LINE.test(match[3] ?? '');
}

export function mayBecomePatchEnvelope(text) {
if (text === '') return false;
return text.startsWith(PATCH_BEGIN) || PATCH_BEGIN.startsWith(text);
}

export function repairFreeformToolInput(argumentsText, toolName = '', namespace) {
const unwrapped = unwrapFreeformToolInput(argumentsText);
const ownsApplyPatchGrammar = namespace === undefined || namespace === 'functions';
return ownsApplyPatchGrammar && toolName === 'apply_patch'
? normalizeApplyPatchDelimiters(unwrapped)
: unwrapped;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
isCompletePatchEnvelope,
normalizeApplyPatchDelimiters,
unwrapFreeformToolInput,
} from './apply-patch-envelope.mjs';
import { declaresCodeModeExec } from './tools.mjs';

function isPlainObject(value) {
return !!value && typeof value === 'object' && !Array.isArray(value);
}

function unwrapPatchInput(value) {
try {
const parsed = JSON.parse(value);
if (isPlainObject(parsed)) {
if (typeof parsed.input === 'string') return parsed.input;
if (typeof parsed.patch === 'string') return parsed.patch;
}
} catch {
// Native custom calls carry the patch body directly.
}
return value;
}

export function compileCodeModeHelperInput(argumentsText, toolName) {
if (typeof argumentsText !== 'string') return '';
if (toolName === 'apply_patch') {
const patch = normalizeApplyPatchDelimiters(unwrapPatchInput(argumentsText));
return `const result = await tools.apply_patch(${JSON.stringify(patch)});\ntext(result);`;
}
let parsed = argumentsText;
try {
parsed = JSON.parse(argumentsText);
} catch {
// Keep malformed provider text as data rather than executable source.
}
const args = isPlainObject(parsed) ? { ...parsed } : parsed;
if (
toolName === 'shell_command'
&& isPlainObject(args)
&& typeof args.command === 'string'
&& args.cmd === undefined
) {
args.cmd = args.command;
delete args.command;
}
if (toolName === 'write_stdin') {
return `const result = await tools.write_stdin(${JSON.stringify(args)});\ntext(result);`;
}
return `const result = await tools.exec_command(${JSON.stringify(args)});\ntext(result);`;
}

export function resolveCodeModeHelperName(
codeModeHelperName,
toolName,
argumentsText,
namespace,
declaredNames,
) {
if (codeModeHelperName) return codeModeHelperName;
if (toolName !== 'exec' || namespace !== undefined) return undefined;
if (!declaresCodeModeExec(declaredNames)) return undefined;
if (typeof argumentsText !== 'string' || argumentsText === '') return undefined;
return isCompletePatchEnvelope(unwrapFreeformToolInput(argumentsText)) ? 'apply_patch' : undefined;
}
Loading