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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Routed PREVC phase auto-commit diagnostics to stderr and installed an MCP stdio console guard so non-protocol output cannot corrupt JSON-RPC on stdout (fixes MCP client disconnect on phase completion).
- Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses.
- Applied the same bounded UTF-8 budget to every MCP resource, rejected oversized files before reading their bodies, enforced action-specific list maxima, and paginated `explore` file listings.
- Bounded `explore` reads before file materialization and replaced whole-glob/whole-file code search with byte-capped streaming discovery, search, and cursor pages.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { execSync } from 'child_process';
import * as fs from 'fs/promises';
import * as os from 'os';
import * as path from 'path';
import { createPlanLinker } from '../planLinker';
import { PlanTrackingStore } from '../planTrackingStore';

const PLAN_SLUG = 'autocommit-stdio';

async function setupGitRepo(): Promise<string> {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plan-autocommit-stdio-'));
await fs.mkdir(path.join(tempDir, '.context', 'plans'), { recursive: true });
await fs.mkdir(path.join(tempDir, '.context', 'runtime', 'workflows'), { recursive: true });

const planPath = path.join(tempDir, '.context', 'plans', `${PLAN_SLUG}.md`);
await fs.writeFile(
planPath,
`---
type: plan
name: "AutoCommit stdio"
description: "Regression for MCP stdout pollution"
generated: "2026-04-13"
status: filled
scaffoldVersion: "2.0.0"
planSlug: "${PLAN_SLUG}"
summary: "Test plan"
agents:
- type: "planner"
role: "Define scope"
docs:
- "README.md"
phases:
- id: "phase-1"
name: "Execute"
prevc: "E"
steps:
- order: 1
description: "Finish"
deliverables:
- "done"
---

# AutoCommit stdio
`
);

execSync('git init', { cwd: tempDir, stdio: 'pipe' });
execSync('git config user.email "test@example.com"', { cwd: tempDir, stdio: 'pipe' });
execSync('git config user.name "Test User"', { cwd: tempDir, stdio: 'pipe' });
execSync('git add -A', { cwd: tempDir, stdio: 'pipe' });
execSync('git commit -m "init"', { cwd: tempDir, stdio: 'pipe' });

return tempDir;
}

