diff --git a/CHANGELOG.md b/CHANGELOG.md index 866630b..0f2f4b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Security and behavior changes +## Unreleased — final context completion + +- Add metadata-only optional existence probes without weakening mandatory file evidence, immutable verification or existing request/API budgets. Verified absent candidates no longer invalidate otherwise complete context; infrastructure/verification errors stay distinct. +- Report the exact trusted-host/model completion conditions when analysis cannot be accepted. Preserve findings and fail closed when on-demand essential evidence becomes unavailable. +- Record required on-demand failure reasons and close/drain lookups before the final result check, preventing late context mutation after submission. No inference, context-budget or approval-policy relaxation. + ## Unreleased — inference diagnostics - Preserve correlated per-request primary and cleanup errors, bounded HTTP/SSE metadata and allowlisted transport causes. A consumer closing after a completed SSE response is no longer mislabeled as a provider failure; successful retries clear stale failures. diff --git a/docs/adaptive-context.md b/docs/adaptive-context.md index a0025c9..f302a95 100644 --- a/docs/adaptive-context.md +++ b/docs/adaptive-context.md @@ -4,7 +4,7 @@ The existing immutable collection and isolated Codex execution remain in place. The collector writes `/workspace/file-index.json`: at most 12 nonrecursive directory walks and 5,000 regular-file paths. A partial supplementary index does not invalidate a small PR. It does not imply exhaustive semantic coverage. No full recursive tree or unrelated blob download is required. -A separate trusted host Unix socket at `/run/proxy/context.sock` accepts only POST `/file` JSON with `snapshot: base|head` and a relative `path`. Successful retrieval materializes a verified file under the existing read-only reviewer mount. Paths, immutable commit/tree/blob identity, object modes, UTF-8, size and Git blob SHA are validated by the same collector. It cannot request another repository/ref, fetch URLs, follow symlinks or execute commands. There are at most 24 lookups, sharing the 768-call/16-MB-source/512-KB-file limits and SHA cache. Missing explicitly requested evidence makes the result incomplete and fails the review job. Optional omissions that were never needed do not. +A separate trusted host Unix socket at `/run/proxy/context.sock` accepts POST `/file` for required contents or `/probe` for optional existence, with JSON containing `snapshot: base|head` and a relative `path`. Successful retrieval materializes a verified file under the existing read-only reviewer mount. Paths, immutable commit/tree/blob identity, object modes, UTF-8, size and Git blob SHA are validated by the same collector. It cannot request another repository/ref, fetch URLs, follow symlinks or execute commands. There are at most 24 lookups, sharing the 768-call/16-MB-source/512-KB-file limits and SHA cache. Missing `/file` evidence makes the result incomplete and fails the review job. A `/probe` returns only `{exists: true|false}` from verified immutable tree metadata and never materializes source or satisfies content evidence. Verified absence is neutral; API/tree verification failures are errors and remain fail-closed, not false absence. The GitHub read token remains on the trusted host through bounded exploration, rather than being revoked before inference. It is never mounted into the reviewer or credential proxy. On completion/failure, the host aborts/drains outstanding lookups, closes the context service, revokes the token and removes temporary source. Token cleanup failure fails the review job; it does not authorize approval. The separate publisher still uses the job conclusion and exact commit to decide whether a safe COMMENT is appropriate. @@ -35,3 +35,9 @@ The publisher independently verifies PNG evidence within 32 additional Git calls The pinned Codex 0.169.0 App Server supports `localImage`; its current adapter has no general local-file input. [Official SIWC limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations) allow model-supported images/files on Responses, but exclude audio/video input, transcription and Files API uploads. This implementation supports verified PNG images, not every binary format. It does not execute, unpack, transcribe or silently skip EXE/archive/audio/PDF files. Those changes require a supported explicit inspection path before approval. No private ChatGPT endpoints or paid fallback are used. The Docker acceptance uses the actual pinned Codex binary to prove PNG conversion, transport, tool inspection and isolation against scripted Responses. It is not proof of real-model visual understanding; no new real-provider inference is part of this hotfix validation. + + +Final completion is checked again by the trusted host after the isolated engine returns and the context service is closed/drained. A missing file requested through `/file` remains essential missing evidence even if the model returns complete findings or has inspected every attached PNG. The host preserves validated findings in the non-approving submission, fails the review job and logs only completion booleans/result enum plus an approved context failure code. On-demand failures enter required coverage diagnostics rather than being labeled supplementary omissions. Paths, model text and credentials are not diagnostic fields. Neither a later successful lookup nor a complete model result clears a previous essential-evidence failure. + + +Optional discovery never uses a model-supplied required/optional flag. The existing `/file` endpoint stays mandatory and rejects extra fields such as `required: false`; the separate `/probe` operation supplies existence only, not readable or verified contents. A probe can report an object exists even when a later content read rejects its Git type, size or blob hash. A successful probe cannot waive initial changed-file/instruction/dependency requirements or clear a previous required failure. Both operations share the unchanged 24-request and GitHub API budgets. Exhausted optional probes fail without invalidating otherwise complete evidence; a denied required fetch remains fatal. There is no extra inference pass or model/budget change. Host checks do not claim to prove exhaustive model reasoning about every possible dependency. diff --git a/docs/architecture.md b/docs/architecture.md index 7c52626..45731e4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ See [operations](operations.md), [security](security.md) and [acceptance](accept ## Adaptive context and browser management -The collector also writes a supplementary regular-file index (12 directories / 5,000 paths, no recursive tree dump). Explicit Python relative imports and Rust sibling modules join JS/TS dependencies; nearby Python/Go/Java test names are considered. A separate host Unix socket accepts only bounded base/head path requests for this authorized immutable repository. It never forwards arbitrary URLs, executes project code or exposes credentials. At most 24 requests share the existing byte/blob/API limits and per-SHA cache. Requested files that cannot be obtained invalidate completeness. The reviewer mount stays read-only and network=none. The read token now lasts through bounded context exploration; shutdown cancels/drains lookups and revokes it before temporary source cleanup. Failed token cleanup fails the review job. +The collector also writes a supplementary regular-file index (12 directories / 5,000 paths, no recursive tree dump). Explicit Python relative imports and Rust sibling modules join JS/TS dependencies; nearby Python/Go/Java test names are considered. A separate host Unix socket accepts bounded base/head `/file` requests for required contents and `/probe` requests for optional existence for this authorized immutable repository. It never forwards arbitrary URLs, executes project code or exposes credentials. At most 24 requests share the existing byte/blob/API limits and per-SHA cache. Required files that cannot be obtained invalidate completeness. A metadata-only probe may establish absence without fetching source; it cannot waive required evidence. Probe API/tree failures remain fail-closed rather than being mislabeled as missing paths. The reviewer mount stays read-only and network=none. The read token now lasts through bounded context exploration; shutdown cancels/drains lookups and revokes it before temporary source cleanup. Failed token cleanup fails the review job. The system prompt asks for introduced, evidence-backed bugs traced through unchanged callers and dependencies, with trusted default-branch guidance subordinate to execution/output safety. Additional comment context is advisory. The model/effort CLI precedence is unchanged; a generated pinned-native catalog powers dashboard validation and distinguishes catalog membership from account entitlement. diff --git a/src/core/diagnostics.ts b/src/core/diagnostics.ts index 779e872..e55ac1c 100644 --- a/src/core/diagnostics.ts +++ b/src/core/diagnostics.ts @@ -4,7 +4,7 @@ import { ExecutionError, executionFailure, proxyRequestDiagnostic, type ProxyReq export const REVIEW_STAGES = ['environment','prepare','context','credentials','analyzing','result','publish','release'] as const; export const FAILURE_CODES = new Set(['missing_environment_credentials','ambiguous_environment_credentials','credential_owner_mismatch','missing_read_token', 'api_key_missing_or_ambiguous_credentials','vault_key_missing_or_ambiguous_credentials','invalid_envelope','invalid_vault_key','invalid_saved_session', - 'context_api_budget','context_collection_timeout','context_diff_size_limit','context_text_patch_truncated','context_unsupported_binary','context_binary_unverifiable','context_binary_size_limit','context_non_text_source','context_missing_dependency','context_file_size_limit','context_byte_budget','context_required_evidence_unavailable','required_file_missing_or_special','blob_integrity_failure','required_tree_unverifiable','review_incomplete','review_context_incomplete','review_output_invalid','read_token_cleanup_failed', + 'context_path_missing','context_special_object','context_github_api_failed','context_lookup_rejected','context_api_budget','context_collection_timeout','context_diff_size_limit','context_text_patch_truncated','context_unsupported_binary','context_binary_unverifiable','context_binary_size_limit','context_non_text_source','context_missing_dependency','context_file_size_limit','context_byte_budget','context_required_evidence_unavailable','required_file_missing_or_special','blob_integrity_failure','required_tree_unverifiable','review_incomplete','review_context_incomplete','review_output_invalid','read_token_cleanup_failed', 'oauth_refresh_too_early','oauth_refresh_window_unavailable', 'session_too_short_reconnect_required','review_image_missing','isolated_review_failed','proxy_start_failed','docker_unavailable','docker_cleanup_failed_check_runner', 'oauth_grant_invalid_reconnect_required','chatgpt_plan_usage_permission_missing','oauth_token_endpoint_failed','oauth_token_exchange_uncertain_reconnect_required', @@ -30,10 +30,26 @@ github_actions_oidc_unavailable invalid_oidc_endpoint github_oidc_request_failed export class BrokerError extends AppError { constructor(public readonly operation: string, status: number, public readonly remoteCode: string | null) { super(`broker_${operation}_failed`, status); } } -export function diagnostic(error: unknown, stage: string): { event: string; stage: string; code: string; status?: number; broker_code?: string; execution?: ExecutionFailure; proxy_failure?: ExecutionFailure; proxy_cleanup?: ExecutionFailure; proxy_request?: Omit } { +export interface ReviewCompletion { + context_complete: boolean; diff_complete: boolean; required_context_complete: boolean; + output_complete: boolean; output_result: 'clean' | 'findings' | 'inconclusive'; quarantined: boolean; output_truncated: boolean; + context_failure_code?: string; +} +/** Only fixed completion conditions leave the trusted runner, never paths or model text. */ +export class ReviewCompletionError extends AppError { + readonly completion: ReviewCompletion; + constructor(value: ReviewCompletion) { + super('review_incomplete'); + this.completion={context_complete:value.context_complete===true,diff_complete:value.diff_complete===true,required_context_complete:value.required_context_complete===true, + output_complete:value.output_complete===true,output_result:value.output_result==='clean'?'clean':value.output_result==='findings'?'findings':'inconclusive',quarantined:value.quarantined===true,output_truncated:value.output_truncated===true, + ...(typeof value.context_failure_code==='string'&&FAILURE_CODES.has(value.context_failure_code)?{context_failure_code:value.context_failure_code}:{})}; + } +} +export function diagnostic(error: unknown, stage: string): { event: string; stage: string; code: string; status?: number; broker_code?: string; execution?: ExecutionFailure; proxy_failure?: ExecutionFailure; proxy_cleanup?: ExecutionFailure; proxy_request?: Omit; completion?: ReviewCompletion } { const result: ReturnType = { event: 'review_failed', stage: REVIEW_STAGES.includes(stage as typeof REVIEW_STAGES[number]) ? stage : 'environment', code: 'external_or_execution_failure' }; + if(error instanceof ReviewCompletionError){result.code=error.code;result.completion=error.completion;return result;} if (error instanceof ExecutionError) { result.code = error.code; result.execution = executionFailure(error.detail)!; diff --git a/src/runner/context-server.ts b/src/runner/context-server.ts index f403374..87e9ae4 100644 --- a/src/runner/context-server.ts +++ b/src/runner/context-server.ts @@ -9,13 +9,14 @@ export async function contextServer(socket: string, lookup: ContextLookup, abort const pending = new Set>(); const server = createServer((request, response) => { const task = (async () => { try { - requireCondition(request.method === 'POST' && request.url === '/file', 'context_request_denied'); + requireCondition(request.method === 'POST' && (request.url === '/file'||request.url === '/probe'), 'context_request_denied'); let body = ''; for await (const chunk of request) { body += String(chunk); requireCondition(Buffer.byteLength(body) <= 1024, 'context_request_too_large'); } const input = record(JSON.parse(body) as unknown); requireCondition(Object.keys(input).length === 2 && (input.snapshot === 'base' || input.snapshot === 'head') && typeof input.path === 'string', 'context_request_denied'); - const available = await lookup(input.snapshot, input.path); - response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); response.end(JSON.stringify({ available })); + const probe=request.url==='/probe'; + const available = probe ? await lookup(input.snapshot,input.path,'probe') : await lookup(input.snapshot,input.path); + response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); response.end(JSON.stringify(probe?{exists:available}:{available})); } catch { response.writeHead(400, { 'Content-Type': 'application/json' }); response.end('{"error":"context_lookup_unavailable"}'); } })().catch(() => { response.destroy(); }).finally(() => { pending.delete(task); }); pending.add(task); }); server.requestTimeout = 20_000; server.headersTimeout = 5000; server.maxConnections = 2; diff --git a/src/runner/context.ts b/src/runner/context.ts index 2201c5e..bf98800 100644 --- a/src/runner/context.ts +++ b/src/runner/context.ts @@ -15,13 +15,13 @@ export interface ContextManifest { complete: boolean; diffComplete: boolean; requiredContextComplete: boolean; supplementary: { strategy: 'bounded-heuristics'; selected: number; omitted: number }; files: number; bytes: number; apiCalls: number; limitations: string[]; failureCodes:string[]; binaryFiles:BinaryChange[]; } -export type ContextLookup = (snapshot: 'base' | 'head', path: string) => Promise; +export type ContextLookup = (snapshot: 'base' | 'head', path: string, operation?: 'probe') => Promise; export async function collectContext(github: Octokit, snapshot: RequestSnapshot, directory: string, register?: (lookup: ContextLookup) => void, signal?: AbortSignal): Promise { const repo = { ...splitRepo(snapshot.repository), request: {timeout:15_000,...(signal?{signal}:{})} }; const manifest: ContextManifest = { complete: false, diffComplete: true, requiredContextComplete: true, supplementary: { strategy: 'bounded-heuristics', selected: 0, omitted: 0 }, files: 0, bytes: 0, apiCalls: 0, limitations: [], failureCodes:[], binaryFiles:[] }; const limited = (required: boolean, error?:unknown) => { - if(required){const code=error instanceof AppError?error.code:'context_required_evidence_unavailable';if(!manifest.failureCodes.includes(code))manifest.failureCodes.push(code);} + if(required){const code=error instanceof AppError?error.code:error&&typeof error==='object'&&'status' in error&&typeof error.status==='number'&&error.status>=400&&error.status<=599?'context_github_api_failed':'context_required_evidence_unavailable';if(!manifest.failureCodes.includes(code))manifest.failureCodes.push(code);} if (required) manifest.requiredContextComplete = false; else manifest.supplementary.omitted++; const reason = required ? 'Essential source or trusted instructions unavailable.' : 'Supplementary context bounded or unavailable.'; if (!manifest.limitations.includes(reason)) manifest.limitations.push(reason); @@ -48,7 +48,8 @@ export async function collectContext(github: Octokit, snapshot: RequestSnapshot, try { const entry = await find(commit, path); if (!entry && optional) return; - requireCondition(entry?.sha && entry.type === 'blob' && ['100644', '100755'].includes(entry.mode ?? ''), 'required_file_missing_or_special'); + requireCondition(entry, 'context_path_missing'); + requireCondition(entry.sha && entry.type === 'blob' && ['100644', '100755'].includes(entry.mode ?? ''), 'context_special_object'); requireCondition(entry.size !== undefined && entry.size <= MAX_FILE_BYTES, 'context_file_size_limit'); requireCondition(manifest.bytes + entry.size <= MAX_BYTES, 'context_byte_budget'); const bytes=await source.read(entry,MAX_FILE_BYTES); @@ -145,18 +146,25 @@ export async function collectContext(github: Octokit, snapshot: RequestSnapshot, await writeFile(join(directory, 'file-index.json'), JSON.stringify({ paths: index, complete: indexComplete && queue.length === 0 && index.length < 5000 }), { mode: 0o600 }); if (register) { let requests = 0, serial = Promise.resolve(); - register(async (label, path) => { - requireCondition((label === 'base' || label === 'head') && safePath(path) && ++requests <= 24, 'context_lookup_rejected'); + register(async (label, path, operation) => { + const required=operation!=='probe'; + try {requireCondition(++requests<=24&&(operation===undefined||operation==='probe')&&(label === 'base' || label === 'head') && safePath(path), 'context_lookup_rejected');} + catch(error){limited(required,error);if(required)manifest.complete=false;const work=serial.then(()=>writeFile(join(directory,'manifest.json'),JSON.stringify(manifest),{mode:0o600}));serial=work.catch(()=>{});await work;throw error;} let available = false; const work = serial.then(async () => { - await collect(label, label === 'head' ? snapshot.head : snapshot.base, path, false); - available = written.has(`${label}/${path}`); - if (!available) { manifest.requiredContextComplete = false; manifest.complete = false; } + if(operation==='probe') { + try {available=Boolean(await find(label==='head'?snapshot.head:snapshot.base,path));if(!available)manifest.supplementary.omitted++;} + catch(error){limited(true,error);manifest.complete=false;await writeFile(join(directory,'manifest.json'),JSON.stringify(manifest),{mode:0o600});throw error;} + } else { + await collect(label, label === 'head' ? snapshot.head : snapshot.base, path, true); + available = written.has(`${label}/${path}`); + if (!available) { manifest.requiredContextComplete = false; manifest.complete = false; } + } await writeFile(join(directory, 'manifest.json'), JSON.stringify(manifest), { mode: 0o600 }); }); serial = work.catch(() => {}); await work; return available; }); - manifest.limitations.push('Additional relevant files: POST {"snapshot":"base"|"head","path":"relative/file"} to /file over /run/proxy/context.sock using node:http. Read /workspace/source// after available=true. Maximum 24 requests, shared 768-call/16-MB source/512-KB file budgets; no URLs or execution. A requested file that cannot be obtained makes the review incomplete; use the index rather than probing optional nonexistent paths.'); + manifest.limitations.push('Context socket /run/proxy/context.sock: POST {"snapshot":"base"|"head","path":"relative/file"} to /file for REQUIRED contents; then read /workspace/source//. For OPTIONAL existence exploration use /probe: {exists:false} means verified absence. Probes supply no contents or completeness waiver. Both share 24 requests and existing byte/API budgets. API/verification errors are not absence. A failed /file permanently invalidates completeness; /probe cannot clear it. No URLs or execution.'); } call(true); const { data: current } = await github.rest.pulls.get({ ...repo, pull_number: snapshot.pr }); requireCondition(current.head.sha === snapshot.head && current.base.sha === snapshot.base, 'pr_changed_during_context_collection', 409); diff --git a/src/runner/main.ts b/src/runner/main.ts index 750619a..59c5685 100644 --- a/src/runner/main.ts +++ b/src/runner/main.ts @@ -6,7 +6,7 @@ import type { RequestSnapshot } from '../worker/store.js'; import type { Envelope } from '../core/crypto.js'; import { unseal, seal, sessionBinding } from '../core/crypto.js'; import { record, requireCondition, AppError } from '../core/errors.js'; -import { diagnostic, FAILURE_CODES, BROKER_CODES } from '../core/diagnostics.js'; +import { diagnostic, FAILURE_CODES, BROKER_CODES, ReviewCompletionError } from '../core/diagnostics.js'; import { OAuth, validateSession } from '../auth/oauth.js'; import { broker, backendUrl, checkWorkload } from './broker.js'; import { collectContext } from './context.js'; @@ -88,8 +88,14 @@ export async function reviewJob(): Promise { stage = 'result'; try { validateReview(output, snapshot.head, JSON.parse(await readFile(join(directory, 'diff.json'), 'utf8')) as ChangedFile[],binaryLocations(manifest.binaryFiles)); } catch { throw new AppError('review_output_invalid'); } - submission = { output, context_complete: manifest.complete }; - requireCondition(manifest.complete && output.complete && output.result !== 'inconclusive' && !output.quarantined && !output.output_truncated, 'review_incomplete'); + // Keep validated findings even if draining reveals unavailable essential context. + submission = { output, context_complete: false }; + await closeContext(); closeContext=undefined; + submission.context_complete=manifest.complete; + if(!(manifest.complete&&manifest.diffComplete&&manifest.requiredContextComplete&&output.complete&&output.result!=='inconclusive'&&!output.quarantined&&!output.output_truncated))throw new ReviewCompletionError({ + context_complete:manifest.complete,diff_complete:manifest.diffComplete,required_context_complete:manifest.requiredContextComplete, + output_complete:output.complete,output_result:output.result,quarantined:output.quarantined===true,output_truncated:output.output_truncated===true, + ...(manifest.failureCodes[0]?{context_failure_code:manifest.failureCodes[0]}:{})}); await broker(backend, id, 'result', submission); } catch (error) { const report = diagnostic(error, stage); console.error(JSON.stringify(report)); diff --git a/tests/context-server.test.ts b/tests/context-server.test.ts index 52a314c..90f9e05 100644 --- a/tests/context-server.test.ts +++ b/tests/context-server.test.ts @@ -8,7 +8,7 @@ import { contextServer } from '../src/runner/context-server.js'; await test('context socket exposes only validated immutable file requests and generic errors, never URL forwarding', async () => { const root = await mkdtemp(join(tmpdir(),'cb-context-')), socket = process.platform === 'win32' ? `\\\\.\\pipe\\cb-test-${crypto.randomUUID()}` : join(root,'context.sock'); const calls: unknown[] = []; - const close = await contextServer(socket, async (snapshot,path) => { calls.push([snapshot,path]); return path === 'src/caller.ts'; }); + const close = await contextServer(socket, async (snapshot,path,operation) => { calls.push(operation?[snapshot,path,operation]:[snapshot,path]); return path === 'src/caller.ts'; }); const send = (body: string, path = '/file', method = 'POST') => new Promise<{ status: number; body: string }>((resolve,reject) => { const req = request({ socketPath:socket, path, method, headers:{'Content-Type':'application/json'} }, response => { let body = ''; response.on('data',chunk => { body += String(chunk); }); response.on('end',() => resolve({ status:response.statusCode!, body })); @@ -16,10 +16,13 @@ await test('context socket exposes only validated immutable file requests and ge }); try { assert.deepEqual(await send('{"snapshot":"head","path":"src/caller.ts"}'), {status:200,body:'{"available":true}'}); - for (const body of ['{"snapshot":"other","path":"file"}','{"snapshot":"head","path":"file","url":"https://evil.invalid"}','{"snapshot":"head"}','sensitive fixture error']) { + assert.deepEqual(await send('{"snapshot":"head","path":"optional.ts"}','/probe'),{status:200,body:'{"exists":false}'}); + assert.deepEqual(await send('{"snapshot":"head","path":"src/caller.ts"}','/probe'),{status:200,body:'{"exists":true}'}); + for (const body of ['{"snapshot":"other","path":"file"}','{"snapshot":"head","path":"file","url":"https://evil.invalid"}','{"snapshot":"head"}','sensitive fixture error','{"snapshot":"head","path":"file","required":false}','{"snapshot":"head","path":"file","operation":"probe"}']) { assert.deepEqual(await send(body),{status:400,body:'{"error":"context_lookup_unavailable"}'}); } - assert.equal((await send('{}','/url')).status,400); assert.equal((await send('{}','/file','GET')).status,400); assert.deepEqual(calls,[['head','src/caller.ts']]); + assert.equal((await send('{"snapshot":"head","path":"file","required":false}','/probe')).status,400); + assert.equal((await send('{}','/url')).status,400); assert.equal((await send('{}','/file','GET')).status,400); assert.deepEqual(calls,[['head','src/caller.ts'],['head','optional.ts','probe'],['head','src/caller.ts','probe']]); } finally { await close(); await rm(root,{recursive:true,force:true}); } }); await test('context shutdown cancels and drains active lookups before temporary source cleanup', async () => { diff --git a/tests/context.test.ts b/tests/context.test.ts index 0b2c335..c815a39 100644 --- a/tests/context.test.ts +++ b/tests/context.test.ts @@ -8,13 +8,14 @@ import { join } from 'node:path'; import { collectContext, type ContextLookup } from '../src/runner/context.js'; import { snapshot, HEAD, BASE, WORKFLOW, files } from './fixtures.js'; -type Options = { source?: string; language?: 'py' | 'rs'; mode?: string; truncated?: boolean; binary?: boolean; corrupt?: boolean; status?: string; patch?: string; apiStatus?: number; missingFiles?: boolean; dependency?: 'present' | 'missing' }; -async function fixture(options: Options = {}, exercise?: (lookup: ContextLookup, directory: string) => Promise) { +type Options = { source?: string; language?: 'py' | 'rs'; mode?: string; truncated?: boolean; binary?: boolean; corrupt?: boolean; status?: string; patch?: string; apiStatus?: number; missingFiles?: boolean; dependency?: 'present' | 'missing'; candidate?:boolean; candidateMode?:string; candidateOversized?:boolean; candidateCorrupt?:boolean; candidateApiStatus?:number; probeFailure?:number|'truncated'|'integrity' }; +async function fixture(options: Options = {}, exercise?: (lookup: ContextLookup, directory: string, manifest: Awaited>) => Promise) { const directory = await mkdtemp(join(tmpdir(), 'codexbot-context-')); const requested: string[] = [], blob = Buffer.from(options.source ?? (options.binary ? 'binary\0data' : options.language === 'py' ? 'from .dep import check\nfixture context text' : options.language === 'rs' ? 'mod dep;\nfixture context text' : options.dependency ? 'import { check } from "./dep.js";\nfixture context text' : 'fixture context text')); const blobSha = createHash('sha1').update(`blob ${blob.length}\0`).update(blob).digest('hex'); const dependency = Buffer.from('export const check = () => true;'), dependencySha = createHash('sha1').update(`blob ${dependency.length}\0`).update(dependency).digest('hex'); - const root = 'e'.repeat(40), src = 'f'.repeat(40); + const root = 'e'.repeat(40), src = 'f'.repeat(40),unexplored='d'.repeat(40),branches=Array.from({length:12},(_,n)=>(n+1).toString(16).padStart(40,'0')); + const candidate=Buffer.from(options.candidateOversized?'x'.repeat(512001):'candidate fixture source'),candidateSha=createHash('sha1').update('blob '+candidate.length+'\0').update(candidate).digest('hex'); const fetcher: typeof fetch = async input => { const url = new URL(String(input)); requested.push(url.pathname); if (url.pathname.endsWith('/pulls/4')) return Response.json({ head: { sha: HEAD }, base: { sha: BASE }, changed_files: options.missingFiles ? 2 : 1 }); @@ -26,15 +27,21 @@ async function fixture(options: Options = {}, exercise?: (lookup: ContextLookup, } if (url.pathname.includes('/git/trees/')) { assert.equal(url.searchParams.has('recursive'), false); - const sha = url.pathname.split('/').at(-1); assert.ok(sha === root || sha === src, 'Trees endpoint must receive resolved tree SHA, never commit SHA'); + const sha = url.pathname.split('/').at(-1); + if(options.probeFailure&&sha===unexplored)return typeof options.probeFailure==='number'?Response.json({message:'private API detail'},{status:options.probeFailure}):Response.json({sha:options.probeFailure==='integrity'?root:sha,truncated:options.probeFailure==='truncated',tree:[]}); + if(options.probeFailure&&branches.includes(sha!))return Response.json({sha,truncated:false,tree:[]}); + assert.ok(sha === root || sha === src, 'Trees endpoint must receive resolved tree SHA, never commit SHA'); return Response.json({ sha, truncated: options.truncated ?? false, tree: sha === root ? [ { type: 'tree', mode: '040000', path: 'src', sha: src }, { type: 'blob', mode: '100644', path: 'AGENTS.md', size: blob.length, sha: blobSha }, + ...(options.candidate?[{type:options.candidateMode==='160000'?'commit':options.candidateMode==='040000'?'tree':'blob',mode:options.candidateMode??'100644',path:'candidate.ts',sha:candidateSha,size:candidate.length}]:[]), + ...(options.probeFailure?[...branches.map((sha,n)=>({type:'tree',mode:'040000',path:'branch'+n,sha})),{type:'tree',mode:'040000',path:'unexplored',sha:unexplored}]:[]), ...Array.from({ length: 1200 }, (_, n) => ({ type: 'blob', mode: '100644', path: `unrelated-${n}.ts`, size: 500_000, sha: '0'.repeat(40) })) ] : [...[options.language ? 'auth.' + options.language : 'auth.ts', 'old.ts'].map(path => ({ type: options.mode === '160000' ? 'commit' : 'blob', mode: options.mode ?? '100644', path, size: blob.length, sha: blobSha })), ...(options.dependency === 'present' ? [{ type: 'blob', mode: '100644', path: options.language ? 'dep.' + options.language : 'dep.ts', size: dependency.length, sha: dependencySha }] : [])] }); } if (url.pathname.includes('/git/blobs/')) { + if(url.pathname.endsWith(candidateSha))return options.candidateApiStatus?Response.json({message:'private blob detail'},{status:options.candidateApiStatus}):Response.json({sha:candidateSha,encoding:'base64',content:(options.candidateCorrupt?Buffer.alloc(candidate.length,120):candidate).toString('base64')}); if (url.pathname.endsWith(dependencySha)) return Response.json({ sha: dependencySha, encoding: 'base64', content: dependency.toString('base64') }); assert.equal(url.pathname.split('/').at(-1), blobSha, 'Unrelated blobs must never be downloaded'); return Response.json({ sha: blobSha, encoding: 'base64', content: (options.corrupt ? Buffer.from('tampered') : blob).toString('base64') }); @@ -44,7 +51,7 @@ async function fixture(options: Options = {}, exercise?: (lookup: ContextLookup, try { let lookup: ContextLookup | undefined; const result = await collectContext(new Octokit({ request: { fetch: fetcher }, log: { debug() {}, info() {}, warn() {}, error() {} } }), snapshot(), directory, exercise ? reader => { lookup = reader; } : undefined); - if (exercise) { assert.ok(lookup); await exercise(lookup, directory); } + if (exercise) { assert.ok(lookup); await exercise(lookup, directory,result); } const instructions = await readFile(join(directory, 'trusted-instructions.json'), 'utf8'); return { result, requested, instructions }; } finally { await rm(directory, { recursive: true, force: true }); } @@ -112,3 +119,47 @@ export const fixture = {generated,template};`; const missing=await fixture({source});assert.equal(missing.result.complete,false,source);assert.equal(missing.result.requiredContextComplete,false,source); } }); + +await test('initially complete context becomes incomplete after an essential on-demand miss, with a safe durable reason',async()=>{ + const {result}=await fixture({},async(lookup,directory,manifest)=>{ + assert.equal(manifest.complete,true);assert.equal(manifest.diffComplete,true); + assert.equal(await lookup('head','src/private-missing-name.ts'),false); + assert.equal(manifest.complete,false);assert.equal(manifest.requiredContextComplete,false);assert(manifest.failureCodes.includes('context_path_missing')); + const persisted=JSON.parse(await readFile(join(directory,'manifest.json'),'utf8')); + assert.equal(persisted.complete,false);assert.equal(persisted.requiredContextComplete,false);assert(!JSON.stringify(persisted.failureCodes).includes('private-missing-name')); + assert.equal(await lookup('head','src/old.ts'),true);assert.equal(manifest.complete,false,'A later success must not erase missing essential evidence'); + });assert.equal(result.complete,false); +}); +await test('exhausting on-demand lookup allowance cannot leave an approving context flag',async()=>{ + await fixture({},async(lookup,_directory,manifest)=>{for(let n=0;n<24;n++)assert.equal(await lookup('head','src/old.ts'),true);assert.equal(manifest.complete,true);await assert.rejects(lookup('head','src/old.ts'),/context_lookup_rejected/);assert.equal(manifest.complete,false);assert.equal(manifest.requiredContextComplete,false);assert(manifest.failureCodes.includes('context_lookup_rejected'));}); +}); + +await test('optional probes verify absence without source reads or completeness loss; required misses stay sticky',async()=>{ + await fixture({},async(lookup,directory,manifest)=>{ + assert.equal(await lookup('head','src/speculative-name.ts','probe'),false);assert.equal(manifest.complete,true);assert.equal(manifest.requiredContextComplete,true);assert.equal(manifest.failureCodes.length,0); + assert.equal(await lookup('head','src/old.ts','probe'),true);await assert.rejects(readFile(join(directory,'source/head/src/old.ts'))); + assert.equal(await lookup('head','src/speculative-name.ts'),false);assert.equal(manifest.complete,false);assert(manifest.failureCodes.includes('context_path_missing')); + assert.equal(await lookup('head','src/speculative-name.ts','probe'),false);assert.equal(await lookup('head','src/old.ts'),true);assert.equal(manifest.complete,false); + assert.equal(JSON.parse(await readFile(join(directory,'manifest.json'),'utf8')).complete,false); + }); + await fixture({dependency:'missing'},async(lookup,_directory,manifest)=>{assert.equal(manifest.complete,false);assert.equal(await lookup('head','src/dep.ts','probe'),false);assert.equal(manifest.complete,false);assert(manifest.failureCodes.includes('context_missing_dependency'));}); + const {requested}=await fixture({candidate:true},async(lookup,directory,manifest)=>{assert.equal(await lookup('head','candidate.ts','probe'),true);assert.equal(manifest.complete,true);await assert.rejects(readFile(join(directory,'source/head/candidate.ts')));});assert.equal(requested.filter(path=>path.includes('/git/blobs/')).length,1,'An existence probe must not fetch source blobs'); +}); +await test('API failures, truncated and inconsistent trees are never converted into optional path absence',async()=>{ + for(const probeFailure of [404,403,429,500,'truncated','integrity'] as const)await fixture({probeFailure},async(lookup,_directory,manifest)=>{ + assert.equal(manifest.complete,true);await assert.rejects(lookup('head','unexplored/candidate.ts','probe'));assert.equal(manifest.complete,false);assert.equal(manifest.requiredContextComplete,false);assert(manifest.failureCodes.includes(typeof probeFailure==='number'?'context_github_api_failed':'required_tree_unverifiable')); + }); +}); +await test('mandatory content distinguishes missing paths, special objects, size limits, API errors and blob verification',async()=>{ + const cases=[{options:{candidate:true,candidateMode:'120000'},code:'context_special_object'},{options:{candidate:true,candidateMode:'160000'},code:'context_special_object'},{options:{candidate:true,candidateMode:'100664'},code:'context_special_object'},{options:{candidate:true,candidateOversized:true},code:'context_file_size_limit'},{options:{candidate:true,candidateCorrupt:true},code:'blob_integrity_failure'},{options:{candidate:true,candidateApiStatus:404},code:'context_github_api_failed'},{options:{candidate:true,candidateApiStatus:429},code:'context_github_api_failed'}]; + for(const {options,code}of cases)await fixture(options,async(lookup,_directory,manifest)=>{assert.equal(manifest.complete,true);assert.equal(await lookup('head','candidate.ts','probe'),true,'Probe means existence only, never readable/verified contents');assert.equal(manifest.complete,true);assert.equal(await lookup('head','candidate.ts'),false);assert.equal(manifest.complete,false);assert(manifest.failureCodes.includes(code),JSON.stringify(manifest.failureCodes));}); +}); +await test('optional probes share the original lookup cap without invalidating coverage; required calls cannot bypass it',async()=>{ + await fixture({},async(lookup,directory,manifest)=>{for(let n=0;n<24;n++)assert.equal(await lookup('head','src/missing-'+n+'.ts','probe'),false);await assert.rejects(lookup('head','src/no-more.ts','probe'),/context_lookup_rejected/);assert.equal(manifest.complete,true);assert.equal(manifest.failureCodes.length,0);await assert.rejects(lookup('head','src/old.ts'),/context_lookup_rejected/);assert.equal(manifest.complete,false);assert(manifest.failureCodes.includes('context_lookup_rejected'));assert.equal(JSON.parse(await readFile(join(directory,'manifest.json'),'utf8')).complete,false);}); +}); +await test('concurrent optional exploration and required reads serialize immutable state and never erase a required failure',async()=>{ + const {requested}=await fixture({candidate:true},async(lookup,directory,manifest)=>{ + const optional=await Promise.all([lookup('head','missing-a.ts','probe'),lookup('base','missing-b.ts','probe'),lookup('head','candidate.ts','probe')]);assert.deepEqual(optional,[false,false,true]);assert.equal(manifest.complete,true); + const mixed=await Promise.all([lookup('head','candidate.ts'),lookup('head','required-missing.ts'),lookup('base','missing-c.ts','probe'),lookup('head','candidate.ts')]);assert.deepEqual(mixed,[true,false,false,true]);assert.equal(manifest.complete,false);assert(manifest.failureCodes.includes('context_path_missing'));assert.equal(JSON.parse(await readFile(join(directory,'manifest.json'),'utf8')).complete,false); + });assert.equal(requested.filter(path=>path.includes('/git/blobs/')).length,2,'Concurrent content requests must reuse verified blobs'); +}); diff --git a/tests/execution.test.ts b/tests/execution.test.ts index ca9a974..efa4e36 100644 --- a/tests/execution.test.ts +++ b/tests/execution.test.ts @@ -1,16 +1,19 @@ import { test, mock } from 'node:test'; import assert from 'node:assert/strict'; import childProcess from 'node:child_process'; +import http from 'node:http'; +import{createHash}from'node:crypto'; import { syncBuiltinESMExports } from 'node:module'; import { EventEmitter } from 'node:events'; import { PassThrough, Writable } from 'node:stream'; import { AppError } from '../src/core/errors.js'; -import { diagnostic } from '../src/core/diagnostics.js'; +import { diagnostic, ReviewCompletionError } from '../src/core/diagnostics.js'; import { ExecutionDiagnostics, ExecutionError, executionEnvelope, executionFailure } from '../src/core/execution.js'; import { docker } from '../src/runner/docker.js'; import { runCodex } from '../src/runner/engine.js'; import { Rpc } from '../src/runner/rpc.js'; import { reviewJob, waitForRefresh } from '../src/runner/main.js'; +import { decision } from '../src/core/review.js'; import { snapshot, clean } from './fixtures.js'; const sensitive = 'Bearer fixture-private-credential OAuth-code private-source prompt-provider-message'; @@ -130,7 +133,11 @@ await test('actual review job records incomplete fallback, releases acquired lea const saved = { ...process.env }, request = snapshot(); request.config.credentials.mode = 'api-key'; const submissions: Record[] = [], operations: string[] = [], logs: unknown[][] = []; let rejectReporting = false, rejectReadTokenCleanup = false; - let containerOutput: unknown = null, unavailableContext = false, runs = 0; + let containerOutput: unknown = null, unavailableContext = false, runs = 0, onDemandMissing = false, probeOnly=false; + let contextSocket='',contextListener:http.Server|undefined; + const realServer=http.createServer; + const serverMock=mock.method(http,'createServer',(...args:Parameters)=>{const server=realServer(...args);contextListener=server;server.once('listening',()=>{const address=server.address();if(typeof address==='string')contextSocket=address;});return server;}); + const blob=Buffer.from('context\nold\n'),blobSha=createHash('sha1').update('blob '+blob.length+'\0').update(blob).digest('hex'); Object.assign(process.env, { CODEXBOT_BACKEND: 'https://broker.invalid', CODEXBOT_REQUEST_ID: request.id, CODEXBOT_API_KEY: sensitive, CODEXBOT_CREDENTIAL_OWNER: '5', CODEXBOT_INSTALLATION_ID: '1', CODEXBOT_IMAGE: 'sha256:fixture', ACTIONS_ID_TOKEN_REQUEST_URL: 'https://oidc.invalid/token', ACTIONS_ID_TOKEN_REQUEST_TOKEN: sensitive }); delete process.env.CODEXBOT_VAULT_KEY; @@ -138,16 +145,17 @@ await test('actual review job records incomplete fallback, releases acquired lea Object.defineProperty(process, 'getuid', { value: () => 1000, configurable: true }); Object.defineProperty(process, 'getgid', { value: () => 1000, configurable: true }); const spawn = mock.method(childProcess, 'spawn', (_file: string, args: string[]) => { const process = child(); - queueMicrotask(() => { + queueMicrotask(() => {void(async()=>{ if (args[0] === 'logs' && args.includes('--follow')) { process.stdout.write('codexbot-proxy-ready\n'); return; } if (args[0] === 'run') { runs++; + if(onDemandMissing){await new Promise((resolve,reject)=>{const req=http.request({socketPath:contextSocket,path:probeOnly?'/probe':'/file',method:'POST'},res=>{let body='';res.on('data',x=>{body+=String(x);});res.on('end',()=>{try{assert.deepEqual(JSON.parse(body),probeOnly?{exists:false}:{available:false});resolve();}catch(error){reject(error);}});});req.on('error',reject);req.end(JSON.stringify({snapshot:'head',path:'private-missing-name.ts'}));});} if (containerOutput !== null) process.stdout.write(JSON.stringify(containerOutput)); else process.stderr.write(executionEnvelope({ component: 'turn', code: 'codex_turn_failed' }) + '\n'); } if (args[0] === 'logs') process.stderr.write(executionEnvelope({ component: 'provider', code: 'provider_http_failed', upstream_status: 401 }) + '\n'); process.stdout.end(); process.stderr.end(); process.emit('close', args[0] === 'run' && containerOutput === null ? 1 : 0, null); - }); return process; + })().catch(()=>process.emit('error',new Error('Synthetic context fixture failed')));}); return process; }); syncBuiltinESMExports(); const fetcher = mock.method(globalThis, 'fetch', async (input: Parameters[0], init?: Parameters[1]) => { const url = new URL(String(input)); @@ -156,14 +164,16 @@ await test('actual review job records incomplete fallback, releases acquired lea const operation = url.pathname.split('/').at(-1)!; operations.push(operation); if (operation === 'prepare') return Response.json({ snapshot: request, read_token: sensitive }); if (operation === 'result' && rejectReporting) return Response.json({ error: 'internal_error', message: sensitive }, { status: 503 }); + if(operation==='result'&&onDemandMissing)assert.equal(contextListener!.listening,false,'Context lookups must drain before result submission'); if (operation === 'result') submissions.push(JSON.parse(String(init?.body)) as Record); return Response.json({ status: 'recorded' }); } if (url.pathname.endsWith('/installation/token')) return rejectReadTokenCleanup ? Response.json({ message: sensitive }, { status: 503 }) : new Response(null, { status: 204 }); - if (url.pathname.endsWith('/pulls/4')) return Response.json({ head: { sha: request.head }, base: { sha: request.base }, changed_files: 0 }); - if (url.pathname.endsWith('/pulls/4/files')) return Response.json([]); + if (url.pathname.endsWith('/pulls/4')) return Response.json({ head: { sha: request.head }, base: { sha: request.base }, changed_files: onDemandMissing?1:0 }); + if (url.pathname.endsWith('/pulls/4/files')) return Response.json(onDemandMissing?[{filename:'auth.ts',status:'modified',patch:'@@ -1,2 +1,2 @@\n context\n-old\n+new'}]:[]); if (url.pathname.includes('/git/commits/')) return Response.json({ sha: url.pathname.split('/').at(-1), tree: { sha: 'e'.repeat(40) } }); - if (url.pathname.includes('/git/trees/')) return Response.json({ sha: 'e'.repeat(40), truncated: unavailableContext, tree: [] }); + if (url.pathname.includes('/git/trees/')) return Response.json({ sha: 'e'.repeat(40), truncated: unavailableContext, tree: onDemandMissing?[{path:'auth.ts',type:'blob',mode:'100644',size:blob.length,sha:blobSha}]:[] }); + if(url.pathname.includes('/git/blobs/'))return Response.json({sha:blobSha,encoding:'base64',content:blob.toString('base64')}); throw new Error('Unexpected fixture route'); }); const logger = mock.method(console, 'error', (...args: unknown[]) => logs.push(args)); @@ -181,6 +191,13 @@ await test('actual review job records incomplete fallback, releases acquired lea rejectReporting = false; containerOutput = clean(); await reviewJob(); assert.equal(submissions.at(-1)!.context_complete, true); assert.equal(submissions.at(-1)!.failure, undefined); + onDemandMissing=true;probeOnly=true;containerOutput=clean(); + await reviewJob();assert.equal(submissions.at(-1)!.context_complete,true);assert.equal(submissions.at(-1)!.failure,undefined);assert.deepEqual(submissions.at(-1)!.output,clean()); + probeOnly=false; + containerOutput={...clean(),result:'findings',findings:[{severity:'high',confidence:0.99,path:'auth.ts',line:2,side:'RIGHT',title:'Synthetic race condition',explanation:'A stale value can overwrite a newer result.',remediation:'Guard the update.'}]}; + await assert.rejects(reviewJob(),error=>{assert(error instanceof ReviewCompletionError);assert.equal(error.completion.context_complete,false);assert.equal(error.completion.required_context_complete,false);assert.equal(error.completion.diff_complete,true);assert.equal(error.completion.output_complete,true);assert.equal(error.completion.output_result,'findings');assert.equal(error.completion.context_failure_code,'context_path_missing');return true;}); + assert.deepEqual(submissions.at(-1)!.output,containerOutput);assert.equal(submissions.at(-1)!.context_complete,false);assert.equal(decision(submissions.at(-1)!.output as ReturnType,request.config,false),'COMMENT');assert.equal((submissions.at(-1)!.failure as {stage:string}).stage,'result');assert(!JSON.stringify(logs).includes('private-missing-name'));assert.equal(operations.at(-1),'release'); + onDemandMissing=false;containerOutput=clean(); rejectReadTokenCleanup = true; await assert.rejects(reviewJob(), /read_token_cleanup_failed/); assert.equal(operations.at(-1), 'release'); rejectReadTokenCleanup = false; @@ -189,6 +206,7 @@ await test('actual review job records incomplete fallback, releases acquired lea assert.equal(submissions.at(-1)!.context_complete, false); assert.equal((submissions.at(-1)!.output as { result: string }).result, 'inconclusive'); assert.equal((submissions.at(-1)!.failure as { code: string }).code, 'review_incomplete'); + assert.deepEqual((submissions.at(-1)!.failure as {completion:unknown}).completion,{context_complete:true,diff_complete:true,required_context_complete:true,output_complete:false,output_result:'inconclusive',quarantined:false,output_truncated:false}); containerOutput = { ...clean(), complete: false }; // A clean label cannot override incomplete analysis. await assert.rejects(reviewJob(), /review_output_invalid/); assert.equal((submissions.at(-1)!.output as { result: string }).result, 'inconclusive'); @@ -198,7 +216,7 @@ await test('actual review job records incomplete fallback, releases acquired lea assert.equal((submissions.at(-1)!.failure as { code: string }).code, 'required_tree_unverifiable'); assert.equal(operations.at(-1), 'release'); } finally { - fetcher.mock.restore(); logger.mock.restore(); spawn.mock.restore(); syncBuiltinESMExports(); + fetcher.mock.restore(); logger.mock.restore(); spawn.mock.restore();serverMock.mock.restore(); syncBuiltinESMExports(); if (uid) Object.defineProperty(process, 'getuid', uid); else Reflect.deleteProperty(process, 'getuid'); if (gid) Object.defineProperty(process, 'getgid', gid); else Reflect.deleteProperty(process, 'getgid'); for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]; Object.assign(process.env, saved); @@ -215,3 +233,8 @@ await test('runner waits for the provider refresh window without consuming a tok for(const earliest of [NaN,Infinity,-1,Date.now()+25*60000+1])await assert.rejects(waitForRefresh(earliest),{code:'oauth_refresh_window_unavailable'}); }finally{t.mock.timers.reset();} }); + +await test('final completion diagnostics project only conditions and approved failure codes, never arbitrary detail',()=>{ + const value={context_complete:false,diff_complete:true,required_context_complete:false,output_complete:true,output_result:'findings' as const,quarantined:false,output_truncated:false,context_failure_code:sensitive,message:sensitive,path:sensitive,summary:sensitive}; + const report=diagnostic(new ReviewCompletionError(value),'result');assert.equal(report.code,'review_incomplete');assert.equal(report.stage,'result');assert.equal(report.status,undefined);assert.equal(report.completion!.context_failure_code,undefined);assert.equal(Object.keys(report.completion!).length,7);assert(!JSON.stringify(report).includes(sensitive)); +}); diff --git a/tests/inspection-check.mjs b/tests/inspection-check.mjs index 92ae4db..aa7e16b 100644 --- a/tests/inspection-check.mjs +++ b/tests/inspection-check.mjs @@ -44,7 +44,9 @@ for (const scenario of ['untrusted', 'findings', 'clean', 'incomplete','vision', explanation: 'The nonempty owner string makes the authorization result truthy for every other role.', remediation: 'Compare role against owner explicitly.' }] }; const encodedResult=scenario==='json-invalid'?'not-json':JSON.stringify(scenario==='schema-invalid'?{unexpected:true}:result); const probe = `import assert from 'node:assert/strict';import fs from 'node:fs';import net from 'node:net';import http from 'node:http';import {createHash} from 'node:crypto'; - const lookup=body=>new Promise((resolve,reject)=>{const r=http.request({socketPath:'/run/proxy/context.sock',path:'/file',method:'POST'},s=>{let text='';s.on('data',b=>text+=b);s.on('end',()=>resolve(JSON.parse(text)))});r.on('error',reject);r.end(JSON.stringify(body))}); + const lookup=(body,path='/file')=>new Promise((resolve,reject)=>{const r=http.request({socketPath:'/run/proxy/context.sock',path,method:'POST'},s=>{let text='';s.on('data',b=>text+=b);s.on('end',()=>resolve(JSON.parse(text)))});r.on('error',reject);r.end(JSON.stringify(body))}); + assert.deepEqual(await lookup({snapshot:'head',path:'optional-missing.js'},'/probe'),{exists:false}); + assert.deepEqual(await lookup({snapshot:'head',path:'src/caller.js'},'/probe'),{exists:true}); assert.deepEqual(await lookup({snapshot:'head',path:'src/caller.js'}),{available:true}); assert.deepEqual(await lookup({snapshot:'head',path:'src/caller.js',url:'https://evil.invalid'}),{error:'context_lookup_unavailable'}); for(const [name,path] of Object.entries({diff:'/workspace/diff.json',source:'/workspace/source/head/src/access.js',base:'/workspace/source/base/src/access.js',instructions:'/workspace/trusted-instructions.json',caller:'/workspace/source/head/src/caller.js',hostile:'/workspace/source/head/README.md'})) console.log('fixture_read_'+name+'='+createHash('sha256').update(fs.readFileSync(path)).digest('hex'));