Skip to content
Open
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

- Fixed `plan link` rejecting `required_sensors` on Execution phases for scaffold-style frontmatter (unquoted `generated` dates no longer invalidate canonical YAML parsing), and rolled back plan index/tracking registration when link fails after validation.
- 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
156 changes: 156 additions & 0 deletions src/harness/application/workflow/__tests__/plansService.link.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';

import { HarnessPlansService } from '../plansService';
import { WorkflowService } from '../workflowService';

function scaffoldStylePlanFixture(requiredSensorsYaml: string): string {
return [
'---',
'type: plan',
'name: link-atomic',
'description: Plan for link regression',
`generated: ${JSON.stringify('2026-04-12')}`,
'status: filled',
'scaffoldVersion: "2.0.0"',
'planSlug: "link-atomic"',
'phases:',
' - id: "phase-1"',
' name: "Planning"',
' prevc: "P"',
' - id: "phase-2"',
' name: "Implementation"',
' prevc: "E"',
requiredSensorsYaml,
' steps:',
' - order: 1',
' description: "Implement"',
'---',
'',
'# Link Atomic',
'',
].join('\n');
}

describe('HarnessPlansService.link', () => {
let tempDir: string;

beforeEach(async () => {
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plans-service-link-'));
await fs.writeJson(
path.join(tempDir, 'package.json'),
{ name: 'plans-service-link', version: '1.0.0' },
{ spaces: 2 }
);
});

afterEach(async () => {
await fs.remove(tempDir);
});

it('accepts required_sensors on E phases when scaffold frontmatter uses unquoted generated dates', async () => {
const plansDir = path.join(tempDir, '.context', 'plans');
await fs.ensureDir(plansDir);
await fs.writeFile(
path.join(plansDir, 'link-atomic.md'),
[
'---',
'type: plan',
'name: link-atomic',
'description: Plan for link regression',
'generated: 2026-04-12',
'status: filled',
'scaffoldVersion: "2.0.0"',
'planSlug: link-atomic',
'phases:',
' - id: phase-1',
' name: Planning',
' prevc: P',
' - id: phase-2',
' name: Implementation',
' prevc: E',
' required_sensors: [verify]',
' steps:',
' - order: 1',
' description: Implement',
'---',
'',
'# Link Atomic',
'',
].join('\n'),
'utf-8'
);

await new WorkflowService(tempDir).init({ name: 'link-atomic', scale: 'MEDIUM' });
const result = await new HarnessPlansService({ repoPath: tempDir }).link('link-atomic');

expect(result.success).toBe(true);
});

it.each([
['inline array', ' required_sensors: [verify]'],
['block list', ' required_sensors:\n - verify'],
['inline quoted array', ' required_sensors: ["verify"]'],
])('accepts required_sensors in %s form', async (_label, sensorsYaml) => {
const plansDir = path.join(tempDir, '.context', 'plans');
await fs.ensureDir(plansDir);
await fs.writeFile(
path.join(plansDir, 'link-atomic.md'),
scaffoldStylePlanFixture(sensorsYaml),
'utf-8'
);

await new WorkflowService(tempDir).init({ name: 'link-atomic', scale: 'MEDIUM' });
const result = await new HarnessPlansService({ repoPath: tempDir }).link('link-atomic');
expect(result.success).toBe(true);
});

it('does not register plan tracking when link validation fails', async () => {
const plansDir = path.join(tempDir, '.context', 'plans');
const workflowDir = path.join(tempDir, '.context', 'runtime', 'workflows');
await fs.ensureDir(plansDir);
await fs.writeFile(
path.join(plansDir, 'missing-sensors.md'),
[
'---',
'type: plan',
'name: missing-sensors',
'description: Plan for link regression',
'generated: 2026-04-12',
'status: filled',
'scaffoldVersion: "2.0.0"',
'planSlug: missing-sensors',
'phases:',
' - id: phase-1',
' name: Planning',
' prevc: P',
' - id: phase-2',
' name: Implementation',
' prevc: E',
' steps:',
' - order: 1',
' description: Implement',
'---',
'',
'# Missing Sensors',
'',
].join('\n'),
'utf-8'
);

await new WorkflowService(tempDir).init({ name: 'missing-sensors', scale: 'MEDIUM' });
const plans = new HarnessPlansService({ repoPath: tempDir });

await expect(plans.link('missing-sensors')).rejects.toThrow(/required_sensors/);

const trackingPath = path.join(workflowDir, 'plan-tracking', 'missing-sensors.json');
const plansIndexPath = path.join(workflowDir, 'plans.json');
expect(await fs.pathExists(trackingPath)).toBe(false);
if (await fs.pathExists(plansIndexPath)) {
const index = await fs.readJson(plansIndexPath);
const slugs = [...index.active, ...index.completed].map((entry: { slug: string }) => entry.slug);
expect(slugs).not.toContain('missing-sensors');
}
});
});
144 changes: 80 additions & 64 deletions src/harness/application/workflow/plansService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { PrevcStatusManager } from '../../domain/workflow/status/statusManager';
import { GitService } from '../../../utils/gitService';
import { resolveRuntimeLayoutFromRepo, toPosixContextPath } from '../../../shared/fs/pathHelpers';
import type { PrevcPhase } from '../../domain/workflow/types';
import type { LinkedPlan } from '../../domain/workflow/plans/types';

