Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ def parse_args(description: str) -> argparse.Namespace:
recipe = register_cli_scan.add_mutually_exclusive_group(required=True)
recipe.add_argument("--recipe-json")
recipe.add_argument("--recipe-json-stdin", action="store_true")
recipe.add_argument("--registration-json-stdin", action="store_true")
Comment thread
ianw-oai marked this conversation as resolved.
register_cli_scan.add_argument("--parent-scan-id")
register_cli_scan.add_argument("--archive-existing", action="store_true")
register_cli_scan.add_argument("--archived-scan-dir")
Expand Down
11 changes: 9 additions & 2 deletions sdk/typescript/_bundled_plugin/scripts/workbench_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1605,7 +1605,13 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
if next(scan_dir.iterdir(), None) is not None:
raise SystemExit("The scan artifact directory must be empty before the scan starts.")

recipe_json = sys.stdin.read() if args.recipe_json_stdin else args.recipe_json
user_context = None
if args.registration_json_stdin:
registration = json.load(sys.stdin)
recipe_json = json.dumps(registration["recipe"], ensure_ascii=False, separators=(",", ":"))
user_context = registration.get("userContext")
Comment thread
ianw-oai marked this conversation as resolved.
else:
recipe_json = sys.stdin.read() if args.recipe_json_stdin else args.recipe_json
recipe = parse_scan_recipe(recipe_json, repository)
requested_target = recipe["target"]
paths = requested_target["paths"]
Expand Down Expand Up @@ -1691,10 +1697,11 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
scan_dir=scan_dir,
)
connection.execute(
"UPDATE scans SET recipe_json = ?, parent_scan_id = ? WHERE id = ?",
"UPDATE scans SET recipe_json = ?, parent_scan_id = ?, user_context = ? WHERE id = ?",
(
json.dumps(recipe, allow_nan=False, separators=(",", ":"), sort_keys=True),
parent_scan_id,
user_context,
scan_id,
),
)
Expand Down
4 changes: 2 additions & 2 deletions sdk/typescript/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ export class CodexSecurity {
repo,
"--scan-dir",
scanDir,
"--recipe-json-stdin",
"--registration-json-stdin",
...(options.archiveExisting === true ? ["--archive-existing"] : []),
...(archivedScanDir === null
? []
Expand All @@ -767,7 +767,7 @@ export class CodexSecurity {
? []
: ["--parent-scan-id", options.parentScanId]),
],
JSON.stringify(recipe),
JSON.stringify({ recipe, userContext: options.scanPrompt }),
);
const scanId = registration["scanId"];
const targetId = registration["targetId"];
Expand Down
23 changes: 16 additions & 7 deletions sdk/typescript/tests-ts/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ describe("CodexSecurity orchestration", () => {
input?: string,
): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
recipe = JSON.parse(input!);
recipe = JSON.parse(input!).recipe;
}
return mockWorkbench(args, input);
},
Expand Down Expand Up @@ -1080,7 +1080,7 @@ describe("CodexSecurity orchestration", () => {
input?: string,
): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
savedRecipe = JSON.parse(input!);
savedRecipe = JSON.parse(input!).recipe;
}
return mockWorkbench(args, input);
},
Expand Down Expand Up @@ -1980,8 +1980,11 @@ describe("CodexSecurity orchestration", () => {
"Additional scan instructions:\nFocus on authentication and authorization.",
);
expect(followUpPrompt).toBe("Draft fixes for confirmed findings.");
expect(commands[0]).toContain("--recipe-json-stdin");
expect(JSON.parse(registrationInput!)).toMatchObject({
expect(commands[0]).toContain("--registration-json-stdin");
expect(JSON.parse(registrationInput!).userContext).toBe(
"Focus on authentication and authorization.",
);
expect(JSON.parse(registrationInput!).recipe).toMatchObject({
repository,
target: { kind: "repository", paths: [] },
mode: "standard",
Expand Down Expand Up @@ -2128,7 +2131,8 @@ describe("CodexSecurity orchestration", () => {
falsePositives: [],
};
}
recipe = JSON.parse(input!);
expect(JSON.parse(input!).userContext).toBeUndefined();
recipe = JSON.parse(input!).recipe;
return mockScanRegistration(args, input);
},
createCodex: () => ({
Expand Down Expand Up @@ -3847,6 +3851,7 @@ describe("CodexSecurity orchestration", () => {
});

test("provides authoritative knowledge-base context without retaining its documents", async () => {
const scanPrompt = "Review the synthetic authorization boundary.";
const root = await temporaryDirectory();
const repository = join(root, "repository");
const codexHome = join(root, "codex-home");
Expand Down Expand Up @@ -3883,7 +3888,8 @@ describe("CodexSecurity orchestration", () => {
};
}
if (args[0] !== "register-cli-scan") return {};
recipe = JSON.parse(input!);
expect(JSON.parse(input!).userContext).toBe(scanPrompt);
recipe = JSON.parse(input!).recipe;
return mockScanRegistration(args, input);
},
createCodex: (options: CodexOptions) => ({
Expand All @@ -3906,7 +3912,10 @@ describe("CodexSecurity orchestration", () => {
);

await expect(
client.run(repository, { knowledgeBasePaths: [knowledgeBase] }),
client.run(repository, {
knowledgeBasePaths: [knowledgeBase],
scanPrompt,
}),
).resolves.toMatchObject({ threadId: "thread-1" });
expect(existsSync(knowledgeDirectory)).toBe(false);
expect(prompt).toContain(
Expand Down
99 changes: 98 additions & 1 deletion sdk/typescript/tests-ts/deep-scan-workbench.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { runWorkbench } from "../src/runtime.js";
import { loadBundledRuntime, PLUGIN_ROOT } from "./plugin-root.js";

const originalClaimToken = "22222222-2222-4222-8222-222222222222";
const replacementClaimToken = "33333333-3333-4333-8333-333333333333";
Expand Down Expand Up @@ -186,6 +187,102 @@ test("recovers an interrupted copied Deep Scan publication", async () => {
});
});

test.each([
["supplied", " Review café authentication.\r\n\t"],
["absent", undefined],
["large", " --café\r\n".repeat(30_000)],
] as const)(
"preserves %s scan instructions from registration through the Deep worker prompt",
async (_label, scanPrompt) => {
const root = await realpath(
await mkdtemp(join(tmpdir(), "codex-security-deep-context-")),
);
temporaryDirectories.push(root);
const repository = join(root, "repository");
const scanDir = join(root, "scan");
await mkdir(repository);
await mkdir(scanDir, { mode: 0o700 });
await writeFile(join(repository, "source.py"), "# synthetic source\n");
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
const command = (args: string[], input?: string) =>
runWorkbench(
{
python: python!,
pluginRoot: PLUGIN_ROOT,
environment: {
...process.env,
CODEX_SECURITY_STATE_DIR: join(root, "state"),
CODEX_HOME: join(root, "codex-home"),
},
},
args,
input,
);
const registration = await command(
[
"register-cli-scan",
"--repository",
repository,
"--scan-dir",
scanDir,
"--registration-json-stdin",
],
JSON.stringify({
recipe: {
config: {
developer_instructions: "Synthetic context. ".repeat(4_000),
},
mode: "deep",
repository,
target: { kind: "repository", paths: [] },
},
userContext: scanPrompt,
}),
);
const scanId = registration["scanId"] as string;
const context = await command(["get-scan", "--scan-id", scanId]);
expect(context["scan"]).toMatchObject({ userContext: scanPrompt ?? null });

const begun = await command([
"begin-deep-scan",
"--scan-id",
scanId,
"--thread-id",
"synthetic-thread",
"--scan-root",
join(root, "scans"),
"--available-parallelism",
"4",
"--workflow-version",
"deep-scan-mcp/v1",
]);
const deepScan = begun["deepScan"] as Record<string, unknown>;

const templates =
/\/\/ templates\/deep-scan\/discovery\.md\n([\s\S]*?)\/\/ src\/deep-scan\/worker-runner\.ts/u.exec(
await loadBundledRuntime(),
)?.[1];
expect(templates).toBeDefined();
const renderDiscoveryPrompt = new Function(
`${templates}\nreturn renderDiscoveryPrompt;`,
)() as (input: Record<string, unknown>) => string;
const prompt = renderDiscoveryPrompt({
...deepScan,
pluginRoot: PLUGIN_ROOT,
workerLabel: "synthetic-worker",
subagents: 0,
});
const workerContext = JSON.parse(
/```json\n([\s\S]*?)\n```/u.exec(prompt)![1]!,
);
expect(workerContext).toMatchObject({
scanId,
userContext: scanPrompt ?? null,
});
},
);

describe("deep scan workbench ownership", () => {
test("starts a Deep Scan with oversized stdin user context", async () => {
const root = await realpath(
Expand Down
6 changes: 3 additions & 3 deletions sdk/typescript/tests-ts/support/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ export function mockScanRegistration(
args: readonly string[],
input?: string,
): JsonObject {
if (!args.includes("--recipe-json-stdin") || input === undefined) {
throw new Error("missing stdin scan recipe");
if (!args.includes("--registration-json-stdin") || input === undefined) {
throw new Error("missing stdin scan registration");
}
const recipe = JSON.parse(input) as {
const recipe = JSON.parse(input).recipe as {
repositoryRevision?: string;
target: { kind: string };
};
Expand Down
Loading