Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
8 changes: 4 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ different pointer, so every branch move and promotion dragged a diff.
Reference *clones* are gitignored: they are third-party source carrying their
own licenses and have no business in this repository's history.

Nothing in the build, typecheck, or test path reads from `devlog/`, so a
contributor who ignores it entirely still passes every gate. `privacy:scan` does
read it — that is deliberate, and it is what makes a public devlog safe rather
than merely visible.
Build and typecheck do not read `devlog/`. The test-layout membership oracle reads
`devlog/_fin/260905_test_modularization_and_windows/001_test_inventory.md`; sparse
checkouts running that test must materialize this tracked input. `privacy:scan`
also reads `devlog/` to keep public development notes safe to publish.

Two mechanical guards in `tests/ci-workflows/repo-hygiene.test.ts` back this up: no `160000`
gitlink may be tracked anywhere, and neither the vendored reference clones nor
Expand Down
4 changes: 2 additions & 2 deletions tests/claude-integration/messages-error-contracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ test("C1/C2 ingress constructors have explicit producer rows and local identity"
for (const path of new Bun.Glob("src/**/*.ts").scanSync(repoRoot())) {
const source = readFileSync(repoPath(path), "utf8");
const calls = [...source.matchAll(/new AnthropicRequestError\(/g)];
if (calls.length) actual[path] = calls.length;
if (calls.length) actual[path.replaceAll("\\", "/")] = calls.length;
for (const call of calls) expect(source.slice(0, call.index).endsWith("markProxyError(")).toBe(true);
}
expect(actual).toEqual(Object.fromEntries(ingressProducerRows.map(([path, count]) => [path, count])));
Expand All @@ -173,7 +173,7 @@ test("W1/W3 envelope writers are covered by explicit dispositions", () => {
for (const path of new Bun.Glob("src/**/*.ts").scanSync(repoRoot())) {
const lines = readFileSync(repoPath(path), "utf8").split("\n");
const count = lines.filter(line => /anthropicError(Response|Body)\(/.test(line)).length;
if (count) actual[path] = count;
if (count) actual[path.replaceAll("\\", "/")] = count;
}
expect(actual).toEqual(Object.fromEntries(envelopeWriterRows.map(([path, count]) => [path, count])));
const bypassRows = [
Expand Down
1 change: 1 addition & 0 deletions tests/claude-integration/messages-proxy-refusals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ for (const kind of ["kiro-continuation", "config", "workflow-unbound", "pool-ref
console.info(`REFUSAL_STATUS ${kind} ${result.status} ${result.code}`);
expect(result.text.length).toBeGreaterThan(0);
expect([result.status, result.code]).toEqual(expected[kind]!);
if (kind === "native-pacing-preflight") expect(result.nativePacingPreflightObserved).toBe(true);
if (kind === "kiro-continuation") {
expect(result.fetched).toBe(1); expect(result.text).not.toContain(result.absent);
const error = result.text.split("\n").filter((line: string) => line.startsWith("data: ")).map((line: string) => JSON.parse(line.slice(6))).find((row: any) => row.type === "error");
Expand Down
11 changes: 10 additions & 1 deletion tests/config/config-ownership-concurrent-record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,16 @@ describe("concurrent first registrations on an absent home (#8093)", () => {
"import { recordOwnedConfigPath } from " + JSON.stringify(modulePath) + ";",
"writeFileSync(" + JSON.stringify(join(signals, rel + ".ready")) + ", \"\");",
"const until = Date.now() + " + BARRIER_MS + "; while (!existsSync(" + JSON.stringify(go) + ") && Date.now() < until) Bun.sleepSync(2);",
"process.exit(recordOwnedConfigPath(" + JSON.stringify(dir) + ", " + JSON.stringify(join(dir, rel)) + ") ? 0 : 2);",
// Match the bounded caller retry used by childScript above.
"let code = 1;",
"for (let attempt = 0; attempt < 400; attempt++) {",
" try { code = recordOwnedConfigPath(" + JSON.stringify(dir) + ", " + JSON.stringify(join(dir, rel)) + ") ? 0 : 2; break; }",
" catch (error) {",
" if (error && error.code === \"CONFIG_OWNERSHIP_LOCK_UNAVAILABLE\") { Bun.sleepSync(5); continue; }",
" console.error(error); break;",
" }",
"}",
"process.exit(code);",
].join("\n");
const children = names.map(name => Bun.spawn([process.execPath, "-e", script(name)], { stderr: "inherit" }));
const deadline = Date.now() + BARRIER_MS;
Expand Down
9 changes: 7 additions & 2 deletions tests/helpers/messages-overflow-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ export async function observeMessagesOverflowBody(response: Response, lane: Mess
return { text, bodySha256, bodyLength };
}

export async function runMessagesOverflowCase(lane: MessagesOverflowLane, fixture: MessagesOverflowFixture) {
/** A slice may lend its real spend owner; single-case callers retain their own lease. */
export async function runMessagesOverflowCase(
lane: MessagesOverflowLane,
fixture: MessagesOverflowFixture,
acquireSpendHome: () => () => void = acquireOwnedSpendHome,
) {
const tail = (fixture.messageStop || fixture.id.startsWith("frame-complete-")) ? 'event: message_stop\ndata: {"type":"message_stop"}\n\n' : "";
const prefix = fixture.prefix ? `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: fixture.prefix } })}\n\nevent: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n` : "";
const error = { ...(fixture.type ? { type: fixture.type } : {}), ...(fixture.status !== undefined ? { status: fixture.status } : {}), message: `${fixture.message} ${overflowSentinel}`, ...(fixture.code !== undefined ? { code: fixture.code } : {}) };
Expand Down Expand Up @@ -112,7 +117,7 @@ export async function runMessagesOverflowCase(lane: MessagesOverflowLane, fixtur
} else {
const passthrough = lane === "passthrough" || lane === "count_tokens";
const native = lane.startsWith("native");
release = acquireOwnedSpendHome(); clearKeyCooldowns();
release = acquireSpendHome(); clearKeyCooldowns();
const builtin = lane === "native-fold-builtin";
const nativeFold = lane === "native-fold" || builtin;
const reply = () => {
Expand Down
67 changes: 40 additions & 27 deletions tests/helpers/messages-overflow-differential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ function replaceOnce(source: string, needle: string, replacement: string): strin
} });
}
const { runMessagesOverflowCase } = await import("./messages-overflow-case");
const { acquireOwnedSpendHome } = await import("./owned-spend-home");
const { upstreamMessagesRequestIdHeaders } = await import("../../src/server/messages-response-headers");
if (base && upstreamMessagesRequestIdHeaders(new Headers({ "request-id": "req_fixture" }))["request-id"] !== "req_fixture") throw new Error("Baseline modules were not loaded");
const rows = [];
Expand All @@ -80,35 +81,47 @@ function intern<T>(values: T[], value: T): number {
if (index >= 0) return index;
return values.push(value) - 1;
}
for (const lane of messagesOverflowLanes.filter(lane => !selectedLane || lane === selectedLane)) for (const input of applicableMessagesOverflowFixtures(lane).slice(first, first + count)) {
const observations = new Map<string, boolean[]>();
(globalThis as any).__messagesOverflowRecord = (tag: string, value: boolean) => {
const values = observations.get(tag) ?? []; values.push(value); observations.set(tag, values);
return value;
};
if (input.fault) process.stderr.write(`fixture ${lane}/${input.id}\n`);
const result = await runMessagesOverflowCase(lane, input);
const passthrough = lane === "passthrough" || lane === "count_tokens";
if (!passthrough && input.rawBody === undefined && !input.fault && !input.localBranch && observations.size === 0) throw new Error(`Missing baseline observation for ${lane}/${input.id}`);
const internalDecisions: Record<string, boolean> = {};
for (const [tag, values] of observations) {
if (values.some(value => value !== values[0])) throw new Error(`Inconsistent ${tag} decisions for ${lane}/${input.id}`);
internalDecisions[tag] = values[0]!;
}
if (base) {
const id = messagesOverflowCaseId(lane, input);
if (Object.hasOwn(outcomes, id)) throw new Error(`Duplicate case id: ${lane}/${input.id}`);
// Outcome-only tuples keep the base fixture small; dictionaries retain exact compared values.
const outcome: unknown[] = [messagesOverflowLanes.indexOf(lane), result.status, result.clientRecognizes,
intern(decisions, internalDecisions), input.classification[lane], intern(types, result.type ?? null),
intern(codes, result.code ?? null), intern(mediaTypes, result.mediaType), result.clientError];
if (input.classification[lane] === "success" || input.fixedLocal) {
outcome.push(result.bodySha256, result.bodyLength);
// A real server owns its spend home for its lifetime. Keep that same ownership
// across this sequential slice, avoiding a full journal replay for every row.
// Pure encoder lanes never acquire a lease; single-case helpers keep their default.
let releaseSpendHome: (() => void) | undefined;
const acquireSliceSpendHome = () => {
releaseSpendHome ??= acquireOwnedSpendHome();
return () => {}; // Borrowed by the row; the slice's finally owns release.
};
try {
for (const lane of messagesOverflowLanes.filter(lane => !selectedLane || lane === selectedLane)) for (const input of applicableMessagesOverflowFixtures(lane).slice(first, first + count)) {
const observations = new Map<string, boolean[]>();
(globalThis as any).__messagesOverflowRecord = (tag: string, value: boolean) => {
const values = observations.get(tag) ?? []; values.push(value); observations.set(tag, values);
return value;
};
if (input.fault) process.stderr.write(`fixture ${lane}/${input.id}\n`);
const result = await runMessagesOverflowCase(lane, input, acquireSliceSpendHome);
const passthrough = lane === "passthrough" || lane === "count_tokens";
if (!passthrough && input.rawBody === undefined && !input.fault && !input.localBranch && observations.size === 0) throw new Error(`Missing baseline observation for ${lane}/${input.id}`);
const internalDecisions: Record<string, boolean> = {};
for (const [tag, values] of observations) {
if (values.some(value => value !== values[0])) throw new Error(`Inconsistent ${tag} decisions for ${lane}/${input.id}`);
internalDecisions[tag] = values[0]!;
}
outcomes[id] = outcome;
} else rows.push({ lane, input, head: { ...result, internalDecisions } });
if (base) {
const id = messagesOverflowCaseId(lane, input);
if (Object.hasOwn(outcomes, id)) throw new Error(`Duplicate case id: ${lane}/${input.id}`);
// Outcome-only tuples keep the base fixture small; dictionaries retain exact compared values.
const outcome: unknown[] = [messagesOverflowLanes.indexOf(lane), result.status, result.clientRecognizes,
intern(decisions, internalDecisions), input.classification[lane], intern(types, result.type ?? null),
intern(codes, result.code ?? null), intern(mediaTypes, result.mediaType), result.clientError];
if (input.classification[lane] === "success" || input.fixedLocal) {
outcome.push(result.bodySha256, result.bodyLength);
}
outcomes[id] = outcome;
} else rows.push({ lane, input, head: { ...result, internalDecisions } });
}
} finally {
delete (globalThis as any).__messagesOverflowRecord;
releaseSpendHome?.();
}
delete (globalThis as any).__messagesOverflowRecord;
if (base) {
const header = { schemaVersion: 8, baseCommit: "72e80d280d614bdf4f1aada9b233f6732404afec", caseTableSha256: messagesOverflowCaseTableHash(),
columns: ["lane", "status", "clientRecognizes", "decisions", "class", "type", "code", "mediaType", "clientError", "bodySha256?", "bodyLength?"],
Expand Down
15 changes: 10 additions & 5 deletions tests/helpers/messages-proxy-refusal-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,23 @@ function readOriginal(path: string): string {
const exported = process.env.MESSAGES_RED_SOURCE && join(process.env.MESSAGES_RED_SOURCE, relative(repoPath(), path));
return readFileSync(exported && existsSync(exported) ? exported : path, "utf8");
}
function replaceOnce(path: string, anchor: string, replacement: string): string {
const source = readOriginal(path);
if (source.split(anchor).length !== 2) throw new Error("Messages refusal fixture anchor changed");
return source.replace(anchor, replacement);
}
if (process.env.MESSAGES_RED_SOURCE) {
const paths = [...new Bun.Glob("src/**/*.ts").scanSync(process.env.MESSAGES_RED_SOURCE)].filter(path => !path.endsWith("server/claude-messages.ts") && !path.endsWith("claude/failure-verdict.ts"));
const paths = [...new Bun.Glob("src/**/*.ts").scanSync(process.env.MESSAGES_RED_SOURCE)].filter(path => !["server/claude-messages.ts", "claude/failure-verdict.ts"].some(excluded => path.replaceAll("\\", "/").endsWith(excluded)));
const filter = new RegExp("^(?:" + paths.map(path => repoPath(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|") + ")$");
Bun.plugin({ name: "935199a98 red source", setup(build) {
build.onLoad({ filter }, ({ path }) => ({ contents: readOriginal(path), loader: "ts" }));
} });
}
const kind = process.argv[2]!;
Bun.plugin({ name: "Messages refusal boundary fixture", setup(build) {
build.onLoad({ filter: /src\/server\/claude-messages\.ts$/ }, ({ path }) => ({ contents: readOriginal(path).replace("const upstream = await handleResponses(internalReq, {", "const upstream = globalThis.__localRefusalReply ?? await handleResponses(internalReq, {"), loader: "ts" }));
build.onLoad({ filter: /src\/server\/messages-native\.ts$/ }, ({ path }) => ({ contents: readOriginal(path).replace("const proactiveKeyProvider = selectProactiveApiKeyTransport(config, route.providerName, route.provider);", "const proactiveKeyProvider = globalThis.__nativePacingPreflight ? (() => { throw globalThis.__nativePacingPreflight; })() : selectProactiveApiKeyTransport(config, route.providerName, route.provider);"), loader: "ts" }));
build.onLoad({ filter: /src\/claude\/failure-verdict\.ts$/ }, ({ path }) => ({ contents: readOriginal(path).replace(" if (sink) (sink.delivered", " if (sink) (globalThis.__observedSinks ??= []).push(sink);\n if (sink) (sink.delivered"), loader: "ts" }));
build.onLoad({ filter: /src[\\/]server[\\/]claude-messages\.ts$/ }, ({ path }) => ({ contents: replaceOnce(path, "const upstream = await handleResponses(internalReq, {", "const upstream = globalThis.__localRefusalReply ?? await handleResponses(internalReq, {"), loader: "ts" }));
build.onLoad({ filter: /src[\\/]server[\\/]messages-native\.ts$/ }, ({ path }) => ({ contents: replaceOnce(path, "const proactiveKeyProvider = selectProactiveApiKeyTransport(config, route.providerName, route.provider);", "const proactiveKeyProvider = globalThis.__nativePacingPreflight ? (() => { globalThis.__nativePacingPreflightObserved = true; throw globalThis.__nativePacingPreflight; })() : selectProactiveApiKeyTransport(config, route.providerName, route.provider);"), loader: "ts" }));
build.onLoad({ filter: /src[\\/]claude[\\/]failure-verdict\.ts$/ }, ({ path }) => ({ contents: replaceOnce(path, " if (sink) (sink.delivered", " if (sink) (globalThis.__observedSinks ??= []).push(sink);\n if (sink) (sink.delivered"), loader: "ts" }));
} });
const { handleClaudeMessages, handleClaudeCountTokens } = await import("../../src/server/claude-messages");
const { markProxyError } = await import("../../src/lib/client-error-body");
Expand Down Expand Up @@ -165,4 +170,4 @@ const direct = kind === "sink-direct" ? await (async () => {
const chat = kind === "chat-roster" ? await (await import("../../src/server/chat-completions")).handleChatCompletions(new Request("http://localhost/v1/chat/completions", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model, messages: [{ role: "user", content: "fixture" }], stream: false }) }), config, logCtx) : undefined;
const response = chat ?? direct ?? (["roster-count", "body-overflow-count"].includes(kind) ? await handleClaudeCountTokens(req, config) : await handleClaudeMessages(req, config, logCtx, kind === "scope-direct" ? { requestId: crypto.randomUUID(), start: Date.now(), admission: { kind: "configured", keyId: "scoped", source: "bearer" } } : undefined));
const text = await response.text();
console.log("REFUSAL_RESULT " + JSON.stringify({ status: response.status, text, absent, code: kind.startsWith("sink") ? null : JSON.parse(text).error?.code ?? null, retained: [...new Set((globalThis as any).__observedSinks ?? [])].reduce((n: number, sink: any) => n + (sink.delivered?.length ?? 0), 0), expectedBody, copilotCalls: (globalThis as any).__copilotCalls, usage: logCtx.usage }));
console.log("REFUSAL_RESULT " + JSON.stringify({ status: response.status, text, absent, code: kind.startsWith("sink") ? null : JSON.parse(text).error?.code ?? null, retained: [...new Set((globalThis as any).__observedSinks ?? [])].reduce((n: number, sink: any) => n + (sink.delivered?.length ?? 0), 0), expectedBody, copilotCalls: (globalThis as any).__copilotCalls, usage: logCtx.usage, nativePacingPreflightObserved: (globalThis as any).__nativePacingPreflightObserved === true }));
2 changes: 1 addition & 1 deletion tests/helpers/messages-sse-workflow-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
const detail = process.argv[2];
// Refuse at the existing native spend gate, using its own exception and catch path.
Bun.plugin({ name: "native spend denial fixture", setup(build) {
build.onLoad({ filter: /src\/server\/messages-native\.ts$/ }, ({ path }) => {
build.onLoad({ filter: /src[\\/]server[\\/]messages-native\.ts$/ }, ({ path }) => {
const source = readFileSync(path, "utf8");
const anchor = "if (!physicalBudget.spendEnforced && !spendTracker.charge()) throw new NativeMessagesSpendRefusal();";
if (source.split(anchor).length !== 2) throw new Error("Native spend gate changed");
Expand Down
Loading