describe('PlanUpdateOrchestrator auto-commit stdio safety', () => {
let tempDir: string;

beforeEach(async () => {
tempDir = await setupGitRepo();
});

afterEach(async () => {
jest.restoreAllMocks();
await fs.rm(tempDir, { recursive: true, force: true });
});

it('does not log AutoCommit diagnostics via console.info when a phase auto-commits', async () => {
const infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
const stderrSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

const linker = await createPlanLinker(tempDir, undefined, true);
await linker.linkPlan(PLAN_SLUG);

const store = new PlanTrackingStore(path.join(tempDir, '.context', 'runtime', 'workflows'));
const tracking = (await store.load(PLAN_SLUG)) ?? store.createEmpty(PLAN_SLUG);
const now = new Date().toISOString();
store.ensurePhase(tracking, 'phase-1', now);
const step = store.ensureStep(tracking, 'phase-1', 1, 'Finish', now);
step.status = 'in_progress';
step.startedAt = now;
await store.save(PLAN_SLUG, tracking);

const ok = await linker.updatePlanStep(PLAN_SLUG, 'phase-1', 1, 'completed');
expect(ok).toBe(true);

const autoCommitInfo = infoSpy.mock.calls.filter((args) =>
String(args[0] ?? '').includes('[AutoCommit]')
);
expect(autoCommitInfo).toHaveLength(0);

const autoCommitStderr = stderrSpy.mock.calls.filter((args) =>
String(args[0] ?? '').includes('[AutoCommit] Created commit')
);
expect(autoCommitStderr.length).toBeGreaterThanOrEqual(1);
});
});
4 changes: 2 additions & 2 deletions src/harness/domain/workflow/plans/planUpdateOrchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ export class PlanUpdateOrchestrator {
try {
const stagedFiles = gitService.stageFiles(['.context/**']);
if (stagedFiles.length === 0) {
console.info('[AutoCommit] No files to commit - skipping');
console.error('[AutoCommit] No files to commit - skipping');
return false;
}

Expand All @@ -336,7 +336,7 @@ export class PlanUpdateOrchestrator {
committedBy: coAuthor,
});

console.info(`[AutoCommit] Created commit ${commitResult.shortHash} for phase ${phaseId}`);
console.error(`[AutoCommit] Created commit ${commitResult.shortHash} for phase ${phaseId}`);
return true;
} catch (error) {
console.warn(`[AutoCommit] Failed to create commit for phase ${phaseId}:`, error);
Expand Down
2 changes: 2 additions & 0 deletions src/mcp/server/mcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ContextCache } from '../../harness/adapters/out/semantic/contextCache';
import { VERSION } from '../../version';
import { WorkflowService } from '../../harness/application/workflow';
import { clearMcpActionSessionCache, logMcpAction } from '../logging/actionLogger';
import { installMcpStdioProtocolGuard } from '../stdio/stdioProtocolGuard';
import {
createBoundedResourceJson,
createBoundedResourceText,
Expand Down Expand Up @@ -1115,6 +1116,7 @@ Actions:
* Start the MCP server with stdio transport
*/
async start(): Promise<void> {
installMcpStdioProtocolGuard();
this.transport = new StdioServerTransport();
await this.server.connect(this.transport);
this.log('MCP Server started on stdio');
Expand Down
43 changes: 43 additions & 0 deletions src/mcp/stdio/__tests__/stdioProtocolGuard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
installMcpStdioProtocolGuard,
resetMcpStdioProtocolGuardForTests,
} from '../stdioProtocolGuard';

describe('installMcpStdioProtocolGuard', () => {
let stdoutWriteSpy: jest.SpyInstance;
let stderrWriteSpy: jest.SpyInstance;

beforeEach(() => {
resetMcpStdioProtocolGuardForTests();
stdoutWriteSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => true);
stderrWriteSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
});

afterEach(() => {
resetMcpStdioProtocolGuardForTests();
stdoutWriteSpy.mockRestore();
stderrWriteSpy.mockRestore();
});

it('routes console.info away from stdout', () => {
installMcpStdioProtocolGuard();

console.info('[AutoCommit] Created commit abc123 for phase phase-1');

const stdout = stdoutWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join('');
const stderr = stderrWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join('');

expect(stdout).not.toContain('[AutoCommit]');
expect(stderr).toContain('[AutoCommit] Created commit abc123 for phase phase-1');
});

it('is idempotent', () => {
installMcpStdioProtocolGuard();
installMcpStdioProtocolGuard();

console.log('diagnostic');

expect(stdoutWriteSpy).not.toHaveBeenCalled();
expect(stderrWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join('')).toContain('diagnostic');
});
});
40 changes: 40 additions & 0 deletions src/mcp/stdio/stdioProtocolGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as util from 'util';

const originalConsole = {
log: console.log,
info: console.info,
debug: console.debug,
};

let installed = false;

function writeConsoleLineToStderr(...args: unknown[]): void {
process.stderr.write(`${util.format(...args)}\n`);
}

/**
* Redirect casual console logging away from stdout while MCP stdio transport runs.
* JSON-RPC framing must be the only payload on stdout.
*/
export function installMcpStdioProtocolGuard(): void {
if (installed) {
return;
}

installed = true;
console.log = writeConsoleLineToStderr as typeof console.log;
console.info = writeConsoleLineToStderr as typeof console.info;
console.debug = writeConsoleLineToStderr as typeof console.debug;
}

/** Restores original console sinks; for unit tests only. */
export function resetMcpStdioProtocolGuardForTests(): void {
if (!installed) {
return;
}

console.log = originalConsole.log;
console.info = originalConsole.info;
console.debug = originalConsole.debug;
installed = false;
}
Loading