diff --git a/.gitignore b/.gitignore index 4a79818..5e9f469 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,9 @@ orchestrator/jobs/ orchestrator/data/ graphify-out/ +# Live cursor-agent NDJSON from v22:vendor-measure. Counts stay in the JSON report. +docs/v22/baseline/raw/cursor-agent-streams/ + # Prune / scratch .prune-snapshots/ *.log diff --git a/docs/v22/VENDOR-MEASURE.md b/docs/v22/VENDOR-MEASURE.md index e9d3272..916db71 100644 --- a/docs/v22/VENDOR-MEASURE.md +++ b/docs/v22/VENDOR-MEASURE.md @@ -11,18 +11,26 @@ O OpenRouter é secundário, compatível com OpenAI em `https://openrouter.ai/ap Dry-run do Cursor, sem chave e sem gasto: ```bash -git clone --branch cursor/v22-gap-vendor-1b-8ae3 https://github.com/GaabDevWeb/EvolveLoop.git && cd EvolveLoop/orchestrator && npm ci && npm run v22:vendor-measure -- --provider cursor-agent --dry-run +git clone --branch cursor/v22-gap-vendor-1c-8ae3 https://github.com/GaabDevWeb/EvolveLoop.git && cd EvolveLoop/orchestrator && npm ci && npm run v22:vendor-measure -- --provider cursor-agent --dry-run ``` Depois do merge, troca o `--branch` para `release/v2.1-freeze-preparation`. ## Cursor, corrida real +Pickup atual, N=5: + +```bash +cd orchestrator && npm ci && CURSOR_API_KEY="$CURSOR_API_KEY" npm run v22:vendor-measure -- --provider cursor-agent --n 5 +``` + +Variante context-sufficient, N=5: + ```bash -cd orchestrator && npm ci && CURSOR_API_KEY="$CURSOR_API_KEY" npm run v22:vendor-measure -- --provider cursor-agent +cd orchestrator && npm ci && CURSOR_API_KEY="$CURSOR_API_KEY" npm run v22:vendor-measure -- --provider cursor-agent --context-sufficient --n 5 ``` -A chave fica só na env. O argv é `cursor-agent -p --output-format stream-json --mode ask --trust`. O prompt vai no stdin. `--mode ask` evita escrita no repo. +A chave fica só na env. O argv é `cursor-agent -p --output-format stream-json --mode ask --trust`. O prompt vai no stdin. `--mode ask` evita escrita no repo. O primeiro comando grava `docs/v22/baseline/raw/p0-vendor-cursor-agent-live.json`. O segundo grava `docs/v22/baseline/raw/p0-vendor-cursor-agent-context-sufficient.json`. ## OpenRouter, dry-run e corrida real @@ -80,3 +88,14 @@ Para cada âncora, 1 se a resposta afirma o mesmo facto que a substring e cita o ### Efeito no corpus `docs/v22/FINAL-REPORT.md` já estava no B0 de `retomada`. O texto novo levou esse braço de 29649 para 30414 tokens. Na tarefa `restricoes_compactacao_handoff` o mesmo ficheiro passou a caber no retrieval: saiu `docs/architecture/v2.2/EVOLVELOOP_V2.2_GOALS.md` e entraram `docs/v22/FINAL-REPORT.md`, `docs/architecture/v2.2/V22-VENDOR-CACHE.md`, `docs/architecture/finalization/adrs/ADR-DR-0005-context-ownership-before-compaction.md` e `global-skills/technical-library-dossier/references/dossier-template.md`. O input V2.2 passou de 22003 para 22054. A compactação foi remensurada em `76636adf6077cb956b748b5af4c1125269833be2`: 22054 para 11251, fidelidade 1, 1430 linhas retiradas. Antes era 22003 para 10896, fidelidade 1, 854 linhas. Os outros quatro cartões mantiveram os tokens. O prompt da corrida live não é este: o sha256 foi conferido antes desta edição. + +## V22-GAP-VENDOR-1c + +As duas ordens que a hipótese aponta estão no prompt V2.2 porque a montagem do harness reutiliza boilerplate. Não são texto do retrieval. + +1. `1. **Ler skill:**` vem de `buildPickupPrompt` em `orchestrator/src/jobs/job-pickup.ts`. É a instrução 1 de todo pickup de SkillJob. O path é `job.skill_path`, e o bench põe `.cursor/skills/orquestrar/SKILL.md`. +2. `Please carefully read the repository and produce an evidence-backed answer.` vem de `buildBenchPickupBriefing` em `orchestrator/src/v22/bench-pickup-fixture.ts`. É o briefing que o harness coloca dentro desse pickup. + +O default desses dois ficheiros não muda. `--context-sufficient` é só do harness de medição. Com o bloco `### Context (budgeted retrieval)` e pelo menos um `--- path: ---`, as duas frases passam a pedir resposta com o contexto fornecido e leitura de arquivo só se faltar evidência. Sem esse bloco, o harness recusa a variante em vez de medir o pickup antigo. + +Cada chamada live do `cursor-agent` grava o NDJSON redigido em `docs/v22/baseline/raw/cursor-agent-streams/default/` ou `context-sufficient/`. Essa pasta está no `.gitignore`. O relatório traz, por chamada, `tool_calls_started`, `tool_calls_read_started`, `tool_calls_write_started`, `tool_calls_other_started` e `stream_path`. Tokens e custo do provider continuam `NOT_MEASURED`. diff --git a/orchestrator/src/providers/llm/cursor-agent-provider.ts b/orchestrator/src/providers/llm/cursor-agent-provider.ts index 62c08d3..b94b328 100644 --- a/orchestrator/src/providers/llm/cursor-agent-provider.ts +++ b/orchestrator/src/providers/llm/cursor-agent-provider.ts @@ -8,7 +8,10 @@ * (CURSOR_API_KEY) and is never placed on argv. */ +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; import { spawn } from "node:child_process"; +import { redactSecrets } from "../../evidence/secret-redaction.js"; export interface CursorToolCallCounts { started: number; @@ -30,6 +33,7 @@ export interface CursorCliMeasurement { cached_tokens: "NOT_MEASURED"; cost_usd: "NOT_MEASURED"; tool_calls: CursorToolCallCounts; + stream_path?: string; schema: "cursor-cli-output-format-2026-10-23"; } @@ -119,6 +123,27 @@ export function parseCursorAgentNdjson(stdout: string): CursorCliMeasurement { }; } +export function cursorStreamFileName(name: string): string { + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.ndjson$/.test(name)) { + throw new Error("cursor_agent_stream_name_invalid"); + } + return name; +} + +/** Writes redacted NDJSON. The unredacted stdout is never written. */ +export function writeRedactedCursorStream(dir: string, name: string, stdout: string, secrets: string[]): string { + const safe = cursorStreamFileName(name); + const canaries = secrets.filter((item) => item.length >= 6); + const redacted = redactSecrets(stdout, { extraCanaries: canaries }); + for (const secret of canaries) { + if (redacted.includes(secret)) throw new Error("cursor_agent_stream_secret"); + } + mkdirSync(dir, { recursive: true }); + const file = path.join(dir, safe); + writeFileSync(file, redacted.endsWith("\n") ? redacted : `${redacted}\n`); + return file; +} + export function spawnCursorAgent( bin: string, args: string[], diff --git a/orchestrator/src/providers/llm/llm-http-provider-adapter.ts b/orchestrator/src/providers/llm/llm-http-provider-adapter.ts index 8f23180..e362967 100644 --- a/orchestrator/src/providers/llm/llm-http-provider-adapter.ts +++ b/orchestrator/src/providers/llm/llm-http-provider-adapter.ts @@ -16,6 +16,7 @@ import { cursorAgentArgs, parseCursorAgentNdjson, spawnCursorAgent, + writeRedactedCursorStream, type CursorAgentSpawn, type CursorCliMeasurement, } from "./cursor-agent-provider.js"; @@ -275,6 +276,9 @@ export class LlmHttpProviderAdapter { cwd: string; env: NodeJS.ProcessEnv; spawnImpl?: CursorAgentSpawn; + streamDir?: string; + streamName?: string; + secrets?: string[]; }): Promise { const bin = input.bin ?? "cursor-agent"; const args = cursorAgentArgs({ model: input.model }); @@ -284,9 +288,13 @@ export class LlmHttpProviderAdapter { cwd: input.cwd, env: input.env, }); + let streamPath: string | undefined; + if (input.streamDir && input.streamName) { + streamPath = writeRedactedCursorStream(input.streamDir, input.streamName, child.stdout, input.secrets ?? []); + } if (child.status !== 0) { throw new Error(`cursor_agent_exit_${child.status}`); } - return parseCursorAgentNdjson(child.stdout); + return { ...parseCursorAgentNdjson(child.stdout), stream_path: streamPath }; } } diff --git a/orchestrator/src/v22/context-sufficient-pickup.ts b/orchestrator/src/v22/context-sufficient-pickup.ts new file mode 100644 index 0000000..94f80de --- /dev/null +++ b/orchestrator/src/v22/context-sufficient-pickup.ts @@ -0,0 +1,53 @@ +/** + * Measurement-only rewrite of two pickup boilerplate orders. + * + * The product pickup stays unchanged. The harness applies this only when + * the caller asks for the context-sufficient variant and the retrieval block + * is already in the prompt. + * + * Sources of the orders, read on the V2.2 assembly: + * - "Ler skill" is instruction 1 of buildPickupPrompt in job-pickup.ts. + * - "Please carefully read the repository" is the bench briefing in + * buildBenchPickupBriefing. + */ + +export const PICKUP_READ_REPO_SENTENCE = + "Please carefully read the repository and produce an evidence-backed answer. Do not guess file paths."; + +export const CONTEXT_SUFFICIENT_SKILL_LINE = + "1. **Responder com o contexto fornecido.** O bloco de retrieval já está neste prompt. Ler um arquivo só se faltar evidência para a resposta."; + +export const CONTEXT_SUFFICIENT_REPO_SENTENCE = + "Answer from the context supplied in this prompt. Read a file only when that context lacks the evidence. Do not guess file paths."; + +const READ_SKILL_LINE = /^1\. \*\*Ler skill:\*\* `[^`]+`$/m; +const RETRIEVAL_MARKER = "### Context (budgeted retrieval)"; + +export interface ContextSufficientRewrite { + text: string; + retrieval_present: boolean; + replaced_skill_order: boolean; + replaced_repo_order: boolean; +} + +export function applyContextSufficientPickup(prompt: string): ContextSufficientRewrite { + const retrievalPresent = prompt.includes(RETRIEVAL_MARKER) && /^--- path:.+ ---$/m.test(prompt); + if (!retrievalPresent) { + return { + text: prompt, + retrieval_present: false, + replaced_skill_order: false, + replaced_repo_order: false, + }; + } + const replacedSkill = READ_SKILL_LINE.test(prompt); + let text = replacedSkill ? prompt.replace(READ_SKILL_LINE, CONTEXT_SUFFICIENT_SKILL_LINE) : prompt; + const replacedRepo = text.includes(PICKUP_READ_REPO_SENTENCE); + if (replacedRepo) text = text.split(PICKUP_READ_REPO_SENTENCE).join(CONTEXT_SUFFICIENT_REPO_SENTENCE); + return { + text, + retrieval_present: true, + replaced_skill_order: replacedSkill, + replaced_repo_order: replacedRepo, + }; +} diff --git a/orchestrator/src/v22/p0-baseline-harness.ts b/orchestrator/src/v22/p0-baseline-harness.ts index 208875a..1a4c7a9 100644 --- a/orchestrator/src/v22/p0-baseline-harness.ts +++ b/orchestrator/src/v22/p0-baseline-harness.ts @@ -26,6 +26,7 @@ import { applyTruthFence, codeOverridesWiki } from "../knowledge/truth-source/fe import type { TruthSourcedItem } from "../knowledge/truth-source/types.js"; import { resolveOrchestratorRoot } from "../cli/run-engine-env.js"; import { buildPickupPrompt } from "../jobs/job-pickup.js"; +import { applyContextSufficientPickup } from "./context-sufficient-pickup.js"; import { normalizeMeasurementPaths, stableJobsLabel } from "./measurement-paths.js"; import type { SkillJob } from "../jobs/job-store.js"; import { preparePickupSpawnContext } from "../jobs/spawn-pickup-context.js"; @@ -447,7 +448,8 @@ function isMeasurementArtifact(rel: string): boolean { key === "orchestrator/src/v22/vendor-measure-cli.ts" || key === "orchestrator/src/providers/llm/cursor-agent-provider.ts" || key === "orchestrator/tests/unit/v22-p0-baseline.test.ts" || - key === "orchestrator/tests/unit/v22-vendor-measure.test.ts" + key === "orchestrator/tests/unit/v22-vendor-measure.test.ts" || + key === "orchestrator/src/v22/context-sufficient-pickup.ts" ); } @@ -730,7 +732,13 @@ function pathsFromBudgeted(inner: string): string[] { return [...new Set(paths)]; } -function assembleV22(task: FrozenTask, cache: CorpusCache, root: string, jobsDir: string): Packed { +function assembleV22( + task: FrozenTask, + cache: CorpusCache, + root: string, + jobsDir: string, + options?: { contextSufficient?: boolean }, +): Packed { const patterns = queryPatterns(task.query); const hits = new Set(rgHits(root, patterns)); for (const page of wikiPages(root)) { @@ -795,11 +803,18 @@ function assembleV22(task: FrozenTask, cache: CorpusCache, root: string, jobsDir const promptRaw = task.handoff ? buildPickupPrompt(job, jobsDir, undefined, { caveman: false, spawnContext: spawn }) : extractBudgetedContext(spawn.budgeted_context_block); - const prompt = normalizeMeasurementPaths(promptRaw, { + let prompt = normalizeMeasurementPaths(promptRaw, { jobsDir, jobsLabel: stableJobsLabel(task.id, "V2.2"), orchestratorRoot: resolveOrchestratorRoot(), }); + if (options?.contextSufficient) { + const rewritten = applyContextSufficientPickup(prompt); + if (!rewritten.retrieval_present || !rewritten.replaced_skill_order || !rewritten.replaced_repo_order) { + throw new Error(`${task.id}: context-sufficient pickup was not applied`); + } + prompt = rewritten.text; + } const inner = extractBudgetedContext(spawn.budgeted_context_block); const retrievalTokens = countOne(inner); if (retrievalTokens > CANONICAL_MAX_INPUT_TOKENS) { @@ -943,6 +958,7 @@ export async function measureP0B0Text( export async function measureP0V22Text( taskId: P0TaskId, repoRoot = repoRootFromModule(), + options?: { contextSufficient?: boolean }, ): Promise<{ text: string; paths: string[] }> { const loaded = loadFrozenTasks(repoRoot); const task = loaded.tasks.find((item) => item.id === taskId); @@ -951,7 +967,7 @@ export async function measureP0V22Text( const jobsDir = path.join(tmpdir(), "v22-p0-compaction", task.id); await mkdir(jobsDir, { recursive: true }); try { - const packed = assembleV22(task, cache, repoRoot, jobsDir); + const packed = assembleV22(task, cache, repoRoot, jobsDir, options); return { text: packed.text, paths: packed.paths }; } finally { await rm(jobsDir, { recursive: true, force: true }); diff --git a/orchestrator/src/v22/vendor-measure-cli.ts b/orchestrator/src/v22/vendor-measure-cli.ts index aa12c09..e49811c 100644 --- a/orchestrator/src/v22/vendor-measure-cli.ts +++ b/orchestrator/src/v22/vendor-measure-cli.ts @@ -45,10 +45,17 @@ try { inputUsdPerMtok: numberOption("--input-usd-per-mtok"), outputUsdPerMtok: numberOption("--output-usd-per-mtok"), apiKey, + contextSufficient: flag("--context-sufficient"), bin: process.env.CURSOR_AGENT_BIN, env: process.env, }); - const out = path.join(repoRootFromModule(), "docs/v22/baseline/raw/p0-vendor-report.json"); + const reportName = + provider === "cursor-agent" + ? flag("--context-sufficient") + ? "p0-vendor-cursor-agent-context-sufficient.json" + : "p0-vendor-cursor-agent-live.json" + : "p0-vendor-report.json"; + const out = path.join(repoRootFromModule(), "docs/v22/baseline/raw", reportName); mkdirSync(path.dirname(out), { recursive: true }); const body = `${JSON.stringify(report, null, 2)}\n`; writeFileSync(out, redactSecrets(body, { extraCanaries: apiKey ? [apiKey] : [] })); diff --git a/orchestrator/src/v22/vendor-measure.ts b/orchestrator/src/v22/vendor-measure.ts index 963b67b..a568224 100644 --- a/orchestrator/src/v22/vendor-measure.ts +++ b/orchestrator/src/v22/vendor-measure.ts @@ -10,6 +10,7 @@ import { createHash } from "node:crypto"; import { spawnSync } from "node:child_process"; +import path from "node:path"; import { performance } from "node:perf_hooks"; import { redactSecrets } from "../evidence/secret-redaction.js"; import { LlmHttpProviderAdapter } from "../providers/llm/llm-http-provider-adapter.js"; @@ -85,6 +86,8 @@ export interface VendorReport { output_tokens_upper: number; calls: number; spent_usd: NumOrNot; + pickup_variant: "default" | "context-sufficient"; + stream_dir: string; cache_probe: { prefix_tokens: number; prefix_over_1024: boolean; @@ -181,14 +184,14 @@ function qualityOf(text: string, needles: string[]): { quality: number; missing: return { quality: (needles.length - missing.length) / needles.length, missing }; } -export async function loadVendorPacks(repoRoot: string): Promise { +export async function loadVendorPacks(repoRoot: string, options?: { contextSufficient?: boolean }): Promise { const loaded = loadFrozenTasks(repoRoot); const packs: VendorPack[] = []; for (const taskId of P0_TASK_IDS) { const task = loaded.tasks.find((item) => item.id === taskId); if (!task) throw new Error(`missing frozen task ${taskId}`); const b0 = await measureP0B0Text(taskId, repoRoot); - const v22 = await measureP0V22Text(taskId, repoRoot); + const v22 = await measureP0V22Text(taskId, repoRoot, { contextSufficient: options?.contextSufficient === true }); packs.push({ taskId, query: task.query, @@ -261,8 +264,10 @@ export async function runVendorMeasure(options: { inputUsdPerMtok?: number; outputUsdPerMtok?: number; apiKey?: string; + contextSufficient?: boolean; adapter?: LlmHttpProviderAdapter; spawnImpl?: CursorAgentSpawn; + saveStreams?: boolean; bin?: string; cwd?: string; env?: NodeJS.ProcessEnv; @@ -272,7 +277,10 @@ export async function runVendorMeasure(options: { if (!Number.isInteger(n) || n < 5) throw new Error("vendor n must be an integer >= 5"); const maxOutputTokens = options.maxOutputTokens ?? VENDOR_MAX_OUTPUT_TOKENS; const repoRoot = options.repoRoot ?? repoRootFromModule(); - const packs = options.packs ?? (await loadVendorPacks(repoRoot)); + const contextSufficient = options.contextSufficient === true; + const packs = options.packs ?? (await loadVendorPacks(repoRoot, { contextSufficient })); + const streamDirRel = `docs/v22/baseline/raw/cursor-agent-streams/${contextSufficient ? "context-sufficient" : "default"}`; + const streamDir = path.join(repoRoot, streamDirRel); const model = options.model?.trim() || (provider === "openrouter" ? OPENROUTER_DEFAULT_MODEL : "cursor-cli-default"); @@ -337,6 +345,8 @@ export async function runVendorMeasure(options: { output_tokens_upper: outputUpper, calls, spent_usd: provider === "openrouter" ? 0 : "NOT_MEASURED", + pickup_variant: contextSufficient ? "context-sufficient" : "default", + stream_dir: streamDirRel, cache_probe: { prefix_tokens: probeTokens ?? 0, prefix_over_1024: (probeTokens ?? 0) > 1024, @@ -363,6 +373,7 @@ export async function runVendorMeasure(options: { if (!options.apiKey?.trim()) return { ...base, status: "ABORTED_MISSING_KEY" }; const secrets = [options.apiKey]; + const saveStreams = provider === "cursor-agent" && options.saveStreams !== false; const adapter = options.adapter ?? new LlmHttpProviderAdapter(); let spent = 0; const runs = new Map(); @@ -407,6 +418,7 @@ export async function runVendorMeasure(options: { const aborted = noteSpend(result.openrouter.cost_usd); if (aborted) return aborted; } else { + const probeName = user.endsWith("probe-1") ? "probe-1.ndjson" : "probe-2.ndjson"; const result = await adapter.completeCursorAgent({ prompt: `${probePrefix}\n${user}`, model: options.model?.trim() || undefined, @@ -414,6 +426,7 @@ export async function runVendorMeasure(options: { cwd: options.cwd ?? repoRoot, env: options.env ?? process.env, spawnImpl: options.spawnImpl, + ...(saveStreams ? { streamDir, streamName: probeName, secrets } : {}), }); base.cache_probe.calls.push({ input_tokens: "NOT_MEASURED", @@ -427,6 +440,7 @@ export async function runVendorMeasure(options: { tool_calls_read_started: result.tool_calls.read_started, tool_calls_write_started: result.tool_calls.write_started, tool_calls_other_started: result.tool_calls.other_started, + stream_path: result.stream_path ? path.relative(repoRoot, result.stream_path) : "NOT_MEASURED", }); if (result.model_id !== "cursor-cli-default") base.model_id = result.model_id; } @@ -462,6 +476,7 @@ export async function runVendorMeasure(options: { const aborted = noteSpend(result.openrouter.cost_usd); if (aborted) return aborted; } else { + const streamName = `${meta.taskId}-${meta.arm}-r${repetition}.ndjson`.replace("V2.2", "v22"); const result = await adapter.completeCursorAgent({ prompt: `${meta.system}\n${meta.user}`, model: options.model?.trim() || undefined, @@ -469,6 +484,7 @@ export async function runVendorMeasure(options: { cwd: options.cwd ?? repoRoot, env: options.env ?? process.env, spawnImpl: options.spawnImpl, + ...(saveStreams ? { streamDir, streamName, secrets } : {}), }); const scored = qualityOf(result.text, pack.needles); bucket.push({ @@ -486,6 +502,7 @@ export async function runVendorMeasure(options: { tool_calls_read_started: result.tool_calls.read_started, tool_calls_write_started: result.tool_calls.write_started, tool_calls_other_started: result.tool_calls.other_started, + stream_path: result.stream_path ? path.relative(repoRoot, result.stream_path) : "NOT_MEASURED", }); runs.set(key, bucket); if (result.model_id !== "cursor-cli-default") base.model_id = result.model_id; diff --git a/orchestrator/tests/unit/v22-p0-baseline.test.ts b/orchestrator/tests/unit/v22-p0-baseline.test.ts index 031c407..70e773c 100644 --- a/orchestrator/tests/unit/v22-p0-baseline.test.ts +++ b/orchestrator/tests/unit/v22-p0-baseline.test.ts @@ -241,6 +241,8 @@ describe("V22-GAP-P0-1 baseline", () => { "docs/v22/baseline/raw/p0-compaction-report.json", "docs/v22/baseline/raw/p0-vendor-report.json", "docs/v22/baseline/raw/p0-vendor-cursor-agent-report.json", + "docs/v22/baseline/raw/p0-vendor-cursor-agent-live.json", + "docs/v22/baseline/raw/p0-vendor-cursor-agent-context-sufficient.json", ]); expect(names.filter((name) => name.startsWith("docs/v22/baseline/raw/") && !allowedRaw.has(name))).toEqual([]); } diff --git a/orchestrator/tests/unit/v22-vendor-measure.test.ts b/orchestrator/tests/unit/v22-vendor-measure.test.ts index 516552d..6a6502a 100644 --- a/orchestrator/tests/unit/v22-vendor-measure.test.ts +++ b/orchestrator/tests/unit/v22-vendor-measure.test.ts @@ -1,10 +1,19 @@ +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { describe, expect, it } from "vitest"; import { LlmHttpProviderAdapter, buildOpenRouterChatBody, openRouterRetryDelayMs, parseRetryAfterMs } from "../../src/providers/llm/llm-http-provider-adapter.js"; import { parseOpenRouterUsage } from "../../src/providers/llm/vendor-cache-usage.js"; import { cursorAgentArgs, parseCursorAgentNdjson, + writeRedactedCursorStream, } from "../../src/providers/llm/cursor-agent-provider.js"; +import { + applyContextSufficientPickup, + PICKUP_READ_REPO_SENTENCE, +} from "../../src/v22/context-sufficient-pickup.js"; +import { measureP0V22Text } from "../../src/v22/p0-baseline-harness.js"; import { OPENROUTER_DEFAULT_MODEL, VENDOR_BUDGET_USD, @@ -247,6 +256,7 @@ describe("V22-GAP-VENDOR-1a", () => { n: 5, packs: [pack()], apiKey: SECRET, + saveStreams: false, spawnImpl: async (_bin, args) => { seen.push(args); expect(args.join(" ")).not.toContain(SECRET); @@ -262,6 +272,8 @@ describe("V22-GAP-VENDOR-1a", () => { expect(report.tasks[0]?.arms.B0.cost_usd).toBe("NOT_MEASURED"); expect(report.tasks[0]?.arms.B0.quality).toBe(1); expect(report.tasks[0]?.arms.B0.runs[0]?.tool_calls_started).toBe(0); + expect(report.tasks[0]?.arms.B0.runs[0]?.stream_path).toBe("NOT_MEASURED"); + expect(report.pickup_variant).toBe("default"); expect(report.cache_probe.calls).toHaveLength(2); expect(seen.length).toBe(12); expect(estimateOpenRouterUsd({ inputTokens: 1_000_000, outputTokensUpper: 0, inputUsdPerMtok: 0.1, outputUsdPerMtok: 0.4 })).toBeCloseTo(0.1); @@ -331,4 +343,83 @@ describe("V22-GAP-VENDOR-1a", () => { expect(message).not.toContain(SECRET); expect(called).toBe(1); }); + + it("rewrites the two pickup read orders only when the retrieval block is present", () => { + const source = [ + "1. **Ler skill:** `.cursor/skills/orquestrar/SKILL.md`", + PICKUP_READ_REPO_SENTENCE, + "### Context (budgeted retrieval)", + "--- path:docs/adr/0013-context-ownership-working-context.md ---", + "body", + ].join("\n"); + const off = source; + expect(off).toContain("**Ler skill:**"); + expect(off).toContain("Please carefully read the repository"); + const on = applyContextSufficientPickup(source); + expect(on.replaced_skill_order).toBe(true); + expect(on.replaced_repo_order).toBe(true); + expect(on.text).not.toContain("Ler skill"); + expect(on.text).not.toContain("Please carefully read the repository"); + expect(on.text).toContain("Responder com o contexto fornecido"); + expect(on.text).toContain("Read a file only when that context lacks the evidence"); + expect(on.text).toContain("--- path:docs/adr/0013-context-ownership-working-context.md ---"); + expect(applyContextSufficientPickup("1. **Ler skill:** `skill.md`").retrieval_present).toBe(false); + }); + + it("keeps the product pickup orders unless the measurement option is set", async () => { + const plain = await measureP0V22Text("curta"); + const variant = await measureP0V22Text("curta", undefined, { contextSufficient: true }); + expect(plain.text).toContain("**Ler skill:**"); + expect(plain.text).toContain(PICKUP_READ_REPO_SENTENCE); + expect(variant.text).not.toContain("Ler skill"); + expect(variant.text).not.toContain("Please carefully read the repository"); + expect(variant.text).toContain("### Context (budgeted retrieval)"); + expect(variant.paths).toEqual(plain.paths); + }, 60_000); + + it("writes one redacted stream-json per cursor-agent call and counts tool_call", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "v22-cursor-stream-")); + try { + const stdout = [ + JSON.stringify({ type: "system", subtype: "init", model: "Auto" }), + JSON.stringify({ + type: "tool_call", + subtype: "started", + tool_call: { readToolCall: { args: { path: ".cursor/skills/orquestrar/SKILL.md" } } }, + }), + JSON.stringify({ + type: "tool_call", + subtype: "completed", + tool_call: { readToolCall: { result: { success: { content: SECRET } } } }, + }), + JSON.stringify({ + type: "result", + subtype: "success", + is_error: false, + duration_ms: 5, + duration_api_ms: 5, + result: "answer", + }), + ].join("\n"); + const file = writeRedactedCursorStream(dir, "curta-b0-r1.ndjson", stdout, [SECRET]); + const saved = readFileSync(file, "utf8"); + expect(saved).not.toContain(SECRET); + expect(saved).toContain('"type":"tool_call"'); + expect(parseCursorAgentNdjson(stdout).tool_calls).toMatchObject({ started: 1, read_started: 1, completed: 1 }); + const adapter = new LlmHttpProviderAdapter(); + const measured = await adapter.completeCursorAgent({ + prompt: "prompt", + cwd: dir, + env: {}, + streamDir: dir, + streamName: "probe-1.ndjson", + secrets: [SECRET], + spawnImpl: async () => ({ status: 0, stdout, stderr: "" }), + }); + expect(measured.tool_calls.started).toBe(1); + expect(readFileSync(measured.stream_path ?? "", "utf8")).not.toContain(SECRET); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); });