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): 三套新 suite 校准完成,登记版本与题包清单
- suites/cindy-eval-v2-20261205.json(7 题)、cindy-eval-opt-v2-20261206.json(3 道真实负载优化题)、cindy-eval-opt-v1-20261205.json(4 道合成负载优化题,作为对照保留)均补上 manifestSha256。
- 补入 opt-cshare-compression@v1、opt-device-link-delta-sync@v1 两道 v1 题,评分器同样走认证结果通道,独立解码同样进权限沙箱,bench 入口判断同样修复。
- 14 道题经 scripts/verify-v2-suite.mjs 起草、校准、冻结、篡改检查全部通过,question.json 状态 draft -> calibrated;versions.json 追加 14 条,publishedRuntime 均为 false(随 Release 发布后再改)。
- build-v2-bank.py 的 README 文案按 suite 生成,不再写死 7 题题包的描述。

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 f07f28450f4de166392e4aef2fe5342328477824
2 changes: 1 addition & 1 deletion questions/codex-namespace-tool-collision/v1/question.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"revision": "v1",
"scoringVersion": "capability-ratio-v1",
"title": "Codex Namespace 工具重名消解与响应还原兼容",
"status": "draft",
"status": "calibrated",
"changeNote": "Eval Bank v2 complex root-cause question extracted from makecindy/cindy PR #14563 (793ac48b27b5).",
"environment": "any",
"sourceRepo": "https://github.com/makecindy/cindy",
Expand Down
2 changes: 1 addition & 1 deletion questions/mcp-apps-exact-origin/v1/question.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"revision": "v1",
"scoringVersion": "quality-composition-v1",
"title": "MCP Apps 精确 Origin CSP 清单校验与兼容保护",
"status": "draft",
"status": "calibrated",
"changeNote": "Eval Bank v2 security/protocol question extracted from makecindy/cindy PR #15220 (5b6d74c1).",
"environment": "any",
"sourceRepo": "https://github.com/makecindy/cindy",
Expand Down
1 change: 1 addition & 0 deletions questions/opt-cshare-compression/v1/author/editable.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["src/"]
538 changes: 538 additions & 0 deletions questions/opt-cshare-compression/v1/author/evaluator.mjs

Large diffs are not rendered by default.

