Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions docs/calibration-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
- [ ] 保护相邻正常行为,阻止禁用缓存、无限缓存、截断内容等绕过。
- [ ] 并发场景使用确定性屏障或虚拟时钟,避免靠脆弱 sleep 排名。
- [ ] 挂起用例有有界清理;环境故障单列而非默认为零。
- [ ] 评分结果走认证通道:评分器每次生成随机口令经 stdin 传给评测进程,`author/result-channel.mjs` 在载入提交代码前读走口令并保存输出函数;评测进程以 `--frozen-intrinsics` 启动,只接受恰好一行带本次口令的结果。提交代码自行打印、提前退出或改写全局对象都只会得到环境无效。
- [ ] 需要隔离执行提交代码的子进程(如独立解码、独立同步端)用 Node 权限模型(Node 22 起 `--permission`,20 为 `--experimental-permission`),只放行运行脚本、提交目录与必要输入,授权路径先取真实路径;解码结果由父进程逐字节比对原文,不信任子进程自报的通过结论。
- [ ] 留存风险写清:同进程提交代码仍可读取作者目录文件(题包本身公开,不构成泄题),调试器/inspector 类内存读取不在防护范围;对抗性排名场景需另行隔离。
- [ ] 实际运行日志、环境版本、清单与 SHA-256 留存。

## 冻结与试跑
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["src/"]
581 changes: 581 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))
39 changes: 39 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,39 @@
"""Isolated pure-Node capability grader for codex-namespace-tool-collision."""
import pathlib, secrets, shutil, tempfile, subprocess, json, sys

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

RESULT_TAG = 'EVAL-RESULT '


