From a4eb16fbafc2dbf8067e8fa1cd1c30455be74eae Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 21:07:09 +0000 Subject: [PATCH] fix(plans): parse required_sensors from scaffold frontmatter and link atomically Coerce unquoted YAML generated dates so canonical plan frontmatter parses required_sensors on Execution phases. Validate plans before persisting link state and revoke new tracking when workflow binding fails. Co-authored-by: Vinicius Lana --- CHANGELOG.md | 1 + .../__tests__/plansService.link.test.ts | 156 ++++++++++++++++++ .../application/workflow/plansService.ts | 144 +++++++++------- .../plans/__tests__/planLinker.test.ts | 35 ++++ .../domain/workflow/plans/planLinker.ts | 29 ++++ src/types/scaffoldFrontmatter.ts | 2 +- src/utils/__tests__/frontMatter.test.ts | 30 ++++ src/utils/frontMatter.ts | 18 +- 8 files changed, 349 insertions(+), 66 deletions(-) create mode 100644 src/harness/application/workflow/__tests__/plansService.link.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index df4bc739..2afe6380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/src/harness/application/workflow/__tests__/plansService.link.test.ts b/src/harness/application/workflow/__tests__/plansService.link.test.ts new file mode 100644 index 00000000..bf60191f --- /dev/null +++ b/src/harness/application/workflow/__tests__/plansService.link.test.ts @@ -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'); + } + }); +}); \ No newline at end of file diff --git a/src/harness/application/workflow/plansService.ts b/src/harness/application/workflow/plansService.ts index 714c94bd..d972d3f9 100644 --- a/src/harness/application/workflow/plansService.ts +++ b/src/harness/application/workflow/plansService.ts @@ -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; @@ -37,59 +38,42 @@ export class HarnessPlansService { } async link(planSlug: string): Promise> { - 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. @@ -97,7 +81,7 @@ 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. @@ -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> { diff --git a/src/harness/domain/workflow/plans/__tests__/planLinker.test.ts b/src/harness/domain/workflow/plans/__tests__/planLinker.test.ts index cc01ce84..71c925f6 100644 --- a/src/harness/domain/workflow/plans/__tests__/planLinker.test.ts +++ b/src/harness/domain/workflow/plans/__tests__/planLinker.test.ts @@ -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`); diff --git a/src/harness/domain/workflow/plans/planLinker.ts b/src/harness/domain/workflow/plans/planLinker.ts index 74cde051..701e59ad 100644 --- a/src/harness/domain/workflow/plans/planLinker.ts +++ b/src/harness/domain/workflow/plans/planLinker.ts @@ -102,6 +102,35 @@ export class PlanLinker { // Initial linking + queries // --------------------------------------------------------------------------- + async parsePlanDocument(planSlug: string): Promise { + const planPath = path.join(this.plansPath, `${planSlug}.md`); + if (!await fs.pathExists(planPath)) { + return null; + } + + const content = await fs.readFile(planPath, 'utf-8'); + const planInfo = this.parser.parsePlanFile(content, planSlug); + const ref: PlanReference = { + slug: planSlug, + path: `plans/${planSlug}.md`, + title: planInfo.title, + summary: planInfo.summary, + linkedAt: new Date().toISOString(), + status: 'active', + }; + + return this.parser.parsePlanToLinked(content, ref); + } + + async revokePlanLink(planSlug: string): Promise { + const trackingFile = this.trackingStore.getTrackingFile(planSlug); + if (await fs.pathExists(trackingFile)) { + await fs.remove(trackingFile); + } + this.indexProjector.invalidateCache(); + await this.refreshWorkflowPlanIndex(); + } + async linkPlan(planSlug: string): Promise { const planPath = path.join(this.plansPath, `${planSlug}.md`); if (!await fs.pathExists(planPath)) { diff --git a/src/types/scaffoldFrontmatter.ts b/src/types/scaffoldFrontmatter.ts index 740f0d52..3c3e5318 100644 --- a/src/types/scaffoldFrontmatter.ts +++ b/src/types/scaffoldFrontmatter.ts @@ -376,7 +376,7 @@ export function serializeFrontmatter(fm: ScaffoldFrontmatter): string { } // Common trailing fields - lines.push(`generated: ${fm.generated}`); + lines.push(`generated: ${JSON.stringify(fm.generated)}`); lines.push(`status: ${fm.status}`); lines.push(`scaffoldVersion: "${fm.scaffoldVersion}"`); diff --git a/src/utils/__tests__/frontMatter.test.ts b/src/utils/__tests__/frontMatter.test.ts index fbedc945..3e9b69f7 100644 --- a/src/utils/__tests__/frontMatter.test.ts +++ b/src/utils/__tests__/frontMatter.test.ts @@ -164,6 +164,36 @@ phases: }); expect(body).toBe('# Structured Delivery'); }); + + it('parses scaffold plans when generated is an unquoted YAML date', () => { + const content = `--- +type: plan +name: Unquoted Generated +description: Scaffold output shape +generated: 2026-04-12 +status: filled +scaffoldVersion: "2.0.0" +planSlug: unquoted-generated +phases: + - id: phase-2 + name: Implementation + prevc: E + required_sensors: + - verify + steps: + - order: 1 + description: Build +--- + +# Plan +`; + + const { frontMatter } = parseScaffoldFrontMatter(content); + + expect(frontMatter).not.toBeNull(); + expect(frontMatter?.generated).toBe('2026-04-12'); + expect(frontMatter?.planPhases?.[0]?.requiredSensors).toEqual(['verify']); + }); }); describe('addFrontMatter', () => { diff --git a/src/utils/frontMatter.ts b/src/utils/frontMatter.ts index 6bfb44c7..d81959b3 100644 --- a/src/utils/frontMatter.ts +++ b/src/utils/frontMatter.ts @@ -84,6 +84,22 @@ function loadYamlFrontMatter(content: string): Record | null { } } +/** + * js-yaml parses unquoted ISO dates (e.g. `generated: 2026-04-12`) as Date objects. + * Scaffold output uses unquoted dates — coerce back to the YYYY-MM-DD string shape. + */ +function coerceScaffoldDateString(value: unknown): string { + if (typeof value === 'string') { + return value.trim(); + } + + if (value instanceof Date && !Number.isNaN(value.getTime())) { + return value.toISOString().split('T')[0]; + } + + return ''; +} + function normalizeStringArray(value: unknown): string[] | undefined { if (typeof value === 'string') { return [value]; @@ -247,7 +263,7 @@ function normalizeParsedScaffoldFrontMatter(frontMatter: Record type, name: typeof frontMatter.name === 'string' ? frontMatter.name : '', description: typeof frontMatter.description === 'string' ? frontMatter.description : '', - generated: typeof frontMatter.generated === 'string' ? frontMatter.generated : '', + generated: coerceScaffoldDateString(frontMatter.generated), status: frontMatter.status === 'filled' ? 'filled' : 'unfilled', scaffoldVersion: '2.0.0', };