/cso searches the whole repository in one call with a hard time limit (GST-3588) (#4742)

/cso can now search every file in a repository with one helper call,
which stops at a hard time limit, and a daily report.md lists its
low-confidence hypotheses.

Why: audits that started never reached the vulnerable file because each
file took its own helper call inside a 10-minute budget
(gstack-evals#443).

Nothing to do: the next `/cso` run uses it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-23 14:12:15 +00:00
1 parent 45b48f17d9
commit a3ecfd530d
9 files changed
+254 -18

No files matched your search

@@ -0,0 +1 @@
**/cso can search the whole repository in one call, and a daily report now lists its low-confidence hypotheses.** Audits that started used up their 10-minute budget reading one file per helper call, so most files were never read. The new `gstack-cso search <run> <regex>` runs one regular expression over every file in the snapshot. It stops at a hard 60-second limit, even on a pattern that never finishes, prints the matches found so far, and lists the files it did not search (the first 50 by name, then a count). The skill now pages the file list 500 paths at a time, and `report.md` lists daily hypotheses under "Hypotheses (unconfirmed)".
+4 -3
View File
@@ -73,6 +73,7 @@ gstack-cso recheck <finding> --repo <repo> [--run <original-run>]
gstack-cso inspect <run>
gstack-cso read <run> <path-or-handle>
gstack-cso history <run> [path-or-handle]
gstack-cso search <run> <regex> [--seconds N]
gstack-cso scan <run> <scanner> [request.json]
gstack-cso scanner-outcome <run> <artifact-id>
gstack-cso import-sarif <run> <results.sarif>
@@ -90,9 +91,9 @@ gstack-cso inspect-v2 <import-id>
**One-run invariant.** Invoke `start` exactly once per run and reuse the same ID. A refused `start` (`"ok":false`) holds no run: apply the one correction it names and start again; for the 64 MiB cap, `du -s` the top level and pass at most 32 `--paths` prefixes (1024 characters) covering the source, leaving out vendored, generated, fixture and media trees. Once a `start` returns a run ID, never call `start` again.
**Audited-source access invariant.** After `start`, inspect source only with that run's `inspect`, `read`, and `history`. Pass the exact `path` from `inspect`; `displayPath` is only a redacted label. Never use host `Read`/`Glob`/`Grep`; direct reads bypass redaction and identity.
**Audited-source access invariant.** After `start`, inspect source only with that run's `inspect`, `read`, `search`, and `history`. Pass the exact `path` from `inspect`; `displayPath` is only a redacted label. Never use host `Read`/`Glob`/`Grep`; direct reads bypass redaction and identity.
**Read the whole inventory.** Save `start` and `inspect` output to private files (removed after `finish`); read the run ID with `jq -r .runId`, never through `head` or `tail`. Check readiness, deadline, and coverage; `jq -r '.manifest.entries[].path'` lists every file. Then read in full every attacker-reachable file: parsers, decoders, serializers, path, URL, redirect and auth code. Never narrow by file name.
**Read the whole inventory.** Save `start` and `inspect` output to private files (removed after `finish`); read the run ID with `jq -r .runId`, never through `head` or `tail`. Check readiness, deadline, and coverage; page `jq -r '.manifest.entries[].path'` through `sed -n '1,500p'`, then 501-1000, to the end. Search source with `gstack-cso search <run> '<regex>'`, one pattern per call; it stops at 60 s and lists unsearched paths as a gap. Then read in full every attacker-reachable file: parsers, decoders, serializers, path, URL, redirect and auth code. Never narrow by file name.
When a finding survives challenge, submit it to the helper **and surface it to the user immediately**; do not wait for the final report; this preserves evidence if the run is interrupted. Malformed model JSON gets **one bounded correction attempt**; then preserve a partial result.
@@ -134,7 +135,7 @@ This **CSO evidence rubric** governs CSO instead of shared review confidence ins
- **Confidence:** how strongly evidence supports that precise claim, with unknowns and counterevidence; a number is not proof.
- **Evidence:** candidate hypothesis, supported static evidence, or a helper-recorded reproduction. Code tracing can support a finding; it cannot establish that an application booted or a repair passed tests.
**Report every finding the code supports; confidence carries doubt, never omission.** **Supported**: code you read traces attacker-controlled input to the defect and no inspected control blocks it; submit at medium or high confidence. A library's public API and parsed data are attacker-controlled when documented use passes untrusted input, even with callers outside the snapshot. A **candidate** has code evidence and one open question (an unread caller, an unclear default): submit it as a low-confidence hypothesis saying what would confirm it, and list it under **Hypotheses (unconfirmed)** in your report. Drop one only when code you read disproves it, naming that code.
**Report every finding the code supports; confidence carries doubt, never omission.** **Supported**: code you read traces attacker-controlled input to the defect and no inspected control blocks it; submit at medium or high confidence. A library's public API and parsed data are attacker-controlled when documented use passes untrusted input, even with callers outside the snapshot. A **candidate** has code evidence and one open question (an unread caller, an unclear default): submit it as a low-confidence hypothesis saying what would confirm it; report.md and your report list it under **Hypotheses (unconfirmed)**. Drop one only when code you read disproves it, naming that code.
Do not apply blanket exclusions for development dependencies, availability/resource attacks, historical secrets, user-role prompt injection, or gstack-owned skills. UUIDs are not authorization; user-controlled URL paths can cross a sensitive boundary; environment variables may come from untrusted workflows; framework escape hatches can bypass safe defaults. Missing hardening alone needs a concrete failure scenario before becoming a finding.
+4 -3
View File
@@ -80,6 +80,7 @@ gstack-cso recheck <finding> --repo <repo> [--run <original-run>]
gstack-cso inspect <run>
gstack-cso read <run> <path-or-handle>
gstack-cso history <run> [path-or-handle]
gstack-cso search <run> <regex> [--seconds N]
gstack-cso scan <run> <scanner> [request.json]
gstack-cso scanner-outcome <run> <artifact-id>
gstack-cso import-sarif <run> <results.sarif>
@@ -97,9 +98,9 @@ gstack-cso inspect-v2 <import-id>
**One-run invariant.** Invoke `start` exactly once per run and reuse the same ID. A refused `start` (`"ok":false`) holds no run: apply the one correction it names and start again; for the 64 MiB cap, `du -s` the top level and pass at most 32 `--paths` prefixes (1024 characters) covering the source, leaving out vendored, generated, fixture and media trees. Once a `start` returns a run ID, never call `start` again.
**Audited-source access invariant.** After `start`, inspect source only with that run's `inspect`, `read`, and `history`. Pass the exact `path` from `inspect`; `displayPath` is only a redacted label. Never use host `Read`/`Glob`/`Grep`; direct reads bypass redaction and identity.
**Audited-source access invariant.** After `start`, inspect source only with that run's `inspect`, `read`, `search`, and `history`. Pass the exact `path` from `inspect`; `displayPath` is only a redacted label. Never use host `Read`/`Glob`/`Grep`; direct reads bypass redaction and identity.
**Read the whole inventory.** Save `start` and `inspect` output to private files (removed after `finish`); read the run ID with `jq -r .runId`, never through `head` or `tail`. Check readiness, deadline, and coverage; `jq -r '.manifest.entries[].path'` lists every file. Then read in full every attacker-reachable file: parsers, decoders, serializers, path, URL, redirect and auth code. Never narrow by file name.
**Read the whole inventory.** Save `start` and `inspect` output to private files (removed after `finish`); read the run ID with `jq -r .runId`, never through `head` or `tail`. Check readiness, deadline, and coverage; page `jq -r '.manifest.entries[].path'` through `sed -n '1,500p'`, then 501-1000, to the end. Search source with `gstack-cso search <run> '<regex>'`, one pattern per call; it stops at 60 s and lists unsearched paths as a gap. Then read in full every attacker-reachable file: parsers, decoders, serializers, path, URL, redirect and auth code. Never narrow by file name.
When a finding survives challenge, submit it to the helper **and surface it to the user immediately**; do not wait for the final report; this preserves evidence if the run is interrupted. Malformed model JSON gets **one bounded correction attempt**; then preserve a partial result.
@@ -133,7 +134,7 @@ This **CSO evidence rubric** governs CSO instead of shared review confidence ins
- **Confidence:** how strongly evidence supports that precise claim, with unknowns and counterevidence; a number is not proof.
- **Evidence:** candidate hypothesis, supported static evidence, or a helper-recorded reproduction. Code tracing can support a finding; it cannot establish that an application booted or a repair passed tests.
**Report every finding the code supports; confidence carries doubt, never omission.** **Supported**: code you read traces attacker-controlled input to the defect and no inspected control blocks it; submit at medium or high confidence. A library's public API and parsed data are attacker-controlled when documented use passes untrusted input, even with callers outside the snapshot. A **candidate** has code evidence and one open question (an unread caller, an unclear default): submit it as a low-confidence hypothesis saying what would confirm it, and list it under **Hypotheses (unconfirmed)** in your report. Drop one only when code you read disproves it, naming that code.
**Report every finding the code supports; confidence carries doubt, never omission.** **Supported**: code you read traces attacker-controlled input to the defect and no inspected control blocks it; submit at medium or high confidence. A library's public API and parsed data are attacker-controlled when documented use passes untrusted input, even with callers outside the snapshot. A **candidate** has code evidence and one open question (an unread caller, an unclear default): submit it as a low-confidence hypothesis saying what would confirm it; report.md and your report list it under **Hypotheses (unconfirmed)**. Drop one only when code you read disproves it, naming that code.
Do not apply blanket exclusions for development dependencies, availability/resource attacks, historical secrets, user-role prompt injection, or gstack-owned skills. UUIDs are not authorization; user-controlled URL paths can cross a sensitive boundary; environment variables may come from untrusted workflows; framework escape hatches can bypass safe defaults. Missing hardening alone needs a concrete failure scenario before becoming a finding.
+120
View File
@@ -183,6 +183,7 @@ Usage:
gstack-cso inspect RUN
gstack-cso read RUN PATH_OR_HANDLE
gstack-cso history RUN [PATH_OR_HANDLE]
gstack-cso search RUN REGEX [--seconds N]
gstack-cso submit RUN SUBMISSION.json
gstack-cso scan RUN gitleaks|osv|semgrep|zizmor|trivy|schemathesis [REQUEST.json]
gstack-cso scanner-outcome RUN ARTIFACT_ID
@@ -1659,6 +1660,122 @@ async function read(args: string[]) {
data = readBoundedStable(full, 1024 * 1024, 'Snapshot path');
emit(data.toString('utf8'));
}
const SEARCH_PATTERN_LIMIT = 512,
SEARCH_OUTPUT_BUDGET = 96 * 1024,
SEARCH_LISTED = 50,
SEARCH_SECONDS = 60;
const listed = (paths: string[]) =>
paths.slice(0, SEARCH_LISTED).join(', ') +
(paths.length > SEARCH_LISTED ? `, and ${paths.length - SEARCH_LISTED} more` : '');
/** One regex over every readable snapshot file in a worker the helper stops at a hard time limit; paths it could not search are listed as a coverage gap. */
async function search(args: string[]) {
const { dir } = run(args);
let seconds = SEARCH_SECONDS;
if (args.length === 3 && args[1] === '--seconds') {
seconds = Number(args[2]);
if (!Number.isInteger(seconds) || seconds < 1 || seconds > SEARCH_SECONDS)
throw new CsoError('INVALID_ARGUMENT', `--seconds must be a whole number from 1 to ${SEARCH_SECONDS}`);
args.splice(1, 2);
}
if (args.length !== 1) throw new CsoError('INVALID_ARGUMENT', 'search requires one regular expression');
if (!args[0] || args[0].length > SEARCH_PATTERN_LIMIT)
throw new CsoError('INVALID_ARGUMENT', `Search pattern must be 1 to ${SEARCH_PATTERN_LIMIT} characters`);
try {
new RegExp(args[0]);
} catch {
throw new CsoError('INVALID_ARGUMENT', 'Search pattern is not a valid regular expression');
}
const stopAt = Date.now() + seconds * 1000,
manifest = readSnapshotManifest(dir);
assertSnapshot(dir, manifest);
const readable = join(dir, 'readable'),
files: Array<{ path: string; shown: string }> = [],
unsearched: string[] = [],
windowed: string[] = [],
out: string[] = [];
let noCopy = 0,
bytes = 0,
hidden = 0,
failed = false,
current = '',
settle: ((done: boolean) => void) | undefined,
unfinished: string[] = [];
for (const entry of manifest.entries) {
const transformation = entry.transformation ?? '';
if (transformation === OUTSIDE_AUDIT_PATHS) continue;
if (
/^(withheld|excluded):/.test(transformation) &&
transformation !== 'withheld: exceeds the 1 MiB redacting-reader limit' &&
!fs.existsSync(containedFile(readable, entry.path))
) {
noCopy++;
continue;
}
files.push({ path: entry.path, shown: publicSnapshotPath(manifest, entry.path, entry.pathId).path });
}
const worker = new Worker(new URL('./search-worker.ts', import.meta.url).href),
step = (message: object) =>
new Promise<boolean>((resolve) => {
const timer = setTimeout(() => resolve(false), Math.max(0, stopAt - Date.now()));
settle = (done) => (clearTimeout(timer), resolve(done));
worker.postMessage(message);
});
worker.onmessage = (event) => {
const reply = event.data as { hit?: { line: number; text: string }; done?: boolean; windowed?: boolean };
if (reply.hit) {
const line = `${current}:${reply.hit.line}:${reply.hit.text}`;
if (bytes + Buffer.byteLength(line) > SEARCH_OUTPUT_BUDGET) hidden++;
else (out.push(line), (bytes += Buffer.byteLength(line) + 1));
}
if (reply.windowed) windowed.push(current);
if (reply.done) settle?.(true);
};
worker.onerror = () => ((failed = true), settle?.(true));
try {
if (!(await step({ pattern: args[0] }))) unfinished = files.map((file) => file.shown);
for (let index = 0; !failed && !unfinished.length && index < files.length; index++) {
current = files[index].shown;
let text: string;
try {
text = readBoundedStable(
containedFile(readable, files[index].path),
1024 * 1024,
'Snapshot path',
).toString('utf8');
} catch (error) {
if (!(error instanceof CsoError) || error.code !== 'MISSING_INPUT') throw error;
unsearched.push(current);
continue;
}
if (Date.now() >= stopAt || !(await step({ text })))
unfinished = files.slice(index).map((file) => file.shown);
}
} finally {
worker.terminate();
}
if (failed) throw new CsoError('INVALID_SCHEMA', 'Search worker failed');
if (!out.length && !hidden) out.push('[gstack-cso search: no matches]');
if (hidden) out.push(`[gstack-cso search: ${hidden} more matching lines not shown; narrow the pattern]`);
if (unfinished.length)
out.push(
`[gstack-cso search: stopped at the ${seconds}-second limit; ${unfinished.length} paths not searched, a coverage gap: ${listed(unfinished)}]`,
);
if (unsearched.length)
out.push(
`[gstack-cso search: ${unsearched.length} unsearched paths (unreadable or over 1 MiB), a coverage gap: ${listed(unsearched)}]`,
);
if (windowed.length)
out.push(
`[gstack-cso search: ${windowed.length} paths have lines over 4096 characters, matched in overlapping 4 KiB windows where ^, $, lookbehind and matches over 256 characters are approximate: ${listed(windowed)}]`,
);
if (noCopy)
out.push(
`[gstack-cso search: ${noCopy} paths the snapshot excluded or withheld have no readable copy; inspect and report.md list them]`,
);
emit(out.join('\n'));
if (unfinished.length)
(await new Promise<void>((resolve) => process.stdout.write('', () => resolve())), process.exit(0));
}
async function history(args: string[]) {
const { dir } = run(args),
manifest = readSnapshotManifest(dir);
@@ -2886,6 +3003,9 @@ export async function dispatchCsoCommand(
case 'history':
await history(args);
return;
case 'search':
await search(args);
return;
case 'submit':
result = submit(args);
break;
+29
View File
@@ -0,0 +1,29 @@
const WINDOW = 4096,
OVERLAP = 256,
EXCERPT = 300,
LEAD = 100;
let pattern: RegExp | undefined;
/** Matches one file's lines in bounded windows and posts each hit as it is found, so a search stopped mid-file keeps the hits before the stop. */
self.onmessage = (event: MessageEvent) => {
const message = event.data as { pattern?: string; text?: string };
if (typeof message.pattern === 'string') {
pattern = new RegExp(message.pattern);
postMessage({ done: true });
return;
}
let windowed = false;
(message.text ?? '').split('\n').forEach((line, index) => {
if (line.length > WINDOW) windowed = true;
for (let start = 0; ; start += WINDOW - OVERLAP) {
const found = pattern!.exec(line.slice(start, start + WINDOW));
if (found) {
const from = Math.max(0, start + found.index - LEAD);
postMessage({ hit: { line: index + 1, text: line.slice(from, from + EXCERPT) } });
return;
}
if (start + WINDOW >= line.length) return;
}
});
postMessage({ done: true, windowed });
};
+19 -1
View File
@@ -930,11 +930,29 @@ export function saveReport(dir: string, report: RunReportV3): void {
);
}
try {
atomicWriteSync(join(dir, 'report.md'), renderReport(safe), { mode: 0o600 });
atomicWriteSync(join(dir, 'report.md'), readableReport(safe), { mode: 0o600 });
} catch {
throw new CsoError('PERSISTENCE_FAILED', 'JSON was saved but the readable report could not be written');
}
}
/** A daily report.md also lists saved hypotheses, in the section the shared renderer writes for comprehensive runs. */
function readableReport(report: RunReportV3): string {
const text = renderReport(report),
next = '\nSnapshot transformations:\n';
const at = text.indexOf(next);
if (
at < 0 ||
report.policy.mode === 'comprehensive' ||
!report.findings.some((f) => f.evidence === 'hypothesis')
)
return text;
const full = renderReport({ ...report, policy: { ...report.policy, mode: 'comprehensive' } });
return (
text.slice(0, at) +
full.slice(full.indexOf('\nHypotheses (unconfirmed):\n'), full.indexOf(next)) +
text.slice(at)
);
}
export function loadReport(dir: string): RunReportV3 {
const v = readJson(join(dir, 'report.json'));
if (v.schemaVersion !== 3 || !Array.isArray(v.coverage) || !Array.isArray(v.findings))
+3 -3
View File
@@ -183,7 +183,7 @@ cso_compile_bun() {
--no-compile-autoload-bunfig \
--no-compile-autoload-tsconfig \
--no-compile-autoload-package-json \
"$1" --outfile "$2"
"$1" "${@:3}" --outfile "$2"
chmod +x "$2"
}
cso_compile_watchdog() {
@@ -229,7 +229,7 @@ cso_build_evaluation_candidate() {
cp -R test/helpers "$source_root/test/"
cp "$candidate_catalog" "$source_root/lib/cso/runtime-catalog.json"
(cd "$source_root" && "$BUN_CMD" --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" scripts/cso-runtime-promotion.ts check-evaluation lib/cso/runtime-catalog.json)
(cd "$source_root" && cso_compile_bun lib/cso/cli.ts "$CSO_EVALUATION_UNIT/gstack-cso-core")
(cd "$source_root" && cso_compile_bun lib/cso/cli.ts "$CSO_EVALUATION_UNIT/gstack-cso-core" lib/cso/search-worker.ts)
(cd "$source_root" && cso_compile_bun scripts/cso-eval-producer.ts "$CSO_EVALUATION_UNIT/cso-eval-producer")
cso_compile_watchdog "$CSO_EVALUATION_UNIT/gstack-cso-watchdog"
if [ "$(uname -s)" = Darwin ]; then
@@ -363,7 +363,7 @@ if [ -n "$CSO_EXE" ];then : > "$CSO_STAGE/.gstack-cso-generation.lock";fi
# These are compile-time switches. Bun otherwise discovers configuration in
# the audited working directory before the helper can apply its own policy.
cso_compile_bun lib/cso/cli.ts "$CSO_STAGE_CORE"
cso_compile_bun lib/cso/cli.ts "$CSO_STAGE_CORE" lib/cso/search-worker.ts
cso_checkpoint core
# POSIX process groups are required by the detached watchdog. Windows keeps
+1 -1
View File
@@ -64,7 +64,7 @@ describe('CSO v3 always-loaded policy', () => {
test('sensitive helper control files stay out of the audited working tree', () => {
const text = controller();
for (const proof of ['Private control files', 'umask 077', 'mode-`0700`', 'mode-`0600`', 'outside the audited repository', 'remove each control file immediately']) expect(text).toContain(proof);
for (const proof of ['Audited-source access invariant', "only with that run's `inspect`, `read`, and `history`", 'exact `path` from `inspect`', '`displayPath` is only a redacted label', 'Never use host `Read`/`Glob`/`Grep`', 'direct reads bypass']) expect(text).toContain(proof);
for (const proof of ['Audited-source access invariant', "only with that run's `inspect`, `read`, `search`, and `history`", 'exact `path` from `inspect`', '`displayPath` is only a redacted label', 'Never use host `Read`/`Glob`/`Grep`', 'direct reads bypass']) expect(text).toContain(proof);
for (const proof of ["copy every record's `domain` and `scope` exactly", 'a new scope leaves the planned scope unassessed', 'Only helper commands may update helper-owned records']) expect(text).toContain(proof);
});
+73 -7
View File
@@ -84,13 +84,73 @@ describe('/cso recall (gstack-evals#443)', () => {
expect(cso(repo, ['finish', run]).status).toBe(0);
});
test('search reads every file in one call, never runs a file name, and lists what it could not search', () => {
const repo = path.join(root, 'hostile');
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
const hostile = 'src/a$(touch PWNED).js';
fs.writeFileSync(path.join(repo, hostile), 'eval(input)\n');
fs.writeFileSync(path.join(repo, 'src/parse.js'), 'const x = 1;\neval(input)\n');
fs.writeFileSync(path.join(repo, 'src/big.js'), 'eval(input)\n' + 'x'.repeat(MIB + 16));
fs.writeFileSync(path.join(repo, 'src/min.js'), 'a(b,c);'.repeat(140_000) + 'eval(late)');
fs.mkdirSync(path.join(repo, '.gstack'));
fs.writeFileSync(path.join(repo, '.gstack/state.js'), 'eval(input)\n');
git(repo, 'init', '-q');
git(repo, 'add', '-A');
git(repo, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', 'commit', '-qm', 'fixture');
const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string;
expect(skill()).toContain("gstack-cso search <run> '<regex>'");
const found = cso(repo, ['search', run, 'eval\\(']);
expect(found.status).toBe(0);
expect(found.stdout).toContain('src/parse.js:2:eval(input)');
expect(found.stdout).toContain(hostile + ':1:eval(input)');
expect(found.stdout).toMatch(/src\/min\.js:1:[a-c(),;]{100}eval\(late\)/);
expect(found.stdout).toMatch(/1 unsearched paths .*coverage gap: src\/big\.js\]/);
expect(found.stdout).not.toContain('.gstack/state.js');
expect(found.stdout).toContain('1 paths the snapshot excluded or withheld have no readable copy');
expect(found.stdout).toMatch(/1 paths have lines over 4096 characters.*: src\/min\.js\]/);
expect(fs.existsSync(path.join(root, 'PWNED'))).toBe(false);
expect(fs.existsSync(path.join(repo, 'PWNED'))).toBe(false);
const none = cso(repo, ['search', run, 'zzz-no-such-text']).stdout;
expect(none).toContain('[gstack-cso search: no matches]');
expect(none).toMatch(/1 unsearched paths .*src\/big\.js/);
const bad = cso(repo, ['search', run, '(']);
expect(bad.status).not.toBe(0);
expect(bad.stderr).toContain('not a valid regular expression');
expect(cso(repo, ['search', run, 'x', '--seconds', '61']).stderr).toContain('--seconds must be a whole number from 1 to 60');
expect(cso(repo, ['finish', run]).status).toBe(0);
});
test('search stays fast on a one-line 1 MiB file and stops a runaway pattern at its time limit with the hits found so far', () => {
const repo = path.join(root, 'minified');
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
fs.writeFileSync(path.join(repo, 'src/a.js'), 'eval(first)\n');
fs.writeFileSync(path.join(repo, 'src/b.min.js'), 'eval(second)\n' + 'x'.repeat(MIB - 64));
git(repo, 'init', '-q');
git(repo, 'add', '-A');
git(repo, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', 'commit', '-qm', 'fixture');
const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string;
let started = Date.now();
const quadratic = cso(repo, ['search', run, '.*password']);
expect(quadratic.status).toBe(0);
expect(quadratic.stdout).toContain('[gstack-cso search: no matches]');
expect(Date.now() - started).toBeLessThan(30_000);
started = Date.now();
const runaway = cso(repo, ['search', run, '(x+x+)+y|eval\\((first|second)', '--seconds', '2']);
expect(runaway.status).toBe(0);
expect(runaway.stdout).toContain('src/a.js:1:eval(first)');
expect(runaway.stdout).toContain('src/b.min.js:1:eval(second)');
expect(runaway.stdout).toMatch(/stopped at the 2-second limit; 1 paths not searched, a coverage gap: src\/b\.min\.js/);
expect(Date.now() - started).toBeLessThan(20_000);
expect(cso(repo, ['finish', run]).status).toBe(0);
}, 90_000);
test('the report rule keeps every supported finding and lists hypotheses instead of dropping them', () => {
const text = skill();
for (const dropped of ['Daily reports hold only', 'Omit daily candidates', 'Prioritize unresolved high impact', 'demonstrated in-scope impact']) expect(text).not.toContain(dropped);
for (const kept of ['jq -r .runId', 'Report every finding the code supports', 'never omission', 'Hypotheses (unconfirmed)', 'even with callers outside the snapshot', 'Drop one only when code you read disproves it', 'Never narrow by file name']) expect(text).toContain(kept);
for (const kept of ['jq -r .runId', "sed -n '1,500p'", 'gstack-cso search', 'Report every finding the code supports', 'never omission', 'Hypotheses (unconfirmed)', 'even with callers outside the snapshot', 'Drop one only when code you read disproves it', 'Never narrow by file name']) expect(text).toContain(kept);
});
test('a daily run saves supported findings and low-confidence hypotheses, and report.md shows only the supported ones', () => {
test('a daily run saves supported findings and low-confidence hypotheses, and report.md lists them in separate sections', () => {
const { repo } = library('report');
const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string;
const finding = (evidence: string, confidence: string, title: string, rootCause: string) => ({
@@ -111,18 +171,24 @@ describe('/cso recall (gstack-evals#443)', () => {
const supported = submit('supported', 'medium', 'Prototype injection in parse', 'parse copies attacker keys onto a plain object');
expect(supported.status).toBe(0);
expect(json(supported.stdout).findings).toBe(1);
const hypothesis = submit('hypothesis', 'low', 'Prototype injection through caller-named keys', 'parse copies keys named by the caller');
const hypothesis = submit('hypothesis', 'low', "Prototype injection through caller-named keys $' and $&", 'parse copies keys named by the caller');
expect(hypothesis.status).toBe(0);
expect(json(hypothesis.stdout).findings).toBe(2);
expect(cso(repo, ['finish', run]).status).toBe(0);
const saved = json(fs.readFileSync(findReport(state, run, 'report.json'), 'utf8')).findings as Array<{ title: string; evidence: string; confidence: string }>;
expect(saved.map((f) => [f.title, f.evidence, f.confidence]).sort()).toEqual([
['Prototype injection in parse', 'supported', 'medium'],
['Prototype injection through caller-named keys', 'hypothesis', 'low'],
["Prototype injection through caller-named keys $' and $&", 'hypothesis', 'low'],
]);
const report = fs.readFileSync(findReport(state, run, 'report.md'), 'utf8');
expect(report).toContain('Supported findings:');
expect(report).toContain('Prototype injection in parse');
expect(report).not.toContain('caller-named keys');
const supportedSection = report.slice(report.indexOf('Supported findings:'), report.indexOf('Hypotheses (unconfirmed):'));
const hypotheses = report.slice(report.indexOf('Hypotheses (unconfirmed):'), report.indexOf('Snapshot transformations:'));
expect(report.indexOf('Hypotheses (unconfirmed):')).toBeGreaterThan(report.indexOf('Supported findings:'));
expect(supportedSection).toContain('Prototype injection in parse');
expect(supportedSection).not.toContain('caller-named keys');
expect(hypotheses).toContain('Prototype injection through caller-named keys');
expect(hypotheses).not.toContain('Prototype injection in parse');
expect(hypotheses).toContain('$&');
expect(report.split('Snapshot transformations:').length).toBe(2);
});
});