Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 22 additions & 3 deletions docs/v22/VENDOR-MEASURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`.
25 changes: 25 additions & 0 deletions orchestrator/src/providers/llm/cursor-agent-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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";
}

Expand Down Expand Up @@ -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[],
Expand Down
10 changes: 9 additions & 1 deletion orchestrator/src/providers/llm/llm-http-provider-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
cursorAgentArgs,
parseCursorAgentNdjson,
spawnCursorAgent,
writeRedactedCursorStream,
type CursorAgentSpawn,
type CursorCliMeasurement,
} from "./cursor-agent-provider.js";
Expand Down Expand Up @@ -275,6 +276,9 @@ export class LlmHttpProviderAdapter {
cwd: string;
env: NodeJS.ProcessEnv;
spawnImpl?: CursorAgentSpawn;
streamDir?: string;
streamName?: string;
secrets?: string[];
}): Promise<CursorCliMeasurement> {
const bin = input.bin ?? "cursor-agent";
const args = cursorAgentArgs({ model: input.model });
Expand All @@ -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 };
}
}
53 changes: 53 additions & 0 deletions orchestrator/src/v22/context-sufficient-pickup.ts
Original file line number Diff line number Diff line change
@@ -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,
};
}
24 changes: 20 additions & 4 deletions orchestrator/src/v22/p0-baseline-harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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"
);
}

Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand All @@ -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 });
Expand Down
9 changes: 8 additions & 1 deletion orchestrator/src/v22/vendor-measure-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] : [] }));
Expand Down
23 changes: 20 additions & 3 deletions orchestrator/src/v22/vendor-measure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<VendorPack[]> {
export async function loadVendorPacks(repoRoot: string, options?: { contextSufficient?: boolean }): Promise<VendorPack[]> {
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,
Expand Down Expand Up @@ -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;
Expand All @@ -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");
Expand Down Expand Up @@ -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,
Expand All @@ -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<string, VendorArmPlan["runs"]>();
Expand Down Expand Up @@ -407,13 +418,15 @@ 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,
bin: options.bin,
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",
Expand All @@ -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;
}
Expand Down Expand Up @@ -462,13 +476,15 @@ 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,
bin: options.bin,
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({
Expand All @@ -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;
Expand Down
Loading
Loading