Adversarial TDD skill · October 10, 2026
Every attempt passed with and without my skill. Making it available used 2.46× the total tokens and 1.60× the elapsed time of the same setup without it.
I built an adversarial TDD skill with separate roles for tests, implementation and refactoring. I compared the same Codex setup with this optional skill available and absent, using eight selected synthetic function-task families and two repetitions per variant.
Independent checks and reference solutions were prepared before the agent runs. These were supplied-function tasks, not real repository changes or a test of when an agent would choose to use a skill during ordinary work.
| variant | change | requested model | checks passed | completed | attempts | elapsed min | tokens |
|---|---|---|---|---|---|---|---|
| baseline | TDD skill absent | gpt-6.1-sol | 16/16 | 16/16 | 16 | 32.26 | 3,405,421 |
| v1 | TDD skill available | gpt-6.1-sol | 16/16 | 16/16 | 16 | 51.73 | 8,390,170 |
baseline = skill absent; v1 = skill available. Eight independent families, two repetitions each: sixteen attempts per variant.
Token totals include the main agent and its child agents, including cached input and repeated context. They measure usage, not dollars. Elapsed attempt time is shown here; it is not the full study preparation or grading effort.
| id | tags | baseline | v1 | task measurements |
|---|---|---|---|---|
| record-normalization | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 51.48 elapsed sec; 60,062 whole-tree tokens baseline, repeat 2: checks passed; 54.67 elapsed sec; 73,554 whole-tree tokens v1, repeat 1: checks passed; 132.87 elapsed sec; 412,029 whole-tree tokens v1, repeat 2: checks passed; 148.48 elapsed sec; 455,693 whole-tree tokensSubmitted code · Evidence |
| path-scope | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 213.55 elapsed sec; 755,177 whole-tree tokens baseline, repeat 2: checks passed; 50.60 elapsed sec; 60,227 whole-tree tokens v1, repeat 1: checks passed; 196.50 elapsed sec; 549,890 whole-tree tokens v1, repeat 2: checks passed; 116.83 elapsed sec; 459,808 whole-tree tokensSubmitted code · Evidence |
| interval-subtraction | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 191.77 elapsed sec; 549,595 whole-tree tokens baseline, repeat 2: checks passed; 67.50 elapsed sec; 63,682 whole-tree tokens v1, repeat 1: checks passed; 149.38 elapsed sec; 404,891 whole-tree tokens v1, repeat 2: checks passed; 203.06 elapsed sec; 395,523 whole-tree tokensSubmitted code · Evidence |
| reservation-replay | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 76.32 elapsed sec; 65,104 whole-tree tokens baseline, repeat 2: checks passed; 246.97 elapsed sec; 598,232 whole-tree tokens v1, repeat 1: checks passed; 162.33 elapsed sec; 569,183 whole-tree tokens v1, repeat 2: checks passed; 239.71 elapsed sec; 723,369 whole-tree tokensSubmitted code · Evidence |
| job-lifecycle | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 98.83 elapsed sec; 82,764 whole-tree tokens baseline, repeat 2: checks passed; 122.81 elapsed sec; 91,282 whole-tree tokens v1, repeat 1: checks passed; 209.53 elapsed sec; 557,887 whole-tree tokens v1, repeat 2: checks passed; 213.89 elapsed sec; 586,143 whole-tree tokensSubmitted code · Evidence |
| response-ledger | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 146.34 elapsed sec; 107,904 whole-tree tokens baseline, repeat 2: checks passed; 130.88 elapsed sec; 91,707 whole-tree tokens v1, repeat 1: checks passed; 202.42 elapsed sec; 503,965 whole-tree tokens v1, repeat 2: checks passed; 281.05 elapsed sec; 737,613 whole-tree tokensSubmitted code · Evidence |
| atomic-edits | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 88.09 elapsed sec; 78,464 whole-tree tokens baseline, repeat 2: checks passed; 74.46 elapsed sec; 65,049 whole-tree tokens v1, repeat 1: checks passed; 242.39 elapsed sec; 527,153 whole-tree tokens v1, repeat 2: checks passed; 202.99 elapsed sec; 446,891 whole-tree tokensSubmitted code · Evidence |
| dependency-waves | synthetic function | 2/2 | 2/2 | Measurements and submitted codebaseline, repeat 1: checks passed; 247.07 elapsed sec; 599,862 whole-tree tokens baseline, repeat 2: checks passed; 74.12 elapsed sec; 62,756 whole-tree tokens v1, repeat 1: checks passed; 183.23 elapsed sec; 541,455 whole-tree tokens v1, repeat 2: checks passed; 218.95 elapsed sec; 518,677 whole-tree tokensSubmitted code · Evidence |
Each cell counts attempts passing the primary checks, out of two repetitions. Open a row for time, tokens and code.
Both variants also passed 272 separately authored robustness cases per repetition. Those extra checks add coverage; they do not increase the number of independent task families or change the registered analysis.
On these tasks, the extra process used more effort without an observed gain on the checks. My practical lesson is to test an optional workflow against a baseline before making it routine.
The formal verdict remains inconclusive. Eight selected synthetic families can hit a quality ceiling, and equal pass counts do not establish equivalent quality or show that the skill is never useful.
The strict exposure detector certified a complete skill read in 15 of 16 treatment attempts. A later diagnostic found the exact full skill text in the remaining attempt’s output; the original flag and verdict remain unchanged. Child-prompt boundaries and dollar costs remain unknown.
The separate repository pilot and AI-DLC comparison investigate different task pools. Their observations are not pooled with this study.
Setup. Requested/pinned codex:gpt-6.1-sol, not provider-attested; codex-cli 0.161.0. 2 repetitions per variant, 300-second attempt limit, with delegation allowed under the same frozen profile. Task definitions, checks, exact skill bytes and execution policy were frozen before comparison. Model identity was requested, not independently provider-attested.
Skill SHA-256. da80b2fd13f451fda6467a88825b909dabdc42bd4d1fd2d508a1b42797f7b2e6
Checks. 182 preregistered primary cases; trusted references passed and distinct wrong controls were rejected before agent execution. The later 272 robustness cases used retained submissions with no additional model calls.
This is a presentation revision. All 32 observations, code hashes, measurements and the frozen verdict are preserved. It does not install, remove or reactivate a skill.
All measurements, submitted code, hashes and limitations · Previous presentation · Original report
Original summary, preserved. The report and data contain the qualifications.
All 32 retained synthetic submissions and their hashes. Private actor transcripts are not published.
SHA-256: 92d3798eb37b95fc0185c7732b3d45ad2c2766c843a0efed6ab5722a9140cbec
exports.solve = (rows) => {
if (!Array.isArray(rows)) {
return { ok: false, error: "invalid-input" };
}
const result = [];
const selectedIds = new Set();
for (const row of rows) {
if (row === null || typeof row !== "object" || Array.isArray(row) ||
row.active !== true || typeof row.id !== "string") {
continue;
}
const id = row.id.trim();
if (id.length === 0 || selectedIds.has(id)) {
continue;
}
selectedIds.add(id);
const tags = [];
const selectedTags = new Set();
if (Array.isArray(row.tags)) {
for (const value of row.tags) {
if (typeof value !== "string") {
continue;
}
const tag = value.trim().toLowerCase();
if (tag.length > 0 && !selectedTags.has(tag)) {
selectedTags.add(tag);
tags.push(tag);
}
}
}
result.push({ id, tags });
}
return { ok: true, result };
};
SHA-256: 40463225fcf8d73db644680b4383a4ea84ec2e99700f02659885a5162623856b
exports.solve = function solve(rows) {
if (!Array.isArray(rows)) {
return { ok: false, error: "invalid-input" };
}
const result = [];
const seenIds = new Set();
for (const row of rows) {
if (
row === null ||
typeof row !== "object" ||
Array.isArray(row) ||
row.active !== true ||
typeof row.id !== "string"
) {
continue;
}
const id = row.id.trim();
if (id.length === 0 || seenIds.has(id)) {
continue;
}
seenIds.add(id);
const tags = [];
const seenTags = new Set();
if (Array.isArray(row.tags)) {
for (const tag of row.tags) {
if (typeof tag !== "string") {
continue;
}
const normalized = tag.trim().toLowerCase();
if (normalized.length > 0 && !seenTags.has(normalized)) {
seenTags.add(normalized);
tags.push(normalized);
}
}
}
result.push({ id, tags });
}
return { ok: true, result };
};
SHA-256: c5b7de37e8568dc7af4cbf65d9c4305f22b373f1f280c6e0163bc63db80c718e
exports.solve = function solve(rows) {
if (!Array.isArray(rows)) {
return { ok: false, error: "invalid-input" };
}
const result = [];
const seenIds = new Set();
for (const row of rows) {
if (row === null || typeof row !== "object" || Array.isArray(row)) {
continue;
}
if (row.active !== true || typeof row.id !== "string") {
continue;
}
const id = row.id.trim();
if (id.length === 0 || seenIds.has(id)) {
continue;
}
seenIds.add(id);
const tags = [];
const seenTags = new Set();
if (Array.isArray(row.tags)) {
for (const value of row.tags) {
if (typeof value !== "string") {
continue;
}
const tag = value.trim().toLowerCase();
if (tag.length === 0 || seenTags.has(tag)) {
continue;
}
seenTags.add(tag);
tags.push(tag);
}
}
result.push({ id, tags });
}
return { ok: true, result };
};
SHA-256: ddf393f485a50426c9e99ed8a9f3383ece6ccf8012d94b517656842c9c7a590f
exports.solve = (rows) => {
if (!Array.isArray(rows)) {
return { ok: false, error: 'invalid-input' };
}
const result = [];
const seenIds = new Set();
for (const row of rows) {
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
continue;
}
if (row.active !== true || typeof row.id !== 'string') {
continue;
}
const id = row.id.trim();
if (id === '' || seenIds.has(id)) {
continue;
}
seenIds.add(id);
const tags = [];
const seenTags = new Set();
if (Array.isArray(row.tags)) {
for (const tag of row.tags) {
if (typeof tag !== 'string') {
continue;
}
const normalized = tag.trim().toLowerCase();
if (normalized !== '' && !seenTags.has(normalized)) {
seenTags.add(normalized);
tags.push(normalized);
}
}
}
result.push({ id, tags });
}
return { ok: true, result };
};
SHA-256: 28ffb7498aca0922977f43bc80314f8ac2999c499fe93f798432cfeecf75b9fe
function canonicalize(path) {
if (typeof path !== 'string' || !path.startsWith('/') ||
/[\\\x00-\x1f\x7f]/.test(path)) {
return null;
}
const segments = path.split('/');
const normalized = [];
for (const segment of segments) {
if (segment === '..') return null;
if (segment !== '' && segment !== '.') normalized.push(segment);
}
return '/' + normalized.join('/');
}
exports.solve = function solve(paths, roots) {
if (!Array.isArray(paths) || !Array.isArray(roots)) {
return { ok: false, error: 'invalid-input' };
}
const canonicalRoots = [];
for (let index = 0; index < roots.length; index++) {
const root = canonicalize(roots[index]);
if (root === null) return { ok: false, error: 'invalid-input' };
canonicalRoots.push(root);
}
const result = [];
for (let index = 0; index < paths.length; index++) {
const canonical = canonicalize(paths[index]);
let allowed = false;
if (canonical !== null) {
for (const root of canonicalRoots) {
if (root === '/' || canonical === root || canonical.startsWith(root + '/')) {
allowed = true;
break;
}
}
}
result.push({ index, canonical, allowed });
}
return { ok: true, result };
};
SHA-256: a4e20d1a85b47fab1f0cb7708efc8b2fe2506fa08d1a1de8612f811d70f3f2dd
function canonicalize(path) {
if (typeof path !== 'string' || !path.startsWith('/') ||
/[\\\x00-\x1f\x7f]/.test(path)) {
return null;
}
const segments = path.split('/');
const normalized = [];
for (const segment of segments) {
if (segment === '..') return null;
if (segment !== '' && segment !== '.') normalized.push(segment);
}
return '/' + normalized.join('/');
}
exports.solve = function solve(paths, roots) {
if (!Array.isArray(paths) || !Array.isArray(roots)) {
return { ok: false, error: 'invalid-input' };
}
const normalizedRoots = [];
for (let index = 0; index < roots.length; index += 1) {
const root = canonicalize(roots[index]);
if (root === null) return { ok: false, error: 'invalid-input' };
normalizedRoots.push(root);
}
const result = [];
for (let index = 0; index < paths.length; index += 1) {
const canonical = canonicalize(paths[index]);
const allowed = canonical !== null && normalizedRoots.some(root =>
root === '/' || canonical === root || canonical.startsWith(root + '/')
);
result.push({ index, canonical, allowed });
}
return { ok: true, result };
};
SHA-256: aebdf36c2761fae4780d9b201499192ce24154ec055207e5a46e28d1676e6991
function normalizePath(path) {
if (typeof path !== "string" || !path.startsWith("/") ||
/[\\\u0000-\u001F\u007F]/.test(path)) {
return null;
}
const segments = path.split("/");
if (segments.includes("..")) return null;
return "/" + segments.filter(segment => segment !== "" && segment !== ".").join("/");
}
exports.solve = function solve(paths, roots) {
if (!Array.isArray(paths) || !Array.isArray(roots)) {
return { ok: false, error: "invalid-input" };
}
const normalizedRoots = [];
for (let index = 0; index < roots.length; index += 1) {
const root = normalizePath(roots[index]);
if (root === null) return { ok: false, error: "invalid-input" };
normalizedRoots.push(root);
}
const result = [];
for (let index = 0; index < paths.length; index += 1) {
const canonical = normalizePath(paths[index]);
const allowed = canonical !== null && normalizedRoots.some(root =>
root === "/" || canonical === root || canonical.startsWith(root + "/")
);
result.push({ index, canonical, allowed });
}
return { ok: true, result };
};
SHA-256: f73de7e420a8320044e2cefcf205d09217ee1c03434e1dc744fe691f4baa2ffc
function canonicalize(path) {
if (typeof path !== 'string' || !path.startsWith('/') ||
/[\\\x00-\x1f\x7f]/.test(path)) {
return null;
}
const segments = path.split('/');
const normalized = [];
for (const segment of segments) {
if (segment === '..') return null;
if (segment !== '' && segment !== '.') normalized.push(segment);
}
return '/' + normalized.join('/');
}
exports.solve = function solve(paths, roots) {
if (!Array.isArray(paths) || !Array.isArray(roots)) {
return {ok: false, error: 'invalid-input'};
}
const normalizedRoots = [];
for (let index = 0; index < roots.length; index++) {
const root = canonicalize(roots[index]);
if (root === null) return {ok: false, error: 'invalid-input'};
normalizedRoots.push(root);
}
const result = [];
for (let index = 0; index < paths.length; index++) {
const canonical = canonicalize(paths[index]);
const allowed = canonical !== null && normalizedRoots.some(root =>
root === '/' || canonical === root || canonical.startsWith(root + '/')
);
result.push({index, canonical, allowed});
}
return {ok: true, result};
};
SHA-256: 9553db7c97f95d4d056eb668964efccfca3f1a029429a14760addc99c5db2079
function normalize(intervals) {
const sorted = intervals.map(([start, end]) => [start, end]);
sorted.sort((left, right) => {
if (left[0] !== right[0]) return left[0] < right[0] ? -1 : 1;
if (left[1] === right[1]) return 0;
return left[1] < right[1] ? -1 : 1;
});
const merged = [];
for (const interval of sorted) {
const previous = merged[merged.length - 1];
if (previous && interval[0] <= previous[1]) {
if (interval[1] > previous[1]) previous[1] = interval[1];
} else {
merged.push(interval);
}
}
return merged;
}
function validIntervals(intervals) {
if (!Array.isArray(intervals)) return false;
for (let index = 0; index < intervals.length; index += 1) {
if (!Object.prototype.hasOwnProperty.call(intervals, index)) return false;
const interval = intervals[index];
if (!Array.isArray(interval) || interval.length !== 2 ||
!Object.prototype.hasOwnProperty.call(interval, 0) ||
!Object.prototype.hasOwnProperty.call(interval, 1) ||
!Number.isSafeInteger(interval[0]) ||
!Number.isSafeInteger(interval[1]) || interval[0] >= interval[1]) {
return false;
}
}
return true;
}
exports.solve = function solve(allowed, blocked) {
if (!validIntervals(allowed) || !validIntervals(blocked)) {
return { ok: false, error: 'invalid-input' };
}
const allowedUnion = normalize(allowed);
const blockedUnion = normalize(blocked);
const result = [];
let blockedIndex = 0;
for (const [start, end] of allowedUnion) {
let cursor = start;
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][1] <= cursor) {
blockedIndex += 1;
}
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][0] < end) {
const [blockedStart, blockedEnd] = blockedUnion[blockedIndex];
if (blockedStart > cursor) result.push([cursor, blockedStart]);
if (blockedEnd > cursor) cursor = blockedEnd;
if (cursor >= end) break;
blockedIndex += 1;
}
if (cursor < end) result.push([cursor, end]);
}
return { ok: true, result };
};
SHA-256: c21448857f9c30f8565a7698b144048ff92faaeca7e2b7cd66d437dfdbdd306f
exports.solve = function solve(allowed, blocked) {
function isValid(collection) {
if (!Array.isArray(collection)) return false;
for (let i = 0; i < collection.length; i += 1) {
const interval = collection[i];
if (!Array.isArray(interval) || interval.length !== 2 ||
!Number.isSafeInteger(interval[0]) ||
!Number.isSafeInteger(interval[1]) ||
interval[0] >= interval[1]) return false;
}
return true;
}
if (!isValid(allowed) || !isValid(blocked)) {
return { ok: false, error: 'invalid-input' };
}
function normalize(collection) {
const sorted = collection.map(interval => [interval[0], interval[1]]);
sorted.sort((a, b) => {
if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1;
return 0;
});
const merged = [];
for (const interval of sorted) {
const previous = merged[merged.length - 1];
if (previous && interval[0] <= previous[1]) {
if (interval[1] > previous[1]) previous[1] = interval[1];
} else {
merged.push(interval);
}
}
return merged;
}
const allowedUnion = normalize(allowed);
const blockedUnion = normalize(blocked);
const result = [];
let blockIndex = 0;
for (const [start, end] of allowedUnion) {
let cursor = start;
while (blockIndex < blockedUnion.length &&
blockedUnion[blockIndex][1] <= cursor) {
blockIndex += 1;
}
while (blockIndex < blockedUnion.length && cursor < end) {
const [blockStart, blockEnd] = blockedUnion[blockIndex];
if (blockStart >= end) break;
if (blockStart > cursor) result.push([cursor, blockStart]);
if (blockEnd >= end) {
cursor = end;
break;
}
cursor = blockEnd;
blockIndex += 1;
}
if (cursor < end) result.push([cursor, end]);
}
return { ok: true, result };
};
SHA-256: fa92a5fb6d5098bdc0613206e4452acbf1eed9f64ff5c79439d71c5c0447aeef
exports.solve = function solve(allowed, blocked) {
const valid = (intervals) => {
if (!Array.isArray(intervals)) return false;
for (let i = 0; i < intervals.length; i++) {
if (!Object.prototype.hasOwnProperty.call(intervals, i)) return false;
const interval = intervals[i];
if (!Array.isArray(interval) || interval.length !== 2 ||
!Number.isSafeInteger(interval[0]) ||
!Number.isSafeInteger(interval[1]) || interval[0] >= interval[1]) {
return false;
}
}
return true;
};
if (!valid(allowed) || !valid(blocked)) {
return { ok: false, error: 'invalid-input' };
}
const normalize = (intervals) => {
const sorted = intervals.map(([start, end]) => [start, end]);
sorted.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const merged = [];
for (const interval of sorted) {
const last = merged[merged.length - 1];
if (last && interval[0] <= last[1]) {
last[1] = Math.max(last[1], interval[1]);
} else {
merged.push(interval);
}
}
return merged;
};
const allowedUnion = normalize(allowed);
const blockedUnion = normalize(blocked);
const result = [];
let blockedIndex = 0;
for (const [start, end] of allowedUnion) {
let cursor = start;
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][1] <= cursor) {
blockedIndex++;
}
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][0] < end) {
const [blockStart, blockEnd] = blockedUnion[blockedIndex];
if (blockStart > cursor) result.push([cursor, blockStart]);
cursor = Math.max(cursor, blockEnd);
// Keep a spanning blocker for the next allowed interval.
if (cursor >= end) break;
blockedIndex++;
}
if (cursor < end) result.push([cursor, end]);
}
return { ok: true, result };
};
SHA-256: 5f6b8fc767a2f9b129f83fbfb36ce441aa80f13fe9361e5c44c5e6df41196570
function validIntervals(intervals) {
if (!Array.isArray(intervals)) return false;
for (const interval of intervals) {
if (!Array.isArray(interval) || interval.length !== 2 ||
!Number.isSafeInteger(interval[0]) ||
!Number.isSafeInteger(interval[1]) ||
interval[0] >= interval[1]) {
return false;
}
}
return true;
}
function normalize(intervals) {
const sorted = intervals.map(interval => [interval[0], interval[1]]);
sorted.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
const merged = [];
for (const interval of sorted) {
const previous = merged[merged.length - 1];
if (previous && interval[0] <= previous[1]) {
previous[1] = Math.max(previous[1], interval[1]);
} else {
merged.push(interval);
}
}
return merged;
}
exports.solve = function solve(allowed, blocked) {
if (!validIntervals(allowed) || !validIntervals(blocked)) {
return {ok: false, error: 'invalid-input'};
}
const allowedUnion = normalize(allowed);
const blockedUnion = normalize(blocked);
const result = [];
let blockedIndex = 0;
for (const [start, end] of allowedUnion) {
let cursor = start;
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][1] <= cursor) {
blockedIndex++;
}
while (blockedIndex < blockedUnion.length &&
blockedUnion[blockedIndex][0] < end) {
const [blockStart, blockEnd] = blockedUnion[blockedIndex];
if (blockStart > cursor) result.push([cursor, blockStart]);
cursor = Math.max(cursor, blockEnd);
if (cursor >= end) break;
blockedIndex++;
}
if (cursor < end) result.push([cursor, end]);
}
return {ok: true, result};
};
SHA-256: 79c0fc1f1190e219c1d994cd1fc9f5acf2d6bc6022e512af3f5dcb0d4615afaf
const isObject = value =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const isNonemptyString = value => typeof value === 'string' && value.length > 0;
exports.solve = function solve(initial, requests, limit) {
if (!Array.isArray(initial) || !Array.isArray(requests) ||
!Number.isSafeInteger(limit) || limit < 0 || limit > 9) {
return {ok: false, error: 'invalid-input'};
}
const records = [];
const ledger = new Map();
let admittedCount = 0;
for (const record of initial) {
if (!isObject(record) || !isNonemptyString(record.id) ||
!isNonemptyString(record.fingerprint) ||
(record.status !== 'admitted' && record.status !== 'denied') ||
ledger.has(record.id)) {
return {ok: false, error: 'invalid-input'};
}
const retained = {
id: record.id,
fingerprint: record.fingerprint,
status: record.status
};
records.push(retained);
ledger.set(retained.id, retained);
if (retained.status === 'admitted') admittedCount++;
}
if (admittedCount > limit) return {ok: false, error: 'invalid-input'};
const events = [];
for (let index = 0; index < requests.length; index++) {
const request = requests[index];
if (!isObject(request) || !isNonemptyString(request.id) ||
!isNonemptyString(request.fingerprint)) {
events.push({index, id: null, status: 'invalid', decision: null});
continue;
}
const {id, fingerprint} = request;
const retained = ledger.get(id);
if (retained) {
const recovered = retained.fingerprint === fingerprint;
events.push({
index,
id,
status: recovered ? 'recovered' : 'conflict',
decision: recovered ? retained.status : null
});
continue;
}
const decision = admittedCount < limit ? 'admitted' : 'denied';
const record = {id, fingerprint, status: decision};
records.push(record);
ledger.set(id, record);
if (decision === 'admitted') admittedCount++;
events.push({index, id, status: 'created', decision});
}
return {ok: true, result: {records, admittedCount, events}};
};
SHA-256: fffff4a08b555ce937e4dd73ffaa5170952b3b0300cefaedc35904800c21e6d6
exports.solve = function solve(initial, requests, limit) {
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isNonemptyString = value => typeof value === 'string' && value.length > 0;
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
const invalidInput = () => ({ ok: false, error: 'invalid-input' });
if (!Array.isArray(initial) || !Array.isArray(requests) ||
!Number.isSafeInteger(limit) || limit < 0 || limit > 9) {
return invalidInput();
}
const records = [];
const ledger = new Map();
let admittedCount = 0;
for (let index = 0; index < initial.length; index += 1) {
if (!hasOwn(initial, index)) return invalidInput();
const entry = initial[index];
if (!isObject(entry) || !isNonemptyString(entry.id) ||
!isNonemptyString(entry.fingerprint) ||
(entry.status !== 'admitted' && entry.status !== 'denied') ||
ledger.has(entry.id)) {
return invalidInput();
}
const record = { id: entry.id, fingerprint: entry.fingerprint, status: entry.status };
records.push(record);
ledger.set(record.id, record);
if (record.status === 'admitted') admittedCount += 1;
if (admittedCount > limit) return invalidInput();
}
const events = [];
for (let index = 0; index < requests.length; index += 1) {
const request = hasOwn(requests, index) ? requests[index] : undefined;
if (!isObject(request) || !isNonemptyString(request.id) ||
!isNonemptyString(request.fingerprint)) {
events.push({ index, id: null, status: 'invalid', decision: null });
continue;
}
const { id, fingerprint } = request;
const retained = ledger.get(id);
if (retained !== undefined) {
const identical = retained.fingerprint === fingerprint;
events.push({ index, id, status: identical ? 'recovered' : 'conflict',
decision: identical ? retained.status : null });
continue;
}
const decision = admittedCount < limit ? 'admitted' : 'denied';
const record = { id, fingerprint, status: decision };
ledger.set(id, record);
records.push(record);
if (decision === 'admitted') admittedCount += 1;
events.push({ index, id, status: 'created', decision });
}
return { ok: true, result: { records, admittedCount, events } };
};
SHA-256: 529d38a69238b91e4a4e649174caedf2408f0b627d524323be89a91ed229e412
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isNonemptyString = value => typeof value === 'string' && value.length > 0;
exports.solve = (initial, requests, limit) => {
const invalidInput = () => ({ ok: false, error: 'invalid-input' });
if (!Array.isArray(initial) || !Array.isArray(requests) ||
!Number.isSafeInteger(limit) || limit < 0 || limit > 9) {
return invalidInput();
}
const records = [];
const ledger = new Map();
let admittedCount = 0;
for (const record of initial) {
if (!isObject(record) || !isNonemptyString(record.id) ||
!isNonemptyString(record.fingerprint) ||
(record.status !== 'admitted' && record.status !== 'denied') ||
ledger.has(record.id)) {
return invalidInput();
}
const retained = { id: record.id, fingerprint: record.fingerprint, status: record.status };
records.push(retained);
ledger.set(retained.id, retained);
if (retained.status === 'admitted') admittedCount += 1;
}
if (admittedCount > limit) return invalidInput();
const events = [];
for (let index = 0; index < requests.length; index += 1) {
const request = requests[index];
if (!isObject(request) || !isNonemptyString(request.id) ||
!isNonemptyString(request.fingerprint)) {
events.push({ index, id: null, status: 'invalid', decision: null });
continue;
}
const id = request.id;
const fingerprint = request.fingerprint;
const retained = ledger.get(id);
if (retained !== undefined) {
if (retained.fingerprint === fingerprint) {
events.push({ index, id, status: 'recovered', decision: retained.status });
} else {
events.push({ index, id, status: 'conflict', decision: null });
}
continue;
}
const decision = admittedCount < limit ? 'admitted' : 'denied';
const record = { id, fingerprint, status: decision };
records.push(record);
ledger.set(id, record);
if (decision === 'admitted') admittedCount += 1;
events.push({ index, id, status: 'created', decision });
}
return { ok: true, result: { records, admittedCount, events } };
};
SHA-256: f040e56d5f711ad87f6405d4d27cecacc07f0c61a939ee242f2023d3b197d928
exports.solve = function solve(initial, requests, limit) {
const isObject = value => value !== null && typeof value === "object" && !Array.isArray(value);
const isNonemptyString = value => typeof value === "string" && value.length > 0;
const invalidInput = () => ({ ok: false, error: "invalid-input" });
if (!Array.isArray(initial) || !Array.isArray(requests) ||
!Number.isSafeInteger(limit) || limit < 0 || limit > 9) {
return invalidInput();
}
const ledger = new Map();
const records = [];
let admittedCount = 0;
for (let index = 0; index < initial.length; index++) {
if (!Object.prototype.hasOwnProperty.call(initial, index)) return invalidInput();
const record = initial[index];
if (!isObject(record) || !isNonemptyString(record.id) ||
!isNonemptyString(record.fingerprint) ||
(record.status !== "admitted" && record.status !== "denied") ||
ledger.has(record.id)) {
return invalidInput();
}
const retained = { id: record.id, fingerprint: record.fingerprint, status: record.status };
ledger.set(retained.id, retained);
records.push(retained);
if (retained.status === "admitted") admittedCount++;
}
if (admittedCount > limit) return invalidInput();
const events = [];
for (let index = 0; index < requests.length; index++) {
const request = Object.prototype.hasOwnProperty.call(requests, index) ? requests[index] : undefined;
if (!isObject(request) || !isNonemptyString(request.id) || !isNonemptyString(request.fingerprint)) {
events.push({ index, id: null, status: "invalid", decision: null });
continue;
}
const id = request.id;
const fingerprint = request.fingerprint;
const retained = ledger.get(id);
if (retained) {
if (retained.fingerprint === fingerprint) {
events.push({ index, id, status: "recovered", decision: retained.status });
} else {
events.push({ index, id, status: "conflict", decision: null });
}
continue;
}
const decision = admittedCount < limit ? "admitted" : "denied";
const record = { id, fingerprint, status: decision };
ledger.set(id, record);
records.push(record);
if (decision === "admitted") admittedCount++;
events.push({ index, id, status: "created", decision });
}
return { ok: true, result: { records, admittedCount, events } };
};
SHA-256: fe8d971ecd55e3b827380d6d10d8bf5d898cafe238a8dd0d468265583750e7a1
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isLease = value => typeof value === 'string' && value.length > 0;
const isVersion = value => Number.isSafeInteger(value) && value >= 0;
function validJob(job) {
if (!isObject(job) || !isVersion(job.version) ||
!Number.isSafeInteger(job.progress) || job.progress < 0 || job.progress > 100) {
return false;
}
switch (job.state) {
case 'pending': return job.lease === null && job.progress === 0;
case 'running': return isLease(job.lease) && job.progress < 100;
case 'completed': return job.lease === null && job.progress === 100;
case 'failed':
case 'cancelled': return job.lease === null && job.progress < 100;
default: return false;
}
}
function validEvent(event) {
if (!isObject(event) || !isVersion(event.version)) return false;
switch (event.kind) {
case 'claim':
case 'complete':
case 'fail': return isLease(event.lease);
case 'progress':
return isLease(event.lease) && Number.isSafeInteger(event.value) &&
event.value >= 0 && event.value <= 99;
case 'cancel':
return !('lease' in event) || event.lease === null || isLease(event.lease);
default: return false;
}
}
exports.solve = function solve(job, events) {
if (!validJob(job) || !Array.isArray(events)) {
return { ok: false, error: 'invalid-input' };
}
const current = {
state: job.state,
lease: job.lease,
progress: job.progress,
version: job.version
};
const outcomes = [];
for (const event of events) {
if (!validEvent(event)) {
outcomes.push('invalid');
continue;
}
if (event.version <= current.version) {
outcomes.push('stale');
continue;
}
const applicable = event.kind === 'claim'
? current.state === 'pending'
: event.kind === 'cancel'
? current.state === 'pending' || current.state === 'running'
: current.state === 'running';
if (!applicable) {
outcomes.push('inapplicable');
continue;
}
if (event.kind !== 'claim') {
const leaseMatches = current.state === 'running'
? event.lease === current.lease
: !('lease' in event) || event.lease === null;
if (!leaseMatches) {
outcomes.push('foreign-lease');
continue;
}
}
switch (event.kind) {
case 'claim':
current.state = 'running';
current.lease = event.lease;
current.progress = 0;
break;
case 'progress':
current.progress = Math.max(current.progress, event.value);
break;
case 'complete':
current.state = 'completed';
current.progress = 100;
current.lease = null;
break;
case 'fail':
current.state = 'failed';
current.lease = null;
break;
case 'cancel':
current.state = 'cancelled';
current.lease = null;
break;
}
current.version = event.version;
outcomes.push('updated');
}
return { ok: true, result: { job: current, outcomes } };
};
SHA-256: c0860f26fdf4d3945e979f82c831b81eca3ad850fcdecfefe279eec826f4b025
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isLease = value => typeof value === 'string' && value.length > 0;
const isVersion = value => Number.isSafeInteger(value) && value >= 0;
exports.solve = function solve(job, events) {
if (!isObject(job) || !Array.isArray(events)) {
return { ok: false, error: 'invalid-input' };
}
let { state, lease, progress, version } = job;
if (!Number.isSafeInteger(progress) || progress < 0 || progress > 100 || !isVersion(version)) {
return { ok: false, error: 'invalid-input' };
}
switch (state) {
case 'pending':
if (lease !== null || progress !== 0) return { ok: false, error: 'invalid-input' };
break;
case 'running':
if (!isLease(lease) || progress >= 100) return { ok: false, error: 'invalid-input' };
break;
case 'completed':
if (lease !== null || progress !== 100) return { ok: false, error: 'invalid-input' };
break;
case 'failed':
case 'cancelled':
if (lease !== null || progress >= 100) return { ok: false, error: 'invalid-input' };
break;
default:
return { ok: false, error: 'invalid-input' };
}
const outcomes = [];
for (const event of events) {
if (!isObject(event) || !isVersion(event.version)) {
outcomes.push('invalid');
continue;
}
const kind = event.kind;
const hasLease = 'lease' in event;
const eventLease = hasLease ? event.lease : null;
const knownKind = kind === 'claim' || kind === 'progress' || kind === 'complete' ||
kind === 'fail' || kind === 'cancel';
if (!knownKind ||
(kind === 'cancel' ? eventLease !== null && !isLease(eventLease) : !isLease(eventLease)) ||
(kind === 'progress' && (!Number.isSafeInteger(event.value) || event.value < 0 || event.value > 99))) {
outcomes.push('invalid');
continue;
}
if (event.version <= version) {
outcomes.push('stale');
continue;
}
const applicable = kind === 'claim' ? state === 'pending' :
kind === 'cancel' ? state === 'pending' || state === 'running' : state === 'running';
if (!applicable) {
outcomes.push('inapplicable');
continue;
}
if (kind !== 'claim' && eventLease !== lease) {
outcomes.push('foreign-lease');
continue;
}
switch (kind) {
case 'claim':
state = 'running';
lease = eventLease;
progress = 0;
break;
case 'progress':
progress = Math.max(progress, event.value);
break;
case 'complete':
state = 'completed';
lease = null;
progress = 100;
break;
case 'fail':
case 'cancel':
state = kind === 'fail' ? 'failed' : 'cancelled';
lease = null;
break;
}
version = event.version;
outcomes.push('updated');
}
return { ok: true, result: { job: { state, lease, progress, version }, outcomes } };
};
SHA-256: 1d0dcb92c87a322b6a689d7862e15a2dbccc2e4b89a7e571288f0cec9fab28ab
'use strict';
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isLease = value => typeof value === 'string' && value.length > 0;
const isVersion = value => Number.isSafeInteger(value) && value >= 0;
exports.solve = function solve(job, events) {
if (!isObject(job) || !Array.isArray(events) ||
!isVersion(job.version) || !Number.isSafeInteger(job.progress) ||
job.progress < 0 || job.progress > 100) {
return {ok: false, error: 'invalid-input'};
}
let validJob = false;
switch (job.state) {
case 'pending':
validJob = job.lease === null && job.progress === 0;
break;
case 'running':
validJob = isLease(job.lease) && job.progress < 100;
break;
case 'completed':
validJob = job.lease === null && job.progress === 100;
break;
case 'failed':
case 'cancelled':
validJob = job.lease === null && job.progress < 100;
break;
}
if (!validJob) return {ok: false, error: 'invalid-input'};
const current = {
state: job.state,
lease: job.lease,
progress: job.progress,
version: job.version
};
const outcomes = [];
for (const event of events) {
if (!isObject(event) || !isVersion(event.version)) {
outcomes.push('invalid');
continue;
}
const kind = event.kind;
const lease = 'lease' in event ? event.lease : null;
let validEvent = false;
switch (kind) {
case 'claim':
case 'complete':
case 'fail':
validEvent = isLease(lease);
break;
case 'progress':
validEvent = isLease(lease) && Number.isSafeInteger(event.value) &&
event.value >= 0 && event.value <= 99;
break;
case 'cancel':
validEvent = lease === null || isLease(lease);
break;
}
if (!validEvent) {
outcomes.push('invalid');
continue;
}
if (event.version <= current.version) {
outcomes.push('stale');
continue;
}
const applicable = kind === 'claim' ? current.state === 'pending' :
kind === 'cancel' ? current.state === 'pending' || current.state === 'running' :
current.state === 'running';
if (!applicable) {
outcomes.push('inapplicable');
continue;
}
if (kind !== 'claim' && lease !== current.lease) {
outcomes.push('foreign-lease');
continue;
}
switch (kind) {
case 'claim':
current.state = 'running';
current.lease = lease;
current.progress = 0;
break;
case 'progress':
current.progress = Math.max(current.progress, event.value);
break;
case 'complete':
current.state = 'completed';
current.progress = 100;
current.lease = null;
break;
case 'fail':
current.state = 'failed';
current.lease = null;
break;
case 'cancel':
current.state = 'cancelled';
current.lease = null;
break;
}
current.version = event.version;
outcomes.push('updated');
}
return {ok: true, result: {job: current, outcomes}};
};
SHA-256: f0450d7d115fa64026b5ae18b8726aa91e531bf151a6454f3acc8891843e770c
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isNonemptyString = value => typeof value === 'string' && value.length > 0;
const isVersion = value => Number.isSafeInteger(value) && value >= 0;
function isValidJob(job) {
if (!isObject(job) || !isVersion(job.version) ||
!Number.isSafeInteger(job.progress) || job.progress < 0 || job.progress > 100) {
return false;
}
switch (job.state) {
case 'pending':
return job.lease === null && job.progress === 0;
case 'running':
return isNonemptyString(job.lease) && job.progress < 100;
case 'completed':
return job.lease === null && job.progress === 100;
case 'failed':
case 'cancelled':
return job.lease === null && job.progress < 100;
default:
return false;
}
}
function isValidEvent(event) {
if (!isObject(event) || !isVersion(event.version)) return false;
switch (event.kind) {
case 'progress':
return isNonemptyString(event.lease) && Number.isSafeInteger(event.value) &&
event.value >= 0 && event.value <= 99;
case 'claim':
case 'complete':
case 'fail':
return isNonemptyString(event.lease);
case 'cancel':
return !('lease' in event) || event.lease === null || isNonemptyString(event.lease);
default:
return false;
}
}
exports.solve = function solve(job, events) {
if (!isValidJob(job) || !Array.isArray(events)) {
return { ok: false, error: 'invalid-input' };
}
const current = {
state: job.state,
lease: job.lease,
progress: job.progress,
version: job.version
};
const outcomes = [];
for (let index = 0; index < events.length; index += 1) {
const event = events[index];
if (!isValidEvent(event)) {
outcomes.push('invalid');
continue;
}
if (event.version <= current.version) {
outcomes.push('stale');
continue;
}
const applicable = event.kind === 'claim'
? current.state === 'pending'
: event.kind === 'cancel'
? current.state === 'pending' || current.state === 'running'
: current.state === 'running';
if (!applicable) {
outcomes.push('inapplicable');
continue;
}
if (event.kind !== 'claim') {
const leaseMatches = current.state === 'pending'
? !('lease' in event) || event.lease === null
: event.lease === current.lease;
if (!leaseMatches) {
outcomes.push('foreign-lease');
continue;
}
}
switch (event.kind) {
case 'claim':
current.state = 'running';
current.lease = event.lease;
current.progress = 0;
break;
case 'progress':
current.progress = Math.max(current.progress, event.value);
break;
case 'complete':
current.state = 'completed';
current.lease = null;
current.progress = 100;
break;
case 'fail':
current.state = 'failed';
current.lease = null;
break;
case 'cancel':
current.state = 'cancelled';
current.lease = null;
break;
}
current.version = event.version;
outcomes.push('updated');
}
return { ok: true, result: { job: current, outcomes } };
};
SHA-256: 8240c276ab123f97540a2ecf5f21ccd19831914c329d297b4c38c453747603f8
exports.solve = function solve(records, rootId, rootTurnId) {
const fail = (error) => ({ ok: false, error });
const isObject = (value) =>
value !== null && typeof value === "object" && !Array.isArray(value);
const isId = (value) => typeof value === "string" && value.length > 0;
const counters = [
"input_tokens",
"cached_input_tokens",
"cache_write_input_tokens",
"output_tokens",
"reasoning_output_tokens",
"total_tokens",
];
const zeroUsage = () => ({
input_tokens: 0,
cached_input_tokens: 0,
cache_write_input_tokens: 0,
output_tokens: 0,
reasoning_output_tokens: 0,
total_tokens: 0,
});
if (!Array.isArray(records) || !isId(rootId) || !isId(rootTurnId)) {
return fail("invalid-input");
}
// Validate ownership and owned IDs everywhere before inspecting usage.
const owned = [];
for (const record of records) {
if (!isObject(record) || !isId(record.sessionId) || !isId(record.rootTurnId)) {
return fail("invalid-input");
}
if (record.sessionId !== rootId || record.rootTurnId !== rootTurnId) continue;
if (!isId(record.threadId) || !isId(record.responseId)) {
return fail("invalid-input");
}
owned.push(record);
}
const validated = [];
for (const record of owned) {
if (!isObject(record.usage)) return fail("invalid-usage");
const usage = zeroUsage();
for (const counter of counters) {
const value = record.usage[counter];
if (!Number.isSafeInteger(value) || value < 0) return fail("invalid-usage");
usage[counter] = value;
}
if (
usage.total_tokens !== usage.input_tokens + usage.output_tokens ||
usage.cached_input_tokens > usage.input_tokens ||
usage.cache_write_input_tokens > usage.input_tokens ||
usage.reasoning_output_tokens > usage.output_tokens
) {
return fail("invalid-usage");
}
validated.push({ threadId: record.threadId, responseId: record.responseId, usage });
}
// Resolve all conflicts before aggregation can report overflow.
const responses = new Map();
for (const record of validated) {
const previous = responses.get(record.responseId);
if (previous) {
if (
previous.threadId !== record.threadId ||
counters.some((counter) => previous.usage[counter] !== record.usage[counter])
) {
return fail("conflicting-response");
}
} else {
responses.set(record.responseId, record);
}
}
const usage = zeroUsage();
const byThread = new Map();
for (const record of responses.values()) {
let threadUsage = byThread.get(record.threadId);
if (!threadUsage) {
threadUsage = zeroUsage();
byThread.set(record.threadId, threadUsage);
}
for (const counter of counters) {
const total = usage[counter] + record.usage[counter];
const threadTotal = threadUsage[counter] + record.usage[counter];
if (!Number.isSafeInteger(total) || !Number.isSafeInteger(threadTotal)) {
return fail("invalid-usage");
}
usage[counter] = total;
threadUsage[counter] = threadTotal;
}
}
if (responses.size > 0 && !byThread.has(rootId)) return fail("missing-root");
const threads = Array.from(byThread.keys())
.sort()
.map((id) => ({ id, usage: byThread.get(id) }));
return { ok: true, result: { usage, threads, responseCount: responses.size } };
};
SHA-256: 30ef6145f0859a2dfdaf580d8011e6b312404ad2b68fc6c353f21cd603de2972
const COUNTERS = [
"input_tokens",
"cached_input_tokens",
"cache_write_input_tokens",
"output_tokens",
"reasoning_output_tokens",
"total_tokens",
];
const isObject = (value) =>
value !== null && typeof value === "object" && !Array.isArray(value);
const isId = (value) => typeof value === "string" && value.length > 0;
const zeroUsage = () => Object.fromEntries(COUNTERS.map((key) => [key, 0]));
const failure = (error) => ({ ok: false, error });
exports.solve = (records, rootId, rootTurnId) => {
if (!Array.isArray(records) || !isId(rootId) || !isId(rootTurnId)) {
return failure("invalid-input");
}
// Complete structural validation before inspecting any owned usage.
const owned = [];
for (const record of records) {
if (!isObject(record) || !isId(record.sessionId) || !isId(record.rootTurnId)) {
return failure("invalid-input");
}
if (record.sessionId !== rootId || record.rootTurnId !== rootTurnId) continue;
if (!isId(record.threadId) || !isId(record.responseId)) {
return failure("invalid-input");
}
owned.push(record);
}
for (const record of owned) {
const usage = record.usage;
if (!isObject(usage)) return failure("invalid-usage");
for (const key of COUNTERS) {
if (!Number.isSafeInteger(usage[key]) || usage[key] < 0) {
return failure("invalid-usage");
}
}
if (
usage.total_tokens !== usage.input_tokens + usage.output_tokens ||
usage.cached_input_tokens > usage.input_tokens ||
usage.cache_write_input_tokens > usage.input_tokens ||
usage.reasoning_output_tokens > usage.output_tokens
) {
return failure("invalid-usage");
}
}
// Maps make every response and thread ID an ordinary string key.
const responses = new Map();
for (const record of owned) {
const previous = responses.get(record.responseId);
if (previous) {
if (
previous.threadId !== record.threadId ||
COUNTERS.some((key) => previous.usage[key] !== record.usage[key])
) {
return failure("conflicting-response");
}
} else {
responses.set(record.responseId, record);
}
}
const usage = zeroUsage();
const threadUsage = new Map();
for (const record of responses.values()) {
let thread = threadUsage.get(record.threadId);
if (!thread) {
thread = zeroUsage();
threadUsage.set(record.threadId, thread);
}
for (const key of COUNTERS) {
const globalSum = usage[key] + record.usage[key];
const threadSum = thread[key] + record.usage[key];
if (!Number.isSafeInteger(globalSum) || !Number.isSafeInteger(threadSum)) {
return failure("invalid-usage");
}
usage[key] = globalSum;
thread[key] = threadSum;
}
}
if (responses.size > 0 && !threadUsage.has(rootId)) {
return failure("missing-root");
}
const threads = Array.from(threadUsage, ([id, usage]) => ({ id, usage }));
threads.sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
return { ok: true, result: { usage, threads, responseCount: responses.size } };
};
SHA-256: 1239e2248ea0765ff607c878796ed83a23c0e49f2237f5d2558d05b28c925e7d
const COUNTERS = [
'input_tokens',
'cached_input_tokens',
'cache_write_input_tokens',
'output_tokens',
'reasoning_output_tokens',
'total_tokens',
];
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isId = value => typeof value === 'string' && value.length > 0;
const failure = error => ({ ok: false, error });
const zeroUsage = () => Object.fromEntries(COUNTERS.map(counter => [counter, 0]));
exports.solve = function solve(records, rootId, rootTurnId) {
if (!Array.isArray(records) || !isId(rootId) || !isId(rootTurnId)) {
return failure('invalid-input');
}
// Complete identity validation before looking at any owned usage.
const owned = [];
for (const record of records) {
if (!isObject(record) || !isId(record.sessionId) || !isId(record.rootTurnId)) {
return failure('invalid-input');
}
if (record.sessionId !== rootId || record.rootTurnId !== rootTurnId) continue;
if (!isId(record.threadId) || !isId(record.responseId)) {
return failure('invalid-input');
}
owned.push(record);
}
const validated = [];
for (const record of owned) {
if (!isObject(record.usage)) return failure('invalid-usage');
const usage = {};
for (const counter of COUNTERS) {
const value = record.usage[counter];
if (!Number.isSafeInteger(value) || value < 0) return failure('invalid-usage');
usage[counter] = value;
}
if (
usage.total_tokens !== usage.input_tokens + usage.output_tokens ||
usage.cached_input_tokens > usage.input_tokens ||
usage.cache_write_input_tokens > usage.input_tokens ||
usage.reasoning_output_tokens > usage.output_tokens
) {
return failure('invalid-usage');
}
validated.push({ threadId: record.threadId, responseId: record.responseId, usage });
}
// IDs are map keys, including names that also occur on Object.prototype.
const responses = new Map();
for (const record of validated) {
const prior = responses.get(record.responseId);
if (prior) {
if (
prior.threadId !== record.threadId ||
COUNTERS.some(counter => prior.usage[counter] !== record.usage[counter])
) {
return failure('conflicting-response');
}
} else {
responses.set(record.responseId, record);
}
}
const usage = zeroUsage();
const threads = new Map();
for (const record of responses.values()) {
let threadUsage = threads.get(record.threadId);
if (!threadUsage) {
threadUsage = zeroUsage();
threads.set(record.threadId, threadUsage);
}
for (const counter of COUNTERS) {
const aggregate = usage[counter] + record.usage[counter];
const threadAggregate = threadUsage[counter] + record.usage[counter];
if (!Number.isSafeInteger(aggregate) || !Number.isSafeInteger(threadAggregate)) {
return failure('invalid-usage');
}
usage[counter] = aggregate;
threadUsage[counter] = threadAggregate;
}
}
if (responses.size > 0 && !threads.has(rootId)) return failure('missing-root');
return {
ok: true,
result: {
usage,
threads: Array.from(threads.keys()).sort().map(id => ({ id, usage: threads.get(id) })),
responseCount: responses.size,
},
};
};
SHA-256: 5bd297e661baeaa526e02d22a2b6258dd94bc3e285873553cdd9ae42d9ff7c6e
const counters = [
'input_tokens',
'cached_input_tokens',
'cache_write_input_tokens',
'output_tokens',
'reasoning_output_tokens',
'total_tokens',
];
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const isId = value => typeof value === 'string' && value.length > 0;
const failure = error => ({ ok: false, error });
const zeroUsage = () => ({
input_tokens: 0,
cached_input_tokens: 0,
cache_write_input_tokens: 0,
output_tokens: 0,
reasoning_output_tokens: 0,
total_tokens: 0,
});
exports.solve = function solve(records, rootId, rootTurnId) {
if (!Array.isArray(records) || !isId(rootId) || !isId(rootTurnId)) {
return failure('invalid-input');
}
// Check every ownership and owned-ID field before inspecting any usage.
const owned = [];
for (const record of records) {
if (!isObject(record) || !isId(record.sessionId) || !isId(record.rootTurnId)) {
return failure('invalid-input');
}
if (record.sessionId !== rootId || record.rootTurnId !== rootTurnId) continue;
if (!isId(record.threadId) || !isId(record.responseId)) return failure('invalid-input');
owned.push(record);
}
// Copy only declared counters so extra fields cannot affect replay equality.
const validated = [];
for (const record of owned) {
if (!isObject(record.usage)) return failure('invalid-usage');
const usage = zeroUsage();
for (const counter of counters) {
const value = record.usage[counter];
if (!Number.isSafeInteger(value) || value < 0) return failure('invalid-usage');
usage[counter] = value;
}
if (
usage.total_tokens !== usage.input_tokens + usage.output_tokens ||
usage.cached_input_tokens > usage.input_tokens ||
usage.cache_write_input_tokens > usage.input_tokens ||
usage.reasoning_output_tokens > usage.output_tokens
) {
return failure('invalid-usage');
}
validated.push({ threadId: record.threadId, responseId: record.responseId, usage });
}
// Resolve all conflicts before sums, even if an earlier response would overflow.
const responses = new Map();
for (const record of validated) {
const previous = responses.get(record.responseId);
if (previous) {
if (
previous.threadId !== record.threadId ||
counters.some(counter => previous.usage[counter] !== record.usage[counter])
) {
return failure('conflicting-response');
}
} else {
responses.set(record.responseId, record);
}
}
const usage = zeroUsage();
const threads = new Map();
for (const record of responses.values()) {
let threadUsage = threads.get(record.threadId);
if (!threadUsage) {
threadUsage = zeroUsage();
threads.set(record.threadId, threadUsage);
}
for (const counter of counters) {
const aggregate = usage[counter] + record.usage[counter];
const threadAggregate = threadUsage[counter] + record.usage[counter];
if (!Number.isSafeInteger(aggregate) || !Number.isSafeInteger(threadAggregate)) {
return failure('invalid-usage');
}
usage[counter] = aggregate;
threadUsage[counter] = threadAggregate;
}
}
if (responses.size > 0 && !threads.has(rootId)) return failure('missing-root');
return {
ok: true,
result: {
usage,
threads: Array.from(threads.keys()).sort().map(id => ({ id, usage: threads.get(id) })),
responseCount: responses.size,
},
};
};
SHA-256: 24b79050b0ffbc01be7374834a1d98f53ddbd3b040f6bed56c7d3f189bb5b468
'use strict';
exports.solve = function solve(source, edits) {
if (typeof source !== 'string' || !Array.isArray(edits)) {
return { ok: false, error: 'invalid-input' };
}
function splitsSurrogatePair(offset) {
if (offset === 0 || offset === source.length) return false;
const left = source.charCodeAt(offset - 1);
const right = source.charCodeAt(offset);
return left >= 0xd800 && left <= 0xdbff && right >= 0xdc00 && right <= 0xdfff;
}
const validated = [];
for (let index = 0; index < edits.length; index += 1) {
const edit = edits[index];
if (edit === null || typeof edit !== 'object' || Array.isArray(edit)) {
return { ok: false, error: 'invalid-input' };
}
const { start, end, text, expected } = edit;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
start < 0 || start > end || end > source.length ||
typeof text !== 'string' || typeof expected !== 'string' ||
splitsSurrogatePair(start) || splitsSurrogatePair(end)) {
return { ok: false, error: 'invalid-input' };
}
validated.push({ start, end, text, expected, index });
}
for (const edit of validated) {
if (source.slice(edit.start, edit.end) !== edit.expected) {
return { ok: false, error: 'stale-edit' };
}
}
// At a shared offset, insertions precede the replacement beginning there.
validated.sort((a, b) => a.start - b.start ||
Number(a.start !== a.end) - Number(b.start !== b.end) || a.index - b.index);
let previousReplacement = null;
for (const edit of validated) {
if (previousReplacement !== null && edit.start < previousReplacement.end) {
return { ok: false, error: 'overlap' };
}
if (edit.start !== edit.end) previousReplacement = edit;
}
const pieces = [];
let cursor = 0;
for (const edit of validated) {
pieces.push(source.slice(cursor, edit.start), edit.text);
cursor = edit.end;
}
pieces.push(source.slice(cursor));
return { ok: true, result: pieces.join('') };
};
SHA-256: e2a9332b5a3a4ec6506494db6e7462f581932f62b1b7c43b0003274c2231b35f
exports.solve = function solve(source, edits) {
if (typeof source !== 'string' || !Array.isArray(edits)) {
return {ok: false, error: 'invalid-input'};
}
function splitsSurrogatePair(offset) {
if (offset === 0 || offset === source.length) return false;
const before = source.charCodeAt(offset - 1);
const after = source.charCodeAt(offset);
return before >= 0xD800 && before <= 0xDBFF &&
after >= 0xDC00 && after <= 0xDFFF;
}
const validated = [];
for (let index = 0; index < edits.length; index++) {
const edit = edits[index];
if (edit === null || typeof edit !== 'object' || Array.isArray(edit)) {
return {ok: false, error: 'invalid-input'};
}
const {start, end, text, expected} = edit;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
start < 0 || start > end || end > source.length ||
typeof text !== 'string' || typeof expected !== 'string' ||
splitsSurrogatePair(start) || splitsSurrogatePair(end)) {
return {ok: false, error: 'invalid-input'};
}
validated.push({start, end, text, expected, index});
}
for (const edit of validated) {
if (edit.expected !== source.slice(edit.start, edit.end)) {
return {ok: false, error: 'stale-edit'};
}
}
// Insertions sort before a replacement at the same start, in input order.
validated.sort((a, b) => a.start - b.start || a.end - b.end || a.index - b.index);
let replacementEnd = 0;
for (const edit of validated) {
if (edit.start < replacementEnd) {
return {ok: false, error: 'overlap'};
}
if (edit.start !== edit.end) replacementEnd = edit.end;
}
const pieces = [];
let cursor = 0;
for (const edit of validated) {
pieces.push(source.slice(cursor, edit.start), edit.text);
cursor = edit.end;
}
pieces.push(source.slice(cursor));
return {ok: true, result: pieces.join('')};
};
SHA-256: 27100198df010686f961ee25b0bc7dc9f3377613ebe4ae046d88acbec147c641
exports.solve = function solve(source, edits) {
if (typeof source !== "string" || !Array.isArray(edits)) {
return { ok: false, error: "invalid-input" };
}
// Offsets are UTF-16 code units, but may not divide a surrogate pair.
function splitsPair(offset) {
if (offset === 0 || offset === source.length) return false;
const before = source.charCodeAt(offset - 1);
const after = source.charCodeAt(offset);
return before >= 0xd800 && before <= 0xdbff &&
after >= 0xdc00 && after <= 0xdfff;
}
const ordered = [];
for (let index = 0; index < edits.length; index += 1) {
const edit = edits[index];
if (edit === null || typeof edit !== "object" || Array.isArray(edit)) {
return { ok: false, error: "invalid-input" };
}
const { start, end, text, expected } = edit;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
start < 0 || start > end || end > source.length ||
typeof text !== "string" || typeof expected !== "string" ||
splitsPair(start) || splitsPair(end)) {
return { ok: false, error: "invalid-input" };
}
ordered.push({ start, end, text, expected, index });
}
for (const edit of ordered) {
if (edit.expected !== source.slice(edit.start, edit.end)) {
return { ok: false, error: "stale-edit" };
}
}
// Insertions precede replacements at the same start. The input index
// breaks ties so multiple insertions at one offset preserve their order.
ordered.sort((a, b) => a.start - b.start || a.end - b.end || a.index - b.index);
let replacementEnd = -1;
for (const edit of ordered) {
if (edit.start < replacementEnd) {
return { ok: false, error: "overlap" };
}
if (edit.start < edit.end) replacementEnd = edit.end;
}
// Application starts only after every validation phase has succeeded.
const pieces = [];
let cursor = 0;
for (const edit of ordered) {
pieces.push(source.slice(cursor, edit.start), edit.text);
cursor = edit.end;
}
pieces.push(source.slice(cursor));
return { ok: true, result: pieces.join("") };
};
SHA-256: 323969d3067c542c06a69b2f9992fb6a0713057efdb86f6cb3564a196f51ba0e
exports.solve = function solve(source, edits) {
const invalid = () => ({ ok: false, error: 'invalid-input' });
if (typeof source !== 'string' || !Array.isArray(edits)) return invalid();
// Offsets are UTF-16 units, but an edit must keep each surrogate pair whole.
const splitsPair = (offset) => {
if (offset === 0 || offset === source.length) return false;
const before = source.charCodeAt(offset - 1);
const after = source.charCodeAt(offset);
return before >= 0xd800 && before <= 0xdbff &&
after >= 0xdc00 && after <= 0xdfff;
};
const validated = [];
for (let index = 0; index < edits.length; index += 1) {
const edit = edits[index];
if (edit === null || typeof edit !== 'object' || Array.isArray(edit)) {
return invalid();
}
const { start, end, text, expected } = edit;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) ||
start < 0 || start > end || end > source.length ||
typeof text !== 'string' || typeof expected !== 'string' ||
splitsPair(start) || splitsPair(end)) {
return invalid();
}
validated.push({ start, end, text, expected, index });
}
// Every edit is validated before checking expectations or conflicts.
for (const edit of validated) {
if (source.slice(edit.start, edit.end) !== edit.expected) {
return { ok: false, error: 'stale-edit' };
}
}
validated.sort((left, right) => {
if (left.start !== right.start) return left.start - right.start;
const leftInsertion = left.start === left.end;
const rightInsertion = right.start === right.end;
if (leftInsertion !== rightInsertion) return leftInsertion ? -1 : 1;
return left.index - right.index;
});
let replacementEnd = 0;
for (const edit of validated) {
if (edit.start < replacementEnd) return { ok: false, error: 'overlap' };
if (edit.start !== edit.end) replacementEnd = edit.end;
}
const pieces = [];
let cursor = 0;
for (const edit of validated) {
pieces.push(source.slice(cursor, edit.start), edit.text);
cursor = edit.end;
}
pieces.push(source.slice(cursor));
return { ok: true, result: pieces.join('') };
};
SHA-256: 85002f90e917167a35ad1b7d89b4d2f93efd03ea27099c816f2e8cbbbe59eb61
exports.solve = function solve(nodes, concurrency) {
const fail = (error) => ({ ok: false, error });
const isNonemptyString = (value) =>
typeof value === "string" && value.length > 0;
if (!Array.isArray(nodes) ||
!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 3) {
return fail("invalid-input");
}
// Validate every node before checking any graph-level error.
for (const node of nodes) {
if (node === null || typeof node !== "object" || Array.isArray(node) ||
!isNonemptyString(node.id) || !Array.isArray(node.deps) ||
!Number.isSafeInteger(node.priority)) {
return fail("invalid-input");
}
for (const dependency of node.deps) {
if (!isNonemptyString(dependency)) return fail("invalid-input");
}
}
const pending = new Map();
for (const node of nodes) {
if (pending.has(node.id)) return fail("duplicate-id");
pending.set(node.id, {
id: node.id,
deps: new Set(node.deps),
priority: node.priority,
});
}
for (const node of pending.values()) {
for (const dependency of node.deps) {
if (!pending.has(dependency)) return fail("unknown-dependency");
}
}
const finished = new Set();
const waves = [];
while (pending.size > 0) {
const eligible = [];
for (const node of pending.values()) {
let ready = true;
for (const dependency of node.deps) {
if (!finished.has(dependency)) {
ready = false;
break;
}
}
if (ready) eligible.push(node);
}
if (eligible.length === 0) return fail("cycle");
eligible.sort((a, b) => {
if (a.priority !== b.priority) return a.priority > b.priority ? -1 : 1;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
const wave = eligible.slice(0, concurrency).map((node) => node.id);
waves.push(wave);
for (const id of wave) {
pending.delete(id);
finished.add(id);
}
}
return { ok: true, result: waves };
};
SHA-256: fd29e59f7b45aa1353e4f4d2a12132dc94e276dd1c65ee7c024820a6d26ec360
exports.solve = function solve(nodes, concurrency) {
const invalid = () => ({ ok: false, error: 'invalid-input' });
const isNonemptyString = (value) => typeof value === 'string' && value.length > 0;
if (!Array.isArray(nodes) || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 3) {
return invalid();
}
// Finish structural validation before checking any graph relationships.
for (const node of nodes) {
if (node === null || typeof node !== 'object' || Array.isArray(node) ||
!isNonemptyString(node.id) || !Array.isArray(node.deps) ||
!Number.isSafeInteger(node.priority)) {
return invalid();
}
for (const dependency of node.deps) {
if (!isNonemptyString(dependency)) return invalid();
}
}
const pending = new Map();
for (const node of nodes) {
if (pending.has(node.id)) return { ok: false, error: 'duplicate-id' };
pending.set(node.id, { id: node.id, deps: new Set(node.deps), priority: node.priority });
}
for (const node of pending.values()) {
for (const dependency of node.deps) {
if (!pending.has(dependency)) return { ok: false, error: 'unknown-dependency' };
}
}
const finished = new Set();
const waves = [];
while (pending.size > 0) {
const eligible = [];
for (const node of pending.values()) {
let ready = true;
for (const dependency of node.deps) {
if (!finished.has(dependency)) {
ready = false;
break;
}
}
if (ready) eligible.push(node);
}
if (eligible.length === 0) return { ok: false, error: 'cycle' };
eligible.sort((left, right) => {
if (left.priority !== right.priority) return left.priority > right.priority ? -1 : 1;
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
});
const wave = eligible.slice(0, concurrency).map((node) => node.id);
waves.push(wave);
for (const id of wave) {
pending.delete(id);
finished.add(id);
}
}
return { ok: true, result: waves };
};
SHA-256: 2f726c9faa0dd5de05ae0768f90e6dad35f0bc1012402566857194c58a05952e
exports.solve = function solve(nodes, concurrency) {
if (!Array.isArray(nodes) || !Number.isSafeInteger(concurrency) ||
concurrency < 1 || concurrency > 3) {
return { ok: false, error: 'invalid-input' };
}
// Finish structural validation before checking any graph-level errors.
const records = [];
for (const node of nodes) {
if (node === null || typeof node !== 'object' || Array.isArray(node) ||
typeof node.id !== 'string' || node.id.length === 0 ||
!Array.isArray(node.deps) || !Number.isSafeInteger(node.priority)) {
return { ok: false, error: 'invalid-input' };
}
for (const dependency of node.deps) {
if (typeof dependency !== 'string' || dependency.length === 0) {
return { ok: false, error: 'invalid-input' };
}
}
records.push({ id: node.id, deps: new Set(node.deps), priority: node.priority });
}
const byId = new Map();
for (const record of records) {
if (byId.has(record.id)) {
return { ok: false, error: 'duplicate-id' };
}
byId.set(record.id, record);
}
for (const record of records) {
for (const dependency of record.deps) {
if (!byId.has(dependency)) {
return { ok: false, error: 'unknown-dependency' };
}
}
}
const remaining = new Map();
const dependents = new Map();
for (const record of records) {
remaining.set(record.id, record.deps.size);
dependents.set(record.id, []);
}
for (const record of records) {
for (const dependency of record.deps) {
dependents.get(dependency).push(record);
}
}
const ready = records.filter(record => record.deps.size === 0);
const result = [];
let completed = 0;
while (completed < records.length) {
if (ready.length === 0) {
return { ok: false, error: 'cycle' };
}
ready.sort((a, b) => {
if (a.priority !== b.priority) {
return a.priority > b.priority ? -1 : 1;
}
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
const wave = ready.splice(0, concurrency);
result.push(wave.map(record => record.id));
completed += wave.length;
// Only release dependents after the entire wave has been selected.
for (const record of wave) {
for (const dependent of dependents.get(record.id)) {
const count = remaining.get(dependent.id) - 1;
remaining.set(dependent.id, count);
if (count === 0) ready.push(dependent);
}
}
}
return { ok: true, result };
};
SHA-256: 0e4ab6a96f9eda3c1f3952b5a71d2aed7148471b522db827f10d15b7fc415acf
exports.solve = function solve(nodes, concurrency) {
const fail = (error) => ({ ok: false, error });
if (!Array.isArray(nodes) || !Number.isSafeInteger(concurrency) ||
concurrency < 1 || concurrency > 3) {
return fail('invalid-input');
}
// Validate every node before checking any graph-level errors.
const tasks = [];
for (const node of nodes) {
if (node === null || typeof node !== 'object' || Array.isArray(node) ||
typeof node.id !== 'string' || node.id.length === 0 ||
!Array.isArray(node.deps) || !Number.isSafeInteger(node.priority)) {
return fail('invalid-input');
}
const deps = new Set();
for (const dep of node.deps) {
if (typeof dep !== 'string' || dep.length === 0) {
return fail('invalid-input');
}
deps.add(dep);
}
tasks.push({ id: node.id, priority: node.priority, deps,
remaining: deps.size, dependents: [] });
}
const byId = new Map();
for (const task of tasks) {
if (byId.has(task.id)) return fail('duplicate-id');
byId.set(task.id, task);
}
for (const task of tasks) {
for (const dep of task.deps) {
if (!byId.has(dep)) return fail('unknown-dependency');
byId.get(dep).dependents.push(task);
}
}
const eligible = tasks.filter((task) => task.remaining === 0);
const waves = [];
let completed = 0;
while (eligible.length > 0) {
eligible.sort((a, b) => {
if (a.priority !== b.priority) return a.priority > b.priority ? -1 : 1;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
const wave = eligible.splice(0, concurrency);
waves.push(wave.map((task) => task.id));
completed += wave.length;
// Only release dependents after selecting the entire wave.
for (const task of wave) {
for (const dependent of task.dependents) {
dependent.remaining -= 1;
if (dependent.remaining === 0) eligible.push(dependent);
}
}
}
if (completed !== tasks.length) return fail('cycle');
return { ok: true, result: waves };
};