export interface HarnessPlansServiceOptions {
repoPath: string;
Expand All @@ -37,67 +38,50 @@ export class HarnessPlansService {
}

async link(planSlug: string): Promise<Record<string, unknown>> {
const ref = await this.linker.linkPlan(planSlug);
const documentPlan = await this.linker.parsePlanDocument(planSlug);

if (!ref) {
if (!documentPlan) {
return {
success: false,
error: `Plan not found: ${planSlug}`,
};
}

// Enforce that the linked plan declares execution evidence for any E
// (Execution) phase. Without it, the `execution_evidence` gate on E -> V
// would degrade to phase-default sensors only, and the plan author would
// have no visible contract surface for the actual required evidence.
// Hard-fail at link time so the caller must either declare requirements
// in `phases[].required_sensors` / `phases[].required_artifacts` or
// remove the E phase from the plan.
const linkedPlan = await this.linker.getLinkedPlan(planSlug);
const emptyExecutionPhases = (linkedPlan?.phases ?? [])
.filter((phase) => phase.prevcPhase === 'E')
.filter((phase) => {
const req = phase.requirements;
return !req || req.requiredSensors.length === 0;
});
this.assertExecutionPhasesDeclareSensors(documentPlan, planSlug);

if (emptyExecutionPhases.length > 0) {
const ids = emptyExecutionPhases.map((phase) => phase.id).join(', ');
throw new Error(
`Plan "${planSlug}" has Execution phase(s) [${ids}] without ` +
`"required_sensors". Declare them in the plan frontmatter so the ` +
`execution_evidence gate can verify the work actually happened. ` +
`Example:\n\n` +
` phases:\n` +
` - id: phase-2\n` +
` prevc: E\n` +
` required_sensors: [tests]\n` +
` required_artifacts: [handoff-summary]\n`
);
}
const hadTracking = (await this.linker.getPlanExecutionStatus(planSlug)) !== null;

const service = new WorkflowService(this.repoPath);
const workflowLink = await service.linkPlanToActiveWorkflow(planSlug);
const workflowActive = workflowLink.workflowActive;
const taskContract = workflowLink.taskContract;
try {
const ref = await this.linker.linkPlan(planSlug);
if (!ref) {
return {
success: false,
error: `Plan not found: ${planSlug}`,
};
}

let canAdvanceToReview = false;
if (workflowActive) {
const gateResult = await service.checkGates();
canAdvanceToReview = gateResult.gates.plan_required.passed;
}
const service = new WorkflowService(this.repoPath);
const workflowLink = await service.linkPlanToActiveWorkflow(planSlug);
const workflowActive = workflowLink.workflowActive;
const taskContract = workflowLink.taskContract;

const workflowStatePath = toPosixContextPath(resolveRuntimeLayoutFromRepo(this.repoPath).prevcFile);
const enhancementPrompt = workflowActive
? `PLAN LINKED TO ACTIVE WORKFLOW
let canAdvanceToReview = false;
if (workflowActive) {
const gateResult = await service.checkGates();
canAdvanceToReview = gateResult.gates.plan_required.passed;
}

const workflowStatePath = toPosixContextPath(resolveRuntimeLayoutFromRepo(this.repoPath).prevcFile);
const enhancementPrompt = workflowActive
? `PLAN LINKED TO ACTIVE WORKFLOW

The linked plan is now attached to the harness-backed PREVC workflow.

Next:
1. Use workflow-guide() to confirm the active phase, next steps, and harness binding
2. Continue planning work
3. Use workflow-advance() when the planning phase is complete`
: `PLAN LINKED - WORKFLOW NOT STARTED
: `PLAN LINKED - WORKFLOW NOT STARTED

The plan reference was created, but no PREVC workflow is active yet.
Until workflow-init runs, the harness does not have canonical workflow state and plan gates are not armed.
Expand All @@ -107,28 +91,60 @@ Next:
2. Call plan({ action: "link", planSlug: "${planSlug}" }) again after workflow-init
3. Use workflow-guide() to verify the plan is bound to the harness workflow`;

const nextSteps = workflowActive
? [
'RECOMMENDED: Call workflow-guide() to confirm the linked plan and harness binding',
'THEN: Continue planning and call workflow-advance() when ready to leave phase P',
]
: [
`REQUIRED: Call workflow-init({ name: "${planSlug}" }) to start the harness-backed PREVC workflow`,
`REQUIRED: Call plan({ action: "link", planSlug: "${planSlug}" }) again after workflow-init so gates see the plan`,
'THEN: Call workflow-guide() to confirm the workflow and harness binding are active',
];
const nextSteps = workflowActive
? [
'RECOMMENDED: Call workflow-guide() to confirm the linked plan and harness binding',
'THEN: Continue planning and call workflow-advance() when ready to leave phase P',
]
: [
`REQUIRED: Call workflow-init({ name: "${planSlug}" }) to start the harness-backed PREVC workflow`,
`REQUIRED: Call plan({ action: "link", planSlug: "${planSlug}" }) again after workflow-init so gates see the plan`,
'THEN: Call workflow-guide() to confirm the workflow and harness binding are active',
];

return {
success: true,
plan: ref,
workflowActive,
workflowStatePath,
planCreatedForGates: workflowLink.planCreatedForGates,
canAdvanceToReview,
taskContract,
enhancementPrompt,
nextSteps,
};
return {
success: true,
plan: ref,
workflowActive,
workflowStatePath,
planCreatedForGates: workflowLink.planCreatedForGates,
canAdvanceToReview,
taskContract,
enhancementPrompt,
nextSteps,
};
} catch (error) {
if (!hadTracking) {
await this.linker.revokePlanLink(planSlug);
}
throw error;
}
}

private assertExecutionPhasesDeclareSensors(plan: LinkedPlan, planSlug: string): void {
const emptyExecutionPhases = plan.phases
.filter((phase) => phase.prevcPhase === 'E')
.filter((phase) => {
const req = phase.requirements;
return !req || req.requiredSensors.length === 0;
});

if (emptyExecutionPhases.length === 0) {
return;
}

const ids = emptyExecutionPhases.map((phase) => phase.id).join(', ');
throw new Error(
`Plan "${planSlug}" has Execution phase(s) [${ids}] without ` +
`"required_sensors". Declare them in the plan frontmatter so the ` +
`execution_evidence gate can verify the work actually happened. ` +
`Example:\n\n` +
` phases:\n` +
` - id: phase-2\n` +
` prevc: E\n` +
` required_sensors: [tests]\n` +
` required_artifacts: [handoff-summary]\n`
);
}

async getLinked(): Promise<Record<string, unknown>> {
Expand Down
35 changes: 35 additions & 0 deletions src/harness/domain/workflow/plans/__tests__/planLinker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,41 @@ describe('PlanLinker plan parsing', () => {
await fs.rm(tempDir, { recursive: true, force: true });
});

it('hydrates Execution phase requirements from canonical frontmatter with unquoted generated', async () => {
const planSlug = 'requirements-plan';
const planPath = path.join(tempDir, '.context', 'plans', `${planSlug}.md`);

await fs.writeFile(
planPath,
`---
type: plan
name: Requirements Plan
description: Required sensors regression
generated: 2026-04-12
status: filled
scaffoldVersion: "2.0.0"
planSlug: "${planSlug}"
phases:
- id: "phase-2"
name: "Implementation"
prevc: "E"
required_sensors: [verify]
steps:
- order: 1
description: "Build feature"
---

# Requirements Plan
`
);

const linker = await createPlanLinker(tempDir, undefined, false);
await linker.linkPlan(planSlug);
const linked = await linker.getLinkedPlan(planSlug);

expect(linked?.phases[0].requirements?.requiredSensors).toEqual(['verify']);
});

it('prefers canonical frontmatter phases and steps over body content', async () => {
const planSlug = 'structured-delivery';
const planPath = path.join(tempDir, '.context', 'plans', `${planSlug}.md`);
Expand Down
Loading
Loading