Files
gstack/test/helpers/plan-count-transcript.ts
Garry TanandOpenAI Codex 9f81911136 v1.86.0.0 feat: route outside reviews by harness (#2850)
* feat: add a restricted and supervised Claude Code runner

Preserve configured authentication and models while enforcing tool access, strict completion JSON, bounded output and process cleanup. Cover argv, failure handling, session metadata and Windows process containment.

* feat: route outside reviews by harness and migrate wrapper installs

Use Claude Code from Codex and Codex from other supported hosts, with shared invocation rendering, positive gate validation and per-phase provenance. Rename /claude to /claude-code, repair managed shared and copied installations safely, and generate native Kiro skills. Add installed-workflow, failure-injection and live cross-harness regression coverage.

* test: recognize CEO mode labels without terminal spacing

The paid workflow rendered SCOPEEXPANSION at option 4, but its driver required a literal space. Match the leading mode title without cursor-spacing artifacts and ignore adjacent preview text. Preserve missing-target failures and downstream posture assertions.

* test: isolate plan-count fixtures before starting review workflows

Seed the complete test plan in a private git repository before launching Claude, so a bare slash command cannot review the live workspace while a delayed fixture message remains queued. Preserve count thresholds, parsers and budgets. Add initial-context and installed-discovery tests, and retain startup/terminal diagnostics on failed evaluations.

* test: stabilize review fixtures and Claude eval startup

Preserve source boundaries in workflow judge inputs, isolate CEO mode plans, and wait for interactive trust input readiness. Keep startup failure evidence and retain existing models, budgets, and assertions.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: classify collapsed review modes and isolate seeded findings

Keep review questions out of the setup count when terminal cursor positioning removes spaces. State existing webhook safeguards so the five-finding control measures its seeded defects without accidental extra security and concurrency gaps. Preserve question bands and the paired control.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: isolate browser daemon state across free shards

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: stabilize native review counting and interactive navigation

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* chore: prepare v1.82.0.0 release

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: eliminate browser and process-cleanup test flakes

Pin every CI surface to Bun 1.4.0 to avoid extra-stdio finalizers closing
reused live sockets. Add an isolated GC/listener regression that fails on
Bun 1.3.13, and prevent coordinated rollback to an affected CI runtime.

Check renderer cleanup against the render's own staging directory so
concurrent renders cannot invalidate the assertion. Make the no-pgrep
process-tree walk tolerate disappearing /proc entries, and synchronize
its test fixture through child readiness and pipe EOF instead of sleeps.

Validation: 9,157 passed, 31 skipped, zero failures across 556 files with
retries disabled. Build, all-host generation freshness, and skill checks
passed. All three races have failing-before/passing-after regressions.

* fix: count completed native review questions in evals

* fix: drive review navigation from confirmed native choices

* fix: require complete section-loading eval reports

* test: isolate telemetry HTTP transport from local assertions

* fix: keep review input on the active native question

* test: let tunnel revocation daemon choose an available port

* test: allocate available ports for pairing and watchdog fixtures

* fix: stabilize planning eval navigation and phase reporting

* test: isolate installed runtime paths in planning evals

* test: stabilize review evidence and concurrent refresh fixtures

* fix: resolve design findings before editing the plan

* fix: honor and persist disabled outside plan reviews

* fix: preserve planning decisions and terminal evidence

Load installed host reviews at autoplan phase entry and wait for completed
reviewers and saved artifacts. Reuse approved remedies while preserving
individual finding decisions.

Drive interactive evals from the current terminal viewport, bind native
questions across scrolling, and require complete native report evidence.
Cover captured stale menus, permission lifecycles, setup classification,
and disabled-review tool availability with deterministic regressions.

Advance release metadata and the upgrade migration to the unclaimed
1.83.0.0 slot.

* fix: drive native review questions and preserve current plans

Use the native single-choice keyboard protocol and current terminal viewport,
with per-question navigation inside packets and completed-call coverage.
Keep permissions, multi-select menus, and Submit controls distinct.

Send Autoplan reviewers the amended implementation plan, keep its review record
separate, and supply retained application contracts in the chain fixture.
Clarify individual DevEx decisions and complete CEO fix options; use one active
plan destination for the section-loading report.

* fix: preserve complete plan-review decisions

* fix: recognize native plan dialogs and reviewer controls

* fix: preserve review decisions and phase completion

* fix: recognize completed reviews without losing findings

* fix: preserve review continuity and native eval completion

* test: fix native review completion and eval retry isolation

* test: handle native review menus and complete eval fixtures

* test: fix native review setup, completion, and isolation failures

* test: limit native skill discovery to runtime assets

* fix: bind Autoplan reviews to full ordered phase inputs

* test: fix planning eval routing, counting, and timeout handling

* chore: advance queued release to v1.84.0.0

* fix: preserve complete review inputs and planning decisions

* fix: reconcile review approvals and preserve phase obligations

* fix: preserve review obligations and unblock eval permissions

Carry recorded Autoplan requirements into blind phase inputs, require Eng
review approvals before exit, and exercise combined asynchronous flows in
CEO reviews. Correct native finding and handoff classification and unblock
repeated report edits using scoped request identities.

* fix: retain plan requirements and complete native review dialogs

* fix: complete native review prompts and retain plan references

* fix: preserve review inputs and classify native eval evidence

* fix: check competing completion orders in CEO reviews

* fix: recognize review decisions and require phase methodology

Require the current phase methodology before Autoplan snapshots. Correct
substantive decision, closed handoff, and cache-finding classification, and
honor the recommended implementation approach in native review dialogs.

Add captured-transcript regressions without changing review thresholds,
provider models, retries, or deadlines.

* test: bind native review decisions and close completed handoffs

* fix: complete review dialogs and verify methodology delivery

* fix: preserve review evidence and unblock native eval prompts

* fix: handle native review question completions

* fix: recognize native review narration and controls

* fix: count native review decisions and isolate eval fixtures

* test: verify seeded review coverage and current artifact permissions

* test: isolate model and brain-aware skill renders

* fix: repair native workflow evaluation and clarify review steps

* fix: stabilize workflow eval evidence and review guidance

* test: repair native workflow observation and fixture isolation

* fix: recognize completed workflow evidence and owned skill reads

* test: repair seeded workflow delivery and completion evidence

* test: recognize current review evidence across native forms

* test: handle native review variants and permission redraws

* fix: honor review preferences and recognize native eval evidence

* test: recognize completed review decisions and queued permissions

* test: match current review contracts and partial-line edits

* test: recognize completed workflow evidence and bounded human waits

* fix: preserve review entry gates and native eval interactions

* fix: recognize native workflow evidence and preserve review gates

* test: recognize current review evidence and preconfigure workflow fixtures

* test: recognize completed review findings and scoped artifact permissions

* fix: stabilize native workflow review and permission evidence

* fix: recognize current review evidence and scoped edit confirmations

Clarify Design and engineering review entry instructions and Design scoring.
Recognize required legacy coverage and public Autoplan completion recaps.
Bind the pending Edit confirmation to its exact file, ordered digest, and
one-request approval when a preceding command display remains visible.
Keep reviews within their existing size limits and preserve scope gates
when extracting workflow fixtures from either supported preamble header.

Keep failure outcomes, review thresholds, provider choices, and eval budgets.

* fix: recover review workflow progress and eval evidence

* fix: recognize valid review evidence and scope selection

* test: fix review evidence parsing and repeated artifact prompts

* test: recognize valid review decisions and pending native cards

* fix(plan-eng-review): keep final navigation consistent with approved tasks

* test: recognize valid review evidence and bind legacy diff requests

* fix: stabilize review eval evidence and harness repair guidance

* docs: update project documentation for v1.85.0.0

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* test: fix Windows CI fixtures and credential scan

Rebase captured JSON values and filesystem evidence using the appropriate
path convention. Compile native fake CLIs on Windows and synchronize pipe
holder readiness, with cleanup retained when assertions fail.

Assemble synthetic credential fixtures at runtime so the added-line scan
keeps enforcing the same gate without flagging its own rejection controls.

Discover generated skills directly for the empty-find regression check,
avoiding a recursive scan through saved evaluation artifacts and dependencies.

* fix: preserve source renders on Windows

Compare canonical generator paths using native separators so an output
sidecar pointing at the source cannot overwrite its skill or metadata.
Keep the regression fixture isolated from the real checkout and expose
freshness diagnostics before asserting subprocess status.

Detach Windows drain-test pipe holders from the fake provider's automatic
child cleanup while preserving the enclosing runner job and its assertions.

* fix: clarify outside review fallback and CEO decisions

Render one applicable own-harness fallback path and retain native review,
disabled policy, and missing-coverage semantics. Align report field names
and mode labels, and make the existing per-cut scope approval explicit.

Regenerate skill outputs and keep the workflow judge's model, thresholds,
and retry policy unchanged.

* chore: move release to free version slot (v1.86.0.0)

PR #2852 now claims v1.85.0.0. Align the release metadata and
rename migration so upgrades from that version still receive it.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* fix: include engineering review prerequisites and restore branch context

* fix: recognize coverage diagrams and clarify design review instructions

* fix: preserve file identities and join Windows test processes

---------

Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-09-14 14:32:45 -07:00

267 lines
14 KiB
TypeScript

/** Lossless, read-only question metadata from one isolated Claude fixture. */
import * as fs from 'node:fs';
import * as path from 'node:path';
export interface NativePlanQuestion {
header: string;
question: string;
options: Array<{ label: string; description?: string }>;
multiSelect?: boolean;
}
export interface NativePlanQuestionCall {
sessionId: string;
toolUseId: string;
questions: NativePlanQuestion[];
answered: boolean;
failed?: boolean;
failure?: string;
answers?: Record<string, string>;
unansweredQuestionIndices?: number[];
answeredAt?: string;
}
/** Optional public tool projection for the Autoplan delivery audit; never thinking. */
export interface NativePublicToolEvent {
sessionId: string;
timestamp: string;
toolUseId: string;
kind: 'use' | 'result';
name?: string;
/** Exact native message/request identity, used only for owned queued tools. */
messageId?: string;
requestId?: string;
input?: Record<string, unknown>;
content?: unknown;
file?: unknown;
isError?: boolean;
}
export interface PlanCountTranscript {
status: 'missing' | 'ready' | 'error';
calls: NativePlanQuestionCall[];
assistantMessages: Array<{ sessionId: string; text: string; timestamp: string }>;
/** Actual native plan-mode approval requests; pending is the UI gate, never an AUQ. */
planReadyRequests?: Array<{ sessionId: string; toolUseId: string; timestamp: string; failed: boolean; source?: 'pre_tool_use' }>;
error?: string;
}
/** A rejected/refused call needs an actual later answer, not unrelated progress. */
export function unresolvedPlanQuestionCalls(calls: NativePlanQuestionCall[]): NativePlanQuestionCall[] {
return calls.filter((call, index) => call.failed && !call.questions.every(q =>
calls.slice(index + 1).some(later => later.answered && later.answers?.[q.question])));
}
const MAX_BYTES = 32 * 1024 * 1024;
const MAX_FILES = 64;
const object = (value: unknown): value is Record<string, any> =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const validTimestamp = (value: unknown): value is string =>
typeof value === 'string' && Number.isFinite(Date.parse(value));
/** Read one length-delimited protobuf field, rejecting malformed/ambiguous input. */
function signatureField(bytes: Uint8Array | undefined, wanted: number): Uint8Array | undefined {
if (!bytes) return;
let cursor = 0;
let result: Uint8Array | undefined;
let seen = false;
const integer = () => {
let value = 0;
for (let shift = 0; shift < 70; shift += 7) {
if (cursor >= bytes.length) throw new Error('truncated signature');
const byte = bytes[cursor++]!;
value += (byte & 127) * 2 ** shift;
if (!Number.isSafeInteger(value)) throw new Error('signature integer overflow');
if (!(byte & 128)) return value;
}
throw new Error('overlong signature integer');
};
while (cursor < bytes.length) {
const key = integer();
const field = Math.floor(key / 8);
if (field < 1 || field > 0x1fffffff) throw new Error('invalid signature field');
if (field === wanted) {
if (seen) throw new Error('duplicate signature field');
seen = true;
}
switch (key % 8) {
case 0: integer(); break;
case 1: cursor += 8; break;
case 2: {
const length = integer();
if (length > bytes.length - cursor) throw new Error('truncated signature field');
if (field === wanted) result = bytes.subarray(cursor, cursor + length);
cursor += length;
break;
}
case 5: cursor += 4; break;
default: throw new Error('unsupported signature wire type');
}
if (cursor > bytes.length) throw new Error('truncated signature field');
}
return result;
}
/**
* Claude's public narration renderer classifies signature fields 2→1→8 as
* block_kind="narration": summaries of inter-tool prose, not private reasoning.
* Match that metadata only in this already-owned native transcript. This is
* classification, not cryptographic signature verification. Never read the
* thinking text of an untagged, unknown, malformed or legacy block.
*/
function publicNarrationText(block: Record<string, any>): string | undefined {
if (block.type !== 'thinking' || typeof block.signature !== 'string' ||
block.signature.length > 64 * 1024 || !/^[A-Za-z0-9+/]+={0,2}$/.test(block.signature)) return;
try {
const bytes = Buffer.from(block.signature, 'base64');
const canonical = bytes.toString('base64');
if (block.signature !== canonical && block.signature !== canonical.replace(/=+$/, '')) return;
const tag = signatureField(signatureField(signatureField(bytes, 2), 1), 8);
if (!tag || Buffer.from(tag).toString('utf8') !== 'narration') return;
return typeof block.thinking === 'string' && block.thinking.trim() ? block.thinking : undefined;
} catch { return; }
}
function validQuestions(value: unknown): value is NativePlanQuestion[] {
return Array.isArray(value) && value.length > 0 && value.every(q =>
object(q) && typeof q.header === 'string' && typeof q.question === 'string' && q.question.trim() &&
Array.isArray(q.options) && q.options.length >= 2 && q.options.every((o: unknown) =>
object(o) && typeof o.label === 'string' && o.label.trim()));
}
/**
* Count callers consume each answered (sessionId, toolUseId) once, regardless
* of questions[].length. A batched tool call must never become N findings.
* Partial final lines remain pending; missing/foreign/sidechain records add
* no coverage. Traversal stays inside the owned config's projects directory.
*/
export function readPlanCountTranscript(configDir: string, cwd: string,
onPublicToolEvent?: (event: NativePublicToolEvent) => void,
/** Optional exact parent journal, already validated by the owning native hook. */
ownedParentTranscript?: string,
): PlanCountTranscript {
const calls = new Map<string, NativePlanQuestionCall>();
const assistantMessages: PlanCountTranscript['assistantMessages'] = [];
const planReadyRequests = new Map<string, NonNullable<PlanCountTranscript['planReadyRequests']>[number]>();
let matched = false;
let bytes = 0;
let files = 0;
const projects = path.join(configDir, 'projects');
try {
if (!fs.existsSync(projects)) return { status: 'missing', calls: [], assistantMessages: [] };
const dirs = fs.readdirSync(projects, { withFileTypes: true }).filter(d => d.isDirectory());
if (dirs.length > MAX_FILES) throw new Error('too many project directories');
for (const dir of dirs) {
const project = path.join(projects, dir.name);
for (const entry of fs.readdirSync(project, { withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;
if (++files > MAX_FILES) throw new Error('too many transcript files');
const file = path.join(project, entry.name);
if (ownedParentTranscript !== undefined && file !== ownedParentTranscript) continue;
bytes += fs.statSync(file).size;
if (bytes > MAX_BYTES) throw new Error('transcript exceeds 32 MiB read limit');
const text = fs.readFileSync(file, 'utf8');
// Native sessions retain their original journal after Bash changes cwd.
// Admit that continuation only through UUID ancestry rooted in this
// fixture's first parent user message; legacy records keep exact-cwd scoping.
let originSeen = false;
const ancestry = new Set<string>();
const nativeUuid = (value: unknown): value is string =>
typeof value === 'string' && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
// Claude appends JSONL during rendering; an unfinished record is not
// evidence of a call or an answer until its newline has been written.
for (const line of text.slice(0, text.lastIndexOf('\n') + 1).split('\n')) {
if (!line.trim()) continue;
const record = JSON.parse(line);
if (!object(record) || typeof record.sessionId !== 'string' ||
entry.name !== `${record.sessionId}.jsonl` ||
(ownedParentTranscript !== undefined && record.agentId != null)) continue;
const parentMetadata = record.isSidechain === false && record.agentId == null &&
typeof record.cwd === 'string' && path.isAbsolute(record.cwd) &&
nativeUuid(record.uuid) && validTimestamp(record.timestamp);
const continuation = parentMetadata && nativeUuid(record.parentUuid) &&
ancestry.has(record.parentUuid) && !ancestry.has(record.uuid);
if (!originSeen && object(record.message) && ['user', 'assistant'].includes(record.message.role)) {
originSeen = true;
if (parentMetadata && record.cwd === cwd && record.message.role === 'user' &&
record.parentUuid === null) ancestry.add(record.uuid);
}
if (continuation) ancestry.add(record.uuid);
if ((record.cwd !== cwd && !continuation) || record.isSidechain !== false ||
!object(record.message) || !Array.isArray(record.message.content)) continue;
matched = true;
for (const block of record.message.content) {
if (!object(block)) continue;
if (onPublicToolEvent && validTimestamp(record.timestamp)) {
if (record.message.role === 'assistant' && block.type === 'tool_use' &&
typeof block.id === 'string' && typeof block.name === 'string' && object(block.input)) {
const batch = typeof record.message.id === 'string' && /^msg_[A-Za-z0-9_-]{1,160}$/.test(record.message.id) &&
typeof record.requestId === 'string' && /^req_[A-Za-z0-9_-]{1,160}$/.test(record.requestId)
? { messageId: record.message.id, requestId: record.requestId } : {};
onPublicToolEvent({ sessionId: record.sessionId, timestamp: record.timestamp,
toolUseId: block.id, kind: 'use', name: block.name, input: block.input, ...batch });
} else if (record.message.role === 'user' && block.type === 'tool_result' &&
typeof block.tool_use_id === 'string') {
onPublicToolEvent({ sessionId: record.sessionId, timestamp: record.timestamp,
toolUseId: block.tool_use_id, kind: 'result', content: block.content,
file: record.toolUseResult?.file, isError: block.is_error === true });
}
}
if (record.message.role === 'assistant' && validTimestamp(record.timestamp)) {
const text = block.type === 'text' && typeof block.text === 'string' && block.text.trim()
? block.text : publicNarrationText(block);
if (text) assistantMessages.push({ sessionId: record.sessionId, text, timestamp: record.timestamp });
}
if (record.message.role === 'assistant' && block.type === 'tool_use' && block.name === 'ExitPlanMode' &&
typeof block.id === 'string' && validTimestamp(record.timestamp)) {
const key = `${record.sessionId}:${block.id}`;
if (!planReadyRequests.has(key)) planReadyRequests.set(key, { sessionId: record.sessionId,
toolUseId: block.id, timestamp: record.timestamp, failed: false });
}
if (record.message.role === 'assistant' && block.type === 'tool_use' && block.name === 'AskUserQuestion' &&
typeof block.id === 'string' && object(block.input) && validQuestions(block.input.questions)) {
const key = `${record.sessionId}:${block.id}`;
const prior = calls.get(key);
if (prior && JSON.stringify(prior.questions) !== JSON.stringify(block.input.questions)) {
throw new Error('conflicting question metadata for one tool call');
}
if (!prior) calls.set(key, { sessionId: record.sessionId, toolUseId: block.id,
questions: block.input.questions, answered: false, failed: false });
} else if (record.message.role === 'user' && block.type === 'tool_result' &&
typeof block.tool_use_id === 'string') {
const ready = planReadyRequests.get(`${record.sessionId}:${block.tool_use_id}`);
if (ready && block.is_error === true) ready.failed = true;
const call = calls.get(`${record.sessionId}:${block.tool_use_id}`);
const answers = record.toolUseResult?.answers;
const validAnswers = call && object(answers) ? Object.fromEntries(call.questions
.filter(q => typeof answers[q.question] === 'string' && answers[q.question].trim())
.map(q => [q.question, answers[q.question]])) : {};
if (call && block.is_error !== true && Object.keys(validAnswers).length > 0) {
// The CLI allows submitting a multi-question packet with
// unanswered tabs. This completes ONE call, not N questions.
call.answered = true;
call.failed = false;
delete call.failure;
call.answers = validAnswers;
call.unansweredQuestionIndices = call.questions.flatMap((q, i) => q.question in validAnswers ? [] : [i]);
call.answeredAt = validTimestamp(record.timestamp) ? record.timestamp : undefined;
} else if (call) {
if (call.answered) throw new Error('conflicting successful and failed results for one question call');
call.failed = true;
call.failure = block.is_error === true ? 'Native question tool returned is_error' : 'Native question returned no matching nonempty answers';
}
}
}
}
}
}
return { status: matched ? 'ready' : 'missing', calls: [...calls.values()], assistantMessages,
...(planReadyRequests.size ? { planReadyRequests: [...planReadyRequests.values()] } : {}) };
} catch (error) {
// A failed read cannot silently turn an incomplete transcript into a
// complete review. Keep the diagnostic explicit and return no coverage.
return { status: 'error', calls: [], assistantMessages: [], error: `Claude question transcript: ${String(error)}` };
}
}