def read_result(stdout, nonce):
"""Only the evaluator knows the per-run nonce (read from stdin before any submission code
loads), so a line printed by the submission cannot pass as the result."""
prefix = f'{RESULT_TAG}{nonce} '
found = [line[len(prefix):] for line in stdout.splitlines() if line.startswith(prefix)]
if len(found) != 1:
return {'status': 'environment_invalid', 'reason': f'expected exactly one authenticated evaluator result, got {len(found)}'}
return json.loads(found[0])


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)
nonce = secrets.token_hex(16)
p = subprocess.run(
['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src)],
input=nonce + '\n', 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'}
return read_result(p.stdout, nonce)

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')
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Trusted result channel (author side, loaded before any submission code).
*
* The grader passes a fresh random nonce on stdin. This module reads it before the evaluator
* imports the submission, captures the clock / memory / GC functions the evaluator measures
* with, and hands them out exactly once. The evaluator writes its result as the only line
* tagged with the nonce; the grader accepts exactly one such line. A submission therefore
* cannot print a result of its own, re-import this module to reuse the emitter, or patch
* `performance.now` / `process.memoryUsage` to bend measurements. Run under
* `--frozen-intrinsics` so `Math`, `JSON`, `Array.prototype` and friends cannot be patched either.
* Reading process memory through a debugger is outside this guard (see docs/versioning.md).
*/
import { readFileSync, writeSync } from 'node:fs';
import { performance } from 'node:perf_hooks';

const nonce = (() => {
if (process.stdin.isTTY) return '';
try {
return readFileSync(0, 'utf8').trim();
} catch {
return '';
}
})();
const write = writeSync;
const stringify = JSON.stringify;
const now = performance.now.bind(performance);
const memoryUsage = process.memoryUsage.bind(process);
const gc = typeof globalThis.gc === 'function' ? globalThis.gc : null;
let taken = false;

export function takeResultChannel() {
if (taken) throw new Error('result channel already taken');
taken = true;
return {
now,
memoryUsage,
gc() {
if (!gc) throw new Error('gc is not exposed');
gc();
},
emit(result) {
write(1, `EVAL-RESULT ${nonce} ${stringify(result)}\n`);
},
};
}
37 changes: 37 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,37 @@
# 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 }) }` supporting `application/json` and `text/event-stream`.

## 2. Namespace Lowering & Collision Disambiguation (`namespaceTools: 'functions'`)

- Top-level declarations (both flat `{ type, name }` and Chat-shaped nested `{ type: 'function', function: { name } }`) and children of the reserved `functions` namespace own their literal bare wire names regardless of declaration order across `tools` and `input[].additional_tools`. Duplicate declarations of the same logical tool deduplicate cleanly.
- Non-`functions` namespace children `(ns, name)` default to wire name `<ns>__<name>`. When a wire name collides with a distinct logical tool, `prepareResponsesCompatibility` disambiguates deterministically (`_2`, `_3`, … capped at 64 chars: `prefix.slice(0, 64 - tail.length) + tail`) without hijacking any declared bare name, namespace child's logical name, or default flattened name across `tools` and `additional_tools`.
- Direct calls to `rewriteRoutedNamespaceToolsForUpstream(body)` default to `disambiguate = false` (throwing `NamespaceToolCollisionError` on collisions); passing `disambiguate = true` enables disambiguation.
- `tool_choice` (direct `{ type, name, namespace? }` and `allowed_tools`) and replayed `input` tool calls rewrite consistently to allocated wire names and drop private `namespace` fields. Authorization strictly matches original declared kinds (`function` vs `custom`).
- Under `customTools: 'preserve-apply-patch'`, any custom tool whose original logical name is `apply_patch` (even if namespaced and disambiguated) remains `type: 'custom'`; under `customTools: 'functions'`, all custom tools convert to `type: 'function'`.
- Canonical-only fields (`defer_loading`) are stripped from `tools` and `input[].additional_tools` when lowering.

## 3. Round-Trip Restoration (JSON & Incremental SSE Parity)

- Converted custom tools restore from `function_call` to `custom_tool_call` (`fc_` → `ctc_`, `{ "input": "..." }` unwrapped; incremental SSE emits `custom_tool_call` + `custom_tool_call_input` without leaking raw `function_call_arguments` deltas) across:
- the allocated wire name,
- unambiguous authorized dotted aliases (`<ns>.<name>` when neither segment contains `__`, non-ambiguous across the catalog, and not declared as a bare tool), and
- provider echoes retaining matching `namespace` alongside original name, allocated wire name, or dotted alias.
- Calls with a non-matching `namespace` or unrelated bare names (e.g. `a__a__b_2`) remain untouched.
- If a call carries an explicit `(namespace, name)` matching an authorized declared namespace tool, that explicit declared identity takes precedence over another tool's alias spelling.

## 4. Conflict Guards & Native-Namespace Repair

- **Code Mode helper guard**: Helper rerouting toward bare custom `exec` must respect declared logical names (both unlowered and lowered, across `tools` and `additional_tools`) so declaring a namespaced `apply_patch` protects bare `apply_patch` from being rerouted to `exec`.
- **Self-named namespace scrubbing**: Strips redundant `namespace: x` from `{ name: x, namespace: x }` when bare `x` is authorized and no active same-name namespace conflict `(x, x)` exists.
- Must account for both original and lowered catalogs, including same-name namespaced `custom` tools that arrive upstream as `function_call`.
- Under `namespaceTools: 'functions'`, a same-name `type: 'namespace'` group declaration blocks scrubbing ONLY if authorized/selected by the turn's `tool_choice`; inline `spec.namespace` declarations retain the conservative guard.
- **Native-namespace argument repair (`namespaceTools: 'native'`, `repairFunctionArguments: true`)**:
- Request declarations pass through unchanged.
- Argument repair applies each tool's own schema keyed by exact `(namespace, name)` identity so bare `ns__name` and namespaced `(ns, name)` never cross-contaminate. Integral floats coerce to integers for `integer` fields; safe integers coerce to strings for `string`-only fields; non-integral floats stay 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
15 changes: 15 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,15 @@
# Task

Production Codex sessions are hitting Responses API tool compatibility failures whenever bare tools, `functions` tools, MCP/namespaced tools, and `custom` tools interact or share wire spellings—across both JSON responses and incremental SSE streams.

Reported issues include:
- Requests failing when bare and namespaced tools flatten to the same wire name.
- Converted namespaced `custom` tools failing to round-trip back to `custom_tool_call` across valid provider echo spellings, or colliding with other declared tools.
- Self-named namespace echo repair, Code Mode helper routing, and native-namespace argument repair misbehaving around colliding, converted, or unselected tools.

Inspect `src/`, read `CONTRACT.md` and `ENVIRONMENT.md`, and fix all demonstrable protocol compatibility defects while preserving behavior for ordinary non-colliding requests.

- Run `npm test` and add verification tests as needed.
- 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
Loading