@trailstep/create-flows 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/feature-implementation/story-router/step.ts","../src/feature-implementation/implement-green/step.ts","../src/feature-implementation/shared/story-state.ts","../src/feature-implementation/commit-reviewed-story/run-git.ts","../src/feature-implementation/validate-story/step.ts","../src/feature-implementation/review-story-implementation/step.ts","../src/feature-implementation/commit-reviewed-story/step.ts","../src/feature-implementation/open-pull-request/step.ts","../src/feature-implementation/shared/input-schema.ts","../src/feature-implementation/shared/output-schema.ts","../src/feature-implementation/shared/review-schema.ts","../src/feature-implementation/shared/constants.ts","../src/feature-implementation/review-story-implementation/prompt.ts","../src/feature-implementation/shared/story-view.ts","../src/feature-implementation/validate-story/validation-runner.ts","../src/feature-implementation/implement-green/prompt.ts","../src/feature-implementation/story-doctor/step.ts","../src/feature-implementation/story-doctor/prompt.ts","../src/feature-implementation/story-isolation-preflight/step.ts","../src/feature-implementation/deterministic-context-preflight/step.ts","../src/feature-implementation/write-red-tests/step.ts","../src/feature-implementation/write-red-tests/prompt.ts"],"sourcesContent":["import type { Document } from \"@trailstep/authoring\";\nimport { fail, state, step } from \"@trailstep/authoring\";\nimport type { ContinuationResult, Failure } from \"@trailstep/core\";\nimport { implementGreenStep } from \"../implement-green/step.js\";\nimport {\n MAX_STORY_REVIEW_ATTEMPTS,\n MAX_STORY_VALIDATION_ATTEMPTS,\n STORY_DOCTOR_VALIDATION_FAILURE_THRESHOLD,\n} from \"../shared/constants.js\";\nimport { extractStoryTitle } from \"../shared/output-schema.js\";\nimport type { ReviewResult } from \"../shared/review-schema.js\";\nimport { reviewPasses } from \"../shared/review-schema.js\";\nimport {\n type BlockedStoryPhase,\n type BlockedStoryRouteSourceReason,\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n resetStoryLocalStateForNextStory,\n STORY_STATE_KEYS,\n type StoryPhaseContexts,\n type StoryRouterState,\n} from \"../shared/story-state.js\";\nimport { storyDoctorStep } from \"../story-doctor/step.js\";\nimport { storyIsolationPreflightStep } from \"../story-isolation-preflight/step.js\";\nimport type { ValidateStoryOutput } from \"../validate-story/prompt.js\";\n\nexport interface StoryRouterInput extends Record<string, unknown> {\n readonly reason:\n | \"start-story\"\n | \"retry-story\"\n | \"story-completed\"\n | \"failed-review\"\n | \"failed-validation\"\n | {\n readonly type: \"blocked\";\n readonly sourceReason: BlockedStoryRouteSourceReason;\n readonly blockedPhase: BlockedStoryPhase;\n readonly blockedReason: string;\n readonly code: string;\n readonly metadata?: Record<string, unknown>;\n };\n readonly currentStory?: Document;\n}\n\ninterface RouterRetryCounts {\n readonly reviewRetryCount: number;\n readonly validationRetryCount: number;\n}\n\ntype RetryRouteSourceReason = \"failed-review\" | \"failed-validation\";\n\nclass StoryRouterFailureError extends Error {\n readonly failure: Failure;\n\n constructor(failure: Failure) {\n super(failure.message);\n this.name = \"StoryRouterFailureError\";\n this.failure = failure;\n }\n}\n\nexport const storyRouterStep = step({ id: \"story-router\" }).do(\n async ({ currentStory, reason }: StoryRouterInput): Promise<ContinuationResult> => {\n const previousActivePhase = await state.get<string | null>(STORY_STATE_KEYS.activePhase);\n await state.set(STORY_STATE_KEYS.activePhase, \"story-router\");\n await incrementStoryPhaseAttempt(\"story-router\");\n\n if (reason === \"failed-review\") {\n const replayedRoute = await replayPersistedRetryRoute(\n reason,\n currentStory,\n previousActivePhase,\n );\n if (replayedRoute) {\n return replayedRoute;\n }\n return routeFailedReview(currentStory);\n }\n if (reason === \"failed-validation\") {\n const replayedRoute = await replayPersistedRetryRoute(\n reason,\n currentStory,\n previousActivePhase,\n );\n if (replayedRoute) {\n return replayedRoute;\n }\n return routeFailedValidation(currentStory);\n }\n if (typeof reason === \"object\" && reason.type === \"blocked\") {\n const blockedReplay = await replayBlockedStoryRoute();\n if (blockedReplay) {\n return blockedReplay;\n }\n return routeBlockedStory(currentStory, reason);\n }\n\n if (reason === \"story-completed\") {\n const repairFailure = await repairStaleStoryCompletion(currentStory);\n if (repairFailure) {\n return fail(repairFailure);\n }\n }\n\n const activeStory =\n currentStory ?? (await state.get<Document | null>(STORY_STATE_KEYS.activeStory));\n if (!activeStory) {\n const [nextStory, ...remaining] =\n (await state.get<Document[]>(STORY_STATE_KEYS.storyQueue)) ?? [];\n if (!nextStory) {\n return fail({\n code: \"story_router_no_active_story\",\n message:\n \"Cannot route story implementation because no active story or queued story is available.\",\n });\n }\n\n const [nextStoryContext = \"\", ...remainingStoryContexts] =\n (await state.get<(string | StoryPhaseContexts)[]>(STORY_STATE_KEYS.storyContextQueue)) ??\n [];\n await state.set(STORY_STATE_KEYS.storyQueue, remaining);\n await state.set(STORY_STATE_KEYS.storyContextQueue, remainingStoryContexts);\n await state.set(STORY_STATE_KEYS.activeStory, nextStory);\n await state.set(STORY_STATE_KEYS.activeStoryContext, nextStoryContext);\n return routeStoryAfterPreflight(nextStory);\n }\n\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n return routeStoryAfterPreflight(activeStory);\n },\n);\n\nasync function routeFailedReview(currentStory?: Document): Promise<ContinuationResult> {\n const activeStory =\n (await state.get<Document | null>(STORY_STATE_KEYS.activeStory)) ?? currentStory;\n if (!activeStory) {\n return fail({\n code: \"story_router_no_active_story\",\n message: \"Cannot route failed story review because no active story is available for retry.\",\n });\n }\n\n const review = await state.get<ReviewResult | null>(STORY_STATE_KEYS.latestReviewResult);\n if (!review) {\n return fail({\n code: \"story_router_missing_review_result\",\n message: \"Cannot route failed story review because no latest review result is available.\",\n details: { storyPath: activeStory.path },\n });\n }\n\n if (reviewPasses(review)) {\n return fail({\n code: \"story_router_review_already_passed\",\n message: \"Cannot route failed story review because the latest review already passes.\",\n details: { review, storyPath: activeStory.path },\n });\n }\n\n const previousCounts = await loadRouterRetryCounts({\n reviewPhaseFallback: \"review-story-implementation\",\n });\n const reviewRetryCount = previousCounts.reviewRetryCount + 1;\n const nextCounts = { ...previousCounts, reviewRetryCount };\n\n if (reviewRetryCount >= MAX_STORY_REVIEW_ATTEMPTS) {\n const routerState = await persistRetryRouterState({\n activeStory,\n route: \"exhausted\",\n sourceReason: \"failed-review\",\n code: \"story_review_exhausted\",\n counts: nextCounts,\n retryLimit: MAX_STORY_REVIEW_ATTEMPTS,\n exhaustedReason: \"review\",\n review,\n });\n return fail({\n code: \"story_review_exhausted\",\n message: `Story failed review ${reviewRetryCount} times; retry limit is ${MAX_STORY_REVIEW_ATTEMPTS} (last score ${review.score}/5).`,\n details: {\n review,\n storyPath: activeStory.path,\n reviewRetryCount,\n retryLimit: MAX_STORY_REVIEW_ATTEMPTS,\n routerState,\n },\n });\n }\n\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.activePhase, \"implement-green\");\n await persistRetryRouterState({\n activeStory,\n route: \"retrying\",\n targetPhase: \"implement-green\",\n sourceReason: \"failed-review\",\n code: \"story_review_retry\",\n counts: nextCounts,\n retryLimit: MAX_STORY_REVIEW_ATTEMPTS,\n review,\n });\n const attempt = await incrementStoryPhaseAttempt(\"implement-green\");\n return implementGreenStep({\n currentStory: activeStory,\n explorationBrief: (await state.get(STORY_STATE_KEYS.latestExplorationBrief)) ?? undefined,\n redTestSummary: (await state.get(STORY_STATE_KEYS.latestRedTestSummary)) ?? undefined,\n attempt,\n previousReviewSummary: review.summary,\n requiredImprovements: review.requiredImprovements,\n implementationContext: await loadStoryPhaseContext(\"implement-green\"),\n });\n}\n\nasync function routeFailedValidation(currentStory?: Document): Promise<ContinuationResult> {\n const activeStory =\n (await state.get<Document | null>(STORY_STATE_KEYS.activeStory)) ?? currentStory;\n if (!activeStory) {\n return fail({\n code: \"story_router_no_active_story\",\n message:\n \"Cannot route failed story validation because no active story is available for retry.\",\n });\n }\n\n const validation = await state.get<ValidateStoryOutput | null>(\n STORY_STATE_KEYS.latestValidationSummary,\n );\n if (!validation) {\n return fail({\n code: \"story_router_missing_validation_result\",\n message:\n \"Cannot route failed story validation because no latest validation result is available.\",\n details: { storyPath: activeStory.path },\n });\n }\n\n if (validation.blocked) {\n return routeBlockedStory(activeStory, {\n type: \"blocked\",\n sourceReason: \"failed-validation\",\n blockedPhase: \"validate-story\",\n blockedReason: validation.blockedReason ?? \"Story validation reported a blocked state.\",\n code: \"story_validation_blocked\",\n metadata: { validation },\n });\n }\n\n if (validation.validationPassed) {\n return fail({\n code: \"story_router_validation_already_passed\",\n message: \"Cannot route failed story validation because the latest validation already passes.\",\n details: { storyPath: activeStory.path, validation },\n });\n }\n\n const previousCounts = await loadRouterRetryCounts({\n validationPhaseFallback: \"validate-story\",\n });\n const validationRetryCount = previousCounts.validationRetryCount + 1;\n const nextCounts = { ...previousCounts, validationRetryCount };\n\n if (validationRetryCount >= MAX_STORY_VALIDATION_ATTEMPTS) {\n const routerState = await persistRetryRouterState({\n activeStory,\n route: \"exhausted\",\n sourceReason: \"failed-validation\",\n code: \"story_validation_exhausted\",\n counts: nextCounts,\n retryLimit: MAX_STORY_VALIDATION_ATTEMPTS,\n exhaustedReason: \"validation\",\n validation,\n });\n return fail({\n code: \"story_validation_exhausted\",\n message: `Story failed validation ${validationRetryCount} times; retry limit is ${MAX_STORY_VALIDATION_ATTEMPTS}.`,\n details: {\n storyPath: activeStory.path,\n validation,\n validationRetryCount,\n retryLimit: MAX_STORY_VALIDATION_ATTEMPTS,\n routerState,\n },\n });\n }\n\n const route =\n validationRetryCount >= STORY_DOCTOR_VALIDATION_FAILURE_THRESHOLD ? \"doctoring\" : \"retrying\";\n const targetPhase = route === \"doctoring\" ? \"story-doctor\" : \"implement-green\";\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.activePhase, targetPhase);\n await persistRetryRouterState({\n activeStory,\n route,\n targetPhase,\n sourceReason: \"failed-validation\",\n code: route === \"doctoring\" ? \"story_validation_doctor\" : \"story_validation_retry\",\n counts: nextCounts,\n retryLimit: MAX_STORY_VALIDATION_ATTEMPTS,\n validation,\n });\n\n if (route === \"doctoring\") {\n await incrementStoryPhaseAttempt(\"story-doctor\");\n return storyDoctorStep({\n currentStory: activeStory,\n explorationBrief: (await state.get(STORY_STATE_KEYS.latestExplorationBrief)) ?? undefined,\n redTestSummary: (await state.get(STORY_STATE_KEYS.latestRedTestSummary)) ?? undefined,\n implementationSummary:\n (await state.get(STORY_STATE_KEYS.latestImplementationSummary)) ?? undefined,\n failedValidationSummary: validation.summary,\n failedValidationCommands: validation.commands,\n validationRetryCount,\n retryLimit: MAX_STORY_VALIDATION_ATTEMPTS,\n });\n }\n\n const attempt = await incrementStoryPhaseAttempt(\"implement-green\");\n return implementGreenStep({\n currentStory: activeStory,\n explorationBrief: (await state.get(STORY_STATE_KEYS.latestExplorationBrief)) ?? undefined,\n redTestSummary: (await state.get(STORY_STATE_KEYS.latestRedTestSummary)) ?? undefined,\n attempt,\n failedValidationSummary: validation.summary,\n failedValidationCommands: validation.commands,\n implementationContext: await loadStoryPhaseContext(\"implement-green\"),\n });\n}\n\nasync function routeBlockedStory(\n currentStory: Document | undefined,\n blockedRoute: Extract<StoryRouterInput[\"reason\"], { readonly type: \"blocked\" }>,\n): Promise<ContinuationResult> {\n const activeStory =\n (await state.get<Document | null>(STORY_STATE_KEYS.activeStory)) ?? currentStory;\n if (!activeStory) {\n return fail({\n code: \"story_router_no_active_story\",\n message: \"Cannot route blocked story because no active story is available.\",\n });\n }\n\n const counts = await loadRouterRetryCounts({});\n const routerState: StoryRouterState = {\n route: \"blocked\",\n activeStory,\n reviewRetryCount: counts.reviewRetryCount,\n validationRetryCount: counts.validationRetryCount,\n blockedPhase: blockedRoute.blockedPhase,\n blockedReason: blockedRoute.blockedReason,\n source: {\n reason: blockedRoute.sourceReason,\n blocked: true,\n code: blockedRoute.code,\n metadata: blockedRoute.metadata,\n },\n };\n\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.latestStoryRouterState, routerState);\n await state.set(STORY_STATE_KEYS.blockedReason, blockedRoute.blockedReason);\n\n return fail(formatBlockedRouteFailure(routerState));\n}\n\nasync function replayBlockedStoryRoute(): Promise<ContinuationResult | null> {\n const routerState = await state.get<StoryRouterState | null>(\n STORY_STATE_KEYS.latestStoryRouterState,\n );\n if (routerState?.route !== \"blocked\") {\n return null;\n }\n\n const activeStory = await state.get<Document | null>(STORY_STATE_KEYS.activeStory);\n if (!activeStory) {\n return fail({\n code: \"story_router_no_active_story\",\n message:\n \"Cannot replay blocked story routing because durable router state exists but no active story is available.\",\n details: { routerState },\n });\n }\n\n if (!storiesMatch(routerState.activeStory, activeStory)) {\n return fail({\n code: \"story_router_blocked_state_mismatch\",\n message:\n \"Cannot replay blocked story routing because durable router state does not match the active story.\",\n details: { storyPath: activeStory.path, routerState },\n });\n }\n\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.blockedReason, routerState.blockedReason ?? null);\n return fail(formatBlockedRouteFailure(routerState));\n}\n\nasync function replayPersistedRetryRoute(\n reason: RetryRouteSourceReason,\n currentStory?: Document,\n previousActivePhase?: string | null,\n): Promise<ContinuationResult | null> {\n const routerState = state.isReplayingCompletedStep\n ? await state.getPersisted<Partial<StoryRouterState> | null>(\n STORY_STATE_KEYS.latestStoryRouterState,\n )\n : await state.get<Partial<StoryRouterState> | null>(STORY_STATE_KEYS.latestStoryRouterState);\n if (!routerState || !isPersistedRetryRoute(routerState.route)) {\n return null;\n }\n\n if (routerState.source?.reason !== reason) {\n return null;\n }\n\n const activeStory =\n (await state.get<Document | null>(STORY_STATE_KEYS.activeStory)) ?? currentStory;\n if (!activeStory) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because no active story is available.\",\n { routerState },\n );\n }\n\n if (!routerState.activeStory) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because the durable router state is missing its active story.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (!storiesMatch(routerState.activeStory, activeStory)) {\n return retryStateMismatch(routerState, activeStory);\n }\n\n const shapeFailure = validatePersistedRetryRouteShape(routerState, reason, activeStory);\n if (shapeFailure) {\n return shapeFailure;\n }\n\n if (routerState.route === \"exhausted\") {\n return fail(formatExhaustedRetryRouteFailure(routerState, activeStory));\n }\n\n if (\n !state.isReplayingCompletedStep &&\n routerState.route !== \"doctoring\" &&\n routerState.targetPhase !== previousActivePhase &&\n previousActivePhase !== \"story-router\"\n ) {\n return null;\n }\n\n if (!(await persistedRetryEvidenceMatches(reason, routerState))) {\n return null;\n }\n\n if (routerState.route === \"retrying\") {\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.activePhase, \"implement-green\");\n const attempt = await incrementStoryPhaseAttempt(\"implement-green\");\n return implementGreenStep({\n currentStory: activeStory,\n explorationBrief: (await state.get(STORY_STATE_KEYS.latestExplorationBrief)) ?? undefined,\n redTestSummary: (await state.get(STORY_STATE_KEYS.latestRedTestSummary)) ?? undefined,\n attempt,\n previousReviewSummary:\n reason === \"failed-review\" ? routerState.latestReview?.summary : undefined,\n requiredImprovements:\n reason === \"failed-review\" ? routerState.latestReview?.requiredImprovements : undefined,\n failedValidationSummary:\n reason === \"failed-validation\" ? routerState.latestValidation?.summary : undefined,\n failedValidationCommands:\n reason === \"failed-validation\" ? routerState.latestValidation?.commands : undefined,\n implementationContext: await loadStoryPhaseContext(\"implement-green\"),\n });\n }\n\n if (routerState.route === \"doctoring\") {\n await state.set(STORY_STATE_KEYS.activeStory, activeStory);\n await state.set(STORY_STATE_KEYS.activePhase, \"story-doctor\");\n await incrementStoryPhaseAttempt(\"story-doctor\");\n return storyDoctorStep({\n currentStory: activeStory,\n explorationBrief: (await state.get(STORY_STATE_KEYS.latestExplorationBrief)) ?? undefined,\n redTestSummary: (await state.get(STORY_STATE_KEYS.latestRedTestSummary)) ?? undefined,\n implementationSummary:\n (await state.get(STORY_STATE_KEYS.latestImplementationSummary)) ?? undefined,\n failedValidationSummary: routerState.latestValidation?.summary ?? \"\",\n failedValidationCommands: routerState.latestValidation?.commands ?? [],\n validationRetryCount: routerState.validationRetryCount ?? 0,\n retryLimit: routerState.retryLimit ?? MAX_STORY_VALIDATION_ATTEMPTS,\n });\n }\n\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route with an unknown route.\",\n {\n storyPath: activeStory.path,\n routerState,\n },\n );\n}\n\nfunction isPersistedRetryRoute(\n route: unknown,\n): route is Extract<StoryRouterState[\"route\"], \"retrying\" | \"doctoring\" | \"exhausted\"> {\n return route === \"retrying\" || route === \"doctoring\" || route === \"exhausted\";\n}\n\nfunction validatePersistedRetryRouteShape(\n routerState: Partial<StoryRouterState>,\n reason: RetryRouteSourceReason,\n activeStory: Document,\n): ContinuationResult | null {\n if (typeof routerState.source?.code !== \"string\" || routerState.source.code.length === 0) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because the durable router state is missing its source code.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (!isNonNegativeInteger(routerState.reviewRetryCount)) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because the review retry count is missing or invalid.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (!isNonNegativeInteger(routerState.validationRetryCount)) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because the validation retry count is missing or invalid.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (!isPositiveInteger(routerState.retryLimit)) {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because the retry limit is missing or invalid.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (routerState.route === \"retrying\" && routerState.targetPhase !== \"implement-green\") {\n return inconsistentRetryState(\n \"Cannot replay persisted story retry route because retrying routes must target implement-green.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (routerState.route === \"doctoring\" && routerState.targetPhase !== \"story-doctor\") {\n return inconsistentRetryState(\n \"Cannot replay persisted story doctor route because doctoring routes must target story-doctor.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (reason === \"failed-review\" && !hasReviewMetadata(routerState.latestReview)) {\n return inconsistentRetryState(\n \"Cannot replay persisted story review retry route because latest review evidence is missing or invalid.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n if (reason === \"failed-validation\" && !hasValidationMetadata(routerState.latestValidation)) {\n return inconsistentRetryState(\n \"Cannot replay persisted story validation retry route because latest validation evidence is missing or invalid.\",\n { storyPath: activeStory.path, routerState },\n );\n }\n\n return null;\n}\n\nasync function persistedRetryEvidenceMatches(\n reason: RetryRouteSourceReason,\n routerState: Partial<StoryRouterState>,\n): Promise<boolean> {\n if (routerState.source?.reason !== reason) {\n return false;\n }\n\n if (state.isReplayingCompletedStep) {\n return true;\n }\n\n return routerStateEvidenceMatchesLatest(routerState);\n}\n\nasync function routerStateEvidenceMatchesLatest(\n routerState: Partial<StoryRouterState>,\n): Promise<boolean> {\n if (routerState.source?.reason === \"failed-review\") {\n if (!hasReviewMetadata(routerState.latestReview)) {\n return false;\n }\n\n const review = await state.get<ReviewResult | null>(STORY_STATE_KEYS.latestReviewResult);\n return (\n !!review &&\n routerState.latestReview.score === review.score &&\n routerState.latestReview.summary === review.summary &&\n stringArraysEqual(routerState.latestReview.requiredImprovements, review.requiredImprovements)\n );\n }\n\n if (routerState.source?.reason === \"failed-validation\") {\n if (!hasValidationMetadata(routerState.latestValidation)) {\n return false;\n }\n\n const validation = await state.get<ValidateStoryOutput | null>(\n STORY_STATE_KEYS.latestValidationSummary,\n );\n return (\n !!validation &&\n routerState.latestValidation.summary === validation.summary &&\n validationCommandArraysEqual(routerState.latestValidation.commands, validation.commands)\n );\n }\n\n return true;\n}\n\nfunction hasReviewMetadata(value: unknown): value is NonNullable<StoryRouterState[\"latestReview\"]> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"score\" in value &&\n typeof value.score === \"number\" &&\n \"summary\" in value &&\n typeof value.summary === \"string\" &&\n \"requiredImprovements\" in value &&\n Array.isArray(value.requiredImprovements) &&\n value.requiredImprovements.every((item) => typeof item === \"string\")\n );\n}\n\nfunction hasValidationMetadata(\n value: unknown,\n): value is NonNullable<StoryRouterState[\"latestValidation\"]> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"summary\" in value &&\n typeof value.summary === \"string\" &&\n \"commands\" in value &&\n Array.isArray(value.commands) &&\n value.commands.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n \"command\" in item &&\n typeof item.command === \"string\" &&\n \"result\" in item &&\n typeof item.result === \"string\",\n )\n );\n}\n\nfunction storiesMatch(left: Document, right: Document): boolean {\n return left.path === right.path && left.content === right.content;\n}\n\nfunction stringArraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((item, index) => item === right[index]);\n}\n\nfunction validationCommandArraysEqual(\n left: readonly { readonly command: string; readonly result: string }[],\n right: readonly { readonly command: string; readonly result: string }[],\n): boolean {\n return (\n left.length === right.length &&\n left.every(\n (item, index) =>\n item.command === right[index]?.command && item.result === right[index]?.result,\n )\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0;\n}\n\nfunction retryStateMismatch(routerState: Partial<StoryRouterState>, activeStory: Document): never {\n throw new StoryRouterFailureError({\n code: \"story_router_retry_state_mismatch\",\n message:\n \"Cannot replay persisted story retry route because durable router state does not match the active story.\",\n details: { storyPath: activeStory.path, routerState },\n });\n}\n\nfunction inconsistentRetryState(message: string, details: Record<string, unknown>): never {\n throw new StoryRouterFailureError({\n code: \"story_router_inconsistent_retry_state\",\n message,\n details,\n });\n}\n\nfunction formatExhaustedRetryRouteFailure(\n routerState: Partial<StoryRouterState>,\n activeStory: Document,\n): {\n code: string;\n message: string;\n details: Record<string, unknown>;\n} {\n const exhaustedReason =\n routerState.exhaustedReason ?? reasonForSource(routerState.source?.reason);\n const retryCount =\n exhaustedReason === \"review\" ? routerState.reviewRetryCount : routerState.validationRetryCount;\n return {\n code: routerState.source?.code ?? `story_${exhaustedReason}_exhausted`,\n message: `Story ${exhaustedReason} retry route is already exhausted (${retryCount}/${routerState.retryLimit}).`,\n details: { storyPath: activeStory.path, routerState },\n };\n}\n\nfunction reasonForSource(\n reason: StoryRouterState[\"source\"][\"reason\"] | undefined,\n): \"review\" | \"validation\" {\n return reason === \"failed-review\" ? \"review\" : \"validation\";\n}\n\nasync function persistRetryRouterState(input: {\n readonly activeStory: Document;\n readonly route: \"retrying\" | \"doctoring\" | \"exhausted\";\n readonly targetPhase?: \"implement-green\" | \"story-doctor\";\n readonly sourceReason: \"failed-review\" | \"failed-validation\";\n readonly code: string;\n readonly counts: RouterRetryCounts;\n readonly retryLimit: number;\n readonly exhaustedReason?: \"review\" | \"validation\";\n readonly review?: ReviewResult;\n readonly validation?: ValidateStoryOutput;\n}): Promise<StoryRouterState> {\n const routerState: StoryRouterState = {\n route: input.route,\n activeStory: input.activeStory,\n targetPhase: input.targetPhase,\n reviewRetryCount: input.counts.reviewRetryCount,\n validationRetryCount: input.counts.validationRetryCount,\n retryLimit: input.retryLimit,\n exhaustedReason: input.exhaustedReason,\n latestReview: input.review\n ? {\n score: input.review.score,\n summary: input.review.summary,\n requiredImprovements: input.review.requiredImprovements,\n }\n : undefined,\n latestValidation: input.validation\n ? {\n summary: input.validation.summary,\n commands: input.validation.commands,\n }\n : undefined,\n source: {\n reason: input.sourceReason,\n code: input.code,\n },\n };\n await state.set(STORY_STATE_KEYS.latestStoryRouterState, routerState);\n return routerState;\n}\n\nasync function loadRouterRetryCounts(input: {\n readonly reviewPhaseFallback?: \"review-story-implementation\";\n readonly validationPhaseFallback?: \"validate-story\";\n}): Promise<RouterRetryCounts> {\n const activeStory = await state.get<Document | null>(STORY_STATE_KEYS.activeStory);\n const routerState = await state.get<Partial<StoryRouterState> | null>(\n STORY_STATE_KEYS.latestStoryRouterState,\n );\n const attemptsByPhase =\n (await state.get<Record<string, number> | null>(STORY_STATE_KEYS.attemptsByPhase)) ?? {};\n const routerStateMatchesActiveStory =\n activeStory &&\n routerState?.activeStory?.path === activeStory.path &&\n routerState.activeStory.content === activeStory.content;\n\n if (routerStateMatchesActiveStory) {\n const fallbackCounts = {\n reviewRetryCount: phaseAttemptFallback(attemptsByPhase, input.reviewPhaseFallback),\n validationRetryCount: phaseAttemptFallback(attemptsByPhase, input.validationPhaseFallback),\n };\n const replayingSameReviewEvidence =\n input.reviewPhaseFallback && routerState.source?.reason === \"failed-review\";\n const replayingSameValidationEvidence =\n input.validationPhaseFallback && routerState.source?.reason === \"failed-validation\";\n\n if (\n (replayingSameReviewEvidence || replayingSameValidationEvidence) &&\n !(await routerStateEvidenceMatchesLatest(routerState))\n ) {\n return fallbackCounts;\n }\n\n return {\n reviewRetryCount: normalizeRetryCount(routerState.reviewRetryCount),\n validationRetryCount: normalizeRetryCount(routerState.validationRetryCount),\n };\n }\n\n if (routerState?.activeStory) {\n return {\n reviewRetryCount: 0,\n validationRetryCount: 0,\n };\n }\n\n return {\n reviewRetryCount: phaseAttemptFallback(attemptsByPhase, input.reviewPhaseFallback),\n validationRetryCount: phaseAttemptFallback(attemptsByPhase, input.validationPhaseFallback),\n };\n}\n\nfunction phaseAttemptFallback(\n attemptsByPhase: Record<string, number>,\n phase: \"review-story-implementation\" | \"validate-story\" | undefined,\n): number {\n if (!phase) {\n return 0;\n }\n\n return Math.max(0, normalizeRetryCount(attemptsByPhase[phase]) - 1);\n}\n\nfunction normalizeRetryCount(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\n}\n\nfunction formatBlockedRouteFailure(routerState: StoryRouterState): {\n code: string;\n message: string;\n details: Record<string, unknown>;\n} {\n return {\n code: routerState.source.code,\n message: routerState.blockedReason ?? \"Story routing is blocked.\",\n details: {\n storyPath: routerState.activeStory.path,\n routerState,\n ...formatBlockedRouteFailureDetails(\n routerState.blockedPhase ?? \"validate-story\",\n routerState.source.metadata,\n ),\n },\n };\n}\n\nfunction formatBlockedRouteFailureDetails(\n blockedPhase: BlockedStoryPhase,\n metadata?: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n blockedPhase,\n ...(metadata ? metadata : {}),\n };\n}\n\nasync function repairStaleStoryCompletion(currentStory?: Document): Promise<Failure | undefined> {\n if (!currentStory) {\n return undefined;\n }\n\n const persistedActiveStory = await state.get<Document | null>(STORY_STATE_KEYS.activeStory);\n if (!persistedActiveStory || storiesMatch(persistedActiveStory, currentStory)) {\n return undefined;\n }\n\n const storyQueue = (await state.get<Document[]>(STORY_STATE_KEYS.storyQueue)) ?? [];\n const queuedCurrentStoryIndex = storyQueue.findIndex((story) =>\n storiesMatch(story, currentStory),\n );\n if (queuedCurrentStoryIndex !== 0) {\n return {\n code: \"story_router_stale_completion_mismatch\",\n message:\n \"Cannot repair stale story completion state because the routed next story is not the immediate queued successor.\",\n details: {\n persistedActiveStoryPath: persistedActiveStory.path,\n currentStoryPath: currentStory.path,\n queuedCurrentStoryIndex,\n queuedStoryPaths: storyQueue.map((story) => story.path),\n },\n };\n }\n\n const completed = (await state.get<string[]>(STORY_STATE_KEYS.completedStories)) ?? [];\n const completedTitle = extractStoryTitle(persistedActiveStory.content, completed.length + 1);\n await resetStoryLocalStateForNextStory();\n await state.set(\n STORY_STATE_KEYS.completedStories,\n completed.includes(completedTitle) ? completed : [...completed, completedTitle],\n );\n await state.set(STORY_STATE_KEYS.storyQueue, storyQueue.slice(1));\n\n const storyContextQueue =\n (await state.get<(string | StoryPhaseContexts)[]>(STORY_STATE_KEYS.storyContextQueue)) ?? [];\n await state.set(STORY_STATE_KEYS.storyContextQueue, storyContextQueue.slice(1));\n await state.set(STORY_STATE_KEYS.activeStory, currentStory);\n await state.set(STORY_STATE_KEYS.activeStoryContext, storyContextQueue[0] ?? \"\");\n return undefined;\n}\n\nasync function routeStoryAfterPreflight(activeStory: Document): Promise<ContinuationResult> {\n return storyIsolationPreflightStep({ currentStory: activeStory });\n}\n","import { state, step } from \"@trailstep/authoring\";\nimport {\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n STORY_STATE_KEYS,\n} from \"../shared/story-state.js\";\nimport { validateStoryStep } from \"../validate-story/step.js\";\nimport {\n type ImplementGreenInput,\n type ImplementGreenOutput,\n implementGreenOutput,\n implementGreenPrompt,\n} from \"./prompt.js\";\n\nexport const implementGreenStep = step({ id: \"implement-green\" })\n .prompt<ImplementGreenInput, ImplementGreenOutput>(implementGreenPrompt, {\n agent: \"storyImplementer\",\n output: implementGreenOutput,\n })\n .do(async (promptOutput, input) => {\n if (promptOutput.blocked) {\n await state.set(\n STORY_STATE_KEYS.blockedReason,\n promptOutput.blockedReason ?? \"Green implementation reported a blocked state.\",\n );\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({\n reason: {\n type: \"blocked\",\n sourceReason: \"failed-implementation\",\n blockedPhase: \"implement-green\",\n blockedReason:\n promptOutput.blockedReason ?? \"Green implementation reported a blocked state.\",\n code: \"story_green_blocked\",\n },\n currentStory: input.currentStory,\n });\n }\n\n await state.set(STORY_STATE_KEYS.latestImplementationSummary, promptOutput);\n await state.set(STORY_STATE_KEYS.activePhase, \"validate-story\");\n const attempt = await incrementStoryPhaseAttempt(\"validate-story\");\n return validateStoryStep({\n currentStory: input.currentStory,\n explorationBrief: input.explorationBrief,\n redTestSummary: input.redTestSummary,\n implementationSummary: promptOutput,\n attempt,\n implementationContext: await loadStoryPhaseContext(\"validate-story\"),\n });\n });\n","import { type Document, state } from \"@trailstep/authoring\";\nimport { runGit } from \"../commit-reviewed-story/run-git.js\";\n\nexport const STORY_STATE_KEYS = {\n activePhase: \"activePhase\",\n activeStory: \"activeStory\",\n activeStoryContext: \"activeStoryContext\",\n activeStoryStartCommit: \"activeStoryStartCommit\",\n attemptsByPhase: \"attemptsByPhase\",\n completedStories: \"completedStories\",\n blockedReason: \"blockedReason\",\n latestExplorationBrief: \"latestExplorationBrief\",\n latestImplementationSummary: \"latestImplementationSummary\",\n latestPreflightStatus: \"latestPreflightStatus\",\n planningCheckpointCount: \"planningCheckpointCount\",\n skipNextPlanningCheckpoint: \"skipNextPlanningCheckpoint\",\n latestRedTestSummary: \"latestRedTestSummary\",\n latestReviewResult: \"latestReviewResult\",\n latestStoryRouterState: \"latestStoryRouterState\",\n latestValidationSummary: \"latestValidationSummary\",\n storyBaseline: \"storyBaseline\",\n storyContextQueue: \"storyContextQueue\",\n storyQueue: \"storyQueue\",\n workflowOptions: \"workflowOptions\",\n workflowWarnings: \"workflowWarnings\",\n} as const;\n\nexport type StoryPhase =\n | \"story-router\"\n | \"story-isolation-preflight\"\n | \"deterministic-context-preflight\"\n | \"explore-story\"\n | \"write-red-tests\"\n | \"implement-green\"\n | \"story-doctor\"\n | \"validate-story\"\n | \"implement-story\"\n | \"review-story-implementation\"\n | \"commit-reviewed-story\";\n\nexport type BlockedStoryPhase =\n | \"explore-story\"\n | \"write-red-tests\"\n | \"implement-green\"\n | \"validate-story\";\n\nexport type BlockedStoryRouteSourceReason =\n | \"failed-exploration\"\n | \"failed-red-tests\"\n | \"failed-implementation\"\n | \"failed-validation\";\n\nexport type StoryRouterRoute = \"blocked\" | \"retrying\" | \"doctoring\" | \"exhausted\";\n\nexport interface StoryRouterState {\n readonly route: StoryRouterRoute;\n readonly activeStory: Document;\n readonly targetPhase?: StoryPhase;\n readonly reviewRetryCount: number;\n readonly validationRetryCount: number;\n readonly retryLimit?: number;\n readonly blockedPhase?: BlockedStoryPhase;\n readonly blockedReason?: string;\n readonly exhaustedReason?: \"review\" | \"validation\";\n readonly latestReview?: {\n readonly score: number;\n readonly summary: string;\n readonly requiredImprovements: readonly string[];\n };\n readonly latestValidation?: {\n readonly summary: string;\n readonly commands: readonly { readonly command: string; readonly result: string }[];\n };\n readonly source: {\n readonly reason: BlockedStoryRouteSourceReason | \"failed-review\" | \"failed-validation\";\n readonly blocked?: true;\n readonly code: string;\n readonly metadata?: Record<string, unknown>;\n };\n}\n\nexport interface StoryPreflightStatus {\n readonly ok: boolean;\n readonly code: string;\n readonly message: string;\n readonly baseline?: string;\n}\n\nexport interface ActiveStoryStartCommit {\n readonly commit?: string;\n readonly warning?: string;\n}\n\nexport type StoryRoutedContextPhase =\n | \"deterministic-context-preflight\"\n | \"explore-story\"\n | \"write-red-tests\"\n | \"implement-green\"\n | \"validate-story\"\n | \"review-story-implementation\";\n\nexport type StoryPhaseContexts = Partial<Record<StoryRoutedContextPhase, string>>;\n\nexport interface StoryReviewGitContext {\n readonly storyStartCommit?: string;\n readonly statusShort?: string;\n readonly changedFiles: readonly string[];\n readonly committedChangedFiles: readonly string[];\n readonly uncommittedChangedFiles: readonly string[];\n readonly committedDiffStat?: string;\n readonly uncommittedDiffStat?: string;\n readonly warnings: readonly string[];\n}\n\nexport async function recordActiveStoryStartCommit(): Promise<ActiveStoryStartCommit> {\n const existing = await state.get<ActiveStoryStartCommit | null>(\n STORY_STATE_KEYS.activeStoryStartCommit,\n );\n if (existing?.commit || existing?.warning) {\n return existing;\n }\n\n const cwd = state.cwd;\n if (!cwd) {\n const missingCwd = {\n warning:\n \"Workflow cwd is unavailable; the story reviewer cannot verify committed story changes from a durable git baseline.\",\n };\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, missingCwd);\n return missingCwd;\n }\n\n const result = await runGit([\"rev-parse\", \"HEAD\"], cwd);\n if (!result.ok || result.stdout.length === 0) {\n const missingGitBaseline = {\n warning: `Unable to record story start commit with \\`git rev-parse HEAD\\`: ${result.ok ? \"no commit was returned\" : result.error}`,\n };\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, missingGitBaseline);\n return missingGitBaseline;\n }\n\n const baseline = { commit: result.stdout };\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, baseline);\n await state.set(STORY_STATE_KEYS.storyBaseline, result.stdout);\n return baseline;\n}\n\nexport async function loadStoryPhaseContext(\n phase: StoryRoutedContextPhase,\n): Promise<string | undefined> {\n const context = await state.get<string | StoryPhaseContexts | null>(\n STORY_STATE_KEYS.activeStoryContext,\n );\n if (!context) {\n return undefined;\n }\n\n if (typeof context === \"string\") {\n return context.length > 0 ? context : undefined;\n }\n\n const scopedContext = context[phase];\n return scopedContext && scopedContext.length > 0 ? scopedContext : undefined;\n}\n\nexport async function incrementStoryPhaseAttempt(phase: StoryPhase): Promise<number> {\n const attempts =\n (await state.get<Record<string, number> | null>(STORY_STATE_KEYS.attemptsByPhase)) ?? {};\n const nextAttempt = (attempts[phase] ?? 0) + 1;\n await state.set(STORY_STATE_KEYS.attemptsByPhase, { ...attempts, [phase]: nextAttempt });\n return nextAttempt;\n}\n\nexport async function resetActiveStoryStartCommit(): Promise<void> {\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, null);\n}\n\ninterface ResetStoryLocalStateOptions {\n readonly preserveActiveStoryStartCommit?: boolean;\n readonly preserveLatestStoryRouterState?: boolean;\n readonly preserveStoryBaseline?: boolean;\n}\n\nexport async function resetStoryLocalState(\n options: ResetStoryLocalStateOptions = {},\n): Promise<void> {\n await resetStoryLocalStateFields(options);\n}\n\nexport async function resetStoryLocalStateForNextStory(): Promise<void> {\n await resetStoryLocalStateFields({\n preserveActiveStoryStartCommit: false,\n preserveLatestStoryRouterState: false,\n preserveStoryBaseline: false,\n });\n}\n\nasync function resetStoryLocalStateFields(options: ResetStoryLocalStateOptions): Promise<void> {\n await state.set(STORY_STATE_KEYS.attemptsByPhase, {});\n if (!options.preserveStoryBaseline) {\n await state.set(STORY_STATE_KEYS.storyBaseline, null);\n }\n if (!options.preserveActiveStoryStartCommit) {\n await resetActiveStoryStartCommit();\n }\n await state.set(STORY_STATE_KEYS.latestPreflightStatus, null);\n await state.set(STORY_STATE_KEYS.latestExplorationBrief, null);\n await state.set(STORY_STATE_KEYS.latestRedTestSummary, null);\n await state.set(STORY_STATE_KEYS.latestImplementationSummary, null);\n await state.set(STORY_STATE_KEYS.latestValidationSummary, null);\n await state.set(STORY_STATE_KEYS.latestReviewResult, null);\n if (!options.preserveLatestStoryRouterState) {\n await state.set(STORY_STATE_KEYS.latestStoryRouterState, null);\n }\n await state.set(STORY_STATE_KEYS.blockedReason, null);\n}\n\nexport async function loadStoryReviewGitContext(): Promise<StoryReviewGitContext> {\n const baseline = await state.get<ActiveStoryStartCommit | null>(\n STORY_STATE_KEYS.activeStoryStartCommit,\n );\n const warnings: string[] = [];\n\n if (baseline?.warning) {\n warnings.push(baseline.warning);\n }\n\n const cwd = state.cwd;\n if (!cwd) {\n warnings.push(\n \"Workflow cwd is unavailable; reviewer must treat committed story-change context as missing.\",\n );\n return {\n storyStartCommit: baseline?.commit,\n changedFiles: [],\n committedChangedFiles: [],\n uncommittedChangedFiles: [],\n warnings,\n };\n }\n\n const status = await runGit([\"status\", \"--short\"], cwd);\n if (!status.ok) {\n warnings.push(`Unable to inspect \\`git status --short\\`: ${status.error}`);\n }\n\n const uncommittedChangedFilesResult = await runGit([\"diff\", \"--name-only\"], cwd);\n if (!uncommittedChangedFilesResult.ok) {\n warnings.push(\n `Unable to inspect uncommitted changed files with \\`git diff --name-only\\`: ${uncommittedChangedFilesResult.error}`,\n );\n }\n\n const uncommittedDiffStatResult = await runGit([\"diff\", \"--stat\"], cwd);\n if (!uncommittedDiffStatResult.ok) {\n warnings.push(\n `Unable to inspect uncommitted diffstat with \\`git diff --stat\\`: ${uncommittedDiffStatResult.error}`,\n );\n }\n\n const storyStartCommit = baseline?.commit;\n let committedChangedFiles: readonly string[] = [];\n let committedDiffStat: string | undefined;\n if (!storyStartCommit) {\n warnings.push(\n \"No durable story start commit is recorded; reviewer must not silently review only the current working tree diff.\",\n );\n } else {\n const baselineReachable = await runGit([\"cat-file\", \"-e\", `${storyStartCommit}^{commit}`], cwd);\n if (!baselineReachable.ok) {\n warnings.push(\n `Recorded story start commit \\`${storyStartCommit}\\` is invalid or unreachable: ${baselineReachable.error}`,\n );\n } else {\n const committedChangedFilesResult = await runGit(\n [\"diff\", \"--name-only\", `${storyStartCommit}..HEAD`],\n cwd,\n );\n if (!committedChangedFilesResult.ok) {\n warnings.push(\n `Unable to inspect committed changed files with \\`git diff --name-only ${storyStartCommit}..HEAD\\`: ${committedChangedFilesResult.error}`,\n );\n } else {\n committedChangedFiles = splitGitLines(committedChangedFilesResult.stdout);\n }\n\n const committedDiffStatResult = await runGit(\n [\"diff\", \"--stat\", `${storyStartCommit}..HEAD`],\n cwd,\n );\n if (!committedDiffStatResult.ok) {\n warnings.push(\n `Unable to inspect committed diffstat with \\`git diff --stat ${storyStartCommit}..HEAD\\`: ${committedDiffStatResult.error}`,\n );\n } else {\n committedDiffStat = committedDiffStatResult.stdout;\n }\n }\n }\n\n const uncommittedTrackedFiles = uncommittedChangedFilesResult.ok\n ? splitGitLines(uncommittedChangedFilesResult.stdout)\n : [];\n const uncommittedStatusFiles = status.ok ? parseStatusChangedFiles(status.stdout) : [];\n const uncommittedChangedFiles = uniqueFiles([\n ...uncommittedTrackedFiles,\n ...uncommittedStatusFiles,\n ]);\n\n return {\n storyStartCommit,\n statusShort: status.ok ? status.stdout : undefined,\n changedFiles: uniqueFiles([...committedChangedFiles, ...uncommittedChangedFiles]),\n committedChangedFiles,\n uncommittedChangedFiles,\n committedDiffStat,\n uncommittedDiffStat: uncommittedDiffStatResult.ok\n ? uncommittedDiffStatResult.stdout\n : undefined,\n warnings,\n };\n}\n\nfunction splitGitLines(stdout: string): readonly string[] {\n return stdout\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n}\n\nfunction parseStatusChangedFiles(stdout: string): readonly string[] {\n return splitGitLines(stdout).flatMap((line) => {\n const path = line.slice(3).trim();\n if (path.length === 0) {\n return [];\n }\n\n const renamedPath = path.split(\" -> \").at(-1)?.trim();\n return renamedPath ? [renamedPath] : [];\n });\n}\n\nfunction uniqueFiles(files: readonly string[]): readonly string[] {\n return Array.from(new Set(files));\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type GitResult =\n | { readonly ok: true; readonly stdout: string }\n | { readonly ok: false; readonly error: string };\n\nexport async function runGit(args: readonly string[], cwd: string): Promise<GitResult> {\n try {\n const { stdout } = await execFileAsync(\"git\", [...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 10,\n });\n return { ok: true, stdout: stdout.trimEnd() };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, error: message };\n }\n}\n","import { state, step } from \"@trailstep/authoring\";\nimport { reviewStoryImplementationStep } from \"../review-story-implementation/step.js\";\nimport {\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n loadStoryReviewGitContext,\n STORY_STATE_KEYS,\n} from \"../shared/story-state.js\";\nimport type { ValidateStoryInput, ValidateStoryOutput } from \"./prompt.js\";\nimport { runFocusedStoryValidation } from \"./validation-runner.js\";\n\nexport const validateStoryStep = step({ id: \"validate-story\" }).do(\n async (input: ValidateStoryInput) => {\n const promptOutput: ValidateStoryOutput = await runFocusedStoryValidation({\n validationInput: input,\n cwd: state.cwd,\n implementationContext: await loadStoryPhaseContext(\"validate-story\"),\n });\n await state.set(STORY_STATE_KEYS.latestValidationSummary, promptOutput);\n if (promptOutput.blocked) {\n await state.set(\n STORY_STATE_KEYS.blockedReason,\n promptOutput.blockedReason ?? \"Story validation reported a blocked state.\",\n );\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({\n reason: {\n type: \"blocked\",\n sourceReason: \"failed-validation\",\n blockedPhase: \"validate-story\",\n blockedReason: promptOutput.blockedReason ?? \"Story validation reported a blocked state.\",\n code: \"story_validation_blocked\",\n metadata: { validation: promptOutput },\n },\n currentStory: input.currentStory,\n });\n }\n\n if (!promptOutput.validationPassed) {\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({ reason: \"failed-validation\", currentStory: input.currentStory });\n }\n\n await state.set(STORY_STATE_KEYS.activePhase, \"review-story-implementation\");\n await incrementStoryPhaseAttempt(\"review-story-implementation\");\n return reviewStoryImplementationStep({\n currentStory: input.currentStory,\n attempt: input.attempt,\n implementationContext: await loadStoryPhaseContext(\"review-story-implementation\"),\n implementationSummary: input.implementationSummary?.summary,\n explorationSummary: input.explorationBrief?.summary,\n redTestSummary: input.redTestSummary?.summary,\n redEvidence: input.redTestSummary?.redEvidence,\n validationSummary: promptOutput.summary,\n validationCommands: promptOutput.commands,\n gitContext: await loadStoryReviewGitContext(),\n });\n },\n);\n","import { state, step } from \"@trailstep/authoring\";\nimport { commitReviewedStoryStep } from \"../commit-reviewed-story/step.js\";\nimport type { ReviewResult } from \"../shared/review-schema.js\";\nimport { reviewOutput, reviewPasses } from \"../shared/review-schema.js\";\nimport { STORY_STATE_KEYS } from \"../shared/story-state.js\";\nimport { type ReviewStoryImplementationInput, reviewStoryImplementationPrompt } from \"./prompt.js\";\n\nexport const reviewStoryImplementationStep = step({ id: \"review-story-implementation\" })\n .prompt<ReviewStoryImplementationInput, ReviewResult>(reviewStoryImplementationPrompt, {\n agent: \"storyReviewer\",\n output: reviewOutput,\n })\n .do(async (review, input) => {\n await state.set(STORY_STATE_KEYS.latestReviewResult, review);\n if (!reviewPasses(review)) {\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({ reason: \"failed-review\", currentStory: input.currentStory });\n }\n\n return commitReviewedStoryStep({\n currentStory: input.currentStory,\n implementationSummary: input.implementationSummary,\n });\n });\n","import type { Document } from \"@trailstep/authoring\";\nimport { fail, state, step } from \"@trailstep/authoring\";\nimport type { ContinuationResult } from \"@trailstep/core\";\nimport { openPullRequestStep } from \"../open-pull-request/step.js\";\nimport {\n defaultTakeItAwayWorkflowOptions,\n type TakeItAwayWorkflowOptions,\n} from \"../shared/input-schema.js\";\nimport { extractStoryTitle, type TakeItAwayOutput } from \"../shared/output-schema.js\";\nimport {\n type ActiveStoryStartCommit,\n resetActiveStoryStartCommit,\n resetStoryLocalStateForNextStory,\n STORY_STATE_KEYS,\n type StoryPhaseContexts,\n} from \"../shared/story-state.js\";\nimport { runGit } from \"./run-git.js\";\n\nexport interface CommitReviewedStoryInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly implementationSummary?: string;\n}\n\ntype StoryCommitResult =\n | { readonly ok: true; readonly warning?: string }\n | {\n readonly ok: false;\n readonly code: string;\n readonly message: string;\n readonly details: Record<string, unknown>;\n };\n\nexport const commitReviewedStoryStep = step({ id: \"commit-reviewed-story\" }).do(\n async (input: CommitReviewedStoryInput): Promise<ContinuationResult> => {\n const activeStory = input.currentStory;\n\n if (!state.isReplayingCompletedStep && (await storyAutoCommitEnabled())) {\n const commitResult = await commitReviewedStoryChanges(\n activeStory,\n input.implementationSummary,\n );\n if (commitResult.ok) {\n if (commitResult.warning) {\n await appendWorkflowWarning(commitResult.warning);\n }\n } else {\n const storyQueue = (await state.get<Document[]>(STORY_STATE_KEYS.storyQueue)) ?? [];\n if (storyQueue.length > 0) {\n return fail({\n code: commitResult.code,\n message: commitResult.message,\n details: commitResult.details,\n });\n }\n\n await appendWorkflowWarning(commitResult.message);\n }\n }\n\n return completeReviewedStory(activeStory);\n },\n);\n\nasync function storyAutoCommitEnabled(): Promise<boolean> {\n const options =\n (await state.get<TakeItAwayWorkflowOptions | null>(STORY_STATE_KEYS.workflowOptions)) ??\n defaultTakeItAwayWorkflowOptions();\n return options.autoCommit;\n}\n\nasync function commitReviewedStoryChanges(\n activeStory: Document,\n implementationSummary: string | undefined,\n): Promise<StoryCommitResult> {\n const cwd = state.cwd;\n if (!cwd) {\n return {\n ok: false,\n code: \"story_commit_missing_cwd\",\n message: \"Cannot commit reviewed story because the TrailStep workflow cwd is unavailable.\",\n details: { storyPath: activeStory.path },\n };\n }\n\n const insideWorkTree = await runGit([\"rev-parse\", \"--is-inside-work-tree\"], cwd);\n if (!insideWorkTree.ok || insideWorkTree.stdout !== \"true\") {\n return {\n ok: false,\n code: \"story_commit_not_git_worktree\",\n message:\n \"Cannot commit reviewed story because the workflow is not running inside a git worktree.\",\n details: {\n storyPath: activeStory.path,\n gitError: insideWorkTree.ok ? undefined : insideWorkTree.error,\n },\n };\n }\n\n const add = await runGit([\"add\", \"-A\"], cwd);\n if (!add.ok) {\n return {\n ok: false,\n code: \"story_commit_stage_failed\",\n message: \"Cannot commit reviewed story because `git add -A` failed.\",\n details: { storyPath: activeStory.path, gitError: add.error },\n };\n }\n\n const staged = await runGit([\"diff\", \"--cached\", \"--name-only\"], cwd);\n if (!staged.ok) {\n return {\n ok: false,\n code: \"story_commit_status_failed\",\n message: \"Cannot commit reviewed story because staged changes could not be inspected.\",\n details: { storyPath: activeStory.path, gitError: staged.error },\n };\n }\n\n const storyTitle = extractStoryTitle(activeStory.content, 1);\n\n if (staged.stdout.trim().length === 0) {\n const baseline = await state.get<ActiveStoryStartCommit | null>(\n STORY_STATE_KEYS.activeStoryStartCommit,\n );\n const head = await runGit([\"rev-parse\", \"HEAD\"], cwd);\n if (baseline?.commit && head.ok && head.stdout !== baseline.commit) {\n return { ok: true };\n }\n\n const headSubject = await runGit([\"log\", \"-1\", \"--format=%s\"], cwd);\n if (\n headSubject.ok &&\n headSubject.stdout === truncateCommitSubject(`trailstep: ${storyTitle}`)\n ) {\n return { ok: true };\n }\n\n return {\n ok: true,\n warning:\n \"The story passed review, but there were no staged or already-committed changes since the story baseline to commit.\",\n };\n }\n\n const commit = await runGit(\n [\n \"commit\",\n \"-m\",\n truncateCommitSubject(`trailstep: ${storyTitle}`),\n \"-m\",\n commitBody(activeStory, implementationSummary, staged.stdout),\n ],\n cwd,\n );\n\n if (!commit.ok) {\n return {\n ok: false,\n code: \"story_commit_failed\",\n message: \"The story passed review, but TrailStep could not create the story commit.\",\n details: { storyPath: activeStory.path, gitError: commit.error },\n };\n }\n\n return { ok: true };\n}\n\nasync function completeReviewedStory(activeStory: Document): Promise<ContinuationResult> {\n const completed = (await state.get<string[]>(STORY_STATE_KEYS.completedStories)) ?? [];\n const completedTitle = extractStoryTitle(activeStory.content, completed.length + 1);\n const storyAlreadyCompleted = completed.includes(completedTitle);\n const updatedCompleted = storyAlreadyCompleted ? completed : [...completed, completedTitle];\n\n const persistedActiveStory = await state.get<Document | null>(STORY_STATE_KEYS.activeStory);\n const storyQueue = (await state.get<Document[]>(STORY_STATE_KEYS.storyQueue)) ?? [];\n const storyContextQueue =\n (await state.get<(string | StoryPhaseContexts)[]>(STORY_STATE_KEYS.storyContextQueue)) ?? [];\n const queuedStories = storyQueue\n .map((story, index) => ({ story, context: storyContextQueue[index] ?? \"\" }))\n .filter(({ story }) => !documentsMatch(story, activeStory));\n\n const persistedStoryAlreadyAdvanced =\n persistedActiveStory && !documentsMatch(persistedActiveStory, activeStory);\n const persistedQueuedIndex = persistedStoryAlreadyAdvanced\n ? queuedStories.findIndex(({ story }) => documentsMatch(story, persistedActiveStory))\n : -1;\n const activeStoryContext =\n persistedStoryAlreadyAdvanced && persistedQueuedIndex < 0\n ? ((await state.get<string | StoryPhaseContexts | null>(\n STORY_STATE_KEYS.activeStoryContext,\n )) ?? \"\")\n : undefined;\n const nextStory = persistedStoryAlreadyAdvanced ? persistedActiveStory : queuedStories[0]?.story;\n const nextStoryContext = persistedStoryAlreadyAdvanced\n ? persistedQueuedIndex >= 0\n ? (queuedStories[persistedQueuedIndex]?.context ?? \"\")\n : activeStoryContext\n : (queuedStories[0]?.context ?? \"\");\n const remainingStoryEntries = persistedStoryAlreadyAdvanced\n ? queuedStories.filter(({ story }) => !documentsMatch(story, persistedActiveStory))\n : queuedStories.slice(1);\n\n if (!nextStory) {\n await state.set(STORY_STATE_KEYS.completedStories, updatedCompleted);\n await state.set(STORY_STATE_KEYS.activeStory, null);\n await state.set(STORY_STATE_KEYS.activeStoryContext, null);\n await state.set(STORY_STATE_KEYS.storyContextQueue, []);\n await resetActiveStoryStartCommit();\n const featureDoc = await state.get<Document>(\"featureDoc\");\n const implementationDoc = await state.get<Document>(\"implementationDoc\");\n const output: TakeItAwayOutput = {\n status: \"implemented\",\n featureDocPath: featureDoc?.path ?? \"\",\n implementationDocPath: implementationDoc?.path ?? \"\",\n storyCount: updatedCompleted.length,\n completedStories: updatedCompleted,\n summary: `Implemented and reviewed ${updatedCompleted.length} ${updatedCompleted.length === 1 ? \"story\" : \"stories\"}.`,\n };\n return openPullRequestStep(output);\n }\n\n if (!state.isReplayingCompletedStep && !(await storyAutoCommitEnabled())) {\n const cleanBoundary = await verifyCleanBoundaryBeforeNextStory(activeStory);\n if (!cleanBoundary.ok) {\n return fail({\n code: cleanBoundary.code,\n message: cleanBoundary.message,\n details: cleanBoundary.details,\n });\n }\n }\n\n await resetStoryLocalStateForNextStory();\n await state.set(STORY_STATE_KEYS.completedStories, updatedCompleted);\n await state.set(\n STORY_STATE_KEYS.storyQueue,\n remainingStoryEntries.map(({ story }) => story),\n );\n await state.set(\n STORY_STATE_KEYS.storyContextQueue,\n remainingStoryEntries.map(({ context }) => context),\n );\n await state.set(STORY_STATE_KEYS.activeStory, nextStory);\n await state.set(STORY_STATE_KEYS.activeStoryContext, nextStoryContext);\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({ reason: \"story-completed\", currentStory: nextStory });\n}\n\nfunction documentsMatch(left: Document, right: Document): boolean {\n return left.path === right.path && left.content === right.content;\n}\n\nasync function appendWorkflowWarning(warning: string): Promise<void> {\n const warnings = (await state.get<string[] | null>(STORY_STATE_KEYS.workflowWarnings)) ?? [];\n await state.set(STORY_STATE_KEYS.workflowWarnings, [...warnings, warning]);\n}\n\nasync function verifyCleanBoundaryBeforeNextStory(activeStory: Document): Promise<\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code: string;\n readonly message: string;\n readonly details: Record<string, unknown>;\n }\n> {\n const cwd = state.cwd;\n if (!cwd) {\n return {\n ok: false,\n code: \"story_boundary_missing_cwd\",\n message:\n \"Cannot advance to the next story because the workflow cwd is unavailable. Commit or restore a clean story boundary from a valid checkout, then retry.\",\n details: { storyPath: activeStory.path },\n };\n }\n\n const status = await runGit([\"status\", \"--short\"], cwd);\n if (!status.ok) {\n return {\n ok: false,\n code: \"story_boundary_status_failed\",\n message:\n \"Cannot advance to the next story because TrailStep could not inspect `git status --short`. Fix git status inspection, commit or restore a clean story boundary, then retry.\",\n details: { storyPath: activeStory.path, cwd, gitError: status.error },\n };\n }\n\n if (status.stdout.trim().length > 0) {\n return {\n ok: false,\n code: \"story_boundary_dirty_without_auto_commit\",\n message:\n \"Cannot advance to the next story because auto-commit is disabled and the reviewed story left uncommitted changes. Commit, stash, or otherwise restore a clean story boundary, then retry the workflow.\",\n details: { storyPath: activeStory.path, cwd, statusShort: status.stdout },\n };\n }\n\n return { ok: true };\n}\n\nfunction truncateCommitSubject(subject: string): string {\n return subject.length <= 72 ? subject : `${subject.slice(0, 69)}...`;\n}\n\nfunction commitBody(\n activeStory: Document,\n implementationSummary: string | undefined,\n stagedFiles: string,\n): string {\n return [\n \"Committed automatically by TrailStep after a passing story review.\",\n \"\",\n `Story artifact: ${activeStory.path}`,\n \"\",\n \"Implementer summary:\",\n implementationSummary?.trim() || \"Not provided.\",\n \"\",\n \"Staged files:\",\n stagedFiles\n .split(\"\\n\")\n .filter((file) => file.length > 0)\n .map((file) => `- ${file}`)\n .join(\"\\n\"),\n ].join(\"\\n\");\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport type { Document } from \"@trailstep/authoring\";\nimport { done, state, step } from \"@trailstep/authoring\";\nimport type { ContinuationResult } from \"@trailstep/core\";\nimport { runGit } from \"../commit-reviewed-story/run-git.js\";\nimport {\n defaultTakeItAwayWorkflowOptions,\n type TakeItAwayWorkflowOptions,\n} from \"../shared/input-schema.js\";\nimport type { TakeItAwayOutput, TakeItAwayPullRequestOutput } from \"../shared/output-schema.js\";\nimport { STORY_STATE_KEYS } from \"../shared/story-state.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport const openPullRequestStep = step({ id: \"open-pull-request\" }).do(\n async (output: TakeItAwayOutput): Promise<ContinuationResult> => {\n const pullRequest = await openPullRequest(output);\n const warnings = await loadWorkflowWarnings();\n const pullRequestWarning = pullRequest.warning;\n const finalWarnings =\n pullRequestWarning === undefined ? warnings : [...warnings, pullRequestWarning];\n\n return done({\n ...output,\n ...(finalWarnings.length === 0 ? {} : { warnings: finalWarnings }),\n pullRequest,\n });\n },\n);\n\nasync function openPullRequest(output: TakeItAwayOutput): Promise<TakeItAwayPullRequestOutput> {\n const options = await loadWorkflowOptions();\n const prOptions = options.pullRequest;\n if (!prOptions.enabled) {\n return { status: \"disabled\" };\n }\n\n const cwd = state.cwd;\n if (!cwd) {\n return skipped(\"Workflow cwd is unavailable, so TrailStep could not safely create a PR.\", {\n branch: \"<branch>\",\n base: prOptions.base,\n remote: prOptions.remote,\n });\n }\n\n const insideWorkTree = await runGit([\"rev-parse\", \"--is-inside-work-tree\"], cwd);\n if (!insideWorkTree.ok || insideWorkTree.stdout !== \"true\") {\n return skipped(\n \"The workflow cwd is not a git worktree, so TrailStep could not safely create a PR.\",\n { branch: \"<branch>\", base: prOptions.base, remote: prOptions.remote },\n );\n }\n\n const branch = await currentBranch(cwd);\n if (!branch.ok) {\n return skipped(branch.warning, {\n branch: \"<branch>\",\n base: prOptions.base,\n remote: prOptions.remote,\n });\n }\n\n const status = await runGit([\"status\", \"--short\"], cwd);\n if (!status.ok) {\n return skipped(\n `TrailStep could not inspect \\`git status --short\\`, so it did not create a PR: ${status.error}`,\n { branch: branch.name, base: prOptions.base, remote: prOptions.remote },\n );\n }\n\n if (status.stdout.trim().length > 0) {\n return skipped(\n \"The working tree is dirty, so TrailStep did not create a PR. Review and commit the remaining changes, then run the suggested commands.\",\n { branch: branch.name, base: prOptions.base, remote: prOptions.remote },\n );\n }\n\n const remote = await runGit([\"remote\", \"get-url\", prOptions.remote], cwd);\n if (!remote.ok) {\n return skipped(\n `Git remote \\`${prOptions.remote}\\` is not configured, so TrailStep could not push and create a PR: ${remote.error}`,\n { branch: branch.name, base: prOptions.base, remote: prOptions.remote },\n );\n }\n\n const existing = await existingPullRequest(cwd, branch.name);\n if (existing.ok && existing.url) {\n return { status: \"existing\", url: existing.url };\n }\n\n const push = await runGit([\"push\", \"--set-upstream\", prOptions.remote, branch.name], cwd);\n if (!push.ok) {\n return skipped(`TrailStep could not push \\`${branch.name}\\`: ${push.error}`, {\n branch: branch.name,\n base: prOptions.base,\n remote: prOptions.remote,\n });\n }\n\n const title = prOptions.title ?? (await defaultPullRequestTitle(output));\n const body = prOptions.body ?? defaultPullRequestBody(output);\n const createArgs = [\n \"pr\",\n \"create\",\n \"--base\",\n prOptions.base,\n \"--head\",\n branch.name,\n \"--title\",\n title,\n \"--body\",\n body,\n ];\n if (prOptions.draft) {\n createArgs.push(\"--draft\");\n }\n\n const created = await runGh(createArgs, cwd);\n if (!created.ok) {\n return skipped(\n `TrailStep pushed \\`${branch.name}\\` but could not create a PR: ${created.error}`,\n {\n branch: branch.name,\n base: prOptions.base,\n remote: prOptions.remote,\n },\n );\n }\n\n return { status: \"created\", url: extractUrl(created.stdout) };\n}\n\nasync function loadWorkflowOptions(): Promise<TakeItAwayWorkflowOptions> {\n return (\n (await state.get<TakeItAwayWorkflowOptions | null>(STORY_STATE_KEYS.workflowOptions)) ??\n defaultTakeItAwayWorkflowOptions()\n );\n}\n\nasync function loadWorkflowWarnings(): Promise<string[]> {\n return (await state.get<string[] | null>(STORY_STATE_KEYS.workflowWarnings)) ?? [];\n}\n\nasync function currentBranch(\n cwd: string,\n): Promise<\n { readonly ok: true; readonly name: string } | { readonly ok: false; readonly warning: string }\n> {\n const branch = await runGit([\"branch\", \"--show-current\"], cwd);\n if (!branch.ok || branch.stdout.trim().length === 0) {\n return {\n ok: false,\n warning: branch.ok\n ? \"Git is in a detached HEAD state, so TrailStep could not safely create a PR.\"\n : `TrailStep could not determine the current branch: ${branch.error}`,\n };\n }\n return { ok: true, name: branch.stdout.trim() };\n}\n\nasync function existingPullRequest(\n cwd: string,\n branch: string,\n): Promise<{ readonly ok: true; readonly url?: string } | { readonly ok: false }> {\n const result = await runGh(\n [\"pr\", \"list\", \"--head\", branch, \"--state\", \"open\", \"--json\", \"url\", \"--jq\", '.[0].url // \"\"'],\n cwd,\n );\n if (!result.ok) {\n return { ok: false };\n }\n\n const url = extractUrl(result.stdout);\n return url ? { ok: true, url } : { ok: true };\n}\n\nasync function defaultPullRequestTitle(output: TakeItAwayOutput): Promise<string> {\n const featureDoc = await state.get<Document | null>(\"featureDoc\");\n const featureTitle = extractHeading(featureDoc?.content ?? \"\");\n if (featureTitle) {\n return truncateTitle(featureTitle);\n }\n\n return truncateTitle(output.completedStories[0] ?? \"TrailStep implementation\");\n}\n\nfunction defaultPullRequestBody(output: TakeItAwayOutput): string {\n return [\n output.summary,\n \"\",\n \"## TrailStep artifacts\",\n `- Feature doc: ${output.featureDocPath}`,\n `- Implementation doc: ${output.implementationDocPath}`,\n \"\",\n \"## Completed stories\",\n ...output.completedStories.map((story) => `- ${story}`),\n ].join(\"\\n\");\n}\n\nfunction skipped(\n warning: string,\n options: { readonly branch: string; readonly base: string; readonly remote: string },\n): TakeItAwayPullRequestOutput {\n return {\n status: \"skipped\",\n warning,\n commands: suggestedCommands(options),\n };\n}\n\nfunction suggestedCommands({\n branch,\n base,\n remote,\n}: {\n readonly branch: string;\n readonly base: string;\n readonly remote: string;\n}): string[] {\n return [\n \"git status --short\",\n 'git add -A && git commit -m \"trailstep: finalize reviewed changes\"',\n `git push --set-upstream ${shellQuote(remote)} ${shellQuote(branch)}`,\n `gh pr create --fill --base ${shellQuote(base)} --head ${shellQuote(branch)}`,\n ];\n}\n\nasync function runGh(\n args: readonly string[],\n cwd: string,\n): Promise<\n { readonly ok: true; readonly stdout: string } | { readonly ok: false; readonly error: string }\n> {\n try {\n const { stdout } = await execFileAsync(\"gh\", [...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 10,\n });\n return { ok: true, stdout: stdout.trimEnd() };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, error: message };\n }\n}\n\nfunction extractHeading(content: string): string | undefined {\n return /^#{1,6}\\s+(.+)$/m.exec(content)?.[1]?.trim();\n}\n\nfunction truncateTitle(title: string): string {\n return title.length <= 72 ? title : `${title.slice(0, 69)}...`;\n}\n\nfunction extractUrl(stdout: string): string | undefined {\n return /https?:\\/\\/\\S+/u.exec(stdout)?.[0];\n}\n\nfunction shellQuote(value: string): string {\n if (/^[A-Za-z0-9_./:@-]+$/u.test(value)) {\n return value;\n }\n\n return `'${value.replace(/'/g, `'\"'\"'`)}'`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\n\nexport interface TakeItAwayPullRequestInput extends Record<string, unknown> {\n readonly enabled?: boolean;\n readonly base?: string;\n readonly remote?: string;\n readonly draft?: boolean;\n readonly title?: string;\n readonly body?: string;\n}\n\nexport interface TakeItAwayPlanningCheckpointInput extends Record<string, unknown> {\n readonly enabled?: boolean;\n}\n\nexport interface TakeItAwayInput extends Record<string, unknown> {\n readonly conversation: string;\n readonly autoCommit?: boolean;\n readonly pullRequest?: TakeItAwayPullRequestInput;\n readonly planningCheckpoint?: TakeItAwayPlanningCheckpointInput;\n}\n\nexport interface TakeItAwayPullRequestOptions extends Record<string, unknown> {\n readonly enabled: boolean;\n readonly base: string;\n readonly remote: string;\n readonly draft: boolean;\n readonly title?: string;\n readonly body?: string;\n}\n\nexport interface TakeItAwayPlanningCheckpointOptions extends Record<string, unknown> {\n readonly enabled: boolean;\n}\n\nexport interface TakeItAwayWorkflowOptions extends Record<string, unknown> {\n readonly autoCommit: boolean;\n readonly pullRequest: TakeItAwayPullRequestOptions;\n readonly planningCheckpoint: TakeItAwayPlanningCheckpointOptions;\n}\n\nexport const takeItAwayInput = jsonSchema<TakeItAwayInput>({\n type: \"object\",\n properties: {\n conversation: { type: \"string\" },\n autoCommit: { type: \"boolean\" },\n pullRequest: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n base: { type: \"string\" },\n remote: { type: \"string\" },\n draft: { type: \"boolean\" },\n title: { type: \"string\" },\n body: { type: \"string\" },\n },\n additionalProperties: false,\n },\n planningCheckpoint: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n required: [\"conversation\"],\n additionalProperties: false,\n});\n\nexport function defaultTakeItAwayWorkflowOptions(): TakeItAwayWorkflowOptions {\n return {\n autoCommit: true,\n pullRequest: {\n enabled: true,\n base: \"main\",\n remote: \"origin\",\n draft: false,\n },\n planningCheckpoint: {\n enabled: false,\n },\n };\n}\n\nexport function normalizeTakeItAwayWorkflowOptions(\n input: TakeItAwayInput,\n): TakeItAwayWorkflowOptions {\n const defaults = defaultTakeItAwayWorkflowOptions();\n const title = nonEmptyOptional(input.pullRequest?.title);\n const body = nonEmptyOptional(input.pullRequest?.body);\n return {\n autoCommit: input.autoCommit ?? defaults.autoCommit,\n pullRequest: {\n enabled: input.pullRequest?.enabled ?? defaults.pullRequest.enabled,\n base: nonEmptyOrDefault(input.pullRequest?.base, defaults.pullRequest.base),\n remote: nonEmptyOrDefault(input.pullRequest?.remote, defaults.pullRequest.remote),\n draft: input.pullRequest?.draft ?? defaults.pullRequest.draft,\n ...(title === undefined ? {} : { title }),\n ...(body === undefined ? {} : { body }),\n },\n planningCheckpoint: {\n enabled: input.planningCheckpoint?.enabled ?? defaults.planningCheckpoint.enabled,\n },\n };\n}\n\nfunction nonEmptyOrDefault(value: string | undefined, fallback: string): string {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : fallback;\n}\n\nfunction nonEmptyOptional(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\n\nexport type TakeItAwayPullRequestStatus = \"created\" | \"existing\" | \"skipped\" | \"disabled\";\n\nexport interface TakeItAwayPullRequestOutput extends Record<string, unknown> {\n readonly status: TakeItAwayPullRequestStatus;\n readonly url?: string;\n readonly warning?: string;\n readonly commands?: readonly string[];\n}\n\nexport interface TakeItAwayOutput extends Record<string, unknown> {\n readonly status: \"implemented\";\n readonly featureDocPath: string;\n readonly implementationDocPath: string;\n readonly storyCount: number;\n readonly completedStories: readonly string[];\n readonly summary: string;\n readonly warnings?: readonly string[];\n readonly pullRequest?: TakeItAwayPullRequestOutput;\n}\n\nexport const takeItAwayOutput = jsonSchema<TakeItAwayOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", const: \"implemented\" },\n featureDocPath: { type: \"string\" },\n implementationDocPath: { type: \"string\" },\n storyCount: { type: \"number\" },\n completedStories: { type: \"array\", items: { type: \"string\" } },\n summary: { type: \"string\" },\n warnings: { type: \"array\", items: { type: \"string\" } },\n pullRequest: {\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"created\", \"existing\", \"skipped\", \"disabled\"] },\n url: { type: \"string\" },\n warning: { type: \"string\" },\n commands: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"status\"],\n additionalProperties: false,\n },\n },\n required: [\n \"status\",\n \"featureDocPath\",\n \"implementationDocPath\",\n \"storyCount\",\n \"completedStories\",\n \"summary\",\n ],\n additionalProperties: false,\n});\n\nexport function extractStoryTitle(storyContent: string, fallbackIndex: number): string {\n const heading = /^#{1,6}\\s+(.+)$/m.exec(storyContent);\n return heading?.[1]?.trim() || `Story ${fallbackIndex}`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\n\nimport { REVIEW_PASS_THRESHOLD } from \"./constants.js\";\n\nexport interface MethodologyRatings extends Record<string, unknown> {\n readonly tdd: number;\n readonly verticalSlicing: number;\n readonly tracerBullet: number;\n readonly dependencies: number;\n readonly architecture: number;\n}\n\nexport interface ReviewResult extends Record<string, unknown> {\n readonly score: number;\n readonly summary: string;\n readonly methodologyRatings: MethodologyRatings;\n readonly requiredImprovements: readonly string[];\n}\n\nconst RATING_SCHEMA = { type: \"integer\", minimum: 1, maximum: 5 } as const;\n\nexport const reviewOutput = jsonSchema<ReviewResult>({\n type: \"object\",\n properties: {\n score: RATING_SCHEMA,\n summary: { type: \"string\" },\n methodologyRatings: {\n type: \"object\",\n properties: {\n tdd: RATING_SCHEMA,\n verticalSlicing: RATING_SCHEMA,\n tracerBullet: RATING_SCHEMA,\n dependencies: RATING_SCHEMA,\n architecture: RATING_SCHEMA,\n },\n required: [\"tdd\", \"verticalSlicing\", \"tracerBullet\", \"dependencies\", \"architecture\"],\n additionalProperties: false,\n },\n requiredImprovements: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"score\", \"summary\", \"methodologyRatings\", \"requiredImprovements\"],\n additionalProperties: false,\n});\n\nexport function reviewPasses(review: ReviewResult): boolean {\n return review.score >= REVIEW_PASS_THRESHOLD;\n}\n","export const STORY_BOUNDARY = \"<!-- trailstep-story-boundary -->\";\n\nexport const STORY_CONTEXT_START = \"<context>\";\n\nexport const STORY_CONTEXT_END = \"</context>\";\n\nexport const REVIEW_PASS_THRESHOLD = 4;\n\nexport const MAX_IMPLEMENTATION_DOC_REVIEW_ATTEMPTS = 5;\n\nexport const MAX_STORY_REVIEW_ATTEMPTS = 3;\n\nexport const MAX_STORY_VALIDATION_ATTEMPTS = 3;\n\nexport const STORY_DOCTOR_VALIDATION_FAILURE_THRESHOLD = 2;\n","import type { Document } from \"@trailstep/authoring\";\nimport { promptSections, section } from \"@trailstep/authoring\";\nimport type { StoryReviewGitContext } from \"../shared/story-state.js\";\nimport { storyViewForReviewer } from \"../shared/story-view.js\";\n\nconst REVIEW_RUBRIC = [\n \"Score 4-5 only when the active story is complete, well-tested, scoped, and integrated with local conventions.\",\n \"Score below 4 for missing acceptance criteria, weak/missing behavioral-red evidence, unsafe diff isolation, broken validation, broad unrelated changes, or poor integration.\",\n \"Scores below 4 must include specific requiredImprovements for the next retry.\",\n].join(\"\\n\");\n\nexport interface ReviewStoryImplementationInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly attempt: number;\n readonly implementationContext?: string;\n readonly explorationSummary?: string;\n readonly redTestSummary?: string;\n readonly redEvidence?: string;\n readonly implementationSummary?: string;\n readonly validationSummary?: string;\n readonly validationCommands?: readonly { readonly command: string; readonly result: string }[];\n readonly gitContext: StoryReviewGitContext;\n}\n\nexport function reviewStoryImplementationPrompt({\n input,\n}: {\n readonly input: ReviewStoryImplementationInput;\n}): string {\n const baseline = input.gitContext.storyStartCommit ?? \"MISSING\";\n const committedDiffCommand = input.gitContext.storyStartCommit\n ? `git diff ${input.gitContext.storyStartCommit}..HEAD`\n : \"git diff <missing-story-start-commit>..HEAD\";\n\n return promptSections(\n section(\n \"Role\",\n \"You are the story reviewer: inspect only the isolated active-story change set. This is a read-only review; do not edit, do not stage, do not commit, do not clean, and do not run tests.\",\n ),\n section(\"Review rubric\", REVIEW_RUBRIC),\n section(\"Story review view\", storyViewForReviewer(input.currentStory.content)),\n section(\"Implementation context\", input.implementationContext),\n section(\"Exploration summary\", input.explorationSummary ?? \"Not provided.\"),\n section(\"Red-test summary\", input.redTestSummary ?? \"Not provided.\"),\n section(\"Red-test evidence\", input.redEvidence ?? \"Not provided.\"),\n section(\"Implementer summary\", input.implementationSummary ?? \"Not provided.\"),\n section(\"Validation summary\", input.validationSummary ?? \"Not provided.\"),\n section(\"Validation commands/results\", formatCommandResults(input.validationCommands ?? [])),\n section(\n \"Story review git metadata\",\n [\n `Recorded story start commit: ${baseline}`,\n \"\",\n \"Changed files:\",\n formatList(input.gitContext.changedFiles),\n \"\",\n \"Committed changed files:\",\n formatList(input.gitContext.committedChangedFiles),\n \"\",\n \"Uncommitted changed files:\",\n formatList(input.gitContext.uncommittedChangedFiles),\n \"\",\n \"Committed diffstat (`git diff --stat <storyStartCommit>..HEAD`):\",\n input.gitContext.committedDiffStat || \"Not available.\",\n \"\",\n \"Uncommitted diffstat (`git diff --stat`):\",\n input.gitContext.uncommittedDiffStat || \"Not available.\",\n \"\",\n \"Working tree status (`git status --short`):\",\n input.gitContext.statusShort || \"Not available.\",\n input.gitContext.warnings.length > 0\n ? [\n \"\",\n \"Warnings / blocked context:\",\n ...input.gitContext.warnings.map((warning) => `- ${warning}`),\n ].join(\"\\n\")\n : \"\",\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\"),\n ),\n section(\n \"Read-only local inspection commands\",\n [\n \"Run only read-only inspection commands if local verification is needed; inspect only, and do not edit, do not stage, do not commit, do not clean, and do not run tests:\",\n \"- `git status --short`\",\n `- \\`${committedDiffCommand}\\``,\n \"- `git diff`\",\n \"Use the captured validation commands/results above; do not run tests yourself.\",\n ].join(\"\\n\"),\n ),\n section(\n \"Task\",\n \"Review only the active story slice represented by the recorded story start commit through HEAD, plus the current uncommitted working tree changes, against the story above and the phase summaries. Use the metadata above first; if you need to inspect locally, use read-only commands only (`git status --short`, the listed committed `git diff <storyStartCommit>..HEAD`, and `git diff`) — do not run tests, do not edit code, do not stage files, do not commit files, do not revert files, do not clean files, and do not try to isolate the diff by changing the repository. If unrelated dirty files, a missing/invalid baseline, or ambiguous context prevents a trustworthy review, say so in the structured review and require the implementer/workflow to fix the isolation; never remove changes yourself. Respond only with the structured review.\",\n ),\n );\n}\n\nfunction formatList(items: readonly string[]): string {\n if (items.length === 0) {\n return \"- None\";\n }\n\n return items.map((item) => `- ${item}`).join(\"\\n\");\n}\n\nfunction formatCommandResults(\n commands: readonly { readonly command: string; readonly result: string }[],\n): string {\n if (commands.length === 0) {\n return \"- Not provided.\";\n }\n\n return commands.map((item) => `- \\`${item.command}\\`: ${item.result}`).join(\"\\n\");\n}\n","const STORY_SECTION_TITLES = [\n \"Dependencies\",\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n \"Red Phase\",\n \"Green Phase\",\n \"Refactor Phase\",\n \"Validation Commands\",\n \"Notes for Implementer\",\n] as const;\n\ntype StorySectionTitle = (typeof STORY_SECTION_TITLES)[number];\n\nconst KNOWN_SECTION_TITLES = new Set<string>(STORY_SECTION_TITLES.map(normalizeHeading));\n\nexport function storyViewForExplorer(storyContent: string): string {\n return storyView(storyContent, [\n \"Dependencies\",\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n ]);\n}\n\nexport function storyViewForTestWriter(storyContent: string): string {\n return storyView(storyContent, [\n \"Dependencies\",\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n \"Red Phase\",\n \"Validation Commands\",\n ]);\n}\n\nexport function storyViewForImplementer(storyContent: string): string {\n return storyView(storyContent, [\n \"Dependencies\",\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n \"Green Phase\",\n \"Refactor Phase\",\n \"Notes for Implementer\",\n ]);\n}\n\nexport function storyViewForValidator(storyContent: string): string {\n return storyView(storyContent, [\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n \"Validation Commands\",\n ]);\n}\n\nexport function storyViewForReviewer(storyContent: string): string {\n return storyView(storyContent, [\n \"Dependencies\",\n \"Goal\",\n \"User-Visible / Integration-Visible Slice\",\n \"Acceptance Criteria\",\n \"Red Phase\",\n \"Green Phase\",\n \"Refactor Phase\",\n \"Validation Commands\",\n \"Notes for Implementer\",\n ]);\n}\n\nfunction storyView(storyContent: string, visibleSections: readonly StorySectionTitle[]): string {\n const parsed = parseStorySections(storyContent);\n const selected = visibleSections.flatMap((title) => {\n const section = parsed.sections.get(normalizeHeading(title));\n return section ? [section] : [];\n });\n\n return [parsed.preamble, ...selected]\n .map((part) => part.trim())\n .filter((part) => part.length > 0)\n .join(\"\\n\\n\");\n}\n\nfunction parseStorySections(storyContent: string): {\n readonly preamble: string;\n readonly sections: ReadonlyMap<string, string>;\n} {\n const normalized = storyContent.replace(/\\r\\n?/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const sections = new Map<string, string>();\n const preambleLines: string[] = [];\n let activeSectionTitle: string | undefined;\n let activeSectionLines: string[] = [];\n\n for (const line of lines) {\n const heading = parseKnownSectionHeading(line);\n if (heading) {\n flushActiveSection();\n activeSectionTitle = heading.normalizedTitle;\n activeSectionLines = [line];\n continue;\n }\n\n if (activeSectionTitle) {\n activeSectionLines.push(line);\n } else {\n preambleLines.push(line);\n }\n }\n\n flushActiveSection();\n\n return {\n preamble: preambleLines.join(\"\\n\"),\n sections,\n };\n\n function flushActiveSection(): void {\n if (!activeSectionTitle) {\n return;\n }\n sections.set(activeSectionTitle, activeSectionLines.join(\"\\n\"));\n activeSectionTitle = undefined;\n activeSectionLines = [];\n }\n}\n\nfunction parseKnownSectionHeading(line: string): { readonly normalizedTitle: string } | undefined {\n const match = /^(#{2,6})\\s+(.+?)\\s*$/u.exec(line.trim());\n if (!match) {\n return undefined;\n }\n\n const normalizedTitle = normalizeHeading(match[2] ?? \"\");\n return KNOWN_SECTION_TITLES.has(normalizedTitle) ? { normalizedTitle } : undefined;\n}\n\nfunction normalizeHeading(value: string): string {\n return value.trim().replace(/\\s+/g, \" \").toLowerCase();\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { ValidateStoryInput, ValidateStoryOutput, ValidationCommandResult } from \"./prompt.js\";\n\nconst execFileAsync = promisify(execFile);\nconst MAX_COMMANDS = 5;\nconst COMMAND_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT = 4_000;\nconst MAX_BUFFER = 256 * 1024;\n\nconst ALLOWED_COMMANDS = new Set([\"pnpm\", \"npm\", \"node\", \"git\", \"./trailstep-dev.sh\"]);\nconst BROAD_PACKAGE_MANAGER_SCRIPTS = new Set([\"test\", \"typecheck\", \"lint\", \"build\"]);\nconst SHELL_META_CHARS = new Set([\"|\", \"&\", \";\", \"<\", \">\", \"(\", \")\"]);\n\nexport async function runFocusedStoryValidation(input: {\n readonly validationInput: ValidateStoryInput;\n readonly cwd?: string;\n readonly implementationContext?: string;\n}): Promise<ValidateStoryOutput> {\n const commands = collectValidationCommands(input.validationInput, input.implementationContext);\n if (commands.length === 0) {\n return {\n blocked: true,\n blockedReason:\n \"No focused validation commands were found in the story or exploration context.\",\n summary: \"Validation blocked: no focused validation commands were found.\",\n commands: [],\n validationPassed: false,\n };\n }\n\n const results: ValidationCommandResult[] = [];\n for (const command of commands.slice(0, MAX_COMMANDS)) {\n results.push(await runValidationCommand(command, input.cwd));\n }\n\n const skipped = results.filter((result) => isSkippedResult(result.result));\n const failed = results.filter((result) => isFailedResult(result.result));\n const passed = results.filter((result) => isPassedResult(result.result));\n const validationPassed = failed.length === 0 && passed.length > 0;\n const blocked = passed.length === 0 && skipped.length === results.length;\n\n return {\n blocked,\n blockedReason: blocked\n ? \"All focused validation commands were rejected or skipped.\"\n : undefined,\n summary: summarizeValidationResults({ passed, failed, skipped, total: results.length }),\n commands: results,\n validationPassed,\n };\n}\n\nexport function collectValidationCommands(\n input: ValidateStoryInput,\n implementationContext?: string,\n): readonly string[] {\n return uniqueCommands([\n ...extractValidationCommandLines(input.currentStory.content),\n ...extractValidationCommandLines(implementationContext ?? \"\"),\n ...(input.explorationBrief?.recommendedValidationCommands ?? []),\n ]);\n}\n\nasync function runValidationCommand(\n command: string,\n cwd?: string,\n): Promise<ValidationCommandResult> {\n const parsed = parseCommand(command);\n if (parsed.ok === false) {\n return { command, result: `skipped: ${parsed.reason}` };\n }\n\n const allowed = validateAllowedCommand(parsed.argv);\n if (allowed.ok === false) {\n return { command, result: `skipped: ${allowed.reason}` };\n }\n\n if (!cwd) {\n return { command, result: \"skipped: workflow cwd is unavailable\" };\n }\n\n try {\n const executable = executableForPlatform(parsed.argv[0] ?? \"\");\n const { stdout, stderr } = await execFileAsync(executable, parsed.argv.slice(1), {\n cwd,\n timeout: COMMAND_TIMEOUT_MS,\n maxBuffer: MAX_BUFFER,\n shell: requiresWindowsCommandShell(executable),\n windowsHide: true,\n });\n const output = formatCommandOutput(stdout, stderr);\n return { command, result: `passed${output ? `: ${output}` : \"\"}` };\n } catch (error) {\n return { command, result: `failed: ${formatExecutionError(error)}` };\n }\n}\n\nfunction executableForPlatform(executable: string): string {\n if (process.platform !== \"win32\") {\n return executable;\n }\n if (executable === \"pnpm\" || executable === \"npm\") {\n return `${executable}.cmd`;\n }\n return executable;\n}\n\nfunction requiresWindowsCommandShell(executable: string): boolean {\n return process.platform === \"win32\" && executable.toLowerCase().endsWith(\".cmd\");\n}\n\nfunction extractValidationCommandLines(content: string): readonly string[] {\n const normalized = content.replace(/\\r\\n?/g, \"\\n\");\n const lines = normalized.split(\"\\n\");\n const commands: string[] = [];\n let inValidationSection = false;\n\n for (const line of lines) {\n if (/^#{2,6}\\s+Validation Commands\\s*$/iu.test(line.trim())) {\n inValidationSection = true;\n continue;\n }\n if (inValidationSection && /^#{2,6}\\s+/u.test(line.trim())) {\n break;\n }\n if (!inValidationSection) {\n continue;\n }\n\n const command = normalizeCommandLine(line);\n if (command) {\n commands.push(command);\n }\n }\n\n return commands;\n}\n\nfunction normalizeCommandLine(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed || trimmed === \"Not provided.\") {\n return null;\n }\n\n const withoutFence = trimmed.replace(/^```(?:sh|bash|shell)?\\s*/iu, \"\").replace(/```$/u, \"\");\n const listMatch = /^(?:[-*+]\\s+|\\d+[.)]\\s+)?(?:`([^`]+)`|(.+))$/u.exec(withoutFence.trim());\n const command = (listMatch?.[1] ?? listMatch?.[2] ?? withoutFence).trim();\n return command.length > 0 ? command : null;\n}\n\nfunction parseCommand(\n command: string,\n):\n | { readonly ok: true; readonly argv: readonly string[] }\n | { readonly ok: false; readonly reason: string } {\n const argv: string[] = [];\n let current = \"\";\n let quote: \"'\" | '\"' | null = null;\n\n for (let index = 0; index < command.length; index += 1) {\n const char = command[index] ?? \"\";\n if (!quote && SHELL_META_CHARS.has(char)) {\n return { ok: false, reason: `shell metacharacter '${char}' is not allowlisted` };\n }\n if (!quote && char === \"$\" && command[index + 1] === \"(\") {\n return { ok: false, reason: \"command substitution is not allowlisted\" };\n }\n if (char === \"`\") {\n return { ok: false, reason: \"backtick command substitution is not allowlisted\" };\n }\n if (quote) {\n if (char === quote) {\n quote = null;\n } else {\n current += char;\n }\n continue;\n }\n if (char === \"'\" || char === '\"') {\n quote = char;\n continue;\n }\n if (/\\s/u.test(char)) {\n if (current.length > 0) {\n argv.push(current);\n current = \"\";\n }\n continue;\n }\n current += char;\n }\n\n if (quote) {\n return { ok: false, reason: \"unterminated quoted argument\" };\n }\n if (current.length > 0) {\n argv.push(current);\n }\n if (argv.length === 0) {\n return { ok: false, reason: \"empty command\" };\n }\n return { ok: true, argv };\n}\n\nfunction validateAllowedCommand(\n argv: readonly string[],\n): { readonly ok: true } | { readonly ok: false; readonly reason: string } {\n const executable = argv[0] ?? \"\";\n if (!ALLOWED_COMMANDS.has(executable)) {\n return { ok: false, reason: `command '${executable}' is not allowlisted` };\n }\n\n if (executable === \"git\") {\n return validateGitCommand(argv);\n }\n\n if ((executable === \"pnpm\" || executable === \"npm\") && isBroadPackageManagerCommand(argv)) {\n return {\n ok: false,\n reason:\n \"broad package validation belongs to final validation; add --filter, a package path, or a specific test file for story validation\",\n };\n }\n\n return { ok: true };\n}\n\nfunction validateGitCommand(\n argv: readonly string[],\n): { readonly ok: true } | { readonly ok: false; readonly reason: string } {\n const subcommand = argv[1];\n if (subcommand === \"status\" || subcommand === \"diff\" || subcommand === \"rev-parse\") {\n return { ok: true };\n }\n return { ok: false, reason: `git subcommand '${subcommand ?? \"\"}' is not allowlisted` };\n}\n\nfunction isBroadPackageManagerCommand(argv: readonly string[]): boolean {\n const scriptIndex = firstPackageManagerScriptIndex(argv);\n if (scriptIndex < 0) {\n return false;\n }\n const script = argv[scriptIndex];\n if (!script || !BROAD_PACKAGE_MANAGER_SCRIPTS.has(script)) {\n return false;\n }\n const args = argv.slice(1);\n if (\n args.includes(\"--filter\") ||\n args.includes(\"-F\") ||\n args.some((arg) => arg.startsWith(\"--filter=\"))\n ) {\n return false;\n }\n const trailing = argv.slice(scriptIndex + 1);\n return !trailing.some(isFocusedValidationArgument);\n}\n\nfunction firstPackageManagerScriptIndex(argv: readonly string[]): number {\n const runIndex = argv.indexOf(\"run\");\n if (runIndex >= 0) {\n return runIndex + 1;\n }\n return argv.findIndex((arg, index) => index > 0 && BROAD_PACKAGE_MANAGER_SCRIPTS.has(arg));\n}\n\nfunction isFocusedValidationArgument(arg: string): boolean {\n return (\n arg.includes(\"/\") ||\n arg.includes(\"\\\\\") ||\n /\\.(?:test|spec)\\.[cm]?[tj]sx?$/u.test(arg) ||\n arg.endsWith(\".ts\") ||\n arg.endsWith(\".tsx\") ||\n arg.startsWith(\"--testNamePattern\") ||\n arg.startsWith(\"-t\")\n );\n}\n\nfunction uniqueCommands(commands: readonly string[]): readonly string[] {\n const seen = new Set<string>();\n const unique: string[] = [];\n for (const command of commands.map((item) => normalizeCommandLine(item) ?? \"\")) {\n if (command && !seen.has(command)) {\n seen.add(command);\n unique.push(command);\n }\n }\n return unique;\n}\n\nfunction formatCommandOutput(stdout: string, stderr: string): string {\n return truncate([stdout.trim(), stderr.trim()].filter(Boolean).join(\"\\n\"));\n}\n\nfunction formatExecutionError(error: unknown): string {\n if (typeof error !== \"object\" || error === null) {\n return truncate(String(error));\n }\n const maybeError = error as {\n readonly signal?: string;\n readonly code?: number | string;\n readonly stdout?: string;\n readonly stderr?: string;\n readonly message?: string;\n readonly killed?: boolean;\n };\n const prefix = maybeError.killed\n ? `timed out after ${COMMAND_TIMEOUT_MS}ms`\n : `exit ${maybeError.code ?? maybeError.signal ?? \"unknown\"}`;\n const output = formatCommandOutput(maybeError.stdout ?? \"\", maybeError.stderr ?? \"\");\n return truncate(\n output ? `${prefix}; ${output}` : `${prefix}; ${maybeError.message ?? \"command failed\"}`,\n );\n}\n\nfunction summarizeValidationResults(input: {\n readonly passed: readonly ValidationCommandResult[];\n readonly failed: readonly ValidationCommandResult[];\n readonly skipped: readonly ValidationCommandResult[];\n readonly total: number;\n}): string {\n if (input.failed.length > 0) {\n return `Focused validation failed: ${input.failed.length}/${input.total} command(s) failed, ${input.passed.length} passed, ${input.skipped.length} skipped.`;\n }\n if (input.passed.length > 0) {\n return `Focused validation passed: ${input.passed.length}/${input.total} command(s) passed, ${input.skipped.length} skipped.`;\n }\n return `Focused validation skipped: ${input.skipped.length}/${input.total} command(s) were rejected or skipped.`;\n}\n\nfunction isPassedResult(result: string): boolean {\n return result.startsWith(\"passed\");\n}\n\nfunction isFailedResult(result: string): boolean {\n return result.startsWith(\"failed\");\n}\n\nfunction isSkippedResult(result: string): boolean {\n return result.startsWith(\"skipped\");\n}\n\nfunction truncate(value: string): string {\n return value.length > OUTPUT_LIMIT ? `${value.slice(0, OUTPUT_LIMIT)}… [truncated]` : value;\n}\n","import { type Document, jsonSchema, promptSections, section } from \"@trailstep/authoring\";\nimport type { ExploreStoryOutput } from \"../explore-story/prompt.js\";\nimport { storyViewForImplementer } from \"../shared/story-view.js\";\nimport type { WriteRedTestsOutput } from \"../write-red-tests/prompt.js\";\n\nexport interface ImplementGreenValidationCommand extends Record<string, unknown> {\n readonly command: string;\n readonly result: string;\n}\n\nexport interface ImplementGreenInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly explorationBrief?: ExploreStoryOutput;\n readonly redTestSummary?: WriteRedTestsOutput;\n readonly attempt: number;\n readonly implementationContext?: string;\n readonly previousReviewSummary?: string;\n readonly requiredImprovements?: readonly string[];\n readonly failedValidationSummary?: string;\n readonly failedValidationCommands?: readonly ImplementGreenValidationCommand[];\n}\n\nexport interface ImplementGreenOutput extends Record<string, unknown> {\n readonly blocked: boolean;\n readonly blockedReason?: string;\n readonly summary: string;\n readonly changedFiles: readonly string[];\n}\n\nexport const implementGreenOutput = jsonSchema<ImplementGreenOutput>({\n type: \"object\",\n properties: {\n blocked: { type: \"boolean\" },\n blockedReason: { type: \"string\" },\n summary: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"blocked\", \"summary\", \"changedFiles\"],\n additionalProperties: false,\n});\n\nexport function implementGreenPrompt({ input }: { readonly input: ImplementGreenInput }): string {\n const validationCommandEvidence = (input.failedValidationCommands ?? [])\n .map(({ command, result }) => `- ${command}: ${result}`)\n .join(\"\\n\");\n\n return promptSections(\n section(\n \"Role\",\n \"You are the green implementer. Make the smallest production change that satisfies the focused red test; do not broaden scope.\",\n ),\n section(\n \"Active story implementation view\",\n storyViewForImplementer(input.currentStory.content),\n ),\n section(\"Implementation context\", input.implementationContext),\n section(\"Exploration summary\", input.explorationBrief?.summary ?? \"Not provided.\"),\n section(\"Red-test summary\", input.redTestSummary?.summary ?? \"Not provided.\"),\n section(\"Red evidence\", input.redTestSummary?.redEvidence ?? \"Not provided.\"),\n input.previousReviewSummary\n ? section(\n \"Previous review summary\",\n `${input.previousReviewSummary}\\n\\nRequired improvements:\\n${(input.requiredImprovements ?? []).map((item) => `- ${item}`).join(\"\\n\") || \"- None\"}`,\n )\n : \"\",\n input.failedValidationSummary\n ? section(\n \"Previous validation failure\",\n `${input.failedValidationSummary}\\n\\nCommand evidence:\\n${validationCommandEvidence || \"- Not provided.\"}`,\n )\n : \"\",\n section(\n \"Task\",\n [\n \"Implement the smallest production-code slice needed to make the focused behavioral red test pass.\",\n \"Preserve the red test and avoid broad refactoring until the focused behavior is green.\",\n \"Do not write new unrelated stories, broad polish, or accumulated-diff cleanup.\",\n \"Run the focused green test when feasible and summarize files changed plus concise evidence.\",\n \"When this prompt includes a previous validation failure, treat that failure as the primary task: fix the root cause and rerun the failing command when feasible before returning.\",\n \"Do not claim the story is complete if focused validation is still red; either keep fixing it or set `blocked: true` with a concrete reason.\",\n \"If implementation is unsafe or ambiguous, set `blocked: true` and explain why.\",\n ].join(\"\\n\"),\n ),\n );\n}\n","import { state, step } from \"@trailstep/authoring\";\nimport { incrementStoryPhaseAttempt, STORY_STATE_KEYS } from \"../shared/story-state.js\";\nimport { validateStoryStep } from \"../validate-story/step.js\";\nimport {\n type StoryDoctorInput,\n type StoryDoctorOutput,\n storyDoctorOutput,\n storyDoctorPrompt,\n} from \"./prompt.js\";\n\nexport const storyDoctorStep = step({ id: \"story-doctor\" })\n .prompt<StoryDoctorInput, StoryDoctorOutput>(storyDoctorPrompt, {\n agent: \"storyDoctor\",\n output: storyDoctorOutput,\n })\n .do(async (promptOutput, input) => {\n if (promptOutput.blocked) {\n await state.set(\n STORY_STATE_KEYS.blockedReason,\n promptOutput.blockedReason ?? \"Story doctor reported a blocked state.\",\n );\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({\n reason: {\n type: \"blocked\",\n sourceReason: \"failed-implementation\",\n blockedPhase: \"implement-green\",\n blockedReason: promptOutput.blockedReason ?? \"Story doctor reported a blocked state.\",\n code: \"story_doctor_blocked\",\n },\n currentStory: input.currentStory,\n });\n }\n\n await state.set(STORY_STATE_KEYS.latestImplementationSummary, promptOutput);\n await state.set(STORY_STATE_KEYS.latestStoryRouterState, null);\n await state.set(STORY_STATE_KEYS.activePhase, \"validate-story\");\n const attempt = await incrementStoryPhaseAttempt(\"validate-story\");\n return validateStoryStep({\n currentStory: input.currentStory,\n explorationBrief: input.explorationBrief,\n redTestSummary: input.redTestSummary,\n implementationSummary: promptOutput,\n attempt,\n });\n });\n","import { type Document, jsonSchema, promptSections, section } from \"@trailstep/authoring\";\nimport type { ExploreStoryOutput } from \"../explore-story/prompt.js\";\nimport type { ImplementGreenOutput } from \"../implement-green/prompt.js\";\nimport { storyViewForImplementer } from \"../shared/story-view.js\";\nimport type { WriteRedTestsOutput } from \"../write-red-tests/prompt.js\";\n\nexport interface StoryDoctorValidationCommand extends Record<string, unknown> {\n readonly command: string;\n readonly result: string;\n}\n\nexport interface StoryDoctorInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly explorationBrief?: ExploreStoryOutput;\n readonly redTestSummary?: WriteRedTestsOutput;\n readonly implementationSummary?: ImplementGreenOutput;\n readonly failedValidationSummary: string;\n readonly failedValidationCommands: readonly StoryDoctorValidationCommand[];\n readonly validationRetryCount: number;\n readonly retryLimit: number;\n}\n\nexport interface StoryDoctorOutput extends Record<string, unknown> {\n readonly blocked: boolean;\n readonly blockedReason?: string;\n readonly summary: string;\n readonly changedFiles: readonly string[];\n}\n\nexport const storyDoctorOutput = jsonSchema<StoryDoctorOutput>({\n type: \"object\",\n properties: {\n blocked: { type: \"boolean\" },\n blockedReason: { type: \"string\" },\n summary: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"blocked\", \"summary\", \"changedFiles\"],\n additionalProperties: false,\n});\n\nexport function storyDoctorPrompt({ input }: { readonly input: StoryDoctorInput }): string {\n const commandEvidence = input.failedValidationCommands\n .map(({ command, result }) => `- ${command}: ${result}`)\n .join(\"\\n\");\n\n return promptSections(\n section(\n \"Role\",\n \"You are the story doctor: a senior recovery agent invoked only after repeated validation failures. Diagnose the actual failing behavior, repair the active story implementation, and do not broaden scope.\",\n ),\n section(\n \"Active story implementation view\",\n storyViewForImplementer(input.currentStory.content),\n ),\n section(\"Exploration summary\", input.explorationBrief?.summary ?? \"Not provided.\"),\n section(\"Red-test summary\", input.redTestSummary?.summary ?? \"Not provided.\"),\n section(\"Red evidence\", input.redTestSummary?.redEvidence ?? \"Not provided.\"),\n section(\n \"Latest implementation summary\",\n input.implementationSummary?.summary ?? \"Not provided.\",\n ),\n section(\n \"Repeated validation failure\",\n [\n `Validation failure count consumed by the router: ${input.validationRetryCount}/${input.retryLimit}.`,\n input.failedValidationSummary,\n \"\",\n \"Command evidence:\",\n commandEvidence || \"- Not provided.\",\n ].join(\"\\n\"),\n ),\n section(\n \"Task\",\n [\n \"Find and fix the root cause of the repeated validation failure for this active story only.\",\n \"Run the focused failing validation command when feasible before returning.\",\n \"Do not claim success unless the focused validation is green or you clearly explain why it cannot be made green.\",\n \"If the story is unsafe, ambiguous, or cannot be repaired without unrelated redesign, set `blocked: true` with a concrete `blockedReason`.\",\n \"Return a concise summary, changed files, and no full logs or diff hunks.\",\n ].join(\"\\n\"),\n ),\n );\n}\n","import type { Document } from \"@trailstep/authoring\";\nimport { fail, state, step } from \"@trailstep/authoring\";\nimport type { ContinuationResult } from \"@trailstep/core\";\nimport { runGit } from \"../commit-reviewed-story/run-git.js\";\nimport { deterministicContextPreflightStep } from \"../deterministic-context-preflight/step.js\";\nimport {\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n STORY_STATE_KEYS,\n type StoryPreflightStatus,\n type StoryRouterState,\n} from \"../shared/story-state.js\";\n\nexport interface StoryIsolationPreflightInput extends Record<string, unknown> {\n readonly currentStory: Document;\n}\n\nexport const storyIsolationPreflightStep = step({ id: \"story-isolation-preflight\" }).do(\n async ({ currentStory }: StoryIsolationPreflightInput): Promise<ContinuationResult> => {\n const result = await runStoryIsolationPreflight(currentStory);\n if (!result.ok) {\n return result.failure;\n }\n\n const implementationContext = await loadStoryPhaseContext(\"deterministic-context-preflight\");\n return deterministicContextPreflightStep({ currentStory, implementationContext });\n },\n);\n\nexport async function runStoryIsolationPreflight(\n currentStory: Document,\n): Promise<StoryIsolationPreflightResult> {\n const completedReplay = await loadCompletedReplayPreflightState(currentStory);\n if (completedReplay) {\n await state.set(STORY_STATE_KEYS.activePhase, \"story-isolation-preflight\");\n await state.set(STORY_STATE_KEYS.storyBaseline, completedReplay.baseline);\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, { commit: completedReplay.baseline });\n await state.set(STORY_STATE_KEYS.latestPreflightStatus, {\n ok: true,\n code: \"story_preflight_replayed\",\n message: \"Completed story isolation preflight was replayed from durable state.\",\n baseline: completedReplay.baseline,\n } satisfies StoryPreflightStatus);\n return { ok: true, baseline: completedReplay.baseline };\n }\n\n await state.set(STORY_STATE_KEYS.activePhase, \"story-isolation-preflight\");\n await incrementStoryPhaseAttempt(\"story-isolation-preflight\");\n\n const blockedReplay = await loadBlockedReplayPreflightState(currentStory);\n if (blockedReplay) {\n await state.set(STORY_STATE_KEYS.storyBaseline, blockedReplay.baseline);\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, { commit: blockedReplay.baseline });\n await state.set(STORY_STATE_KEYS.latestPreflightStatus, {\n ok: true,\n code: \"story_preflight_passed\",\n message: \"Story isolation preflight passed.\",\n baseline: blockedReplay.baseline,\n } satisfies StoryPreflightStatus);\n return { ok: true, baseline: blockedReplay.baseline };\n }\n\n const cwd = state.cwd;\n if (!cwd) {\n return preflightFailure(\n \"story_preflight_missing_cwd\",\n \"Cannot start story implementation because the TrailStep workflow cwd is unavailable. Retry from a valid project checkout so TrailStep can record a git story baseline.\",\n { storyPath: currentStory.path },\n );\n }\n\n const insideWorkTree = await runGit([\"rev-parse\", \"--is-inside-work-tree\"], cwd);\n if (!insideWorkTree.ok || insideWorkTree.stdout !== \"true\") {\n return preflightFailure(\n \"story_preflight_not_git_worktree\",\n \"Cannot start story implementation because the workflow cwd is not a valid git worktree. Run take-it-away/grill-it-away from a git repository with a clean story boundary.\",\n {\n storyPath: currentStory.path,\n cwd,\n gitError: insideWorkTree.ok ? undefined : insideWorkTree.error,\n },\n );\n }\n\n const head = await runGit([\"rev-parse\", \"HEAD\"], cwd);\n if (!head.ok || head.stdout.length === 0) {\n return preflightFailure(\n \"story_preflight_missing_head\",\n \"Cannot start story implementation because `git rev-parse HEAD` did not produce a usable baseline commit. Create an initial commit or fix the git repository, then retry.\",\n {\n storyPath: currentStory.path,\n cwd,\n gitError: head.ok ? \"No commit was returned.\" : head.error,\n },\n );\n }\n\n const existingBaseline = await state.get<string | null>(STORY_STATE_KEYS.storyBaseline);\n const baseline = existingBaseline ?? head.stdout;\n const reachable = await runGit([\"cat-file\", \"-e\", `${baseline}^{commit}`], cwd);\n if (!reachable.ok) {\n return preflightFailure(\n \"story_preflight_unreachable_baseline\",\n `Cannot start story implementation because the recorded story baseline \\`${baseline}\\` is missing or unreachable. Fix the checkout or retry after restoring a valid story boundary.`,\n { storyPath: currentStory.path, cwd, baseline, gitError: reachable.error },\n );\n }\n\n const status = await runGit([\"status\", \"--short\"], cwd);\n if (!status.ok) {\n return preflightFailure(\n \"story_preflight_status_failed\",\n \"Cannot start story implementation because TrailStep could not inspect `git status --short`. Fix git status inspection and retry.\",\n { storyPath: currentStory.path, cwd, baseline, gitError: status.error },\n );\n }\n\n if (status.stdout.trim().length > 0) {\n return preflightFailure(\n \"story_preflight_dirty_worktree\",\n \"Cannot start story implementation because the working tree is dirty before the story begins. Commit, stash, or otherwise restore a clean story boundary, then retry.\",\n { storyPath: currentStory.path, cwd, baseline, statusShort: status.stdout },\n );\n }\n\n await state.set(STORY_STATE_KEYS.storyBaseline, baseline);\n await state.set(STORY_STATE_KEYS.activeStoryStartCommit, { commit: baseline });\n await state.set(STORY_STATE_KEYS.latestPreflightStatus, {\n ok: true,\n code: \"story_preflight_passed\",\n message: \"Story isolation preflight passed.\",\n baseline,\n } satisfies StoryPreflightStatus);\n\n return { ok: true, baseline };\n}\n\ntype StoryIsolationPreflightResult =\n | { readonly ok: true; readonly baseline: string }\n | { readonly ok: false; readonly failure: ContinuationResult };\n\nasync function loadCompletedReplayPreflightState(\n currentStory: Document,\n): Promise<{ readonly baseline: string } | null> {\n if (!state.isReplayingCompletedStep) {\n return null;\n }\n\n const activeStory = await state.getPersisted<Document | null>(STORY_STATE_KEYS.activeStory);\n const baseline = await loadPersistedRecordedBaseline();\n if (!activeStory || documentsMatch(activeStory, currentStory)) {\n return baseline ? { baseline } : { baseline: \"replayed-completed-step\" };\n }\n\n // Historical story preflights are replayed only to reconstruct the continuation graph.\n // They must not re-check today's worktree cleanliness, because later story work may\n // legitimately be dirty after the completed preflight originally succeeded.\n return { baseline: \"replayed-completed-step\" };\n}\n\nasync function loadBlockedReplayPreflightState(\n currentStory: Document,\n): Promise<{ readonly baseline: string } | null> {\n const routerState = await state.get<StoryRouterState | null>(\n STORY_STATE_KEYS.latestStoryRouterState,\n );\n if (\n routerState?.route !== \"blocked\" ||\n routerState.activeStory.path !== currentStory.path ||\n routerState.activeStory.content !== currentStory.content\n ) {\n return null;\n }\n\n const baseline = await loadRecordedBaseline();\n return baseline ? { baseline } : null;\n}\n\nasync function loadRecordedBaseline(): Promise<string | null> {\n return (\n (await state.get<string | null>(STORY_STATE_KEYS.storyBaseline)) ??\n (await state.get<{ readonly commit?: string } | null>(STORY_STATE_KEYS.activeStoryStartCommit))\n ?.commit ??\n null\n );\n}\n\nasync function loadPersistedRecordedBaseline(): Promise<string | null> {\n return (\n (await state.getPersisted<string | null>(STORY_STATE_KEYS.storyBaseline)) ??\n (\n await state.getPersisted<{ readonly commit?: string } | null>(\n STORY_STATE_KEYS.activeStoryStartCommit,\n )\n )?.commit ??\n null\n );\n}\n\nfunction documentsMatch(left: Document, right: Document): boolean {\n return left.path === right.path && left.content === right.content;\n}\n\nasync function preflightFailure(\n code: string,\n message: string,\n details: Record<string, unknown>,\n): Promise<StoryIsolationPreflightResult> {\n await state.set(STORY_STATE_KEYS.latestPreflightStatus, {\n ok: false,\n code,\n message,\n baseline: typeof details.baseline === \"string\" ? details.baseline : undefined,\n } satisfies StoryPreflightStatus);\n return { ok: false, failure: fail({ code, message, details }) };\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport { isAbsolute, join, relative } from \"node:path\";\n\nimport type { Document } from \"@trailstep/authoring\";\nimport { state, step } from \"@trailstep/authoring\";\nimport type { ContinuationResult } from \"@trailstep/core\";\nimport type { ExploreStoryOutput } from \"../explore-story/prompt.js\";\nimport {\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n STORY_STATE_KEYS,\n} from \"../shared/story-state.js\";\nimport { writeRedTestsStep } from \"../write-red-tests/step.js\";\n\nconst DEFAULT_VALIDATION_COMMANDS = [\"pnpm test\", \"pnpm typecheck\", \"pnpm lint\"] as const;\n\nconst MAX_ITEMS = 12;\n\nexport interface DeterministicContextPreflightInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly implementationContext?: string;\n}\n\nexport interface DeterministicContextPreflightBrief extends ExploreStoryOutput {\n readonly packageHints: readonly string[];\n readonly symbols: readonly string[];\n readonly searchHints: readonly string[];\n readonly focusedValidationHints: readonly string[];\n}\n\nexport const deterministicContextPreflightStep = step({ id: \"deterministic-context-preflight\" }).do(\n async ({\n currentStory,\n implementationContext,\n }: DeterministicContextPreflightInput): Promise<ContinuationResult> => {\n await state.set(STORY_STATE_KEYS.activePhase, \"deterministic-context-preflight\");\n await incrementStoryPhaseAttempt(\"deterministic-context-preflight\");\n\n const brief = await buildDeterministicContextPreflightBrief({\n currentStory,\n implementationContext,\n cwd: state.cwd,\n });\n await state.set(STORY_STATE_KEYS.latestExplorationBrief, brief);\n\n await state.set(STORY_STATE_KEYS.activePhase, \"write-red-tests\");\n const attempt = await incrementStoryPhaseAttempt(\"write-red-tests\");\n return writeRedTestsStep({\n currentStory,\n explorationBrief: brief,\n attempt,\n implementationContext: await loadStoryPhaseContext(\"write-red-tests\"),\n });\n },\n);\n\nexport async function buildDeterministicContextPreflightBrief({\n currentStory,\n implementationContext,\n cwd,\n}: {\n readonly currentStory: Document;\n readonly implementationContext?: string;\n readonly cwd?: string;\n}): Promise<DeterministicContextPreflightBrief> {\n const sourceText = [currentStory.path, currentStory.content, implementationContext]\n .filter(Boolean)\n .join(\"\\n\");\n const relevantFiles = uniqueBounded([\n normalizeFileHint(currentStory.path, cwd),\n ...extractPathHints(sourceText),\n ...extractPathHints(implementationContext ?? \"\"),\n ]);\n const packageHints = uniqueBounded(await packageHintsForFiles(relevantFiles, cwd));\n const symbols = uniqueBounded(extractSymbolHints(sourceText));\n const searchHints = uniqueBounded([\n ...symbols.slice(0, 6).map((symbol) => `rg ${shellQuote(symbol)}`),\n relevantFiles.length === 0 && symbols.length === 0\n ? \"rg focused story keywords from the Goal and Acceptance Criteria\"\n : undefined,\n ]);\n const explicitValidationCommands = extractValidationCommands(sourceText);\n const focusedValidationHints = uniqueBounded([\n ...explicitValidationCommands,\n ...packageHints.flatMap((filter) => [\n `pnpm --filter ${filter} test`,\n `pnpm --filter ${filter} typecheck`,\n `pnpm --filter ${filter} lint`,\n ]),\n ...(packageHints.length === 0 ? DEFAULT_VALIDATION_COMMANDS : []),\n ]);\n const graphifyHint = cwd ? await graphifyAvailable(cwd) : false;\n const relevantFileText = relevantFiles.length > 0 ? relevantFiles.join(\", \") : \"none detected\";\n const packageText = packageHints.length > 0 ? packageHints.join(\", \") : \"none detected\";\n const symbolText = symbols.length > 0 ? symbols.join(\", \") : \"none detected\";\n const contextHints = uniqueBounded(extractContextHints(implementationContext ?? \"\"), 4);\n const contextText = contextHints.length > 0 ? ` Context hints: ${contextHints.join(\"; \")}.` : \"\";\n const graphText = graphifyHint\n ? \"graphify appears available; use graphify query before broad grep for structural questions.\"\n : \"graphify availability was not detected; use focused rg hints if more context is needed.\";\n\n return {\n blocked: false,\n summary: `Deterministic context preflight completed without blocking. Likely files: ${relevantFileText}. Package/filter hints: ${packageText}. Symbols: ${symbolText}.${contextText} ${graphText}`,\n relevantFiles,\n testSeams: uniqueBounded([\n ...extractSectionBullets(sourceText, [\n \"red phase\",\n \"acceptance criteria\",\n \"validation commands\",\n ]),\n ...symbols.map((symbol) => `Behavior around ${symbol}`),\n ...searchHints,\n ]),\n recommendedValidationCommands: focusedValidationHints,\n packageHints,\n symbols,\n searchHints: uniqueBounded([\n ...(graphifyHint\n ? [\n `graphify query ${shellQuote(`Where is ${symbols[0] ?? currentStory.path} implemented or tested?`)}`,\n ]\n : []),\n ...searchHints,\n ]),\n focusedValidationHints,\n };\n}\n\nfunction extractPathHints(text: string): readonly string[] {\n const candidates: string[] = [];\n const pathPattern =\n /(?:^|[\\s('\"`])((?:\\.{1,2}\\/)?(?:packages|src|docs|scripts|test|tests|\\.github|\\.pi)\\/[A-Za-z0-9_./-]+|[A-Za-z0-9_.-]+\\.(?:ts|tsx|js|jsx|json|md|mjs|cjs|svelte|css|yml|yaml))/gmu;\n for (const match of text.matchAll(pathPattern)) {\n const candidate = sanitizePathCandidate(match[1]);\n if (candidate) {\n candidates.push(candidate);\n }\n }\n return candidates;\n}\n\nfunction sanitizePathCandidate(candidate?: string): string | undefined {\n const cleaned = candidate\n ?.trim()\n .replace(/[),.;:]+$/u, \"\")\n .replace(/^`|`$/gu, \"\");\n if (\n !cleaned ||\n cleaned.includes(\"://\") ||\n cleaned.includes(\"../\") ||\n /^[A-Za-z]:/u.test(cleaned)\n ) {\n return undefined;\n }\n return cleaned.replace(/\\\\/gu, \"/\");\n}\n\nfunction normalizeFileHint(path: string, cwd?: string): string {\n const normalizedPath = path.replace(/\\\\/gu, \"/\");\n if (!cwd || !isAbsolute(path)) {\n return normalizedPath;\n }\n\n const relativePath = relative(cwd, path).replace(/\\\\/gu, \"/\");\n return relativePath.length > 0 && !relativePath.startsWith(\"../\") ? relativePath : normalizedPath;\n}\n\nfunction extractSymbolHints(text: string): readonly string[] {\n const symbols: string[] = [];\n for (const match of text.matchAll(/`([^`\\n]{3,80})`/gmu)) {\n const token = match[1]?.trim();\n if (token && !token.includes(\" \") && !token.includes(\"/\")) {\n symbols.push(token);\n }\n }\n for (const match of text.matchAll(/\\b[A-Z][A-Za-z0-9]*(?:[A-Z][A-Za-z0-9]*)+\\b/gmu)) {\n if (match[0].length <= 80) {\n symbols.push(match[0]);\n }\n }\n return symbols;\n}\n\nfunction extractContextHints(text: string): readonly string[] {\n return text\n .split(/\\r?\\n/u)\n .map((line) => line.replace(/^\\s*[-*]\\s*/u, \"\").trim())\n .filter((line) => line.length > 0 && !/^[A-Za-z-]+:\\s*/u.test(line));\n}\n\nfunction extractValidationCommands(text: string): readonly string[] {\n return uniqueBounded(\n text\n .split(/\\r?\\n/u)\n .map((line) => line.replace(/^\\s*[-*]\\s*/u, \"\").trim())\n .filter((line) => /\\b(pnpm|npm|yarn|vitest|tsc|biome|node)\\b/u.test(line))\n .map((line) => line.replace(/^`|`$/gu, \"\")),\n );\n}\n\nfunction extractSectionBullets(text: string, sectionTitles: readonly string[]): readonly string[] {\n const normalizedTitles = new Set(sectionTitles.map((title) => title.toLowerCase()));\n const lines = text.replace(/\\r\\n?/gu, \"\\n\").split(\"\\n\");\n const bullets: string[] = [];\n let active = false;\n for (const line of lines) {\n const heading = /^#{2,6}\\s+(.+?)\\s*$/u.exec(line.trim());\n if (heading) {\n active = normalizedTitles.has((heading[1] ?? \"\").trim().toLowerCase());\n continue;\n }\n if (!active) {\n continue;\n }\n const bullet = /^\\s*[-*]\\s+(.+)$/u.exec(line);\n if (bullet?.[1]) {\n bullets.push(bullet[1].trim());\n }\n }\n return bullets;\n}\n\nasync function packageHintsForFiles(\n files: readonly string[],\n cwd?: string,\n): Promise<readonly string[]> {\n const packageDirs = uniqueBounded(\n files.flatMap((file) => {\n const normalizedFile = file.replace(/\\\\/gu, \"/\");\n const match = /^packages\\/([^/]+)/u.exec(normalizedFile);\n return match?.[1] ? [`packages/${match[1]}`] : [];\n }),\n );\n\n const hints: string[] = [];\n for (const packageDir of packageDirs) {\n const packageJsonPath = cwd ? join(cwd, packageDir, \"package.json\") : undefined;\n const packageName = packageJsonPath ? await readPackageName(packageJsonPath) : undefined;\n hints.push(packageName ?? packageDir);\n }\n return hints;\n}\n\nasync function readPackageName(packageJsonPath: string): Promise<string | undefined> {\n try {\n const parsed = JSON.parse(await readFile(packageJsonPath, \"utf8\")) as {\n readonly name?: unknown;\n };\n return typeof parsed.name === \"string\" ? parsed.name : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function graphifyAvailable(cwd: string): Promise<boolean> {\n try {\n await access(join(cwd, \"graphify-out\", \"graph.json\"));\n return true;\n } catch {\n return false;\n }\n}\n\nfunction uniqueBounded<T>(items: readonly (T | undefined)[], max = MAX_ITEMS): readonly T[] {\n const values: T[] = [];\n const seen = new Set<string>();\n for (const item of items) {\n if (item === undefined || item === null) {\n continue;\n }\n const key = String(item);\n if (key.length === 0 || seen.has(key)) {\n continue;\n }\n seen.add(key);\n values.push(item);\n if (values.length >= max) {\n break;\n }\n }\n return values;\n}\n\nfunction shellQuote(value: string): string {\n return JSON.stringify(value);\n}\n","import { state, step } from \"@trailstep/authoring\";\nimport { implementGreenStep } from \"../implement-green/step.js\";\nimport {\n incrementStoryPhaseAttempt,\n loadStoryPhaseContext,\n STORY_STATE_KEYS,\n} from \"../shared/story-state.js\";\nimport {\n type WriteRedTestsInput,\n type WriteRedTestsOutput,\n writeRedTestsOutput,\n writeRedTestsPrompt,\n} from \"./prompt.js\";\n\nexport const writeRedTestsStep = step({ id: \"write-red-tests\" })\n .prompt<WriteRedTestsInput, WriteRedTestsOutput>(writeRedTestsPrompt, {\n agent: \"testWriter\",\n output: writeRedTestsOutput,\n })\n .do(async (promptOutput, input) => {\n if (promptOutput.blocked) {\n await state.set(\n STORY_STATE_KEYS.blockedReason,\n promptOutput.blockedReason ?? \"Red-test phase reported a blocked state.\",\n );\n const { storyRouterStep } = await import(\"../story-router/step.js\");\n return storyRouterStep({\n reason: {\n type: \"blocked\",\n sourceReason: \"failed-red-tests\",\n blockedPhase: \"write-red-tests\",\n blockedReason: promptOutput.blockedReason ?? \"Red-test phase reported a blocked state.\",\n code: \"story_red_tests_blocked\",\n },\n currentStory: input.currentStory,\n });\n }\n\n await state.set(STORY_STATE_KEYS.latestRedTestSummary, promptOutput);\n await state.set(STORY_STATE_KEYS.activePhase, \"implement-green\");\n const attempt = await incrementStoryPhaseAttempt(\"implement-green\");\n return implementGreenStep({\n currentStory: input.currentStory,\n explorationBrief: input.explorationBrief,\n redTestSummary: promptOutput,\n attempt,\n implementationContext: await loadStoryPhaseContext(\"implement-green\"),\n });\n });\n","import { type Document, jsonSchema, promptSections, section } from \"@trailstep/authoring\";\nimport type { ExploreStoryOutput } from \"../explore-story/prompt.js\";\nimport { storyViewForTestWriter } from \"../shared/story-view.js\";\n\nexport interface WriteRedTestsInput extends Record<string, unknown> {\n readonly currentStory: Document;\n readonly explorationBrief?: ExploreStoryOutput;\n readonly attempt: number;\n readonly implementationContext?: string;\n}\n\nexport interface WriteRedTestsOutput extends Record<string, unknown> {\n readonly blocked: boolean;\n readonly blockedReason?: string;\n readonly summary: string;\n readonly redEvidence: string;\n readonly changedFiles: readonly string[];\n}\n\nexport const writeRedTestsOutput = jsonSchema<WriteRedTestsOutput>({\n type: \"object\",\n properties: {\n blocked: { type: \"boolean\" },\n blockedReason: { type: \"string\" },\n summary: { type: \"string\" },\n redEvidence: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"blocked\", \"summary\", \"redEvidence\", \"changedFiles\"],\n additionalProperties: false,\n});\n\nexport function writeRedTestsPrompt({ input }: { readonly input: WriteRedTestsInput }): string {\n return promptSections(\n section(\n \"Role\",\n \"You are the red-test writer. Create focused behavioral failing tests; do not implement production behavior or review the story.\",\n ),\n section(\"Active story test view\", storyViewForTestWriter(input.currentStory.content)),\n section(\"Implementation context\", input.implementationContext),\n section(\"Exploration summary\", input.explorationBrief?.summary ?? \"Not provided.\"),\n section(\n \"Exploration test seams\",\n input.explorationBrief?.testSeams?.map((item) => `- ${item}`).join(\"\\n\") ?? \"Not provided.\",\n ),\n section(\n \"Task\",\n [\n \"Write or update the focused behavioral red test for only this active story.\",\n \"The test must fail for the intended product/integration behavior before green implementation.\",\n \"Do not implement production code except the absolute minimum needed to compile the red test harness.\",\n \"Run the focused red test when feasible and report only the command plus concise failing evidence in `redEvidence`.\",\n \"Do not include unrelated stories, green implementation work, or review scoring.\",\n \"If a safe red test cannot be written, set `blocked: true` and explain why.\",\n ].join(\"\\n\"),\n ),\n );\n}\n"],"mappings":";AACA,SAAS,QAAAA,OAAM,SAAAC,SAAO,QAAAC,cAAY;;;ACDlC,SAAS,SAAAC,QAAO,QAAAC,aAAY;;;ACA5B,SAAwB,aAAa;;;ACArC,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAE1B,IAAM,gBAAgB,UAAU,QAAQ;AAMxC,eAAsB,OAAO,MAAyB,KAAiC;AACrF,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,cAAc,OAAO,CAAC,GAAG,IAAI,GAAG;AAAA,MACvD;AAAA,MACA,WAAW,OAAO,OAAO;AAAA,IAC3B,CAAC;AACD,WAAO,EAAE,IAAI,MAAM,QAAQ,OAAO,QAAQ,EAAE;AAAA,EAC9C,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,EAAE,IAAI,OAAO,OAAO,QAAQ;AAAA,EACrC;AACF;;;ADjBO,IAAM,mBAAmB;AAAA,EAC9B,aAAa;AAAA,EACb,aAAa;AAAA,EACb,oBAA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SAAO;AACT;AAEA,eAAe,yBAAyB,aAAoD;AAC1F,SAAO,4BAA4B,EAAE,cAAc,YAAY,CAAC;AAClE;","names":["fail","state","step","state","step","state","step","state","step","state","step","execFile","promisify","state","execFileAsync","promisify","execFile","state","jsonSchema","step","state","storyRouterStep","jsonSchema","jsonSchema","section","step","state","storyRouterStep","execFile","promisify","execFileAsync","skipped","step","state","storyRouterStep","jsonSchema","promptSections","section","jsonSchema","promptSections","section","step","state","storyRouterStep","state","step","jsonSchema","promptSections","section","jsonSchema","promptSections","section","step","state","storyRouterStep","fail","state","step","state","step","state","step","jsonSchema","promptSections","section","jsonSchema","promptSections","section","step","state","storyRouterStep","step","state","shellQuote","step","state","documentsMatch","fail","step","state","fail"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,12 @@
1
- import * as _trailstep_authoring from '@trailstep/authoring';
1
+ import * as _trailstep_core from '@trailstep/core';
2
2
 
3
+ type TakeItAwayPullRequestStatus = "created" | "existing" | "skipped" | "disabled";
4
+ interface TakeItAwayPullRequestOutput extends Record<string, unknown> {
5
+ readonly status: TakeItAwayPullRequestStatus;
6
+ readonly url?: string;
7
+ readonly warning?: string;
8
+ readonly commands?: readonly string[];
9
+ }
3
10
  interface TakeItAwayOutput extends Record<string, unknown> {
4
11
  readonly status: "implemented";
5
12
  readonly featureDocPath: string;
@@ -7,14 +14,30 @@ interface TakeItAwayOutput extends Record<string, unknown> {
7
14
  readonly storyCount: number;
8
15
  readonly completedStories: readonly string[];
9
16
  readonly summary: string;
17
+ readonly warnings?: readonly string[];
18
+ readonly pullRequest?: TakeItAwayPullRequestOutput;
10
19
  }
11
20
 
12
- declare const grillItAway: _trailstep_authoring.DefinedWorkflow<Record<string, never>, TakeItAwayOutput>;
21
+ declare const grillItAway: _trailstep_core.DefinedWorkflow<Record<string, never>, TakeItAwayOutput>;
13
22
 
23
+ interface TakeItAwayPullRequestInput extends Record<string, unknown> {
24
+ readonly enabled?: boolean;
25
+ readonly base?: string;
26
+ readonly remote?: string;
27
+ readonly draft?: boolean;
28
+ readonly title?: string;
29
+ readonly body?: string;
30
+ }
31
+ interface TakeItAwayPlanningCheckpointInput extends Record<string, unknown> {
32
+ readonly enabled?: boolean;
33
+ }
14
34
  interface TakeItAwayInput extends Record<string, unknown> {
15
35
  readonly conversation: string;
36
+ readonly autoCommit?: boolean;
37
+ readonly pullRequest?: TakeItAwayPullRequestInput;
38
+ readonly planningCheckpoint?: TakeItAwayPlanningCheckpointInput;
16
39
  }
17
40
 
18
- declare const takeItAway: _trailstep_authoring.DefinedWorkflow<TakeItAwayInput, TakeItAwayOutput>;
41
+ declare const takeItAway: _trailstep_core.DefinedWorkflow<TakeItAwayInput, TakeItAwayOutput>;
19
42
 
20
43
  export { grillItAway, takeItAway };