diff --git a/.github/workflows/auto-sync.yml b/.github/workflows/auto-sync.yml index 10fdfae..0dd273b 100644 --- a/.github/workflows/auto-sync.yml +++ b/.github/workflows/auto-sync.yml @@ -162,7 +162,9 @@ jobs: - name: Run Loopwright id: loopwright - uses: gpustack/loopwright@9fc93a1f0b48844f24d76dafb16575fd562947aa # v0.0.1 + # The Action tracks the protected default branch so this repository dogfoods its own harness. + # Third-party Actions in this workflow stay pinned to commit SHAs. + uses: gpustack/loopwright@main with: taskpack-path: .auto-sync/taskpack.yaml mode: auto diff --git a/docs/walkthroughs/declarative-taskpack.md b/docs/walkthroughs/declarative-taskpack.md index 33e737b..2d4362e 100644 --- a/docs/walkthroughs/declarative-taskpack.md +++ b/docs/walkthroughs/declarative-taskpack.md @@ -179,7 +179,7 @@ jobs: ### Bootstrap provenance - **Trusted checkout**: Check out `refs/heads/main` with `persist-credentials: false`, gate `issue_comment` to authorized collaborators, and fetch `+refs/pull//head` without checking out untrusted PR heads. -- **Commit SHA pinning**: Pin third-party Actions and `gpustack/loopwright` to 40-character commit SHAs instead of `uses: ./` during self-upgrades so candidate branches cannot replace control-plane code. +- **Commit SHA pinning**: Pin third-party Actions to 40-character commit SHAs instead of `uses: ./` during self-upgrades so candidate branches cannot replace control-plane code. Pin `gpustack/loopwright` the same way during self-upgrades in other repositories. Exception: the Auto Sync workflow of the Loopwright repository itself uses `gpustack/loopwright@main`, so the harness dogfoods its default branch. ## Step 4: Review outcomes diff --git a/packages/agent-pi/test/multi-provider.test.ts b/packages/agent-pi/test/multi-provider.test.ts index b750e81..5e7f803 100644 --- a/packages/agent-pi/test/multi-provider.test.ts +++ b/packages/agent-pi/test/multi-provider.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; import { test } from 'node:test'; import { hasPositiveModelCost, resolveBuiltInPiCatalogModel, resolveCatalogModel, resolveProviderAuthHeaderName, @@ -7,6 +8,19 @@ import { import { evaluateRawResponse } from '../src/response.js'; import { inspectRawResponse } from '../src/usage.js'; +// Model entries that the built-in Pi catalog declares for one API. Derived from the shipped +// data file so an upstream prune of a legacy model cannot break the probes below. +function builtInCatalogEntries(provider: string, api: string): { readonly id: string; readonly cost: unknown }[] { + const data = JSON.parse(readFileSync(new URL(`./providers/data/${provider}.json`, import.meta.resolve('@earendil-works/pi-ai')), 'utf8')) as Record>; + return Object.entries(data[api] ?? {}).filter(([key]) => key.startsWith('chat:')).map(([key, entry]) => ({ id: key.slice('chat:'.length), cost: entry.cost })); +} + +// The catalog's own shape for a cost record, before the resolver validates and freezes it. +function declaresCost(cost: unknown): boolean { + if (cost === null || typeof cost !== 'object') return false; + return 'input' in cost && typeof cost.input === 'number' && 'output' in cost && typeof cost.output === 'number'; +} + test('built-in token Pi providers (zai/glm-5.3, zai-coding-cn/glm-5.3, anthropic, openai) resolve destinations and auth headers', () => { const zai = validateSelection({ provider: 'zai', @@ -135,19 +149,19 @@ test('openai-completions and openai-responses SSE streams evaluate stop reasons, }); test('built-in catalog resolves positive model cost metadata while keeping legacy github-copilot cost omitted', () => { - const anthropic = resolveBuiltInPiCatalogModel('anthropic', 'claude-haiku-4-5', 'anthropic-messages'); - assert.ok(anthropic?.cost); - assert.equal(hasPositiveModelCost(anthropic.cost), true); - assert.ok(anthropic.cost.input > 0 && anthropic.cost.output > 0); - - const openai = resolveBuiltInPiCatalogModel('openai', 'gpt-4', 'openai-responses'); - assert.ok(openai?.cost); - assert.equal(hasPositiveModelCost(openai.cost), true); - assert.ok(openai.cost.input > 0 && openai.cost.output > 0); - - const zai = resolveBuiltInPiCatalogModel('zai', 'glm-5.3', 'openai-completions'); - assert.ok(zai?.cost); - assert.equal(hasPositiveModelCost(zai.cost), true); + for (const [provider, api] of [ + ['anthropic', 'anthropic-messages'], + ['openai', 'openai-responses'], + ['zai', 'openai-completions'], + ] as const) { + const entries = builtInCatalogEntries(provider, api); + assert.ok(entries.length > 0, `${provider}: built-in catalog declares no ${api} models`); + const declared = entries.filter((entry) => declaresCost(entry.cost)); + assert.ok(declared.length > 0, `${provider}: built-in catalog declares no ${api} model cost`); + const resolved = declared.map((entry) => resolveBuiltInPiCatalogModel(provider, entry.id, api)); + assert.ok(resolved.every((record) => record?.cost !== undefined), `${provider}: an ${api} model that declares cost must resolve with it`); + assert.ok(resolved.some((record) => record !== null && hasPositiveModelCost(record.cost)), `${provider}: no ${api} model resolves with positive cost`); + } assert.equal(hasPositiveModelCost(undefined), false); assert.equal(hasPositiveModelCost({ input: 0, output: 0 }), false); diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index 0db340d..edb01b1 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -244,22 +244,50 @@ export async function createCycle(input: RunCycleInput, ports: ControllerPorts): return { loaded: input.configuration, plan, lock, directory, source, store, authority, owner, artifacts, progress, descriptor, signal: input.signal ?? new AbortController().signal, onEvent: input.onEvent, ports: effectivePorts }; } catch (error) { if (store) stateValue(store.close()); if (owner) await owner.release(); throw error; } } -function extractGateVerdictDetail(checked: VerifiedCheck, isBenchmark: boolean): string | undefined { +interface RepairFinding { + readonly title: string; + readonly severity: string; + readonly path?: string | null; + readonly line?: number | null; + readonly evidence?: string; +} +interface GateVerdictExcerpt { readonly detail?: string; readonly findings?: readonly RepairFinding[] } +const MAX_REPAIR_FINDINGS = 8; +const MAX_REPAIR_FINDING_EVIDENCE_CODEPOINTS = 512; +const MAX_REPAIR_DETAIL_CODEPOINTS = 256; + +/** Bounded view of an authenticated gate verdict for the implementation-repair prompt. + * The structured check-out (`detail`, `findings`) wins over `reason`: the local command gate + * reduces `reason` to stdio tails that name no test, file, or assertion. */ +function extractGateVerdictExcerpt(checked: VerifiedCheck, isBenchmark: boolean): GateVerdictExcerpt { const trusted = isBenchmark ? authenticatedBenchmarkGate(checked) : authenticatedGate(checked); const outCap = isBenchmark ? BENCHMARK_OUTPUT_BYTES : GATE_OUTPUT_BYTES; try { const parsed = parsePrivateJson(Buffer.from(trusted.outputBytes), outCap); const verdict = isRecord(parsed) && isRecord(parsed.verdict) ? parsed.verdict : null; - if (!verdict) return undefined; - let rawDetail: string | undefined; - if (isBenchmark && typeof verdict.detail === 'string' && verdict.detail.length > 0) { - rawDetail = verdict.detail; - } else if (typeof verdict.reason === 'string' && verdict.reason.length > 0) { - rawDetail = verdict.reason; - } - return rawDetail !== undefined ? Array.from(rawDetail).slice(0, 256).join('') : undefined; + if (!verdict) return {}; + let detail: string | undefined; + if (typeof verdict.detail === 'string' && verdict.detail.length > 0) detail = verdict.detail; + else if (typeof verdict.reason === 'string' && verdict.reason.length > 0) detail = verdict.reason; + const findings: RepairFinding[] = []; + for (const item of Array.isArray(verdict.findings) ? verdict.findings : []) { + if (findings.length >= MAX_REPAIR_FINDINGS) break; + if (!isRecord(item) || typeof item.title !== 'string' || typeof item.severity !== 'string') continue; + const evidence = typeof item.evidence === 'string' ? Array.from(item.evidence).slice(0, MAX_REPAIR_FINDING_EVIDENCE_CODEPOINTS).join('') : undefined; + findings.push({ + title: item.title, + severity: item.severity, + ...(typeof item.path === 'string' || item.path === null ? { path: item.path } : {}), + ...(typeof item.line === 'number' || item.line === null ? { line: item.line } : {}), + ...(evidence !== undefined ? { evidence } : {}), + }); + } + return { + ...(detail !== undefined ? { detail: Array.from(detail).slice(0, MAX_REPAIR_DETAIL_CODEPOINTS).join('') } : {}), + ...(findings.length > 0 ? { findings } : {}), + }; } catch { - return undefined; + return {}; } } @@ -635,7 +663,7 @@ export class Cycle { : undefined; if (reworkCheckNode?.onRework) { const detail = (gateSlot || benchmarkSlot) - ? extractGateVerdictDetail(checked, benchmarkSlot) + ? extractGateVerdictExcerpt(checked, benchmarkSlot).detail : undefined; const reasonText = checked.reason ?? 'check_failed'; const summary = detail @@ -1794,40 +1822,44 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar this.repairBound('implementation', true, Math.max(0, ...this.draft.failures.filter(item => failed.some(check => same(check.output, item.evidence))).map(item => item.count))); const candidateDigest = this.draft.candidate.digest; if (!(await this.evaluateAlignment('implementation_repair', target!, candidateDigest))) return null; - const findings: { + const checkFindings: { checkId: string; handler: typeof plan.verifierSlots[number]['handler']['implementation']; code: string | null; detail?: string; + findings?: readonly RepairFinding[]; parameters: typeof plan.verifierSlots[number]['handler']['parameters']; candidate: typeof candidateDigest; }[] = failed.map(check => { const slot = plan.verifierSlots.find(slot => slot.id === check.slotId)!; - const detail = (slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'benchmark-gate.v1') - ? extractGateVerdictDetail(check, slot.handler.implementation === 'benchmark-gate.v1') - : undefined; + const excerpt = (slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'benchmark-gate.v1') + ? extractGateVerdictExcerpt(check, slot.handler.implementation === 'benchmark-gate.v1') + : {}; return { checkId: check.checkId, handler: slot.handler.implementation, code: check.reason, - ...(detail !== undefined ? { detail } : {}), + ...(excerpt.detail !== undefined ? { detail: excerpt.detail } : {}), + ...(excerpt.findings !== undefined ? { findings: excerpt.findings } : {}), parameters: slot.handler.parameters, candidate: candidateDigest, }; }); const maxPromptBytes = Math.min(16384, role.policy.limits.promptBytes); const prefix = 'Repair only writable candidate files for these findings; submit status "blocked" if caused by protected scripts or host environment. Return the complete structured submission. Findings:\n'; - let prompt = prefix + canonical(findings); + let prompt = prefix + canonical(checkFindings); if (Buffer.byteLength(prompt, 'utf8') > maxPromptBytes) { - for (let index = findings.length - 1; index >= 0 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes; index--) { - if (findings[index]!.detail !== undefined) { - delete findings[index]!.detail; - prompt = prefix + canonical(findings); + for (const field of ['detail', 'findings'] as const) { + for (let index = checkFindings.length - 1; index >= 0 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes; index--) { + if (checkFindings[index]![field] !== undefined) { + delete checkFindings[index]![field]; + prompt = prefix + canonical(checkFindings); + } } } - while (findings.length > 1 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes) { - findings.pop(); - prompt = prefix + canonical(findings); + while (checkFindings.length > 1 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes) { + checkFindings.pop(); + prompt = prefix + canonical(checkFindings); } } return { targetNodeId: target!, role, prompt }; diff --git a/packages/controller/test/report-and-t3.test.ts b/packages/controller/test/report-repair-and-source-freeze.test.ts similarity index 97% rename from packages/controller/test/report-and-t3.test.ts rename to packages/controller/test/report-repair-and-source-freeze.test.ts index c681267..f82be10 100644 --- a/packages/controller/test/report-and-t3.test.ts +++ b/packages/controller/test/report-repair-and-source-freeze.test.ts @@ -489,7 +489,7 @@ function createMockRolePort(options: { }; } -function startMockGateServer(script: (attempt: number) => { readonly status: 'approved' | 'denied'; readonly reason: string | null }) { +function startMockGateServer(script: (attempt: number) => { readonly status: 'approved' | 'denied'; readonly reason: string | null; readonly detail?: string | null; readonly findings?: readonly Record[] }) { return new Promise<{ readonly url: string; readonly hits: () => number; readonly close: () => Promise }>(resolve => { let hits = 0; const server = createServer((request: IncomingMessage, response: ServerResponse) => { @@ -518,6 +518,8 @@ function startMockGateServer(script: (attempt: number) => { readonly status: 'ap candidateDigest: parsed.candidateDigest, status: verdictInput.status, reason: verdictInput.reason, + ...(verdictInput.detail !== undefined ? { detail: verdictInput.detail } : {}), + ...(verdictInput.findings !== undefined ? { findings: verdictInput.findings } : {}), expiresAtMs: String(Date.now() + 600000), }; const bytes = Buffer.from(JSON.stringify(verdict)); @@ -604,10 +606,17 @@ function startMockPublicationServer(externalUrl: string | null) { }); } -test('Cycle.implementationRepair includes bounded gate.v1 verdict detail and caps repair prompt at 16 KiB', async () => { - const expectedReason = 'lint_failed: src/app.ts:12 unexpected token'; +test('Cycle.implementationRepair carries gate.v1 verdict detail and structured findings into the repair prompt and caps it at 16 KiB', async () => { + const expectedReason = 'command exited with status 1: npm warn deprecated node-domexception@1.0.0 | ERR_ASSERTION expected: true'; + const expectedDetail = "verify.sh: contained stage 'runtime-gates' failed with exit code 1: test at .test-build/x.test.js:1:1"; + const expectedFinding = { + title: 'Test failed: built-in catalog resolves positive model cost metadata', + severity: 'high', + path: 'packages/agent-pi/test/multi-provider.test.ts', + evidence: 'assert.ok(openai?.cost) | actual: undefined, expected: true', + }; const gate = await startMockGateServer(attempt => - attempt === 1 ? { status: 'denied', reason: expectedReason } : { status: 'approved', reason: null }, + attempt === 1 ? { status: 'denied', reason: expectedReason, detail: expectedDetail, findings: [expectedFinding] } : { status: 'approved', reason: null }, ); const f = await configurationFixture(); try { @@ -693,7 +702,11 @@ test('Cycle.implementationRepair includes bounded gate.v1 verdict detail and cap assert.equal(execution.value.result.spec.status, 'completed'); assert.equal(commands.length, 2); assert.equal(commands[1]!.repair, 'implementation'); - assert.ok(commands[1]!.text.includes(`"detail":"${expectedReason}"`)); + assert.ok(commands[1]!.text.includes(`"detail":"${expectedDetail}"`)); + assert.ok(commands[1]!.text.includes(`"title":"${expectedFinding.title}"`)); + assert.ok(commands[1]!.text.includes(`"path":"${expectedFinding.path}"`)); + assert.ok(commands[1]!.text.includes(`"evidence":"${expectedFinding.evidence}"`)); + assert.ok(!commands[1]!.text.includes(expectedReason)); assert.ok(Buffer.byteLength(commands[1]!.text, 'utf8') <= 16384); } finally { await gate.close(); @@ -703,7 +716,8 @@ test('Cycle.implementationRepair includes bounded gate.v1 verdict detail and cap test('Cycle.implementationRepair enforces the 16 KiB repair prompt byte ceiling when findings are large', async () => { const longReason = 'R'.repeat(256); - const gate = await startMockGateServer(() => ({ status: 'denied', reason: longReason })); + const eightFindings = Array.from({ length: 8 }, (_, idx) => ({ title: `Test failed: case ${String(idx)}`, severity: 'high', path: 'src/case.ts', evidence: 'E'.repeat(512) })); + const gate = await startMockGateServer(() => ({ status: 'denied', reason: longReason, detail: longReason, findings: eightFindings })); const f = await configurationFixture(); try { f.environment.GATE_SECRET = GATE_SECRET; @@ -806,7 +820,8 @@ test('Cycle.implementationRepair enforces the 16 KiB repair prompt byte ceiling parsedFindings.map(item => item.checkId), ['approval', 'big-a', 'big-b'].slice(0, parsedFindings.length), ); - assert.equal(parsedFindings.every(item => item.detail === undefined), true); + // The gate entry keeps its place; its detail and structured findings are stripped before any entry is dropped. + assert.equal(parsedFindings.every(item => item.detail === undefined && item.findings === undefined), true); } finally { await gate.close(); await f.cleanup(); diff --git a/packages/github-app/test/self-upgrade-verifier.test.ts b/packages/github-app/test/self-upgrade-verifier.test.ts index f8c5401..df93bc2 100644 --- a/packages/github-app/test/self-upgrade-verifier.test.ts +++ b/packages/github-app/test/self-upgrade-verifier.test.ts @@ -754,7 +754,30 @@ with tarfile.open(sys.argv[1], "w:gz") as tf: assert.equal(workflowRaw.includes('allow-workflow-writes'), false); assert.equal(workflowRaw.includes('bootstrap-loopwright'), false); assert.equal(workflowRaw.includes('92d90440b9e48cac42dd7ef058da1e8c48ec858c'), false); - assert.match(workflowRaw, /uses: gpustack\/loopwright@[0-9a-f]{40} # v\d+\.\d+\.\d+/); + // Action refs: third-party Actions at 40-character SHAs; gpustack/loopwright at main or a SHA. Never `./`, a tag, or another branch. + const ACTION_REF_LINE_START = /^\s*(?:-\s*)?uses:/; + const ACTION_REF_LINE = /^\s*(?:-\s*)?uses:\s*([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@(\S+)(?:\s+#.*)?\s*$/; + const actionRefLines = (raw: string): string[] => raw.split('\n').filter(line => ACTION_REF_LINE_START.test(line)); + const actionRefAllowed = (line: string): boolean => { + const match = ACTION_REF_LINE.exec(line); + if (!match) return false; + const action = match[1]!, ref = match[2]!; + return ref === 'main' ? action === 'gpustack/loopwright' : /^[0-9a-f]{40}$/.test(ref); + }; + const usesLines = actionRefLines(workflowRaw); + assert.ok(usesLines.length >= 2); + for (const line of usesLines) assert.ok(actionRefAllowed(line), `Action ref must be a commit SHA, or main for gpustack/loopwright: ${line.trim()}`); + // The scan must see one-line steps too, or a tag or branch could slip past the gate. + assert.deepEqual( + actionRefLines('steps:\n - uses: actions/checkout@v4\n - name: Build\n uses: x/y@z\n run: |\n echo hi\n'), + [' - uses: actions/checkout@v4', ' uses: x/y@z'], + ); + for (const allowed of ['uses: gpustack/loopwright@main', 'uses: gpustack/loopwright@main ', 'uses: gpustack/loopwright@9fc93a1f0b48844f24d76dafb16575fd562947aa # v0.0.1', 'uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2', '- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683']) { + assert.equal(actionRefAllowed(` ${allowed}`), true, allowed); + } + for (const refused of ['uses: ./', 'uses: ./.github/actions/local', 'uses: gpustack/loopwright@v0.0.1', 'uses: gpustack/loopwright@release', 'uses: gpustack/loopwright@main-feature', 'uses: gpustack/loopwright@main extra', 'uses: actions/checkout@v4', 'uses: actions/checkout@main', 'uses: actions/checkout@11bd719', '- uses: actions/checkout@v4', '- uses: actions/checkout@main']) { + assert.equal(actionRefAllowed(` ${refused}`), false, refused); + } assert.equal(workflowRaw.includes('name: Run preflight'), false); assert.equal(workflowRaw.includes('name: Resolve mode'), false); assert.equal(workflowRaw.includes('name: Verify no-change'), false); diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index ac806bb..125a00c 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -45,7 +45,7 @@ const PRIORITY_WEIGHTS = new Map([ ['tree-overlay.test.js', 46], ['step-engine.test.js', 46], ['self-upgrade-verifier.test.js', 45], - ['report-and-t3.test.js', 45], + ['report-repair-and-source-freeze.test.js', 45], ['step-cli-fencing.test.js', 45], ['turnkey-action.test.js', 44], ['step-cli.test.js', 44],