48 changes: 48 additions & 0 deletions questions/opt-cshare-compression/v1/author/grade.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Trusted submission gate: protected inputs/tests/benchmarks 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=300
)
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))
45 changes: 45 additions & 0 deletions questions/opt-cshare-compression/v1/author/grade_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Isolated pure-Node quantitative grader for opt-cshare-compression."""
import pathlib, secrets, shutil, tempfile, subprocess, json, sys

HERE = pathlib.Path(__file__).resolve().parent
Q = HERE.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()
src_dir = submission_root / 'src'
if not src_dir.is_dir():
return {'status': 'environment_invalid', 'reason': 'submission src/ directory missing'}

with tempfile.TemporaryDirectory(prefix='eval-cshare-opt-') as td:
tmp = pathlib.Path(td)
sub_src = tmp / 'sub_src'
shutil.copytree(src_dir, sub_src)
corpus_gen = Q / 'candidate' / 'lib' / 'corpus-generator.mjs'
nonce = secrets.token_hex(16)
p = subprocess.run(
['node', '--frozen-intrinsics', str(HERE / 'evaluator.mjs'), str(sub_src), str(corpus_gen)],
input=nonce + '\n', capture_output=True, text=True, timeout=180
)
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')
45 changes: 45 additions & 0 deletions questions/opt-cshare-compression/v1/author/result-channel.mjs
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`);
},
};
}
54 changes: 54 additions & 0 deletions questions/opt-cshare-compression/v1/candidate/CONTRACT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Codec & Container Contract

This contract defines the required API, outer wire header, lossless correctness invariants, statelessness requirements, and execution bounds for the `.cshare` archive codec. Everything after byte 12 of the encoded output is completely open-ended as long as all invariants below hold.

## 1. Public Module Interface (`src/cshare-codec.mjs`)

Must export:
- `XDTSHARE_MAGIC = 'XDTSHARE'`
- `XDTSHARE_PLAIN_HEADER_LENGTH = 12`
- `encodeArchive(bundle)`:
- Input: `{ headerVersion?: 1, entries: Array<{ path: string, content: Uint8Array }> }` (`content` may be any `Uint8Array` or `Buffer`, including views with a non-zero `byteOffset`).
- Output: `Uint8Array` (or `Buffer`, which is a `Uint8Array` subclass) starting with the exact 12-byte `XDTSHARE` plain header.
- Must not mutate the caller's `bundle`, `entries` array, or `entry.content` byte buffers.
- Must be deterministic: encoding the same bundle twice must produce identical archive bytes.
- `decodeArchive(bytes)`:
- Input: `Uint8Array` (or `Buffer`), including views with a non-zero `byteOffset`.
- Output: `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`.
- Must reject malformed or unsupported outer headers (length < 12, invalid magic, `headerVersion !== 1`, `cipher !== 0`) by throwing an `Error`.

## 2. Outer `XDTSHARE` Plain Header (Fixed 12 Bytes)

| Offset | Length | Field | Required Value |
| --- | --- | --- | --- |
| `0` | `8` | `magic` | ASCII `"XDTSHARE"` (`58 44 54 53 48 41 52 45`) |
| `8` | `1` | `headerVersion` | `1` (`u8`) |
| `9` | `1` | `cipher` | `0` (`u8`, plaintext unencrypted archive) |
| `10` | `2` | `reserved` | `0x00, 0x00` |
| `12` | `...` | `payload` | Candidate-defined self-contained lossless archive format |

## 3. Bit-Exact Lossless Correctness Invariants

For every valid input bundle, `decodeArchive(encodeArchive(bundle))` MUST preserve:
1. `headerVersion === 1`
2. Exact entry count (`decoded.entries.length === bundle.entries.length`)
3. Exact entry order (`decoded.entries[i].path === bundle.entries[i].path`)
4. Exact bytes of every entry (`Buffer.compare(decoded.entries[i].content, bundle.entries[i].content) === 0`)

This MUST hold not only for realistic `.cshare` bundles, but also for arbitrary and adversarial inputs:
- Empty archives (`entries: []`)
- Zero-byte files (`content.byteLength === 0`, including `.json`, `.jsonl`, `.png`)
- Arbitrary binary payloads containing all 256 byte values (`0x00..0xFF`), including binary files named `.json` or `.jsonl`
- UTF-8 CJK and emoji characters in both `path` and `content`
- Exact line-ending and formatting preservation (`\r\n` vs `\n` vs no trailing newline, pretty-printed vs compact JSON, duplicate keys, control characters)
- Malformed non-JSON files named `.jsonl` or `.json`, and non-PNG data named `.png`
- High-entropy incompressible random buffers
- Duplicate entry paths (both with identical contents and with distinct contents) in their original order

## 4. Stateless Isolated Decode & Runtime Bounds

- **Stateless decode**: The encoded `Uint8Array` MUST be completely self-contained. Grading writes encoded archives to disk and invokes `decodeArchive` inside a fresh child Node.js process with an isolated working directory and `TMPDIR`—in-memory caches, module globals, or filesystem side-channels cannot be used to pass data from encode to decode.
- **No external dependencies**: Only standard Node.js >= 18 built-in modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. Do not require external npm packages or native binaries. Note that `deflateRawSync`, `gzipSync`, and `brotliCompressSync` are available across all Node.js >= 18 runtimes; do not assume `zstdCompressSync` exists without feature detection and fallback.
- **Performance limits (held-out corpus total across 3 bundles)**:
- Total `encodeArchive` time: `<= 12,000 ms` (12 seconds)
- Total `decodeArchive` time: `<= 5,000 ms` (5 seconds)
11 changes: 11 additions & 0 deletions questions/opt-cshare-compression/v1/candidate/ENVIRONMENT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Environment

- Runtime: Pure Node.js (`>= 18`, ESM `.mjs`), zero external npm dependencies, offline.
- Built-in Node.js modules (`node:zlib`, `node:crypto`, `node:buffer`, etc.) are allowed. For Node.js 18+ portability, `zlib.deflateRawSync`, `zlib.gzipSync`, and `zlib.brotliCompressSync` are always available; do not assume `zlib.zstdCompressSync` is present without checking availability first.
- Platform: Cross-platform (`environment: "any"` — macOS, Linux, Windows).
- Determinism & held-out evaluation:
- Public benchmark (`npm run bench`) runs on a deterministic 3-bundle public `.cshare` corpus generated by `lib/corpus-generator.mjs`.
- Official grading evaluates bit-exact lossless correctness, stateless child-process decoding, header/timing limits (`encode <= 12s`, `decode <= 5s`), and total `archive_bytes` on an **unseen held-out 3-bundle corpus** with different seeds, project domain, file paths, code identifiers, vocabulary, UUID spaces, timestamps, and media.
- Public checks:
- `npm test` — lossless round-trip, header validation, and adversarial edge-case smoke tests
- `npm run bench` — deterministic public corpus benchmark reporting raw size, `archive_bytes`, compression ratio, and encode/decode timings
29 changes: 29 additions & 0 deletions questions/opt-cshare-compression/v1/candidate/TASK.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Task

You are optimizing Cindy's `.cshare` session-archive lossless compression codec (`src/cshare-codec.mjs` and helper modules under `src/`), extracted from Cindy's desktop session-share export pipeline (`sessionShareExport.ts` and `xdtshareFormat.pure.ts`).

## Observed Production Symptoms

Cindy exports AI coding sessions—including single-agent sessions, Claude fork chains, media attachments, and Orca multi-worker team archives—into `.cshare` files using per-entry raw DEFLATE (level 6) with no cross-file solid compression, no content deduplication, and no structural preprocessing. As a result, realistic 10–14 MiB session exports still occupy multiple megabytes when shared or migrated across devices, despite containing massive structural and semantic redundancy across:
- Pretty-printed JSON metadata (`manifest.json`, `session.json`, `media-map.json`)
- Database `messages.jsonl` and native vendor transcripts (`transcripts/claude/*.jsonl`, `transcripts/codex/rollout.jsonl`)
- Structured JSONL telemetry, timestamps, IDs, and numeric usage counters
- Fork chains (`fork-0.jsonl`, `fork-1.jsonl`, `fork-2.jsonl`) and Orca worker subdirectories (`orca/workers/0..3/`)
- Evolving file snapshots and duplicated binary media attachments (`media/*.png`)

## Requirements

- Read `CONTRACT.md` and `ENVIRONMENT.md` before making changes.
- Preserve the required public API in `src/cshare-codec.mjs`:
- `XDTSHARE_MAGIC` (`'XDTSHARE'`)
- `XDTSHARE_PLAIN_HEADER_LENGTH` (`12`)
- `encodeArchive(bundle)` → `Uint8Array`
- `decodeArchive(bytes)` → `{ headerVersion: 1, entries: Array<{ path: string, content: Uint8Array }> }`
- Preserve the exact 12-byte outer `XDTSHARE` plain header (`"XDTSHARE"` ASCII 8B + `headerVersion=1` u8 + `cipher=0` u8 + 2 zero reserved bytes). Everything from byte 12 onward is your open-ended lossless container and compression format.
- Guarantee **100% bit-exact lossless round-trip** (`headerVersion`, entry count, exact entry order, exact UTF-8 paths, and byte-exact contents) across all valid `.cshare` bundles and arbitrary binary/edge-case payloads.
- Guarantee **stateless, deterministic** encoding and decoding: `decodeArchive(bytes)` must reconstruct every entry in a fresh isolated Node.js process given only the encoded archive bytes.
- **Open-ended optimization goal**: Minimize total encoded `archive_bytes` on the **unseen held-out evaluation suite** (which uses different seeds, project domains, file names, code identifiers, vocabulary, UUID spaces, timestamps, and media—hardcoded dictionaries will not generalize), while staying within Node.js built-ins (zero external npm packages) and the held-out runtime limits (`encode <= 12s`, `decode <= 5s`).
- Run `npm test` and `npm run bench` to verify correctness and compare public corpus sizes before and after your changes.
- Record your analysis, format design, trade-offs, and verified metrics in `BUGS_FOUND.md`.

允许修改的源码范围:仅限 `src/` 目录下的源码文件;可新增测试,不修改已有测试、基准脚本、语料生成器、运行环境和题面。
80 changes: 80 additions & 0 deletions questions/opt-cshare-compression/v1/candidate/bench/workload.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import crypto from 'node:crypto';
import { performance } from 'node:perf_hooks';

import { encodeArchive, decodeArchive } from '../src/cshare-codec.mjs';
import { generatePublicSuite, measureBundleRawBytes } from '../lib/corpus-generator.mjs';
import { realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

function isMainModule() {
try {
return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
} catch {
return false;
}
}

function sha256(u8) {
return crypto.createHash('sha256').update(u8).digest('hex');
}

export function runPublicBenchmark() {
const suite = generatePublicSuite();
const perBundle = [];
let totalRawBytes = 0;
let totalArchiveBytes = 0;
let totalEncodeMs = 0;
let totalDecodeMs = 0;

for (const bundle of suite.bundles) {
const rawBytes = measureBundleRawBytes(bundle);
const t0 = performance.now();
const encoded = encodeArchive(bundle);
const encodeMs = performance.now() - t0;

const t1 = performance.now();
const decoded = decodeArchive(encoded);
const decodeMs = performance.now() - t1;

if (decoded.entries.length !== bundle.entries.length) {
throw new Error(`Entry count mismatch on ${bundle.name}`);
}
for (let i = 0; i < bundle.entries.length; i++) {
if (decoded.entries[i].path !== bundle.entries[i].path) {
throw new Error(`Path mismatch at ${bundle.name}[${i}]`);
}
if (sha256(decoded.entries[i].content) !== sha256(bundle.entries[i].content)) {
throw new Error(`Content hash mismatch at ${bundle.name}:${bundle.entries[i].path}`);
}
}

totalRawBytes += rawBytes;
totalArchiveBytes += encoded.byteLength;
totalEncodeMs += encodeMs;
totalDecodeMs += decodeMs;

perBundle.push({
name: bundle.name,
entries: bundle.entries.length,
raw_bytes: rawBytes,
archive_bytes: encoded.byteLength,
ratio: Number((rawBytes / encoded.byteLength).toFixed(2)),
encode_ms: Number(encodeMs.toFixed(1)),
decode_ms: Number(decodeMs.toFixed(1)),
});
}

return {
suite: suite.suiteName,
raw_bytes: totalRawBytes,
archive_bytes: totalArchiveBytes,
compression_ratio: Number((totalRawBytes / totalArchiveBytes).toFixed(2)),
encode_ms: Number(totalEncodeMs.toFixed(1)),
decode_ms: Number(totalDecodeMs.toFixed(1)),
bundles: perBundle,
};
}

if (isMainModule()) {
console.log(JSON.stringify(runPublicBenchmark(), null, 2));
}
Loading