diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..29b9013f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto eol=lf + +*.gif binary diff --git a/CHANGELOG.md b/CHANGELOG.md index 134163cc..329db32f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Goal postponement**: Added `jumbo goal postpone --id ` to move a defined goal to `postponed`. Postponed goals remain visible in CLI and TUI goal views but are excluded from automatic work selection. +- **Goal reinstatement**: Added `jumbo goal reinstate --id ` to return a postponed goal to `defined` status and make it eligible for refinement again. + ### Fixed - **Adding relations after removal**: Adding the same connection again creates a new relation with the supplied guidance while preserving the removed relation and its event history. diff --git a/docs/guides/goal-management.md b/docs/guides/goal-management.md index abac66e1..cad65665 100644 --- a/docs/guides/goal-management.md +++ b/docs/guides/goal-management.md @@ -50,6 +50,22 @@ Keep goals small and focused. Keep objectives specific — "Implement JWT auth" See [goal add reference](../reference/commands/goal.md) for the full list of options. +### Postponing defined goals + +Postpone defined work that should remain recorded but should not be selected by automatic work streams: + +```bash +jumbo goal postpone --id goal_abc123 +``` + +The goal remains visible in CLI lists and the TUI under the `postponed` status. When the work becomes relevant again, return it to `defined` status and renewed refinement eligibility: + +```bash +jumbo goal reinstate --id goal_abc123 +``` + +Only postponed goals can be reinstated. Automatic refinement continues to exclude postponed goals until this explicit transition occurs. + ### Prerequisite goals Goals can declare prerequisites that must be completed before they can start: @@ -189,7 +205,7 @@ jumbo goals list --status doing jumbo goals list --status doing,blocked ``` -Valid status filters: `defined`, `doing`, `blocked`, `paused`, `refined`, `in-refinement`, `in-review`, `approved`, `done`. +Valid status filters: `defined`, `postponed`, `doing`, `blocked`, `paused`, `refined`, `in-refinement`, `in-review`, `approved`, `done`. --- diff --git a/docs/reference/commands/goal.md b/docs/reference/commands/goal.md index 34893f11..566264c5 100644 --- a/docs/reference/commands/goal.md +++ b/docs/reference/commands/goal.md @@ -80,6 +80,60 @@ Start refinement of a goal — displays details and transitions to `in-refinemen --- +## jumbo goal postpone + +Postpone a defined goal so it remains visible without entering automatic work-selection streams. This transitions the goal from `defined` to `postponed`. + +### Synopsis + +```bash +> jumbo goal postpone --id +``` + +### Options + +| Option | Description | +|--------|-------------| +| `-i, --id ` | ID of the defined goal to postpone (required) | + +### Examples + +```bash +> jumbo goal postpone --id goal_abc123 +``` + +:::note +Postponed goals remain available in goal lists and TUI filters. Use `jumbo goal reinstate` when the work should become eligible for refinement again. +::: + +--- + +## jumbo goal reinstate + +Return a postponed goal to `defined` status so it becomes eligible for refinement again. + +### Synopsis + +```bash +> jumbo goal reinstate --id +``` + +### Options + +| Option | Description | +|--------|-------------| +| `-i, --id ` | ID of the postponed goal to reinstate (required) | + +### Examples + +```bash +> jumbo goal reinstate --id goal_abc123 +``` + +Only postponed goals can be reinstated. Other source statuses are rejected without changing the goal. + +--- + ## jumbo goal commit Commit a goal after refinement is complete — transitions from `in-refinement` to `refined`. diff --git a/docs/reference/commands/index.md b/docs/reference/commands/index.md index be269a99..30c881b4 100644 --- a/docs/reference/commands/index.md +++ b/docs/reference/commands/index.md @@ -12,7 +12,7 @@ Complete reference for all Jumbo CLI commands. |---------------|-------------| | [Search Command](search.md) | search | | [Index Commands](search-index.md) | rebuild | -| [Goal Commands](goal.md) | add, refine, commit, start, pause, resume, block, unblock, submit, review, approve, reject, codify, close, qualify, reset, update, update-progress, show, remove, list | +| [Goal Commands](goal.md) | add, refine, postpone, reinstate, commit, start, pause, resume, block, unblock, submit, review, approve, reject, codify, close, qualify, reset, update, update-progress, show, remove, list | | [Session Commands](session.md) | start, end, list, compact | | [Project Commands](project.md) | init, update | | [Architecture Commands](architecture.md) | define, update, view | diff --git a/src/application/context/goals/get/IGetGoalViewReader.ts b/src/application/context/goals/get/IGetGoalViewReader.ts new file mode 100644 index 00000000..76b4f0c5 --- /dev/null +++ b/src/application/context/goals/get/IGetGoalViewReader.ts @@ -0,0 +1,5 @@ +import { GoalView } from "../GoalView.js"; + +export interface IGetGoalViewReader { + findById(goalId: string): Promise; +} diff --git a/src/application/context/goals/get/LocalGetGoalsGateway.ts b/src/application/context/goals/get/LocalGetGoalsGateway.ts index 10b5a6ca..ac2dbd05 100644 --- a/src/application/context/goals/get/LocalGetGoalsGateway.ts +++ b/src/application/context/goals/get/LocalGetGoalsGateway.ts @@ -8,6 +8,7 @@ const VALID_STATUSES: readonly string[] = Object.values(GoalStatus); const DEFAULT_STATUSES: readonly GoalStatusType[] = [ GoalStatus.TODO, + GoalStatus.POSTPONED, GoalStatus.REFINED, GoalStatus.DOING, GoalStatus.BLOCKED, diff --git a/src/application/context/goals/postpone/GoalPostponedEventHandler.ts b/src/application/context/goals/postpone/GoalPostponedEventHandler.ts new file mode 100644 index 00000000..82456d0a --- /dev/null +++ b/src/application/context/goals/postpone/GoalPostponedEventHandler.ts @@ -0,0 +1,12 @@ +import { BaseEvent } from "../../../../domain/BaseEvent.js"; +import { GoalPostponedEvent } from "../../../../domain/goals/postpone/GoalPostponedEvent.js"; +import { IEventHandler } from "../../../messaging/IEventHandler.js"; +import { IGoalPostponedProjector } from "./IGoalPostponedProjector.js"; + +export class GoalPostponedEventHandler implements IEventHandler { + constructor(private readonly projector: IGoalPostponedProjector) {} + + async handle(event: BaseEvent): Promise { + await this.projector.applyGoalPostponed(event as GoalPostponedEvent); + } +} diff --git a/src/application/context/goals/postpone/IGoalPostponedEventReader.ts b/src/application/context/goals/postpone/IGoalPostponedEventReader.ts new file mode 100644 index 00000000..2e8779f4 --- /dev/null +++ b/src/application/context/goals/postpone/IGoalPostponedEventReader.ts @@ -0,0 +1,5 @@ +import { GoalEvent } from "../../../../domain/goals/EventIndex.js"; + +export interface IGoalPostponedEventReader { + readStream(streamId: string): Promise; +} diff --git a/src/application/context/goals/postpone/IGoalPostponedEventWriter.ts b/src/application/context/goals/postpone/IGoalPostponedEventWriter.ts new file mode 100644 index 00000000..87f52270 --- /dev/null +++ b/src/application/context/goals/postpone/IGoalPostponedEventWriter.ts @@ -0,0 +1,6 @@ +import { BaseEvent } from "../../../../domain/BaseEvent.js"; +import { AppendResult } from "../../../persistence/IEventStore.js"; + +export interface IGoalPostponedEventWriter { + append(event: BaseEvent): Promise; +} diff --git a/src/application/context/goals/postpone/IGoalPostponedProjector.ts b/src/application/context/goals/postpone/IGoalPostponedProjector.ts new file mode 100644 index 00000000..06b19b88 --- /dev/null +++ b/src/application/context/goals/postpone/IGoalPostponedProjector.ts @@ -0,0 +1,5 @@ +import { GoalPostponedEvent } from "../../../../domain/goals/postpone/GoalPostponedEvent.js"; + +export interface IGoalPostponedProjector { + applyGoalPostponed(event: GoalPostponedEvent): Promise; +} diff --git a/src/application/context/goals/postpone/IPostponeGoalGateway.ts b/src/application/context/goals/postpone/IPostponeGoalGateway.ts new file mode 100644 index 00000000..aa2abccb --- /dev/null +++ b/src/application/context/goals/postpone/IPostponeGoalGateway.ts @@ -0,0 +1,6 @@ +import { PostponeGoalRequest } from "./PostponeGoalRequest.js"; +import { PostponeGoalResponse } from "./PostponeGoalResponse.js"; + +export interface IPostponeGoalGateway { + postponeGoal(request: PostponeGoalRequest): Promise; +} diff --git a/src/application/context/goals/postpone/LocalPostponeGoalGateway.ts b/src/application/context/goals/postpone/LocalPostponeGoalGateway.ts new file mode 100644 index 00000000..2f24b33b --- /dev/null +++ b/src/application/context/goals/postpone/LocalPostponeGoalGateway.ts @@ -0,0 +1,14 @@ +import { GoalStatus } from "../../../../domain/goals/Constants.js"; +import { IPostponeGoalGateway } from "./IPostponeGoalGateway.js"; +import { PostponeGoalCommandHandler } from "./PostponeGoalCommandHandler.js"; +import { PostponeGoalRequest } from "./PostponeGoalRequest.js"; +import { PostponeGoalResponse } from "./PostponeGoalResponse.js"; + +export class LocalPostponeGoalGateway implements IPostponeGoalGateway { + constructor(private readonly commandHandler: PostponeGoalCommandHandler) {} + + async postponeGoal(request: PostponeGoalRequest): Promise { + await this.commandHandler.execute({ goalId: request.goalId }); + return { status: GoalStatus.POSTPONED }; + } +} diff --git a/src/application/context/goals/postpone/PostponeGoalCommand.ts b/src/application/context/goals/postpone/PostponeGoalCommand.ts new file mode 100644 index 00000000..405c7cf4 --- /dev/null +++ b/src/application/context/goals/postpone/PostponeGoalCommand.ts @@ -0,0 +1,4 @@ +/** Command that transitions a goal from defined to postponed. */ +export interface PostponeGoalCommand { + readonly goalId: string; +} diff --git a/src/application/context/goals/postpone/PostponeGoalCommandHandler.ts b/src/application/context/goals/postpone/PostponeGoalCommandHandler.ts new file mode 100644 index 00000000..d9cef04d --- /dev/null +++ b/src/application/context/goals/postpone/PostponeGoalCommandHandler.ts @@ -0,0 +1,34 @@ +import { Goal } from "../../../../domain/goals/Goal.js"; +import { GoalErrorMessages, formatErrorMessage } from "../../../../domain/goals/Constants.js"; +import { IEventBus } from "../../../messaging/IEventBus.js"; +import { IGetGoalViewReader } from "../get/IGetGoalViewReader.js"; +import { IGoalPostponedEventReader } from "./IGoalPostponedEventReader.js"; +import { IGoalPostponedEventWriter } from "./IGoalPostponedEventWriter.js"; +import { PostponeGoalCommand } from "./PostponeGoalCommand.js"; + +export class PostponeGoalCommandHandler { + constructor( + private readonly eventWriter: IGoalPostponedEventWriter, + private readonly eventReader: IGoalPostponedEventReader, + private readonly goalReader: IGetGoalViewReader, + private readonly eventBus: IEventBus + ) {} + + async execute(command: PostponeGoalCommand): Promise<{ status: string }> { + const view = await this.goalReader.findById(command.goalId); + if (!view) { + throw new Error( + formatErrorMessage(GoalErrorMessages.GOAL_NOT_FOUND, { id: command.goalId }) + ); + } + + const history = await this.eventReader.readStream(command.goalId); + const goal = Goal.rehydrate(command.goalId, history); + const event = goal.postpone(); + + await this.eventWriter.append(event); + await this.eventBus.publish(event); + + return { status: event.payload.status }; + } +} diff --git a/src/application/context/goals/postpone/PostponeGoalController.ts b/src/application/context/goals/postpone/PostponeGoalController.ts new file mode 100644 index 00000000..dff93342 --- /dev/null +++ b/src/application/context/goals/postpone/PostponeGoalController.ts @@ -0,0 +1,11 @@ +import { IPostponeGoalGateway } from "./IPostponeGoalGateway.js"; +import { PostponeGoalRequest } from "./PostponeGoalRequest.js"; +import { PostponeGoalResponse } from "./PostponeGoalResponse.js"; + +export class PostponeGoalController { + constructor(private readonly gateway: IPostponeGoalGateway) {} + + async handle(request: PostponeGoalRequest): Promise { + return this.gateway.postponeGoal(request); + } +} diff --git a/src/application/context/goals/postpone/PostponeGoalRequest.ts b/src/application/context/goals/postpone/PostponeGoalRequest.ts new file mode 100644 index 00000000..481773a8 --- /dev/null +++ b/src/application/context/goals/postpone/PostponeGoalRequest.ts @@ -0,0 +1,4 @@ +/** Request model for postponing a defined goal. */ +export interface PostponeGoalRequest { + readonly goalId: string; +} diff --git a/src/application/context/goals/postpone/PostponeGoalResponse.ts b/src/application/context/goals/postpone/PostponeGoalResponse.ts new file mode 100644 index 00000000..07ae6ad6 --- /dev/null +++ b/src/application/context/goals/postpone/PostponeGoalResponse.ts @@ -0,0 +1,4 @@ +/** Minimal result returned after a goal is postponed. */ +export interface PostponeGoalResponse { + readonly status: string; +} diff --git a/src/application/context/goals/reinstate/GoalReinstatedEventHandler.ts b/src/application/context/goals/reinstate/GoalReinstatedEventHandler.ts new file mode 100644 index 00000000..8cf1a426 --- /dev/null +++ b/src/application/context/goals/reinstate/GoalReinstatedEventHandler.ts @@ -0,0 +1,12 @@ +import { BaseEvent } from "../../../../domain/BaseEvent.js"; +import { GoalReinstatedEvent } from "../../../../domain/goals/reinstate/GoalReinstatedEvent.js"; +import { IEventHandler } from "../../../messaging/IEventHandler.js"; +import { IGoalReinstatedProjector } from "./IGoalReinstatedProjector.js"; + +export class GoalReinstatedEventHandler implements IEventHandler { + constructor(private readonly projector: IGoalReinstatedProjector) {} + + async handle(event: BaseEvent): Promise { + await this.projector.applyGoalReinstated(event as GoalReinstatedEvent); + } +} diff --git a/src/application/context/goals/reinstate/IGoalReinstatedEventReader.ts b/src/application/context/goals/reinstate/IGoalReinstatedEventReader.ts new file mode 100644 index 00000000..4e3be4d9 --- /dev/null +++ b/src/application/context/goals/reinstate/IGoalReinstatedEventReader.ts @@ -0,0 +1,5 @@ +import { GoalEvent } from "../../../../domain/goals/EventIndex.js"; + +export interface IGoalReinstatedEventReader { + readStream(streamId: string): Promise; +} diff --git a/src/application/context/goals/reinstate/IGoalReinstatedEventWriter.ts b/src/application/context/goals/reinstate/IGoalReinstatedEventWriter.ts new file mode 100644 index 00000000..ef630415 --- /dev/null +++ b/src/application/context/goals/reinstate/IGoalReinstatedEventWriter.ts @@ -0,0 +1,6 @@ +import { BaseEvent } from "../../../../domain/BaseEvent.js"; +import { AppendResult } from "../../../persistence/IEventStore.js"; + +export interface IGoalReinstatedEventWriter { + append(event: BaseEvent): Promise; +} diff --git a/src/application/context/goals/reinstate/IGoalReinstatedProjector.ts b/src/application/context/goals/reinstate/IGoalReinstatedProjector.ts new file mode 100644 index 00000000..961635b0 --- /dev/null +++ b/src/application/context/goals/reinstate/IGoalReinstatedProjector.ts @@ -0,0 +1,5 @@ +import { GoalReinstatedEvent } from "../../../../domain/goals/reinstate/GoalReinstatedEvent.js"; + +export interface IGoalReinstatedProjector { + applyGoalReinstated(event: GoalReinstatedEvent): Promise; +} diff --git a/src/application/context/goals/reinstate/IReinstateGoalGateway.ts b/src/application/context/goals/reinstate/IReinstateGoalGateway.ts new file mode 100644 index 00000000..8b67dbf6 --- /dev/null +++ b/src/application/context/goals/reinstate/IReinstateGoalGateway.ts @@ -0,0 +1,6 @@ +import { ReinstateGoalRequest } from "./ReinstateGoalRequest.js"; +import { ReinstateGoalResponse } from "./ReinstateGoalResponse.js"; + +export interface IReinstateGoalGateway { + reinstateGoal(request: ReinstateGoalRequest): Promise; +} diff --git a/src/application/context/goals/reinstate/LocalReinstateGoalGateway.ts b/src/application/context/goals/reinstate/LocalReinstateGoalGateway.ts new file mode 100644 index 00000000..fc024ce6 --- /dev/null +++ b/src/application/context/goals/reinstate/LocalReinstateGoalGateway.ts @@ -0,0 +1,14 @@ +import { GoalStatus } from "../../../../domain/goals/Constants.js"; +import { IReinstateGoalGateway } from "./IReinstateGoalGateway.js"; +import { ReinstateGoalCommandHandler } from "./ReinstateGoalCommandHandler.js"; +import { ReinstateGoalRequest } from "./ReinstateGoalRequest.js"; +import { ReinstateGoalResponse } from "./ReinstateGoalResponse.js"; + +export class LocalReinstateGoalGateway implements IReinstateGoalGateway { + constructor(private readonly commandHandler: ReinstateGoalCommandHandler) {} + + async reinstateGoal(request: ReinstateGoalRequest): Promise { + await this.commandHandler.execute({ goalId: request.goalId }); + return { status: GoalStatus.TODO }; + } +} diff --git a/src/application/context/goals/reinstate/ReinstateGoalCommand.ts b/src/application/context/goals/reinstate/ReinstateGoalCommand.ts new file mode 100644 index 00000000..f28e7304 --- /dev/null +++ b/src/application/context/goals/reinstate/ReinstateGoalCommand.ts @@ -0,0 +1,4 @@ +/** Command that transitions a goal from postponed to defined. */ +export interface ReinstateGoalCommand { + readonly goalId: string; +} diff --git a/src/application/context/goals/reinstate/ReinstateGoalCommandHandler.ts b/src/application/context/goals/reinstate/ReinstateGoalCommandHandler.ts new file mode 100644 index 00000000..1e2eaaf3 --- /dev/null +++ b/src/application/context/goals/reinstate/ReinstateGoalCommandHandler.ts @@ -0,0 +1,34 @@ +import { Goal } from "../../../../domain/goals/Goal.js"; +import { GoalErrorMessages, formatErrorMessage } from "../../../../domain/goals/Constants.js"; +import { IEventBus } from "../../../messaging/IEventBus.js"; +import { IGetGoalViewReader } from "../get/IGetGoalViewReader.js"; +import { IGoalReinstatedEventReader } from "./IGoalReinstatedEventReader.js"; +import { IGoalReinstatedEventWriter } from "./IGoalReinstatedEventWriter.js"; +import { ReinstateGoalCommand } from "./ReinstateGoalCommand.js"; + +export class ReinstateGoalCommandHandler { + constructor( + private readonly eventWriter: IGoalReinstatedEventWriter, + private readonly eventReader: IGoalReinstatedEventReader, + private readonly goalReader: IGetGoalViewReader, + private readonly eventBus: IEventBus + ) {} + + async execute(command: ReinstateGoalCommand): Promise<{ status: string }> { + const view = await this.goalReader.findById(command.goalId); + if (!view) { + throw new Error( + formatErrorMessage(GoalErrorMessages.GOAL_NOT_FOUND, { id: command.goalId }) + ); + } + + const history = await this.eventReader.readStream(command.goalId); + const goal = Goal.rehydrate(command.goalId, history); + const event = goal.reinstate(); + + await this.eventWriter.append(event); + await this.eventBus.publish(event); + + return { status: event.payload.status }; + } +} diff --git a/src/application/context/goals/reinstate/ReinstateGoalController.ts b/src/application/context/goals/reinstate/ReinstateGoalController.ts new file mode 100644 index 00000000..8eb08197 --- /dev/null +++ b/src/application/context/goals/reinstate/ReinstateGoalController.ts @@ -0,0 +1,11 @@ +import { IReinstateGoalGateway } from "./IReinstateGoalGateway.js"; +import { ReinstateGoalRequest } from "./ReinstateGoalRequest.js"; +import { ReinstateGoalResponse } from "./ReinstateGoalResponse.js"; + +export class ReinstateGoalController { + constructor(private readonly gateway: IReinstateGoalGateway) {} + + async handle(request: ReinstateGoalRequest): Promise { + return this.gateway.reinstateGoal(request); + } +} diff --git a/src/application/context/goals/reinstate/ReinstateGoalRequest.ts b/src/application/context/goals/reinstate/ReinstateGoalRequest.ts new file mode 100644 index 00000000..ad9bca5d --- /dev/null +++ b/src/application/context/goals/reinstate/ReinstateGoalRequest.ts @@ -0,0 +1,4 @@ +/** Request model for reinstating a postponed goal. */ +export interface ReinstateGoalRequest { + readonly goalId: string; +} diff --git a/src/application/context/goals/reinstate/ReinstateGoalResponse.ts b/src/application/context/goals/reinstate/ReinstateGoalResponse.ts new file mode 100644 index 00000000..63951fe4 --- /dev/null +++ b/src/application/context/goals/reinstate/ReinstateGoalResponse.ts @@ -0,0 +1,4 @@ +/** Minimal result returned after a goal is reinstated. */ +export interface ReinstateGoalResponse { + readonly status: string; +} diff --git a/src/application/host/IApplicationContainer.ts b/src/application/host/IApplicationContainer.ts index 6fd8ee6d..61674254 100644 --- a/src/application/host/IApplicationContainer.ts +++ b/src/application/host/IApplicationContainer.ts @@ -46,6 +46,9 @@ import { IGoalBlockedProjector } from "../context/goals/block/IGoalBlockedProjec import { IGoalUnblockedProjector } from "../context/goals/unblock/IGoalUnblockedProjector.js"; import { IGoalPausedProjector } from "../context/goals/pause/IGoalPausedProjector.js"; import { IGoalPauseReader } from "../context/goals/pause/IGoalPauseReader.js"; +import { IGoalPostponedProjector } from "../context/goals/postpone/IGoalPostponedProjector.js"; +import { IGoalReinstatedProjector } from "../context/goals/reinstate/IGoalReinstatedProjector.js"; +import { IGetGoalViewReader } from "../context/goals/get/IGetGoalViewReader.js"; import { IGoalResumedProjector } from "../context/goals/resume/IGoalResumedProjector.js"; import { IGoalCompletedProjector } from "../context/goals/complete/IGoalCompletedProjector.js"; import { IGoalCompleteReader } from "../context/goals/complete/IGoalCompleteReader.js"; @@ -82,6 +85,8 @@ import { UnblockGoalController } from "../context/goals/unblock/UnblockGoalContr import { GetGoalsController } from "../context/goals/get/GetGoalsController.js"; import { ShowGoalController } from "../context/goals/get/ShowGoalController.js"; import { PauseGoalController } from "../context/goals/pause/PauseGoalController.js"; +import { PostponeGoalController } from "../context/goals/postpone/PostponeGoalController.js"; +import { ReinstateGoalController } from "../context/goals/reinstate/ReinstateGoalController.js"; import { ResumeGoalController } from "../context/goals/resume/ResumeGoalController.js"; import { RemoveGoalController } from "../context/goals/remove/RemoveGoalController.js"; import { UpdateGoalController } from "../context/goals/update/UpdateGoalController.js"; @@ -272,6 +277,10 @@ import { IGoalUnblockedEventWriter } from "../context/goals/unblock/IGoalUnblock import { IGoalUnblockedEventReader } from "../context/goals/unblock/IGoalUnblockedEventReader.js"; import { IGoalPausedEventWriter } from "../context/goals/pause/IGoalPausedEventWriter.js"; import { IGoalPausedEventReader } from "../context/goals/pause/IGoalPausedEventReader.js"; +import { IGoalPostponedEventWriter } from "../context/goals/postpone/IGoalPostponedEventWriter.js"; +import { IGoalPostponedEventReader } from "../context/goals/postpone/IGoalPostponedEventReader.js"; +import { IGoalReinstatedEventWriter } from "../context/goals/reinstate/IGoalReinstatedEventWriter.js"; +import { IGoalReinstatedEventReader } from "../context/goals/reinstate/IGoalReinstatedEventReader.js"; import { IGoalResumedEventWriter } from "../context/goals/resume/IGoalResumedEventWriter.js"; import { IGoalResumedEventReader } from "../context/goals/resume/IGoalResumedEventReader.js"; import { IGoalCompletedEventWriter } from "../context/goals/complete/IGoalCompletedEventWriter.js"; @@ -392,6 +401,8 @@ export interface IApplicationContainer { goalBlockedEventStore: IGoalBlockedEventWriter & IGoalBlockedEventReader; goalUnblockedEventStore: IGoalUnblockedEventWriter & IGoalUnblockedEventReader; goalPausedEventStore: IGoalPausedEventWriter & IGoalPausedEventReader; + goalPostponedEventStore: IGoalPostponedEventWriter & IGoalPostponedEventReader; + goalReinstatedEventStore: IGoalReinstatedEventWriter & IGoalReinstatedEventReader; goalResumedEventStore: IGoalResumedEventWriter & IGoalResumedEventReader; goalCompletedEventStore: IGoalCompletedEventWriter & IGoalCompletedEventReader; goalRefinedEventStore: IGoalRefineEventWriter & IGoalRefineEventReader; @@ -418,6 +429,8 @@ export interface IApplicationContainer { goalBlockedProjector: IGoalBlockedProjector; goalUnblockedProjector: IGoalUnblockedProjector; goalPausedProjector: IGoalPausedProjector & IGoalReader & IGoalPauseReader; + goalPostponedProjector: IGoalPostponedProjector; + goalReinstatedProjector: IGoalReinstatedProjector; goalResumedProjector: IGoalResumedProjector & IGoalReader; goalCompletedProjector: IGoalCompletedProjector & IGoalCompleteReader; goalRefinedProjector: IGoalRefinedProjector & IGoalRefineReader; @@ -430,6 +443,7 @@ export interface IApplicationContainer { goalContextAssembler: IGoalContextAssembler; goalContextQueryHandler: GoalContextQueryHandler; goalBacklogPreviewQueryHandler: GoalBacklogPreviewQueryHandler; + goalViewReader: IGetGoalViewReader; goalStatusReader: IGoalStatusReader; // Session Controllers sessionStartController: SessionStartController; @@ -456,6 +470,8 @@ export interface IApplicationContainer { getGoalsController: GetGoalsController; showGoalController: ShowGoalController; pauseGoalController: PauseGoalController; + postponeGoalController: PostponeGoalController; + reinstateGoalController: ReinstateGoalController; resumeGoalController: ResumeGoalController; refineGoalController: RefineGoalController; removeGoalController: RemoveGoalController; diff --git a/src/domain/goals/Constants.ts b/src/domain/goals/Constants.ts index 7253057c..9343dcf9 100644 --- a/src/domain/goals/Constants.ts +++ b/src/domain/goals/Constants.ts @@ -12,6 +12,8 @@ export const GoalEventType = { BLOCKED: 'GoalBlockedEvent', UNBLOCKED: 'GoalUnblockedEvent', PAUSED: 'GoalPausedEvent', + POSTPONED: 'GoalPostponedEvent', + REINSTATED: 'GoalReinstatedEvent', RESUMED: 'GoalResumedEvent', COMPLETED: 'GoalCompletedEvent', RESET: 'GoalResetEvent', @@ -38,6 +40,7 @@ export const GoalStatus = { DOING: 'doing', BLOCKED: 'blocked', PAUSED: 'paused', + POSTPONED: 'postponed', COMPLETED: 'done', INREVIEW: 'in-review', QUALIFIED: 'approved', @@ -82,6 +85,8 @@ export const GoalErrorMessages = { CANNOT_RESET_BLOCKED: 'Cannot reset a blocked goal. Unblock it first to preserve blocker context.', ALREADY_TODO: 'Goal is already in defined status', CANNOT_PAUSE_IN_STATUS: 'Cannot pause goal in {status} status. Goal must be in doing status.', + CANNOT_POSTPONE_IN_STATUS: 'Cannot postpone goal in {status} status. Goal must be in defined status.', + CANNOT_REINSTATE_IN_STATUS: 'Cannot reinstate goal in {status} status. Goal must be in postponed status.', CANNOT_RESUME_IN_STATUS: 'Cannot resume goal in {status} status. Goal must be paused.', // Embedded context: file path errors FILE_PATH_TOO_LONG: 'File path must be less than {max} characters', @@ -109,7 +114,7 @@ export const GoalLimits = { TITLE_MAX_LENGTH: 60, OBJECTIVE_MAX_LENGTH: 1500, SUCCESS_CRITERION_MAX_LENGTH: 1000, - MAX_SUCCESS_CRITERIA: 50, + MAX_SUCCESS_CRITERIA: 100, SCOPE_ITEM_MAX_LENGTH: 200, MAX_SCOPE_ITEMS: 100, NOTE_MAX_LENGTH: 500, @@ -126,6 +131,7 @@ export const WAITING_STATES: ReadonlySet = new Set([ GoalStatus.SUBMITTED, GoalStatus.QUALIFIED, GoalStatus.PAUSED, + GoalStatus.POSTPONED, GoalStatus.BLOCKED, ] as GoalStatusType[]); diff --git a/src/domain/goals/EventIndex.ts b/src/domain/goals/EventIndex.ts index 2c1c3d2a..65a20d60 100644 --- a/src/domain/goals/EventIndex.ts +++ b/src/domain/goals/EventIndex.ts @@ -4,6 +4,8 @@ export * from "./refine/GoalRefinementStartedEvent.js"; export * from "./block/GoalBlockedEvent.js"; export * from "./complete/GoalCompletedEvent.js"; export * from "./pause/GoalPausedEvent.js"; +export * from "./postpone/GoalPostponedEvent.js"; +export * from "./reinstate/GoalReinstatedEvent.js"; export * from "./remove/GoalRemovedEvent.js"; export * from "./reset/GoalResetEvent.js"; export * from "./resume/GoalResumedEvent.js"; @@ -27,6 +29,8 @@ import { GoalRefinementStartedEvent} from "./refine/GoalRefinementStartedEvent.j import { GoalBlockedEvent} from "./block/GoalBlockedEvent.js"; import { GoalCompletedEvent} from "./complete/GoalCompletedEvent.js"; import { GoalPausedEvent} from "./pause/GoalPausedEvent.js"; +import { GoalPostponedEvent } from "./postpone/GoalPostponedEvent.js"; +import { GoalReinstatedEvent } from "./reinstate/GoalReinstatedEvent.js"; import { GoalRemovedEvent} from "./remove/GoalRemovedEvent.js"; import { GoalResetEvent} from "./reset/GoalResetEvent.js"; import { GoalResumedEvent} from "./resume/GoalResumedEvent.js"; @@ -52,6 +56,8 @@ export type GoalEvent = GoalBlockedEvent | GoalCompletedEvent | GoalPausedEvent | + GoalPostponedEvent | + GoalReinstatedEvent | GoalProgressUpdatedEvent | GoalRemovedEvent | GoalResetEvent | diff --git a/src/domain/goals/Goal.ts b/src/domain/goals/Goal.ts index 576d524a..529bef01 100644 --- a/src/domain/goals/Goal.ts +++ b/src/domain/goals/Goal.ts @@ -2,7 +2,7 @@ import { BaseAggregate, AggregateState } from "../BaseAggregate.js"; import { UUID } from "../BaseEvent.js"; import { GoalId } from "./GoalId.js"; import { ValidationRuleSet } from "../validation/ValidationRule.js"; -import { GoalEvent, GoalAddedEvent, GoalRefinedEvent, GoalStartedEvent, GoalUpdatedEvent, GoalBlockedEvent, GoalUnblockedEvent, GoalCompletedEvent, GoalResetEvent, GoalRemovedEvent, GoalPausedEvent, GoalResumedEvent, GoalProgressUpdatedEvent, GoalSubmittedForReviewEvent, GoalQualifiedEvent, GoalRefinementStartedEvent, GoalCommittedEvent, GoalRejectedEvent, GoalSubmittedEvent, GoalCodifyingStartedEvent, GoalClosedEvent, GoalApprovedEvent, GoalStatusMigratedEvent } from "./EventIndex.js"; +import { GoalEvent, GoalAddedEvent, GoalRefinedEvent, GoalStartedEvent, GoalUpdatedEvent, GoalBlockedEvent, GoalUnblockedEvent, GoalCompletedEvent, GoalResetEvent, GoalRemovedEvent, GoalPausedEvent, GoalPostponedEvent, GoalReinstatedEvent, GoalResumedEvent, GoalProgressUpdatedEvent, GoalSubmittedForReviewEvent, GoalQualifiedEvent, GoalRefinementStartedEvent, GoalCommittedEvent, GoalRejectedEvent, GoalSubmittedEvent, GoalCodifyingStartedEvent, GoalClosedEvent, GoalApprovedEvent, GoalStatusMigratedEvent } from "./EventIndex.js"; import { GoalEventType, GoalStatus, GoalStatusType, WAITING_STATES, IN_PROGRESS_STATES, TERMINAL_STATES, DETERMINISTIC_RESET_TARGETS } from "./Constants.js"; import { GoalPausedReasonsType } from "./GoalPausedReasons.js"; import { OBJECTIVE_RULES } from "./rules/ObjectiveRules.js"; @@ -30,6 +30,8 @@ import { CanRejectRule } from "./rules/CanRejectRule.js"; import { CanSubmitRule } from "./rules/CanSubmitRule.js"; import { CanCodifyRule } from "./rules/CanCodifyRule.js"; import { CanCloseRule } from "./rules/CanCloseRule.js"; +import { CanPostponeRule } from "./rules/CanPostponeRule.js"; +import { CanReinstateRule } from "./rules/CanReinstateRule.js"; // Domain state: business properties + aggregate metadata export interface GoalState extends AggregateState { @@ -178,6 +180,20 @@ export class Goal extends BaseAggregate { break; } + case GoalEventType.POSTPONED: { + const e = event as GoalPostponedEvent; + state.status = e.payload.status; + state.version = e.version; + break; + } + + case GoalEventType.REINSTATED: { + const e = event as GoalReinstatedEvent; + state.status = e.payload.status; + state.version = e.version; + break; + } + case GoalEventType.RESUMED: { const e = event as GoalResumedEvent; state.status = e.payload.status; // 'doing' @@ -686,6 +702,40 @@ export class Goal extends BaseAggregate { ) as GoalPausedEvent; } + /** + * Postpones a defined goal so automatic work selectors ignore it. + * Transitions status from "defined" to "postponed". + * + * @returns GoalPostponedEvent + * @throws Error if the goal is not in 'defined' status + */ + postpone(): GoalPostponedEvent { + ValidationRuleSet.ensure(this.state, [new CanPostponeRule()]); + + return this.makeEvent( + GoalEventType.POSTPONED, + { status: GoalStatus.POSTPONED }, + Goal.apply + ) as GoalPostponedEvent; + } + + /** + * Reinstates a postponed goal so it can enter refinement again. + * Transitions status from "postponed" to "defined". + * + * @returns GoalReinstatedEvent + * @throws Error if the goal is not in 'postponed' status + */ + reinstate(): GoalReinstatedEvent { + ValidationRuleSet.ensure(this.state, [new CanReinstateRule()]); + + return this.makeEvent( + GoalEventType.REINSTATED, + { status: GoalStatus.TODO }, + Goal.apply + ) as GoalReinstatedEvent; + } + /** * Resumes a paused goal. * Transitions status from "paused" to "doing". diff --git a/src/domain/goals/postpone/GoalPostponedEvent.ts b/src/domain/goals/postpone/GoalPostponedEvent.ts new file mode 100644 index 00000000..33d19357 --- /dev/null +++ b/src/domain/goals/postpone/GoalPostponedEvent.ts @@ -0,0 +1,10 @@ +import { BaseEvent } from "../../BaseEvent.js"; +import { GoalEventType, GoalStatusType } from "../Constants.js"; + +/** Emitted when a defined goal is removed from automatic work selection. */ +export interface GoalPostponedEvent extends BaseEvent { + readonly type: typeof GoalEventType.POSTPONED; + readonly payload: { + readonly status: GoalStatusType; + }; +} diff --git a/src/domain/goals/reinstate/GoalReinstatedEvent.ts b/src/domain/goals/reinstate/GoalReinstatedEvent.ts new file mode 100644 index 00000000..a18d3750 --- /dev/null +++ b/src/domain/goals/reinstate/GoalReinstatedEvent.ts @@ -0,0 +1,9 @@ +import { BaseEvent } from "../../BaseEvent.js"; +import { GoalStatusType } from "../Constants.js"; + +/** Emitted when a postponed goal returns to the defined backlog. */ +export interface GoalReinstatedEvent extends BaseEvent { + readonly payload: { + readonly status: GoalStatusType; + }; +} diff --git a/src/domain/goals/rules/CanPostponeRule.ts b/src/domain/goals/rules/CanPostponeRule.ts new file mode 100644 index 00000000..476e6fbf --- /dev/null +++ b/src/domain/goals/rules/CanPostponeRule.ts @@ -0,0 +1,20 @@ +import { ValidationRule, ValidationResult } from "../../validation/ValidationRule.js"; +import { GoalState } from "../Goal.js"; +import { GoalErrorMessages, GoalStatus, formatErrorMessage } from "../Constants.js"; + +/** Allows postponement only while a goal is still defined. */ +export class CanPostponeRule implements ValidationRule { + validate(state: GoalState): ValidationResult { + const isValid = state.status === GoalStatus.TODO; + + return { + isValid, + errors: isValid + ? [] + : [formatErrorMessage( + GoalErrorMessages.CANNOT_POSTPONE_IN_STATUS, + { status: state.status } + )], + }; + } +} diff --git a/src/domain/goals/rules/CanReinstateRule.ts b/src/domain/goals/rules/CanReinstateRule.ts new file mode 100644 index 00000000..2df54a6d --- /dev/null +++ b/src/domain/goals/rules/CanReinstateRule.ts @@ -0,0 +1,20 @@ +import { ValidationRule, ValidationResult } from "../../validation/ValidationRule.js"; +import { GoalState } from "../Goal.js"; +import { GoalErrorMessages, GoalStatus, formatErrorMessage } from "../Constants.js"; + +/** Allows reinstatement only while a goal is postponed. */ +export class CanReinstateRule implements ValidationRule { + validate(state: GoalState): ValidationResult { + const isValid = state.status === GoalStatus.POSTPONED; + + return { + isValid, + errors: isValid + ? [] + : [formatErrorMessage( + GoalErrorMessages.CANNOT_REINSTATE_IN_STATUS, + { status: state.status } + )], + }; + } +} diff --git a/src/infrastructure/context/goals/get/SqliteGetGoalViewReader.ts b/src/infrastructure/context/goals/get/SqliteGetGoalViewReader.ts new file mode 100644 index 00000000..f8da0e06 --- /dev/null +++ b/src/infrastructure/context/goals/get/SqliteGetGoalViewReader.ts @@ -0,0 +1,19 @@ +import { Database } from "better-sqlite3"; +import { IGetGoalViewReader } from "../../../../application/context/goals/get/IGetGoalViewReader.js"; +import { GoalView } from "../../../../application/context/goals/GoalView.js"; +import { GoalRecord } from "../GoalRecord.js"; +import { GoalRecordMapper } from "../GoalRecordMapper.js"; + +export class SqliteGetGoalViewReader implements IGetGoalViewReader { + private readonly mapper = new GoalRecordMapper(); + + constructor(private readonly db: Database) {} + + async findById(goalId: string): Promise { + const row = this.db + .prepare("SELECT *, goalId AS id FROM goal_views WHERE goalId = ?") + .get(goalId) as GoalRecord | undefined; + + return row ? this.mapper.toView(row) : null; + } +} diff --git a/src/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.ts b/src/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.ts new file mode 100644 index 00000000..51a46505 --- /dev/null +++ b/src/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.ts @@ -0,0 +1,13 @@ +import { IGoalPostponedEventReader } from "../../../../application/context/goals/postpone/IGoalPostponedEventReader.js"; +import { IGoalPostponedEventWriter } from "../../../../application/context/goals/postpone/IGoalPostponedEventWriter.js"; +import { ILogger } from "../../../../application/logging/ILogger.js"; +import { FsEventStore } from "../../../persistence/FsEventStore.js"; + +export class FsGoalPostponedEventStore + extends FsEventStore + implements IGoalPostponedEventWriter, IGoalPostponedEventReader +{ + constructor(rootDir: string, logger: ILogger) { + super(rootDir, logger); + } +} diff --git a/src/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.ts b/src/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.ts new file mode 100644 index 00000000..bdf12ffb --- /dev/null +++ b/src/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.ts @@ -0,0 +1,21 @@ +import { Database } from "better-sqlite3"; +import { IGoalPostponedProjector } from "../../../../application/context/goals/postpone/IGoalPostponedProjector.js"; +import { GoalPostponedEvent } from "../../../../domain/goals/postpone/GoalPostponedEvent.js"; + +export class SqliteGoalPostponedProjector implements IGoalPostponedProjector { + constructor(private readonly db: Database) {} + + async applyGoalPostponed(event: GoalPostponedEvent): Promise { + this.db.prepare(` + UPDATE goal_views + SET status = ?, version = ?, updatedAt = ? + WHERE goalId = ? + `).run( + event.payload.status, + event.version, + event.timestamp, + event.aggregateId + ); + } + +} diff --git a/src/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.ts b/src/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.ts new file mode 100644 index 00000000..c95348fa --- /dev/null +++ b/src/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.ts @@ -0,0 +1,13 @@ +import { IGoalReinstatedEventReader } from "../../../../application/context/goals/reinstate/IGoalReinstatedEventReader.js"; +import { IGoalReinstatedEventWriter } from "../../../../application/context/goals/reinstate/IGoalReinstatedEventWriter.js"; +import { ILogger } from "../../../../application/logging/ILogger.js"; +import { FsEventStore } from "../../../persistence/FsEventStore.js"; + +export class FsGoalReinstatedEventStore + extends FsEventStore + implements IGoalReinstatedEventWriter, IGoalReinstatedEventReader +{ + constructor(rootDir: string, logger: ILogger) { + super(rootDir, logger); + } +} diff --git a/src/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.ts b/src/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.ts new file mode 100644 index 00000000..39f7b663 --- /dev/null +++ b/src/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.ts @@ -0,0 +1,20 @@ +import { Database } from "better-sqlite3"; +import { IGoalReinstatedProjector } from "../../../../application/context/goals/reinstate/IGoalReinstatedProjector.js"; +import { GoalReinstatedEvent } from "../../../../domain/goals/reinstate/GoalReinstatedEvent.js"; + +export class SqliteGoalReinstatedProjector implements IGoalReinstatedProjector { + constructor(private readonly db: Database) {} + + async applyGoalReinstated(event: GoalReinstatedEvent): Promise { + this.db.prepare(` + UPDATE goal_views + SET status = ?, version = ?, updatedAt = ? + WHERE goalId = ? + `).run( + event.payload.status, + event.version, + event.timestamp, + event.aggregateId + ); + } +} diff --git a/src/infrastructure/host/HostBuilder.ts b/src/infrastructure/host/HostBuilder.ts index 74c86c00..b9a1a0f0 100644 --- a/src/infrastructure/host/HostBuilder.ts +++ b/src/infrastructure/host/HostBuilder.ts @@ -62,6 +62,8 @@ import { FsGoalUpdatedEventStore } from "../context/goals/update/FsGoalUpdatedEv import { FsGoalBlockedEventStore } from "../context/goals/block/FsGoalBlockedEventStore.js"; import { FsGoalUnblockedEventStore } from "../context/goals/unblock/FsGoalUnblockedEventStore.js"; import { FsGoalPausedEventStore } from "../context/goals/pause/FsGoalPausedEventStore.js"; +import { FsGoalPostponedEventStore } from "../context/goals/postpone/FsGoalPostponedEventStore.js"; +import { FsGoalReinstatedEventStore } from "../context/goals/reinstate/FsGoalReinstatedEventStore.js"; import { FsGoalResumedEventStore } from "../context/goals/resume/FsGoalResumedEventStore.js"; import { FsGoalCompletedEventStore } from "../context/goals/complete/FsGoalCompletedEventStore.js"; import { FsGoalCodifyingStartedEventStore } from "../context/goals/codify/FsGoalCodifyingStartedEventStore.js"; @@ -196,6 +198,8 @@ import { SqliteGoalUpdatedProjector } from "../context/goals/update/SqliteGoalUp import { SqliteGoalBlockedProjector } from "../context/goals/block/SqliteGoalBlockedProjector.js"; import { SqliteGoalUnblockedProjector } from "../context/goals/unblock/SqliteGoalUnblockedProjector.js"; import { SqliteGoalPausedProjector } from "../context/goals/pause/SqliteGoalPausedProjector.js"; +import { SqliteGoalPostponedProjector } from "../context/goals/postpone/SqliteGoalPostponedProjector.js"; +import { SqliteGoalReinstatedProjector } from "../context/goals/reinstate/SqliteGoalReinstatedProjector.js"; import { SqliteGoalResumedProjector } from "../context/goals/resume/SqliteGoalResumedProjector.js"; import { SqliteGoalCompletedProjector } from "../context/goals/complete/SqliteGoalCompletedProjector.js"; import { SqliteGoalRefinedProjector } from "../context/goals/refine/SqliteGoalRefinedProjector.js"; @@ -212,6 +216,7 @@ import { SqliteGoalClosedProjector } from "../context/goals/close/SqliteGoalClos import { SqliteGoalApprovedProjector } from "../context/goals/approve/SqliteGoalApprovedProjector.js"; import { SqliteGoalStatusMigratedProjector } from "../context/goals/migrate/SqliteGoalStatusMigratedProjector.js"; import { SqliteGoalContextAssembler } from "../context/SqliteGoalContextAssembler.js"; +import { SqliteGetGoalViewReader } from "../context/goals/get/SqliteGetGoalViewReader.js"; import { SqliteGoalStatusReader } from "../context/goals/SqliteGoalStatusReader.js"; // Decision Projection Stores - decomposed by use case import { SqliteDecisionAddedProjector } from "../context/decisions/add/SqliteDecisionAddedProjector.js"; @@ -312,6 +317,9 @@ import { GoalUpdatedEventHandler } from "../../application/context/goals/update/ import { GoalBlockedEventHandler } from "../../application/context/goals/block/GoalBlockedEventHandler.js"; import { GoalUnblockedEventHandler } from "../../application/context/goals/unblock/GoalUnblockedEventHandler.js"; import { GoalPausedEventHandler } from "../../application/context/goals/pause/GoalPausedEventHandler.js"; +import { GoalPostponedEventHandler } from "../../application/context/goals/postpone/GoalPostponedEventHandler.js"; +import { GoalReinstatedEventHandler } from "../../application/context/goals/reinstate/GoalReinstatedEventHandler.js"; +import { GoalEventType } from "../../domain/goals/Constants.js"; import { GoalResumedEventHandler } from "../../application/context/goals/resume/GoalResumedEventHandler.js"; import { GoalCompletedEventHandler } from "../../application/context/goals/complete/GoalCompletedEventHandler.js"; import { GoalRefinedEventHandler } from "../../application/context/goals/refine/GoalRefinedEventHandler.js"; @@ -508,6 +516,16 @@ import { PauseGoalCommandHandler } from "../../application/context/goals/pause/P import { LocalPauseGoalGateway } from "../../application/context/goals/pause/LocalPauseGoalGateway.js"; import { PauseGoalController } from "../../application/context/goals/pause/PauseGoalController.js"; +// PostponeGoal Controller-Gateway +import { PostponeGoalCommandHandler } from "../../application/context/goals/postpone/PostponeGoalCommandHandler.js"; +import { LocalPostponeGoalGateway } from "../../application/context/goals/postpone/LocalPostponeGoalGateway.js"; +import { PostponeGoalController } from "../../application/context/goals/postpone/PostponeGoalController.js"; + +// ReinstateGoal Controller-Gateway +import { ReinstateGoalCommandHandler } from "../../application/context/goals/reinstate/ReinstateGoalCommandHandler.js"; +import { LocalReinstateGoalGateway } from "../../application/context/goals/reinstate/LocalReinstateGoalGateway.js"; +import { ReinstateGoalController } from "../../application/context/goals/reinstate/ReinstateGoalController.js"; + // GetGoals Controller-Gateway import { GetGoalsController } from "../../application/context/goals/get/GetGoalsController.js"; import { LocalGetGoalsGateway } from "../../application/context/goals/get/LocalGetGoalsGateway.js"; @@ -721,6 +739,8 @@ export class HostBuilder { const goalBlockedEventStore = new FsGoalBlockedEventStore(this.rootDir, logger); const goalUnblockedEventStore = new FsGoalUnblockedEventStore(this.rootDir, logger); const goalPausedEventStore = new FsGoalPausedEventStore(this.rootDir, logger); + const goalPostponedEventStore = new FsGoalPostponedEventStore(this.rootDir, logger); + const goalReinstatedEventStore = new FsGoalReinstatedEventStore(this.rootDir, logger); const goalResumedEventStore = new FsGoalResumedEventStore(this.rootDir, logger); const goalCompletedEventStore = new FsGoalCompletedEventStore(this.rootDir, logger); const goalRefinedEventStore = new FsGoalRefinedEventStore(this.rootDir, logger); @@ -806,6 +826,8 @@ export class HostBuilder { const goalBlockedProjector = new SqliteGoalBlockedProjector(this.db); const goalUnblockedProjector = new SqliteGoalUnblockedProjector(this.db); const goalPausedProjector = new SqliteGoalPausedProjector(this.db); + const goalPostponedProjector = new SqliteGoalPostponedProjector(this.db); + const goalReinstatedProjector = new SqliteGoalReinstatedProjector(this.db); const goalResumedProjector = new SqliteGoalResumedProjector(this.db); const goalCompletedProjector = new SqliteGoalCompletedProjector(this.db); const goalRefinedProjector = new SqliteGoalRefinedProjector(this.db); @@ -821,6 +843,7 @@ export class HostBuilder { const goalClosedProjector = new SqliteGoalClosedProjector(this.db); const goalApprovedProjector = new SqliteGoalApprovedProjector(this.db); const goalStatusMigratedProjector = new SqliteGoalStatusMigratedProjector(this.db); + const goalViewReader = new SqliteGetGoalViewReader(this.db); const goalStatusReader = new SqliteGoalStatusReader(this.db); // Upgrade command handler @@ -1207,6 +1230,26 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); pauseGoalGateway ); + // PostponeGoal Controller + const postponeGoalCommandHandler = new PostponeGoalCommandHandler( + goalPostponedEventStore, + goalPostponedEventStore, + goalViewReader, + eventBus + ); + const postponeGoalGateway = new LocalPostponeGoalGateway(postponeGoalCommandHandler); + const postponeGoalController = new PostponeGoalController(postponeGoalGateway); + + // ReinstateGoal Controller + const reinstateGoalCommandHandler = new ReinstateGoalCommandHandler( + goalReinstatedEventStore, + goalReinstatedEventStore, + goalViewReader, + eventBus + ); + const reinstateGoalGateway = new LocalReinstateGoalGateway(reinstateGoalCommandHandler); + const reinstateGoalController = new ReinstateGoalController(reinstateGoalGateway); + // RemoveGoal Controller const removeGoalCommandHandler = new RemoveGoalCommandHandler( goalRemovedEventStore, @@ -1865,6 +1908,8 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); const goalBlockedEventHandler = new GoalBlockedEventHandler(goalBlockedProjector); const goalUnblockedEventHandler = new GoalUnblockedEventHandler(goalUnblockedProjector); const goalPausedEventHandler = new GoalPausedEventHandler(goalPausedProjector); + const goalPostponedEventHandler = new GoalPostponedEventHandler(goalPostponedProjector); + const goalReinstatedEventHandler = new GoalReinstatedEventHandler(goalReinstatedProjector); const goalResumedEventHandler = new GoalResumedEventHandler(goalResumedProjector); const goalCompletedEventHandler = new GoalCompletedEventHandler(goalCompletedProjector); const goalRefinedEventHandler = new GoalRefinedEventHandler(goalRefinedProjector); @@ -2001,6 +2046,8 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); eventBus.subscribe("GoalBlockedEvent", goalBlockedEventHandler); eventBus.subscribe("GoalUnblockedEvent", goalUnblockedEventHandler); eventBus.subscribe("GoalPausedEvent", goalPausedEventHandler); + eventBus.subscribe(GoalEventType.POSTPONED, goalPostponedEventHandler); + eventBus.subscribe(GoalEventType.REINSTATED, goalReinstatedEventHandler); eventBus.subscribe("GoalResumedEvent", goalResumedEventHandler); eventBus.subscribe("GoalCompletedEvent", goalCompletedEventHandler); eventBus.subscribe("GoalRefinedEvent", goalRefinedEventHandler); @@ -2137,6 +2184,8 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); goalBlockedEventStore, goalUnblockedEventStore, goalPausedEventStore, + goalPostponedEventStore, + goalReinstatedEventStore, goalResumedEventStore, goalCompletedEventStore, goalRefinedEventStore, @@ -2162,6 +2211,8 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); goalBlockedProjector, goalUnblockedProjector, goalPausedProjector, + goalPostponedProjector, + goalReinstatedProjector, goalResumedProjector, goalCompletedProjector, goalRefinedProjector, @@ -2174,6 +2225,7 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); goalContextAssembler, goalContextQueryHandler, goalBacklogPreviewQueryHandler, + goalViewReader, goalStatusReader, // Session Controllers sessionStartController, @@ -2198,6 +2250,8 @@ const audiencePainContextReader = new SqliteAudiencePainContextReader(this.db); getGoalsController, showGoalController, pauseGoalController, + postponeGoalController, + reinstateGoalController, resumeGoalController, refineGoalController, removeGoalController, diff --git a/src/infrastructure/messaging/ProjectionBusFactory.ts b/src/infrastructure/messaging/ProjectionBusFactory.ts index b4c0f7f2..c54e942a 100644 --- a/src/infrastructure/messaging/ProjectionBusFactory.ts +++ b/src/infrastructure/messaging/ProjectionBusFactory.ts @@ -30,6 +30,8 @@ import { SqliteGoalUpdatedProjector } from "../context/goals/update/SqliteGoalUp import { SqliteGoalBlockedProjector } from "../context/goals/block/SqliteGoalBlockedProjector.js"; import { SqliteGoalUnblockedProjector } from "../context/goals/unblock/SqliteGoalUnblockedProjector.js"; import { SqliteGoalPausedProjector } from "../context/goals/pause/SqliteGoalPausedProjector.js"; +import { SqliteGoalPostponedProjector } from "../context/goals/postpone/SqliteGoalPostponedProjector.js"; +import { SqliteGoalReinstatedProjector } from "../context/goals/reinstate/SqliteGoalReinstatedProjector.js"; import { SqliteGoalResumedProjector } from "../context/goals/resume/SqliteGoalResumedProjector.js"; import { SqliteGoalCompletedProjector } from "../context/goals/complete/SqliteGoalCompletedProjector.js"; import { SqliteGoalRefinedProjector } from "../context/goals/refine/SqliteGoalRefinedProjector.js"; @@ -154,6 +156,8 @@ import type { GoalCommittedEvent } from "../../domain/goals/commit/GoalCommitted import type { GoalCompletedEvent } from "../../domain/goals/complete/GoalCompletedEvent.js"; import type { GoalStatusMigratedEvent } from "../../domain/goals/migrate/GoalStatusMigratedEvent.js"; import type { GoalPausedEvent } from "../../domain/goals/pause/GoalPausedEvent.js"; +import type { GoalPostponedEvent } from "../../domain/goals/postpone/GoalPostponedEvent.js"; +import type { GoalReinstatedEvent } from "../../domain/goals/reinstate/GoalReinstatedEvent.js"; import type { GoalQualifiedEvent } from "../../domain/goals/qualify/GoalQualifiedEvent.js"; import type { GoalRefinedEvent } from "../../domain/goals/refine/GoalRefinedEvent.js"; import type { GoalRefinementStartedEvent } from "../../domain/goals/refine/GoalRefinementStartedEvent.js"; @@ -225,6 +229,8 @@ export class ProjectionBusFactory { const goalBlockedProjector = new SqliteGoalBlockedProjector(db); const goalUnblockedProjector = new SqliteGoalUnblockedProjector(db); const goalPausedProjector = new SqliteGoalPausedProjector(db); + const goalPostponedProjector = new SqliteGoalPostponedProjector(db); + const goalReinstatedProjector = new SqliteGoalReinstatedProjector(db); const goalResumedProjector = new SqliteGoalResumedProjector(db); const goalCompletedProjector = new SqliteGoalCompletedProjector(db); const goalRefinedProjector = new SqliteGoalRefinedProjector(db); @@ -246,6 +252,8 @@ export class ProjectionBusFactory { on(bus, GoalEventType.BLOCKED, (e) => goalBlockedProjector.applyGoalBlocked(e)); on(bus, GoalEventType.UNBLOCKED, (e) => goalUnblockedProjector.applyGoalUnblocked(e)); on(bus, GoalEventType.PAUSED, (e) => goalPausedProjector.applyGoalPaused(e)); + on(bus, GoalEventType.POSTPONED, (e) => goalPostponedProjector.applyGoalPostponed(e)); + on(bus, GoalEventType.REINSTATED, (e) => goalReinstatedProjector.applyGoalReinstated(e)); on(bus, GoalEventType.RESUMED, (e) => goalResumedProjector.applyGoalResumed(e)); on(bus, GoalEventType.COMPLETED, (e) => goalCompletedProjector.applyGoalCompleted(e)); on(bus, GoalEventType.REFINED, (e) => goalRefinedProjector.applyGoalRefined(e)); diff --git a/src/presentation/cli/commands/goals/list/GoalListOutputBuilder.ts b/src/presentation/cli/commands/goals/list/GoalListOutputBuilder.ts index 2fddd786..35b75978 100644 --- a/src/presentation/cli/commands/goals/list/GoalListOutputBuilder.ts +++ b/src/presentation/cli/commands/goals/list/GoalListOutputBuilder.ts @@ -21,7 +21,8 @@ export const STATUS_ORDER: Readonly> = { "in-refinement": 8, "codifying": 9, "refined": 10, - "defined": 11 + "defined": 11, + "postponed": 12 }; /** @@ -39,7 +40,8 @@ const STATUS_HEADINGS: Readonly> = { "in-refinement": "[IN-REFINEMENT]", "codifying": "[CODIFYING]", "refined": "[REFINED]", - "defined": "[DEFINED]" + "defined": "[DEFINED]", + "postponed": "[POSTPONED]" }; /** diff --git a/src/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.ts b/src/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.ts new file mode 100644 index 00000000..9013b44a --- /dev/null +++ b/src/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.ts @@ -0,0 +1,24 @@ +import { PostponeGoalResponse } from "../../../../../application/context/goals/postpone/PostponeGoalResponse.js"; +import { TerminalOutput } from "../../../output/TerminalOutput.js"; +import { TerminalOutputBuilder } from "../../../output/TerminalOutputBuilder.js"; +import { Colors, Symbols } from "../../../rendering/StyleConfig.js"; + +/** Builds human-readable and structured output for goal.postpone. */ +export class GoalPostponeOutputBuilder { + private readonly builder = new TerminalOutputBuilder(); + + buildSuccess(response: PostponeGoalResponse): TerminalOutput { + this.builder.reset(); + this.builder.addPrompt(`${Symbols.check} ${Colors.success(`Goal ${response.status}`)}`); + this.builder.addData({ status: response.status }); + return this.builder.build(); + } + + buildFailureError(error: Error | string): TerminalOutput { + const details = error instanceof Error ? error.message : error; + this.builder.reset(); + this.builder.addPrompt(`${Symbols.cross} ${Colors.error(`Failed to postpone goal: ${details}`)}`); + this.builder.addData({ error: "Failed to postpone goal", details }); + return this.builder.build(); + } +} diff --git a/src/presentation/cli/commands/goals/postpone/goal.postpone.ts b/src/presentation/cli/commands/goals/postpone/goal.postpone.ts new file mode 100644 index 00000000..839f352f --- /dev/null +++ b/src/presentation/cli/commands/goals/postpone/goal.postpone.ts @@ -0,0 +1,54 @@ +import { IApplicationContainer } from "../../../../../application/host/IApplicationContainer.js"; +import { Renderer } from "../../../rendering/Renderer.js"; +import { RenderData } from "../../../rendering/types.js"; +import { CommandMetadata } from "../../registry/CommandMetadata.js"; +import { GoalPostponeOutputBuilder } from "./GoalPostponeOutputBuilder.js"; + +export const metadata: CommandMetadata = { + description: "Postpone a defined goal so automatic work streams skip it", + category: "work", + requiredOptions: [ + { + flags: "-i, --id ", + description: "ID of the defined goal to postpone", + }, + ], + examples: [ + { + command: "jumbo goal postpone --id abc123", + description: "Keep a defined goal visible while excluding it from automatic work streams", + }, + ], + related: ["goals list", "goal refine"], + requiresProject: true, +}; + +export async function goalPostpone( + options: { id: string }, + container: IApplicationContainer +): Promise { + const renderer = Renderer.getInstance(); + const outputBuilder = new GoalPostponeOutputBuilder(); + + try { + const response = await container.postponeGoalController.handle({ goalId: options.id }); + const output = outputBuilder.buildSuccess(response); + + if (renderer.getConfig().format === "text") { + renderer.info(output.toHumanReadable()); + return; + } + + const data = output.getSections().find((section) => section.type === "data")?.content; + if (data) renderer.data(data as RenderData); + } catch (error) { + const output = outputBuilder.buildFailureError(error instanceof Error ? error : String(error)); + if (renderer.getConfig().format === "text") { + renderer.error(output.toHumanReadable()); + } else { + const data = output.getSections().find((section) => section.type === "data")?.content as RenderData; + renderer.error(String(data.error), String(data.details)); + } + process.exit(1); + } +} diff --git a/src/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.ts b/src/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.ts new file mode 100644 index 00000000..f65cb5f5 --- /dev/null +++ b/src/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.ts @@ -0,0 +1,24 @@ +import { ReinstateGoalResponse } from "../../../../../application/context/goals/reinstate/ReinstateGoalResponse.js"; +import { TerminalOutput } from "../../../output/TerminalOutput.js"; +import { TerminalOutputBuilder } from "../../../output/TerminalOutputBuilder.js"; +import { Colors, Symbols } from "../../../rendering/StyleConfig.js"; + +/** Builds human-readable and structured output for goal.reinstate. */ +export class GoalReinstateOutputBuilder { + private readonly builder = new TerminalOutputBuilder(); + + buildSuccess(response: ReinstateGoalResponse): TerminalOutput { + this.builder.reset(); + this.builder.addPrompt(`${Symbols.check} ${Colors.success(`Goal ${response.status}`)}`); + this.builder.addData({ status: response.status }); + return this.builder.build(); + } + + buildFailureError(error: Error | string): TerminalOutput { + const details = error instanceof Error ? error.message : error; + this.builder.reset(); + this.builder.addPrompt(`${Symbols.cross} ${Colors.error(`Failed to reinstate goal: ${details}`)}`); + this.builder.addData({ error: "Failed to reinstate goal", details }); + return this.builder.build(); + } +} diff --git a/src/presentation/cli/commands/goals/reinstate/goal.reinstate.ts b/src/presentation/cli/commands/goals/reinstate/goal.reinstate.ts new file mode 100644 index 00000000..3dfebd97 --- /dev/null +++ b/src/presentation/cli/commands/goals/reinstate/goal.reinstate.ts @@ -0,0 +1,54 @@ +import { IApplicationContainer } from "../../../../../application/host/IApplicationContainer.js"; +import { Renderer } from "../../../rendering/Renderer.js"; +import { RenderData } from "../../../rendering/types.js"; +import { CommandMetadata } from "../../registry/CommandMetadata.js"; +import { GoalReinstateOutputBuilder } from "./GoalReinstateOutputBuilder.js"; + +export const metadata: CommandMetadata = { + description: "Reinstate a postponed goal as defined so it is eligible for refinement", + category: "work", + requiredOptions: [ + { + flags: "-i, --id ", + description: "ID of the postponed goal to reinstate", + }, + ], + examples: [ + { + command: "jumbo goal reinstate --id abc123", + description: "Return a postponed goal to defined status and renewed refinement eligibility", + }, + ], + related: ["goals list", "goal postpone", "goal refine"], + requiresProject: true, +}; + +export async function goalReinstate( + options: { id: string }, + container: IApplicationContainer +): Promise { + const renderer = Renderer.getInstance(); + const outputBuilder = new GoalReinstateOutputBuilder(); + + try { + const response = await container.reinstateGoalController.handle({ goalId: options.id }); + const output = outputBuilder.buildSuccess(response); + + if (renderer.getConfig().format === "text") { + renderer.info(output.toHumanReadable()); + return; + } + + const data = output.getSections().find((section) => section.type === "data")?.content; + if (data) renderer.data(data as RenderData); + } catch (error) { + const output = outputBuilder.buildFailureError(error instanceof Error ? error : String(error)); + if (renderer.getConfig().format === "text") { + renderer.error(output.toHumanReadable()); + } else { + const data = output.getSections().find((section) => section.type === "data")?.content as RenderData; + renderer.error(String(data.error), String(data.details)); + } + process.exit(1); + } +} diff --git a/src/presentation/cli/commands/goals/show/GoalShowOutputBuilder.ts b/src/presentation/cli/commands/goals/show/GoalShowOutputBuilder.ts index 84651099..c6ddafa5 100644 --- a/src/presentation/cli/commands/goals/show/GoalShowOutputBuilder.ts +++ b/src/presentation/cli/commands/goals/show/GoalShowOutputBuilder.ts @@ -12,6 +12,7 @@ const STATUS_DISPLAY: Record str doing: { symbol: Symbols.filledCircle, color: Colors.success, label: "In Progress" }, blocked: { symbol: Symbols.cross, color: Colors.error, label: "Blocked" }, defined: { symbol: Symbols.dot, color: Colors.muted, label: "Planned" }, + postponed: { symbol: Symbols.dot, color: Colors.warning, label: "Postponed" }, done: { symbol: Symbols.check, color: Colors.success, label: "Completed" }, refined: { symbol: Symbols.check, color: Colors.accent, label: "Ready to Start" }, paused: { symbol: Symbols.dot, color: Colors.warning, label: "Paused" }, diff --git a/src/presentation/cli/commands/registry/generated-commands.ts b/src/presentation/cli/commands/registry/generated-commands.ts index 7a8d7d6c..72ec0619 100644 --- a/src/presentation/cli/commands/registry/generated-commands.ts +++ b/src/presentation/cli/commands/registry/generated-commands.ts @@ -50,7 +50,9 @@ import { goalCodify, metadata as goalCodifyMeta } from '../../commands/goals/cod import { goalCommit, metadata as goalCommitMeta } from '../../commands/goals/commit/goal.commit.js'; import { goalsList, metadata as goalsListMeta } from '../../commands/goals/list/goals.list.js'; import { goalPause, metadata as goalPauseMeta } from '../../commands/goals/pause/goal.pause.js'; +import { goalPostpone, metadata as goalPostponeMeta } from '../../commands/goals/postpone/goal.postpone.js'; import { goalRefine, metadata as goalRefineMeta } from '../../commands/goals/refine/goal.refine.js'; +import { goalReinstate, metadata as goalReinstateMeta } from '../../commands/goals/reinstate/goal.reinstate.js'; import { goalReject, metadata as goalRejectMeta } from '../../commands/goals/reject/goal.reject.js'; import { goalRemove, metadata as goalRemoveMeta } from '../../commands/goals/remove/goal.remove.js'; import { goalReset, metadata as goalResetMeta } from '../../commands/goals/reset/goal.reset.js'; @@ -308,11 +310,21 @@ export const commands: RegisteredCommand[] = [ metadata: goalPauseMeta, handler: goalPause }, + { + path: 'goal postpone', + metadata: goalPostponeMeta, + handler: goalPostpone + }, { path: 'goal refine', metadata: goalRefineMeta, handler: goalRefine }, + { + path: 'goal reinstate', + metadata: goalReinstateMeta, + handler: goalReinstate + }, { path: 'goal reject', metadata: goalRejectMeta, diff --git a/src/presentation/tui/goals/GoalsScreen.tsx b/src/presentation/tui/goals/GoalsScreen.tsx index 0975fe22..c870239a 100644 --- a/src/presentation/tui/goals/GoalsScreen.tsx +++ b/src/presentation/tui/goals/GoalsScreen.tsx @@ -109,6 +109,7 @@ interface GoalsScreenProps { const STATUS_COLORS: Record = { [GoalStatus.TODO]: SemanticColors.muted, + [GoalStatus.POSTPONED]: SemanticColors.warning, [GoalStatus.REFINED]: SemanticColors.info, [GoalStatus.DOING]: SemanticColors.success, [GoalStatus.BLOCKED]: SemanticColors.error, diff --git a/src/presentation/tui/goals/GoalsScreenConstants.ts b/src/presentation/tui/goals/GoalsScreenConstants.ts index 6b7340a7..ffa61958 100644 --- a/src/presentation/tui/goals/GoalsScreenConstants.ts +++ b/src/presentation/tui/goals/GoalsScreenConstants.ts @@ -5,6 +5,7 @@ export const GOAL_STATUS_FILTER_ALL = "all"; export const GOAL_STATUS_FILTERS = [ GOAL_STATUS_FILTER_ALL, GoalStatus.TODO, + GoalStatus.POSTPONED, GoalStatus.IN_REFINEMENT, GoalStatus.REFINED, GoalStatus.DOING, diff --git a/src/presentation/tui/navigation/MegaMenuDefinitions.ts b/src/presentation/tui/navigation/MegaMenuDefinitions.ts index 6e3a58a3..d0eb21cc 100644 --- a/src/presentation/tui/navigation/MegaMenuDefinitions.ts +++ b/src/presentation/tui/navigation/MegaMenuDefinitions.ts @@ -36,10 +36,11 @@ const MEGA_MENU_PRESENTATION_KEYS = { } as const; export const MEGA_MENU_GOAL_STATUS_FILTERS = { - backlog: [GoalStatus.TODO, GoalStatus.REFINED], + backlog: [GoalStatus.TODO, GoalStatus.POSTPONED, GoalStatus.REFINED], active: [GoalStatus.DOING, GoalStatus.BLOCKED, GoalStatus.INREVIEW], archive: [GoalStatus.DONE], defined: [GoalStatus.TODO], + postponed: [GoalStatus.POSTPONED], refined: [GoalStatus.REFINED], doing: [GoalStatus.DOING], blocked: [GoalStatus.BLOCKED], @@ -79,6 +80,12 @@ export const MEGA_MENU_SECTIONS: readonly MegaMenuSection[] = [ screenKey: "goals", goalStatusFilter: MEGA_MENU_GOAL_STATUS_FILTERS.refined, }, + { + key: GoalStatus.POSTPONED, + label: "Postponed", + screenKey: "goals", + goalStatusFilter: MEGA_MENU_GOAL_STATUS_FILTERS.postponed, + }, ], }, { diff --git a/tests/application/context/goals/postpone/GoalPostponedEventHandler.test.ts b/tests/application/context/goals/postpone/GoalPostponedEventHandler.test.ts new file mode 100644 index 00000000..10675dda --- /dev/null +++ b/tests/application/context/goals/postpone/GoalPostponedEventHandler.test.ts @@ -0,0 +1,24 @@ +import { jest } from "@jest/globals"; +import { GoalPostponedEventHandler } from "../../../../../src/application/context/goals/postpone/GoalPostponedEventHandler"; +import { IGoalPostponedProjector } from "../../../../../src/application/context/goals/postpone/IGoalPostponedProjector"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalPostponedEvent } from "../../../../../src/domain/goals/postpone/GoalPostponedEvent"; + +describe("GoalPostponedEventHandler", () => { + it("delegates the event to the postponed projector", async () => { + const projector: jest.Mocked = { + applyGoalPostponed: jest.fn().mockResolvedValue(undefined), + }; + const event: GoalPostponedEvent = { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }; + + await new GoalPostponedEventHandler(projector).handle(event); + + expect(projector.applyGoalPostponed).toHaveBeenCalledWith(event); + }); +}); diff --git a/tests/application/context/goals/postpone/LocalPostponeGoalGateway.test.ts b/tests/application/context/goals/postpone/LocalPostponeGoalGateway.test.ts new file mode 100644 index 00000000..e74eead6 --- /dev/null +++ b/tests/application/context/goals/postpone/LocalPostponeGoalGateway.test.ts @@ -0,0 +1,19 @@ +import { jest } from "@jest/globals"; +import { LocalPostponeGoalGateway } from "../../../../../src/application/context/goals/postpone/LocalPostponeGoalGateway"; +import { PostponeGoalCommandHandler } from "../../../../../src/application/context/goals/postpone/PostponeGoalCommandHandler"; +import { GoalStatus } from "../../../../../src/domain/goals/Constants"; + +describe("LocalPostponeGoalGateway", () => { + it("executes the command and exposes only operation status", async () => { + const commandHandler: jest.Mocked> = { + execute: jest.fn().mockResolvedValue({ status: GoalStatus.POSTPONED }), + }; + const gateway = new LocalPostponeGoalGateway(commandHandler as PostponeGoalCommandHandler); + + const response = await gateway.postponeGoal({ goalId: "goal_123" }); + + expect(commandHandler.execute).toHaveBeenCalledWith({ goalId: "goal_123" }); + expect(response).toEqual({ status: GoalStatus.POSTPONED }); + expect(Object.keys(response)).toEqual(["status"]); + }); +}); diff --git a/tests/application/context/goals/postpone/PostponeGoalCommandHandler.test.ts b/tests/application/context/goals/postpone/PostponeGoalCommandHandler.test.ts new file mode 100644 index 00000000..1e7233bd --- /dev/null +++ b/tests/application/context/goals/postpone/PostponeGoalCommandHandler.test.ts @@ -0,0 +1,94 @@ +import { jest } from "@jest/globals"; +import { IGetGoalViewReader } from "../../../../../src/application/context/goals/get/IGetGoalViewReader"; +import { IGoalPostponedEventReader } from "../../../../../src/application/context/goals/postpone/IGoalPostponedEventReader"; +import { IGoalPostponedEventWriter } from "../../../../../src/application/context/goals/postpone/IGoalPostponedEventWriter"; +import { PostponeGoalCommandHandler } from "../../../../../src/application/context/goals/postpone/PostponeGoalCommandHandler"; +import { IEventBus } from "../../../../../src/application/messaging/IEventBus"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; + +const addedEvent = { + type: GoalEventType.ADDED, + aggregateId: "goal_123", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Later work", + objective: "Keep this visible", + successCriteria: ["Postponed"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, +} as const; + +describe("PostponeGoalCommandHandler", () => { + let eventWriter: jest.Mocked; + let eventReader: jest.Mocked; + let goalReader: jest.Mocked; + let eventBus: jest.Mocked; + let handler: PostponeGoalCommandHandler; + + beforeEach(() => { + eventWriter = { append: jest.fn().mockResolvedValue({ nextSeq: 2 }) }; + eventReader = { readStream: jest.fn().mockResolvedValue([addedEvent]) }; + goalReader = { + findById: jest.fn().mockResolvedValue({ + goalId: "goal_123", + title: "Later work", + objective: "Keep this visible", + successCriteria: ["Postponed"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + version: 1, + createdAt: addedEvent.timestamp, + updatedAt: addedEvent.timestamp, + progress: [], + }), + }; + eventBus = { + subscribe: jest.fn(), + publish: jest.fn().mockResolvedValue(undefined), + }; + handler = new PostponeGoalCommandHandler(eventWriter, eventReader, goalReader, eventBus); + }); + + it("rehydrates, persists, and publishes GoalPostponedEvent", async () => { + await expect(handler.execute({ goalId: "goal_123" })).resolves.toEqual({ status: GoalStatus.POSTPONED }); + + const event = eventWriter.append.mock.calls[0][0]; + expect(event).toEqual(expect.objectContaining({ + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + payload: { status: GoalStatus.POSTPONED }, + })); + expect(eventBus.publish).toHaveBeenCalledWith(event); + }); + + it("rejects a missing goal without reading or writing events", async () => { + goalReader.findById.mockResolvedValue(null); + + await expect(handler.execute({ goalId: "missing" })).rejects.toThrow("Goal not found: missing"); + expect(eventReader.readStream).not.toHaveBeenCalled(); + expect(eventWriter.append).not.toHaveBeenCalled(); + }); + + it("propagates the domain rejection for a non-defined source state", async () => { + eventReader.readStream.mockResolvedValue([ + addedEvent, + { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }, + ]); + + await expect(handler.execute({ goalId: "goal_123" })).rejects.toThrow( + "Cannot postpone goal in postponed status. Goal must be in defined status." + ); + expect(eventWriter.append).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/application/context/goals/postpone/PostponeGoalController.test.ts b/tests/application/context/goals/postpone/PostponeGoalController.test.ts new file mode 100644 index 00000000..14722605 --- /dev/null +++ b/tests/application/context/goals/postpone/PostponeGoalController.test.ts @@ -0,0 +1,15 @@ +import { jest } from "@jest/globals"; +import { IPostponeGoalGateway } from "../../../../../src/application/context/goals/postpone/IPostponeGoalGateway"; +import { PostponeGoalController } from "../../../../../src/application/context/goals/postpone/PostponeGoalController"; + +describe("PostponeGoalController", () => { + it("delegates the typed request and returns the gateway response", async () => { + const gateway: jest.Mocked = { + postponeGoal: jest.fn().mockResolvedValue({ status: "postponed" }), + }; + const controller = new PostponeGoalController(gateway); + + await expect(controller.handle({ goalId: "goal_123" })).resolves.toEqual({ status: "postponed" }); + expect(gateway.postponeGoal).toHaveBeenCalledWith({ goalId: "goal_123" }); + }); +}); diff --git a/tests/application/context/goals/query/GoalBacklogPreviewQueryHandler.test.ts b/tests/application/context/goals/query/GoalBacklogPreviewQueryHandler.test.ts index 996bf21b..2b5820e8 100644 --- a/tests/application/context/goals/query/GoalBacklogPreviewQueryHandler.test.ts +++ b/tests/application/context/goals/query/GoalBacklogPreviewQueryHandler.test.ts @@ -92,6 +92,7 @@ describe("GoalBacklogPreviewQueryHandler", () => { const reader: jest.Mocked = { findAll: jest.fn().mockResolvedValue([ goal("paused", GoalStatus.PAUSED, "2026-01-01T00:00:00.000Z"), + goal("postponed", GoalStatus.POSTPONED, "2026-01-01T00:00:00.000Z"), goal("submitted", GoalStatus.SUBMITTED, "2026-01-01T00:00:00.000Z"), goal("unblocked", GoalStatus.UNBLOCKED, "2026-01-01T00:00:00.000Z"), goal("done", GoalStatus.DONE, "2026-01-01T00:00:00.000Z"), diff --git a/tests/application/context/goals/refine/RefinerProcessManager.test.ts b/tests/application/context/goals/refine/RefinerProcessManager.test.ts index b5d0e09f..5b7909f7 100644 --- a/tests/application/context/goals/refine/RefinerProcessManager.test.ts +++ b/tests/application/context/goals/refine/RefinerProcessManager.test.ts @@ -54,6 +54,24 @@ describe("RefinerProcessManager", () => { })); }); + it("selects only defined goals and never queries the postponed status", async () => { + const manager = new RefinerProcessManager( + goalStatusReader, + goalReader, + claimPolicy as unknown as GoalClaimPolicy, + { workerId: "worker_1" }, + refineGoalController as unknown as RefineGoalController, + agentGateway, + telemetryClient, + ); + + await manager.selectEligibleGoals(); + + expect(goalStatusReader.findByStatus).toHaveBeenCalledTimes(1); + expect(goalStatusReader.findByStatus).toHaveBeenCalledWith(GoalStatus.TODO); + expect(goalStatusReader.findByStatus).not.toHaveBeenCalledWith(GoalStatus.POSTPONED); + }); + it("emits a structured foraging event when no goals are eligible", async () => { goalStatusReader.findByStatus.mockResolvedValue([]); const events: unknown[] = []; diff --git a/tests/application/context/goals/reinstate/GoalReinstatedEventHandler.test.ts b/tests/application/context/goals/reinstate/GoalReinstatedEventHandler.test.ts new file mode 100644 index 00000000..11e288ab --- /dev/null +++ b/tests/application/context/goals/reinstate/GoalReinstatedEventHandler.test.ts @@ -0,0 +1,24 @@ +import { jest } from "@jest/globals"; +import { GoalReinstatedEventHandler } from "../../../../../src/application/context/goals/reinstate/GoalReinstatedEventHandler"; +import { IGoalReinstatedProjector } from "../../../../../src/application/context/goals/reinstate/IGoalReinstatedProjector"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalReinstatedEvent } from "../../../../../src/domain/goals/reinstate/GoalReinstatedEvent"; + +describe("GoalReinstatedEventHandler", () => { + it("delegates the event to the reinstated projector", async () => { + const projector: jest.Mocked = { + applyGoalReinstated: jest.fn().mockResolvedValue(undefined), + }; + const event: GoalReinstatedEvent = { + type: GoalEventType.REINSTATED, + aggregateId: "goal_123", + version: 3, + timestamp: "2026-09-11T11:00:00.000Z", + payload: { status: GoalStatus.TODO }, + }; + + await new GoalReinstatedEventHandler(projector).handle(event); + + expect(projector.applyGoalReinstated).toHaveBeenCalledWith(event); + }); +}); diff --git a/tests/application/context/goals/reinstate/LocalReinstateGoalGateway.test.ts b/tests/application/context/goals/reinstate/LocalReinstateGoalGateway.test.ts new file mode 100644 index 00000000..dca40030 --- /dev/null +++ b/tests/application/context/goals/reinstate/LocalReinstateGoalGateway.test.ts @@ -0,0 +1,19 @@ +import { jest } from "@jest/globals"; +import { LocalReinstateGoalGateway } from "../../../../../src/application/context/goals/reinstate/LocalReinstateGoalGateway"; +import { ReinstateGoalCommandHandler } from "../../../../../src/application/context/goals/reinstate/ReinstateGoalCommandHandler"; +import { GoalStatus } from "../../../../../src/domain/goals/Constants"; + +describe("LocalReinstateGoalGateway", () => { + it("executes the command and exposes only operation status", async () => { + const commandHandler: jest.Mocked> = { + execute: jest.fn().mockResolvedValue({ status: GoalStatus.TODO }), + }; + const gateway = new LocalReinstateGoalGateway(commandHandler as ReinstateGoalCommandHandler); + + const response = await gateway.reinstateGoal({ goalId: "goal_123" }); + + expect(commandHandler.execute).toHaveBeenCalledWith({ goalId: "goal_123" }); + expect(response).toEqual({ status: GoalStatus.TODO }); + expect(Object.keys(response)).toEqual(["status"]); + }); +}); diff --git a/tests/application/context/goals/reinstate/RefineGoalCommandHandlerPostponed.test.ts b/tests/application/context/goals/reinstate/RefineGoalCommandHandlerPostponed.test.ts new file mode 100644 index 00000000..051b44a1 --- /dev/null +++ b/tests/application/context/goals/reinstate/RefineGoalCommandHandlerPostponed.test.ts @@ -0,0 +1,73 @@ +import { jest } from "@jest/globals"; +import { RefineGoalCommandHandler } from "../../../../../src/application/context/goals/refine/RefineGoalCommandHandler"; +import { GoalClaimPolicy } from "../../../../../src/application/context/goals/claims/GoalClaimPolicy"; +import { GoalContextQueryHandler } from "../../../../../src/application/context/goals/get/GoalContextQueryHandler"; +import { IWorkerIdentityReader } from "../../../../../src/application/host/workers/IWorkerIdentityReader"; +import { ISettingsReader } from "../../../../../src/application/settings/ISettingsReader"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; + +describe("RefineGoalCommandHandler postponed safeguard", () => { + it("rejects a postponed goal when the handler is invoked directly", async () => { + const eventWriter = { append: jest.fn().mockResolvedValue({ nextSeq: 3 }) }; + const eventReader = { + readStream: jest.fn().mockResolvedValue([ + { + type: GoalEventType.ADDED, + aggregateId: "goal_123", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Later work", + objective: "Keep this visible", + successCriteria: ["Excluded from refinement"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, + }, + { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }, + ]), + }; + const goalReader = { findById: jest.fn().mockResolvedValue({ goalId: "goal_123", status: GoalStatus.POSTPONED }) }; + const eventBus = { subscribe: jest.fn(), publish: jest.fn().mockResolvedValue(undefined) }; + const claimPolicy = { + prepareEntryClaim: jest.fn().mockReturnValue({ + allowed: true, + claim: { + goalId: "goal_123", + claimedBy: "worker_test", + claimedAt: "2026-09-11T10:30:00.000Z", + claimExpiresAt: "2026-09-11T11:30:00.000Z", + }, + }), + storeClaim: jest.fn(), + }; + const settingsReader = { + read: jest.fn().mockResolvedValue({ claims: { claimDurationMinutes: 60 } }), + }; + const goalContextQueryHandler = { execute: jest.fn() }; + const handler = new RefineGoalCommandHandler( + eventWriter, + eventReader, + goalReader, + eventBus, + claimPolicy as unknown as GoalClaimPolicy, + { workerId: "worker_test" } as IWorkerIdentityReader, + settingsReader as unknown as ISettingsReader, + goalContextQueryHandler as unknown as GoalContextQueryHandler + ); + + await expect(handler.execute({ goalId: "goal_123" })).rejects.toThrow( + "Cannot refine goal in postponed status. Goal must be in defined status." + ); + expect(eventWriter.append).not.toHaveBeenCalled(); + expect(claimPolicy.storeClaim).not.toHaveBeenCalled(); + expect(eventBus.publish).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/application/context/goals/reinstate/ReinstateGoalCommandHandler.test.ts b/tests/application/context/goals/reinstate/ReinstateGoalCommandHandler.test.ts new file mode 100644 index 00000000..edcb7c79 --- /dev/null +++ b/tests/application/context/goals/reinstate/ReinstateGoalCommandHandler.test.ts @@ -0,0 +1,94 @@ +import { jest } from "@jest/globals"; +import { IGetGoalViewReader } from "../../../../../src/application/context/goals/get/IGetGoalViewReader"; +import { IGoalReinstatedEventReader } from "../../../../../src/application/context/goals/reinstate/IGoalReinstatedEventReader"; +import { IGoalReinstatedEventWriter } from "../../../../../src/application/context/goals/reinstate/IGoalReinstatedEventWriter"; +import { ReinstateGoalCommandHandler } from "../../../../../src/application/context/goals/reinstate/ReinstateGoalCommandHandler"; +import { IEventBus } from "../../../../../src/application/messaging/IEventBus"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; + +const addedEvent = { + type: GoalEventType.ADDED, + aggregateId: "goal_123", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Later work", + objective: "Keep this visible", + successCriteria: ["Reinstated"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, +} as const; + +const postponedEvent = { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, +} as const; + +describe("ReinstateGoalCommandHandler", () => { + let eventWriter: jest.Mocked; + let eventReader: jest.Mocked; + let goalReader: jest.Mocked; + let eventBus: jest.Mocked; + let handler: ReinstateGoalCommandHandler; + + beforeEach(() => { + eventWriter = { append: jest.fn().mockResolvedValue({ nextSeq: 3 }) }; + eventReader = { readStream: jest.fn().mockResolvedValue([addedEvent, postponedEvent]) }; + goalReader = { + findById: jest.fn().mockResolvedValue({ + goalId: "goal_123", + title: "Later work", + objective: "Keep this visible", + successCriteria: ["Reinstated"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.POSTPONED, + version: 2, + createdAt: addedEvent.timestamp, + updatedAt: postponedEvent.timestamp, + progress: [], + }), + }; + eventBus = { + subscribe: jest.fn(), + publish: jest.fn().mockResolvedValue(undefined), + }; + handler = new ReinstateGoalCommandHandler(eventWriter, eventReader, goalReader, eventBus); + }); + + it("rehydrates, persists, and publishes GoalReinstatedEvent", async () => { + await expect(handler.execute({ goalId: "goal_123" })).resolves.toEqual({ status: GoalStatus.TODO }); + + const event = eventWriter.append.mock.calls[0][0]; + expect(event).toEqual(expect.objectContaining({ + type: GoalEventType.REINSTATED, + aggregateId: "goal_123", + version: 3, + payload: { status: GoalStatus.TODO }, + })); + expect(eventBus.publish).toHaveBeenCalledWith(event); + }); + + it("rejects a missing goal without reading or writing events", async () => { + goalReader.findById.mockResolvedValue(null); + + await expect(handler.execute({ goalId: "missing" })).rejects.toThrow("Goal not found: missing"); + expect(eventReader.readStream).not.toHaveBeenCalled(); + expect(eventWriter.append).not.toHaveBeenCalled(); + }); + + it("propagates the domain rejection for a non-postponed source state", async () => { + eventReader.readStream.mockResolvedValue([addedEvent]); + + await expect(handler.execute({ goalId: "goal_123" })).rejects.toThrow( + "Cannot reinstate goal in defined status. Goal must be in postponed status." + ); + expect(eventWriter.append).not.toHaveBeenCalled(); + expect(eventBus.publish).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/application/context/goals/reinstate/ReinstateGoalController.test.ts b/tests/application/context/goals/reinstate/ReinstateGoalController.test.ts new file mode 100644 index 00000000..6f260d97 --- /dev/null +++ b/tests/application/context/goals/reinstate/ReinstateGoalController.test.ts @@ -0,0 +1,15 @@ +import { jest } from "@jest/globals"; +import { IReinstateGoalGateway } from "../../../../../src/application/context/goals/reinstate/IReinstateGoalGateway"; +import { ReinstateGoalController } from "../../../../../src/application/context/goals/reinstate/ReinstateGoalController"; + +describe("ReinstateGoalController", () => { + it("delegates the typed request and returns the gateway response", async () => { + const gateway: jest.Mocked = { + reinstateGoal: jest.fn().mockResolvedValue({ status: "defined" }), + }; + const controller = new ReinstateGoalController(gateway); + + await expect(controller.handle({ goalId: "goal_123" })).resolves.toEqual({ status: "defined" }); + expect(gateway.reinstateGoal).toHaveBeenCalledWith({ goalId: "goal_123" }); + }); +}); diff --git a/tests/domain/goals/Goal.test.ts b/tests/domain/goals/Goal.test.ts index 9534866b..e6b55e88 100644 --- a/tests/domain/goals/Goal.test.ts +++ b/tests/domain/goals/Goal.test.ts @@ -152,11 +152,14 @@ describe("Goal Aggregate", () => { it("should throw error if too many success criteria", () => { // Arrange const goal = Goal.create("goal_123"); - const tooManyCriteria = Array.from({ length: 51 }, (_, i) => `Criterion ${i}`); + const tooManyCriteria = Array.from( + { length: GoalLimits.MAX_SUCCESS_CRITERIA + 1 }, + (_, i) => `Criterion ${i}` + ); // Act & Assert expect(() => goal.add("Test goal", "My objective", tooManyCriteria)).toThrow( - "Cannot have more than 50 success criteria" + `Cannot have more than ${GoalLimits.MAX_SUCCESS_CRITERIA} success criteria` ); }); @@ -594,11 +597,14 @@ describe("Goal Aggregate", () => { // Arrange const goal = Goal.create("goal_123"); goal.add("Original goal", "Original objective", ["Criterion 1"]); - const tooManyCriteria = Array.from({ length: 51 }, (_, i) => `Criterion ${i}`); + const tooManyCriteria = Array.from( + { length: GoalLimits.MAX_SUCCESS_CRITERIA + 1 }, + (_, i) => `Criterion ${i}` + ); // Act & Assert expect(() => goal.update(undefined, undefined, tooManyCriteria)).toThrow( - "Cannot have more than 50 success criteria" + `Cannot have more than ${GoalLimits.MAX_SUCCESS_CRITERIA} success criteria` ); }); diff --git a/tests/domain/goals/reinstate/CanReinstateRule.test.ts b/tests/domain/goals/reinstate/CanReinstateRule.test.ts new file mode 100644 index 00000000..2bd4ce72 --- /dev/null +++ b/tests/domain/goals/reinstate/CanReinstateRule.test.ts @@ -0,0 +1,41 @@ +import { GoalState } from "../../../../src/domain/goals/Goal"; +import { + GoalErrorMessages, + GoalStatus, + GoalStatusType, + formatErrorMessage, +} from "../../../../src/domain/goals/Constants"; +import { CanReinstateRule } from "../../../../src/domain/goals/rules/CanReinstateRule"; + +function state(status: GoalStatusType): GoalState { + return { + id: "goal_test", + title: "Test", + objective: "Test reinstatement", + successCriteria: ["It works"], + scopeIn: [], + scopeOut: [], + status, + version: 2, + progress: [], + }; +} + +describe("CanReinstateRule", () => { + it("allows a postponed goal", () => { + expect(new CanReinstateRule().validate(state(GoalStatus.POSTPONED))).toEqual({ + isValid: true, + errors: [], + }); + }); + + it.each([...new Set(Object.values(GoalStatus))].filter((status) => status !== GoalStatus.POSTPONED))( + "rejects %s with the constant-backed domain error", + (status) => { + expect(new CanReinstateRule().validate(state(status))).toEqual({ + isValid: false, + errors: [formatErrorMessage(GoalErrorMessages.CANNOT_REINSTATE_IN_STATUS, { status })], + }); + } + ); +}); diff --git a/tests/domain/goals/reinstate/Goal.reinstate.test.ts b/tests/domain/goals/reinstate/Goal.reinstate.test.ts new file mode 100644 index 00000000..1b27176b --- /dev/null +++ b/tests/domain/goals/reinstate/Goal.reinstate.test.ts @@ -0,0 +1,72 @@ +import { Goal } from "../../../../src/domain/goals/Goal"; +import { GoalId } from "../../../../src/domain/goals/GoalId"; +import { GoalEvent } from "../../../../src/domain/goals/EventIndex"; +import { GoalEventType, GoalStatus } from "../../../../src/domain/goals/Constants"; + +describe("Goal.reinstate", () => { + it("emits and applies GoalReinstatedEvent from postponed", () => { + const goal = Goal.create(GoalId.fromLegacy("goal_test")); + goal.add("Test goal", "Test reinstatement", ["It works"]); + goal.postpone(); + + const event = goal.reinstate(); + + expect(event).toEqual(expect.objectContaining({ + type: GoalEventType.REINSTATED, + aggregateId: "goal_test", + version: 3, + payload: { status: GoalStatus.TODO }, + })); + expect(goal.snapshot.status).toBe(GoalStatus.TODO); + expect(goal.snapshot.version).toBe(3); + }); + + it("rejects a repeated reinstatement", () => { + const goal = Goal.create(GoalId.fromLegacy("goal_test")); + goal.add("Test goal", "Test reinstatement", ["It works"]); + goal.postpone(); + goal.reinstate(); + + expect(() => goal.reinstate()).toThrow( + "Cannot reinstate goal in defined status. Goal must be in postponed status." + ); + }); + + it.each([...new Set(Object.values(GoalStatus))].filter((status) => status !== GoalStatus.POSTPONED))( + "rejects reinstatement from %s", + (status) => { + const goal = Goal.rehydrate("goal_test", [ + { + type: GoalEventType.ADDED, + aggregateId: "goal_test", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Test goal", + objective: "Test reinstatement", + successCriteria: ["It works"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, + }, + { + type: GoalEventType.STATUS_MIGRATED, + aggregateId: "goal_test", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { + fromStatus: GoalStatus.TODO, + toStatus: status, + status, + migratedAt: "2026-09-11T10:00:00.000Z", + }, + }, + ] as GoalEvent[]); + + expect(() => goal.reinstate()).toThrow( + `Cannot reinstate goal in ${status} status. Goal must be in postponed status.` + ); + } + ); +}); diff --git a/tests/domain/goals/rules/StateTransitionRules.test.ts b/tests/domain/goals/rules/StateTransitionRules.test.ts index 70ca0a66..58ecb514 100644 --- a/tests/domain/goals/rules/StateTransitionRules.test.ts +++ b/tests/domain/goals/rules/StateTransitionRules.test.ts @@ -85,6 +85,16 @@ describe("StateTransitionRules", () => { expect(result.errors[0]).toContain("Cannot refine goal in doing status"); }); + it("should fail when status is postponed", () => { + const rule = new CanRefineRule(); + const state = createGoalState({ status: GoalStatus.POSTPONED }); + const result = rule.validate(state); + expect(result.isValid).toBe(false); + expect(result.errors).toContain( + "Cannot refine goal in postponed status. Goal must be in defined status." + ); + }); + it("should fail when status is completed", () => { const rule = new CanRefineRule(); const state = createGoalState({ status: GoalStatus.COMPLETED }); diff --git a/tests/domain/work/goals/Goal.apply.test.ts b/tests/domain/work/goals/Goal.apply.test.ts index 105ae6d5..45c6624d 100644 --- a/tests/domain/work/goals/Goal.apply.test.ts +++ b/tests/domain/work/goals/Goal.apply.test.ts @@ -4,7 +4,7 @@ */ import { Goal, GoalState } from "../../../../src/domain/goals/Goal"; -import { GoalAddedEvent, GoalRefinedEvent, GoalStartedEvent, GoalCompletedEvent, GoalPausedEvent, GoalResumedEvent, GoalSubmittedForReviewEvent, GoalQualifiedEvent } from "../../../../src/domain/goals/EventIndex"; +import { GoalAddedEvent, GoalRefinedEvent, GoalStartedEvent, GoalCompletedEvent, GoalPausedEvent, GoalPostponedEvent, GoalReinstatedEvent, GoalResumedEvent, GoalSubmittedForReviewEvent, GoalQualifiedEvent } from "../../../../src/domain/goals/EventIndex"; import { GoalEventType, GoalStatus } from "../../../../src/domain/goals/Constants"; function createEmptyGoalState(id: string): GoalState { @@ -327,6 +327,53 @@ describe("Goal", () => { }); }); + describe("apply() - GoalPostponedEvent", () => { + it("applies postponed status and version without changing goal details", () => { + const state = createEmptyGoalState("goal_123"); + state.title = "Later work"; + state.objective = "Keep visible without automatic selection"; + state.version = 1; + const event: GoalPostponedEvent = { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }; + + Goal.apply(state, event); + + expect(state.status).toBe(GoalStatus.POSTPONED); + expect(state.version).toBe(2); + expect(state.title).toBe("Later work"); + expect(state.objective).toBe("Keep visible without automatic selection"); + }); + }); + + describe("apply() - GoalReinstatedEvent", () => { + it("applies defined status and version without changing goal details", () => { + const state = createEmptyGoalState("goal_123"); + state.title = "Later work"; + state.objective = "Return to refinement"; + state.status = GoalStatus.POSTPONED; + state.version = 2; + const event: GoalReinstatedEvent = { + type: GoalEventType.REINSTATED, + aggregateId: "goal_123", + version: 3, + timestamp: "2026-09-11T11:00:00.000Z", + payload: { status: GoalStatus.TODO }, + }; + + Goal.apply(state, event); + + expect(state.status).toBe(GoalStatus.TODO); + expect(state.version).toBe(3); + expect(state.title).toBe("Later work"); + expect(state.objective).toBe("Return to refinement"); + }); + }); + describe("apply() - GoalResumedEvent", () => { it("should apply GoalResumedEvent event correctly", () => { // Arrange diff --git a/tests/domain/work/goals/postpone/CanPostponeRule.test.ts b/tests/domain/work/goals/postpone/CanPostponeRule.test.ts new file mode 100644 index 00000000..86b45e0c --- /dev/null +++ b/tests/domain/work/goals/postpone/CanPostponeRule.test.ts @@ -0,0 +1,46 @@ +import { GoalState } from "../../../../../src/domain/goals/Goal"; +import { + GoalErrorMessages, + GoalStatus, + GoalStatusType, + WAITING_STATES, + formatErrorMessage, +} from "../../../../../src/domain/goals/Constants"; +import { CanPostponeRule } from "../../../../../src/domain/goals/rules/CanPostponeRule"; + +function state(status: GoalStatusType): GoalState { + return { + id: "goal_test", + title: "Test", + objective: "Test postponement", + successCriteria: ["It works"], + scopeIn: [], + scopeOut: [], + status, + version: 1, + progress: [], + }; +} + +describe("CanPostponeRule", () => { + it("allows a defined goal", () => { + expect(new CanPostponeRule().validate(state(GoalStatus.TODO))).toEqual({ + isValid: true, + errors: [], + }); + }); + + it.each([...new Set(Object.values(GoalStatus))].filter((status) => status !== GoalStatus.TODO))( + "rejects %s with the constant-backed domain error", + (status) => { + expect(new CanPostponeRule().validate(state(status))).toEqual({ + isValid: false, + errors: [formatErrorMessage(GoalErrorMessages.CANNOT_POSTPONE_IN_STATUS, { status })], + }); + } + ); + + it("classifies postponed as a waiting state", () => { + expect(WAITING_STATES.has(GoalStatus.POSTPONED)).toBe(true); + }); +}); diff --git a/tests/domain/work/goals/postpone/Goal.postpone.test.ts b/tests/domain/work/goals/postpone/Goal.postpone.test.ts new file mode 100644 index 00000000..93262f78 --- /dev/null +++ b/tests/domain/work/goals/postpone/Goal.postpone.test.ts @@ -0,0 +1,70 @@ +import { Goal } from "../../../../../src/domain/goals/Goal"; +import { GoalId } from "../../../../../src/domain/goals/GoalId"; +import { GoalEvent } from "../../../../../src/domain/goals/EventIndex"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; + +describe("Goal.postpone", () => { + it("emits and applies GoalPostponedEvent from defined", () => { + const goal = Goal.create(GoalId.fromLegacy("goal_test")); + goal.add("Test goal", "Test postponement", ["It works"]); + + const event = goal.postpone(); + + expect(event).toEqual(expect.objectContaining({ + type: GoalEventType.POSTPONED, + aggregateId: "goal_test", + version: 2, + payload: { status: GoalStatus.POSTPONED }, + })); + expect(goal.snapshot.status).toBe(GoalStatus.POSTPONED); + expect(goal.snapshot.version).toBe(2); + }); + + it("rejects a repeated postponement", () => { + const goal = Goal.create(GoalId.fromLegacy("goal_test")); + goal.add("Test goal", "Test postponement", ["It works"]); + goal.postpone(); + + expect(() => goal.postpone()).toThrow( + "Cannot postpone goal in postponed status. Goal must be in defined status." + ); + }); + + it.each([...new Set(Object.values(GoalStatus))].filter((status) => status !== GoalStatus.TODO))( + "rejects postponement from %s", + (status) => { + const goal = Goal.rehydrate("goal_test", [ + { + type: GoalEventType.ADDED, + aggregateId: "goal_test", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Test goal", + objective: "Test postponement", + successCriteria: ["It works"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, + }, + { + type: GoalEventType.STATUS_MIGRATED, + aggregateId: "goal_test", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { + fromStatus: GoalStatus.TODO, + toStatus: status, + status, + migratedAt: "2026-09-11T10:00:00.000Z", + }, + }, + ] as GoalEvent[]); + + expect(() => goal.postpone()).toThrow( + `Cannot postpone goal in ${status} status. Goal must be in defined status.` + ); + } + ); +}); diff --git a/tests/infrastructure/context/goals/get/LocalGetGoalsGateway.test.ts b/tests/infrastructure/context/goals/get/LocalGetGoalsGateway.test.ts index fdeb0ed0..db910894 100644 --- a/tests/infrastructure/context/goals/get/LocalGetGoalsGateway.test.ts +++ b/tests/infrastructure/context/goals/get/LocalGetGoalsGateway.test.ts @@ -47,6 +47,17 @@ describe("LocalGetGoalsGateway", () => { expect(response.goals.map(g => g.goalId)).toEqual(["g1", "g3"]); }); + it("keeps postponed goals visible in the default listing", async () => { + mockReader.findAll.mockResolvedValue([ + makeGoal({ goalId: "postponed", status: "postponed" }), + makeGoal({ goalId: "completed", status: "done" }), + ]); + + const response = await gateway.getGoals({}); + + expect(response.goals.map((goal) => goal.goalId)).toEqual(["postponed"]); + }); + it("should filter by specified statuses", async () => { const allGoals = [ makeGoal({ goalId: "g1", status: "doing" }), diff --git a/tests/infrastructure/context/goals/get/SqliteGetGoalViewReader.test.ts b/tests/infrastructure/context/goals/get/SqliteGetGoalViewReader.test.ts new file mode 100644 index 00000000..6cb96adf --- /dev/null +++ b/tests/infrastructure/context/goals/get/SqliteGetGoalViewReader.test.ts @@ -0,0 +1,76 @@ +import Database from "better-sqlite3"; +import { GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { SqliteGetGoalViewReader } from "../../../../../src/infrastructure/context/goals/get/SqliteGetGoalViewReader"; + +describe("SqliteGetGoalViewReader", () => { + let db: Database.Database; + let reader: SqliteGetGoalViewReader; + + beforeEach(() => { + db = new Database(":memory:"); + db.exec(` + CREATE TABLE goal_views ( + goalId TEXT PRIMARY KEY, + title TEXT DEFAULT '', + objective TEXT, + successCriteria TEXT DEFAULT '[]', + scopeIn TEXT DEFAULT '[]', + scopeOut TEXT DEFAULT '[]', + status TEXT, + version INTEGER, + createdAt TEXT, + updatedAt TEXT, + note TEXT, + progress TEXT DEFAULT '[]', + reviewIssues TEXT, + claimedBy TEXT, + claimedAt TEXT, + claimExpiresAt TEXT, + nextGoalId TEXT, + prerequisiteGoals TEXT DEFAULT '[]', + branch TEXT, + worktree TEXT + ) + `); + reader = new SqliteGetGoalViewReader(db); + }); + + afterEach(() => db.close()); + + it("returns the mapped goal view by id", async () => { + db.prepare(` + INSERT INTO goal_views ( + goalId, title, objective, successCriteria, scopeIn, scopeOut, + status, version, createdAt, updatedAt, progress, prerequisiteGoals + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + "goal_123", + "Later work", + "Keep visible", + '["Postponed"]', + '["src/**"]', + "[]", + GoalStatus.TODO, + 1, + "2026-09-11T09:00:00.000Z", + "2026-09-11T09:00:00.000Z", + '["Implemented command"]', + "[]" + ); + + await expect(reader.findById("goal_123")).resolves.toEqual( + expect.objectContaining({ + goalId: "goal_123", + title: "Later work", + status: GoalStatus.TODO, + successCriteria: ["Postponed"], + scopeIn: ["src/**"], + progress: ["Implemented command"], + }) + ); + }); + + it("returns null when the goal does not exist", async () => { + await expect(reader.findById("missing")).resolves.toBeNull(); + }); +}); diff --git a/tests/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.test.ts b/tests/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.test.ts new file mode 100644 index 00000000..49ab16d0 --- /dev/null +++ b/tests/infrastructure/context/goals/postpone/FsGoalPostponedEventStore.test.ts @@ -0,0 +1,41 @@ +import fs from "fs-extra"; +import os from "node:os"; +import path from "node:path"; +import { ILogger } from "../../../../../src/application/logging/ILogger"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalPostponedEvent } from "../../../../../src/domain/goals/postpone/GoalPostponedEvent"; +import { FsGoalPostponedEventStore } from "../../../../../src/infrastructure/context/goals/postpone/FsGoalPostponedEventStore"; + +const logger: ILogger = { + error: () => undefined, + warn: () => undefined, + info: () => undefined, + debug: () => undefined, +}; + +describe("FsGoalPostponedEventStore", () => { + let rootDir: string; + + beforeEach(async () => { + rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "jumbo-postponed-store-")); + }); + + afterEach(async () => { + await fs.remove(rootDir); + }); + + it("persists and reads a postponed event through the goal stream", async () => { + const store = new FsGoalPostponedEventStore(rootDir, logger); + const event: GoalPostponedEvent = { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }; + + await store.append(event); + + await expect(store.readStream("goal_123")).resolves.toContainEqual(event); + }); +}); diff --git a/tests/infrastructure/context/goals/postpone/HostBuilderPostponeWiring.test.ts b/tests/infrastructure/context/goals/postpone/HostBuilderPostponeWiring.test.ts new file mode 100644 index 00000000..69746ce2 --- /dev/null +++ b/tests/infrastructure/context/goals/postpone/HostBuilderPostponeWiring.test.ts @@ -0,0 +1,40 @@ +import Database from "better-sqlite3"; +import fs from "fs-extra"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { PostponeGoalController } from "../../../../../src/application/context/goals/postpone/PostponeGoalController"; +import { SqliteGetGoalViewReader } from "../../../../../src/infrastructure/context/goals/get/SqliteGetGoalViewReader"; +import { FsGoalPostponedEventStore } from "../../../../../src/infrastructure/context/goals/postpone/FsGoalPostponedEventStore"; +import { SqliteGoalPostponedProjector } from "../../../../../src/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector"; +import { HostBuilder } from "../../../../../src/infrastructure/host/HostBuilder"; +import { MigrationRunner } from "../../../../../src/infrastructure/persistence/MigrationRunner"; +import { getNamespaceMigrations } from "../../../../../src/infrastructure/persistence/migrations.config"; + +const currentDirectory = path.dirname(fileURLToPath(import.meta.url)); + +describe("HostBuilder postpone wiring", () => { + let rootDir: string; + let db: Database.Database; + + beforeEach(async () => { + rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "jumbo-postpone-host-")); + db = new Database(":memory:"); + const infrastructureDir = path.resolve(currentDirectory, "../../../../../src/infrastructure"); + new MigrationRunner(db).runNamespaceMigrations(getNamespaceMigrations(infrastructureDir)); + }); + + afterEach(async () => { + db.close(); + await fs.remove(rootDir); + }); + + it("exposes the postpone controller, event store, projector, and goal view reader", async () => { + const container = await new HostBuilder(rootDir, db).build(); + + expect(container.postponeGoalController).toBeInstanceOf(PostponeGoalController); + expect(container.goalPostponedEventStore).toBeInstanceOf(FsGoalPostponedEventStore); + expect(container.goalPostponedProjector).toBeInstanceOf(SqliteGoalPostponedProjector); + expect(container.goalViewReader).toBeInstanceOf(SqliteGetGoalViewReader); + }); +}); diff --git a/tests/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.test.ts b/tests/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.test.ts new file mode 100644 index 00000000..295062ab --- /dev/null +++ b/tests/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector.test.ts @@ -0,0 +1,67 @@ +import Database from "better-sqlite3"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalPostponedEvent } from "../../../../../src/domain/goals/postpone/GoalPostponedEvent"; +import { SqliteGoalPostponedProjector } from "../../../../../src/infrastructure/context/goals/postpone/SqliteGoalPostponedProjector"; + +describe("SqliteGoalPostponedProjector", () => { + let db: Database.Database; + let projector: SqliteGoalPostponedProjector; + + beforeEach(() => { + db = new Database(":memory:"); + db.exec(` + CREATE TABLE goal_views ( + goalId TEXT PRIMARY KEY, + title TEXT DEFAULT '', + objective TEXT, + successCriteria TEXT DEFAULT '[]', + scopeIn TEXT DEFAULT '[]', + scopeOut TEXT DEFAULT '[]', + status TEXT, + version INTEGER, + createdAt TEXT, + updatedAt TEXT, + note TEXT, + progress TEXT DEFAULT '[]', + reviewIssues TEXT, + claimedBy TEXT, + claimedAt TEXT, + claimExpiresAt TEXT, + nextGoalId TEXT, + prerequisiteGoals TEXT DEFAULT '[]', + branch TEXT, + worktree TEXT + ) + `); + db.prepare(` + INSERT INTO goal_views (goalId, title, objective, status, version, createdAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + "goal_123", + "Later work", + "Keep visible", + GoalStatus.TODO, + 1, + "2026-09-11T09:00:00.000Z", + "2026-09-11T09:00:00.000Z" + ); + projector = new SqliteGoalPostponedProjector(db); + }); + + afterEach(() => db.close()); + + it("updates status, version, and updatedAt", async () => { + const event: GoalPostponedEvent = { + type: GoalEventType.POSTPONED, + aggregateId: "goal_123", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + }; + + await projector.applyGoalPostponed(event); + + expect(db.prepare("SELECT status, version, updatedAt FROM goal_views WHERE goalId = ?").get("goal_123")) + .toEqual({ status: GoalStatus.POSTPONED, version: 2, updatedAt: event.timestamp }); + }); +}); diff --git a/tests/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.test.ts b/tests/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.test.ts new file mode 100644 index 00000000..ca3ef617 --- /dev/null +++ b/tests/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore.test.ts @@ -0,0 +1,41 @@ +import fs from "fs-extra"; +import os from "node:os"; +import path from "node:path"; +import { ILogger } from "../../../../../src/application/logging/ILogger"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalReinstatedEvent } from "../../../../../src/domain/goals/reinstate/GoalReinstatedEvent"; +import { FsGoalReinstatedEventStore } from "../../../../../src/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore"; + +const logger: ILogger = { + error: () => undefined, + warn: () => undefined, + info: () => undefined, + debug: () => undefined, +}; + +describe("FsGoalReinstatedEventStore", () => { + let rootDir: string; + + beforeEach(async () => { + rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "jumbo-reinstated-store-")); + }); + + afterEach(async () => { + await fs.remove(rootDir); + }); + + it("persists and reads a reinstated event through the goal stream", async () => { + const store = new FsGoalReinstatedEventStore(rootDir, logger); + const event: GoalReinstatedEvent = { + type: GoalEventType.REINSTATED, + aggregateId: "goal_123", + version: 3, + timestamp: "2026-09-11T11:00:00.000Z", + payload: { status: GoalStatus.TODO }, + }; + + await store.append(event); + + await expect(store.readStream("goal_123")).resolves.toContainEqual(event); + }); +}); diff --git a/tests/infrastructure/context/goals/reinstate/HostBuilderReinstateWiring.test.ts b/tests/infrastructure/context/goals/reinstate/HostBuilderReinstateWiring.test.ts new file mode 100644 index 00000000..a7f0f204 --- /dev/null +++ b/tests/infrastructure/context/goals/reinstate/HostBuilderReinstateWiring.test.ts @@ -0,0 +1,60 @@ +import Database from "better-sqlite3"; +import fs from "fs-extra"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { ReinstateGoalController } from "../../../../../src/application/context/goals/reinstate/ReinstateGoalController"; +import { Goal } from "../../../../../src/domain/goals/Goal"; +import { GoalId } from "../../../../../src/domain/goals/GoalId"; +import { GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { SqliteGetGoalViewReader } from "../../../../../src/infrastructure/context/goals/get/SqliteGetGoalViewReader"; +import { FsGoalReinstatedEventStore } from "../../../../../src/infrastructure/context/goals/reinstate/FsGoalReinstatedEventStore"; +import { SqliteGoalReinstatedProjector } from "../../../../../src/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector"; +import { HostBuilder } from "../../../../../src/infrastructure/host/HostBuilder"; +import { MigrationRunner } from "../../../../../src/infrastructure/persistence/MigrationRunner"; +import { getNamespaceMigrations } from "../../../../../src/infrastructure/persistence/migrations.config"; + +const currentDirectory = path.dirname(fileURLToPath(import.meta.url)); + +describe("HostBuilder reinstate wiring", () => { + let rootDir: string; + let db: Database.Database; + + beforeEach(async () => { + rootDir = await fs.mkdtemp(path.join(os.tmpdir(), "jumbo-reinstate-host-")); + db = new Database(":memory:"); + const infrastructureDir = path.resolve(currentDirectory, "../../../../../src/infrastructure"); + new MigrationRunner(db).runNamespaceMigrations(getNamespaceMigrations(infrastructureDir)); + }); + + afterEach(async () => { + db.close(); + await fs.remove(rootDir); + }); + + it("exposes the reinstate controller, event store, projector, and shared goal view reader", async () => { + const container = await new HostBuilder(rootDir, db).build(); + + expect(container.reinstateGoalController).toBeInstanceOf(ReinstateGoalController); + expect(container.goalReinstatedEventStore).toBeInstanceOf(FsGoalReinstatedEventStore); + expect(container.goalReinstatedProjector).toBeInstanceOf(SqliteGoalReinstatedProjector); + expect(container.goalViewReader).toBeInstanceOf(SqliteGetGoalViewReader); + }); + + it("projects reinstatement through the live event-bus subscription", async () => { + const container = await new HostBuilder(rootDir, db).build(); + const goal = Goal.create(GoalId.fromLegacy("goal_123")); + const addedEvent = goal.add("Later work", "Return this goal to refinement", ["It is defined"]); + const postponedEvent = goal.postpone(); + await container.goalAddedEventStore.append(addedEvent); + await container.eventBus.publish(addedEvent); + await container.goalPostponedEventStore.append(postponedEvent); + await container.eventBus.publish(postponedEvent); + + await expect(container.reinstateGoalController.handle({ goalId: "goal_123" })) + .resolves.toEqual({ status: GoalStatus.TODO }); + + expect(db.prepare("SELECT status, version FROM goal_views WHERE goalId = ?").get("goal_123")) + .toEqual({ status: GoalStatus.TODO, version: 3 }); + }); +}); diff --git a/tests/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.test.ts b/tests/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.test.ts new file mode 100644 index 00000000..572902b6 --- /dev/null +++ b/tests/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector.test.ts @@ -0,0 +1,67 @@ +import Database from "better-sqlite3"; +import { GoalEventType, GoalStatus } from "../../../../../src/domain/goals/Constants"; +import { GoalReinstatedEvent } from "../../../../../src/domain/goals/reinstate/GoalReinstatedEvent"; +import { SqliteGoalReinstatedProjector } from "../../../../../src/infrastructure/context/goals/reinstate/SqliteGoalReinstatedProjector"; + +describe("SqliteGoalReinstatedProjector", () => { + let db: Database.Database; + let projector: SqliteGoalReinstatedProjector; + + beforeEach(() => { + db = new Database(":memory:"); + db.exec(` + CREATE TABLE goal_views ( + goalId TEXT PRIMARY KEY, + title TEXT DEFAULT '', + objective TEXT, + successCriteria TEXT DEFAULT '[]', + scopeIn TEXT DEFAULT '[]', + scopeOut TEXT DEFAULT '[]', + status TEXT, + version INTEGER, + createdAt TEXT, + updatedAt TEXT, + note TEXT, + progress TEXT DEFAULT '[]', + reviewIssues TEXT, + claimedBy TEXT, + claimedAt TEXT, + claimExpiresAt TEXT, + nextGoalId TEXT, + prerequisiteGoals TEXT DEFAULT '[]', + branch TEXT, + worktree TEXT + ) + `); + db.prepare(` + INSERT INTO goal_views (goalId, title, objective, status, version, createdAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run( + "goal_123", + "Later work", + "Keep visible", + GoalStatus.POSTPONED, + 2, + "2026-09-11T09:00:00.000Z", + "2026-09-11T10:00:00.000Z" + ); + projector = new SqliteGoalReinstatedProjector(db); + }); + + afterEach(() => db.close()); + + it("updates status, version, and updatedAt", async () => { + const event: GoalReinstatedEvent = { + type: GoalEventType.REINSTATED, + aggregateId: "goal_123", + version: 3, + timestamp: "2026-09-11T11:00:00.000Z", + payload: { status: GoalStatus.TODO }, + }; + + await projector.applyGoalReinstated(event); + + expect(db.prepare("SELECT status, version, updatedAt FROM goal_views WHERE goalId = ?").get("goal_123")) + .toEqual({ status: GoalStatus.TODO, version: 3, updatedAt: event.timestamp }); + }); +}); diff --git a/tests/infrastructure/messaging/ProjectionBusFactory.test.ts b/tests/infrastructure/messaging/ProjectionBusFactory.test.ts index bb93e5ae..93d723f1 100644 --- a/tests/infrastructure/messaging/ProjectionBusFactory.test.ts +++ b/tests/infrastructure/messaging/ProjectionBusFactory.test.ts @@ -13,6 +13,7 @@ import { InvariantEventType } from "../../../src/domain/invariants/Constants"; import { EntityType, RelationEventType, RelationStatus } from "../../../src/domain/relations/Constants"; import os from "os"; import { BaseEvent } from "../../../src/domain/BaseEvent"; +import { GoalEventType, GoalStatus } from "../../../src/domain/goals/Constants"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -76,6 +77,42 @@ describe("ProjectionBusFactory", () => { expect(row.status).toBe(ComponentStatus.DEPRECATED); }); + it("rebuilds reinstated goal state from its complete event history", async () => { + const bus = new ProjectionBusFactory().create(db); + + await bus.publish({ + type: GoalEventType.ADDED, + aggregateId: "goal-postponed", + version: 1, + timestamp: "2026-09-11T09:00:00.000Z", + payload: { + title: "Later work", + objective: "Keep this goal visible", + successCriteria: ["It remains listed"], + scopeIn: [], + scopeOut: [], + status: GoalStatus.TODO, + }, + } as BaseEvent); + await bus.publish({ + type: GoalEventType.POSTPONED, + aggregateId: "goal-postponed", + version: 2, + timestamp: "2026-09-11T10:00:00.000Z", + payload: { status: GoalStatus.POSTPONED }, + } as BaseEvent); + await bus.publish({ + type: GoalEventType.REINSTATED, + aggregateId: "goal-postponed", + version: 3, + timestamp: "2026-09-11T11:00:00.000Z", + payload: { status: GoalStatus.TODO }, + } as BaseEvent); + + expect(db.prepare("SELECT status, version FROM goal_views WHERE goalId = ?").get("goal-postponed")) + .toEqual({ status: GoalStatus.TODO, version: 3 }); + }); + it("creates an event bus that rebuilds the global search index from memory events", async () => { const factory = new ProjectionBusFactory(); const bus = factory.create(db); diff --git a/tests/presentation/cli/command-compliance.test.ts b/tests/presentation/cli/command-compliance.test.ts index 2ee38491..1ac9d87a 100644 --- a/tests/presentation/cli/command-compliance.test.ts +++ b/tests/presentation/cli/command-compliance.test.ts @@ -133,4 +133,23 @@ describe("Command Compliance", () => { "jumbo relations audit --format json", ); }); + + test("goal postpone is a project-scoped command with a required id and automatic-selection help", () => { + const command = commands.find((candidate) => candidate.path === "goal postpone"); + + expect(command).toBeDefined(); + expect(command?.metadata.requiresProject).toBe(true); + expect(command?.metadata.requiredOptions?.map((option) => option.flags)).toEqual(["-i, --id "]); + expect(command?.metadata.description).toContain("automatic work streams"); + }); + + test("goal reinstate is project-scoped with a required id and renewed refinement help", () => { + const command = commands.find((candidate) => candidate.path === "goal reinstate"); + + expect(command).toBeDefined(); + expect(command?.metadata.requiresProject).toBe(true); + expect(command?.metadata.requiredOptions?.map((option) => option.flags)).toEqual(["-i, --id "]); + expect(command?.metadata.description).toContain("postponed goal as defined"); + expect(command?.metadata.description).toContain("eligible for refinement"); + }); }); diff --git a/tests/presentation/cli/commands/goals/list/GoalListOutputBuilder.test.ts b/tests/presentation/cli/commands/goals/list/GoalListOutputBuilder.test.ts index 3f646e12..16b71c4f 100644 --- a/tests/presentation/cli/commands/goals/list/GoalListOutputBuilder.test.ts +++ b/tests/presentation/cli/commands/goals/list/GoalListOutputBuilder.test.ts @@ -31,7 +31,7 @@ describe("GoalListOutputBuilder", () => { const expectedStatuses = [ "approved", "in-review", "submitted", "paused", "doing", "blocked", "unblocked", "rejected", "in-refinement", "codifying", - "refined", "defined" + "refined", "defined", "postponed" ]; for (const status of expectedStatuses) { expect(STATUS_ORDER).toHaveProperty(status); @@ -148,6 +148,16 @@ describe("GoalListOutputBuilder", () => { expect(output).toContain("g_submitted"); }); + it("should render postponed goals under a dedicated heading", () => { + const output = builder.buildActiveGoalsList([ + makeGoal({ goalId: "g_postponed", status: "postponed", objective: "Later work" }), + ]).toHumanReadable(); + + expect(output).toContain("[POSTPONED]"); + expect(output).toContain("g_postponed"); + expect(output).toContain("Later work"); + }); + it("should drop redundant status prefix from per-goal lines", () => { const goals = [makeGoal({ goalId: "g1", status: "doing" })]; const output = builder.buildActiveGoalsList(goals).toHumanReadable(); diff --git a/tests/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.test.ts b/tests/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.test.ts new file mode 100644 index 00000000..16bc7a6a --- /dev/null +++ b/tests/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder.test.ts @@ -0,0 +1,21 @@ +import { GoalStatus } from "../../../../../../src/domain/goals/Constants"; +import { GoalPostponeOutputBuilder } from "../../../../../../src/presentation/cli/commands/goals/postpone/GoalPostponeOutputBuilder"; + +describe("GoalPostponeOutputBuilder", () => { + it("exposes only operation status on success", () => { + const output = new GoalPostponeOutputBuilder().buildSuccess({ status: GoalStatus.POSTPONED }); + + expect(output.toHumanReadable()).toContain("Goal postponed"); + expect(output.toHumanReadable()).not.toContain("goal_"); + expect(output.getSections().find((section) => section.type === "data")?.content) + .toEqual({ status: GoalStatus.POSTPONED }); + }); + + it("keeps failure copy and details inside the builder", () => { + const output = new GoalPostponeOutputBuilder().buildFailureError(new Error("wrong state")); + + expect(output.toHumanReadable()).toContain("Failed to postpone goal: wrong state"); + expect(output.getSections().find((section) => section.type === "data")?.content) + .toEqual({ error: "Failed to postpone goal", details: "wrong state" }); + }); +}); diff --git a/tests/presentation/cli/commands/goals/postpone/goal.postpone.test.ts b/tests/presentation/cli/commands/goals/postpone/goal.postpone.test.ts new file mode 100644 index 00000000..13a27840 --- /dev/null +++ b/tests/presentation/cli/commands/goals/postpone/goal.postpone.test.ts @@ -0,0 +1,67 @@ +import { jest } from "@jest/globals"; +import { IApplicationContainer } from "../../../../../../src/application/host/IApplicationContainer"; +import { GoalStatus } from "../../../../../../src/domain/goals/Constants"; +import { goalPostpone, metadata } from "../../../../../../src/presentation/cli/commands/goals/postpone/goal.postpone"; +import { Renderer } from "../../../../../../src/presentation/cli/rendering/Renderer"; + +describe("goal postpone command", () => { + const controller = { handle: jest.fn<() => Promise<{ status: string }>>() }; + const container = { postponeGoalController: controller } as unknown as IApplicationContainer; + let logSpy: jest.SpiedFunction; + let errorSpy: jest.SpiedFunction; + let exitSpy: jest.SpiedFunction; + + beforeEach(() => { + controller.handle.mockReset().mockResolvedValue({ status: GoalStatus.POSTPONED }); + logSpy = jest.spyOn(console, "log").mockImplementation(() => undefined); + errorSpy = jest.spyOn(console, "error").mockImplementation(() => undefined); + exitSpy = jest.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`exit ${code}`); + }); + }); + + afterEach(() => { + Renderer.reset(); + logSpy.mockRestore(); + errorSpy.mockRestore(); + exitSpy.mockRestore(); + }); + + it("declares required id, project scope, and automatic-work-stream help copy", () => { + expect(metadata.requiredOptions).toEqual([ + { flags: "-i, --id ", description: "ID of the defined goal to postpone" }, + ]); + expect(metadata.requiresProject).toBe(true); + expect(metadata.description).toContain("automatic work streams"); + expect(metadata.examples?.[0].description).toContain("excluding it from automatic work streams"); + }); + + it("routes the id and emits status-only human output", async () => { + Renderer.configure({ format: "text" }); + + await goalPostpone({ id: "goal_123" }, container); + + expect(controller.handle).toHaveBeenCalledWith({ goalId: "goal_123" }); + const output = logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("Goal postponed"); + expect(output).not.toContain("goal_123"); + }); + + it("emits only status in JSON mode", async () => { + Renderer.configure({ format: "json" }); + + await goalPostpone({ id: "goal_123" }, container); + + expect(logSpy).toHaveBeenCalledWith(JSON.stringify({ status: GoalStatus.POSTPONED })); + }); + + it("uses the standard error renderer and exits on failure", async () => { + Renderer.configure({ format: "json" }); + controller.handle.mockRejectedValue(new Error("wrong state")); + + await expect(goalPostpone({ id: "goal_123" }, container)).rejects.toThrow("exit 1"); + expect(errorSpy).toHaveBeenCalledWith( + JSON.stringify({ error: "Failed to postpone goal", details: "wrong state" }) + ); + }); +}); diff --git a/tests/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.test.ts b/tests/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.test.ts new file mode 100644 index 00000000..3710b2ef --- /dev/null +++ b/tests/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder.test.ts @@ -0,0 +1,21 @@ +import { GoalStatus } from "../../../../../../src/domain/goals/Constants"; +import { GoalReinstateOutputBuilder } from "../../../../../../src/presentation/cli/commands/goals/reinstate/GoalReinstateOutputBuilder"; + +describe("GoalReinstateOutputBuilder", () => { + it("exposes only operation status on success", () => { + const output = new GoalReinstateOutputBuilder().buildSuccess({ status: GoalStatus.TODO }); + + expect(output.toHumanReadable()).toContain("Goal defined"); + expect(output.toHumanReadable()).not.toContain("goal_"); + expect(output.getSections().find((section) => section.type === "data")?.content) + .toEqual({ status: GoalStatus.TODO }); + }); + + it("keeps failure copy and details inside the builder", () => { + const output = new GoalReinstateOutputBuilder().buildFailureError(new Error("wrong state")); + + expect(output.toHumanReadable()).toContain("Failed to reinstate goal: wrong state"); + expect(output.getSections().find((section) => section.type === "data")?.content) + .toEqual({ error: "Failed to reinstate goal", details: "wrong state" }); + }); +}); diff --git a/tests/presentation/cli/commands/goals/reinstate/goal.reinstate.test.ts b/tests/presentation/cli/commands/goals/reinstate/goal.reinstate.test.ts new file mode 100644 index 00000000..fe2a3061 --- /dev/null +++ b/tests/presentation/cli/commands/goals/reinstate/goal.reinstate.test.ts @@ -0,0 +1,67 @@ +import { jest } from "@jest/globals"; +import { IApplicationContainer } from "../../../../../../src/application/host/IApplicationContainer"; +import { GoalStatus } from "../../../../../../src/domain/goals/Constants"; +import { goalReinstate, metadata } from "../../../../../../src/presentation/cli/commands/goals/reinstate/goal.reinstate"; +import { Renderer } from "../../../../../../src/presentation/cli/rendering/Renderer"; + +describe("goal reinstate command", () => { + const controller = { handle: jest.fn<() => Promise<{ status: string }>>() }; + const container = { reinstateGoalController: controller } as unknown as IApplicationContainer; + let logSpy: jest.SpiedFunction; + let errorSpy: jest.SpiedFunction; + let exitSpy: jest.SpiedFunction; + + beforeEach(() => { + controller.handle.mockReset().mockResolvedValue({ status: GoalStatus.TODO }); + logSpy = jest.spyOn(console, "log").mockImplementation(() => undefined); + errorSpy = jest.spyOn(console, "error").mockImplementation(() => undefined); + exitSpy = jest.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`exit ${code}`); + }); + }); + + afterEach(() => { + Renderer.reset(); + logSpy.mockRestore(); + errorSpy.mockRestore(); + exitSpy.mockRestore(); + }); + + it("declares required id, project scope, and transition help copy", () => { + expect(metadata.requiredOptions).toEqual([ + { flags: "-i, --id ", description: "ID of the postponed goal to reinstate" }, + ]); + expect(metadata.requiresProject).toBe(true); + expect(metadata.description).toContain("postponed goal as defined"); + expect(metadata.description).toContain("eligible for refinement"); + }); + + it("routes the id and emits status-only human output", async () => { + Renderer.configure({ format: "text" }); + + await goalReinstate({ id: "goal_123" }, container); + + expect(controller.handle).toHaveBeenCalledWith({ goalId: "goal_123" }); + const output = logSpy.mock.calls.flat().join("\n"); + expect(output).toContain("Goal defined"); + expect(output).not.toContain("goal_123"); + }); + + it("emits only status in JSON mode", async () => { + Renderer.configure({ format: "json" }); + + await goalReinstate({ id: "goal_123" }, container); + + expect(logSpy).toHaveBeenCalledWith(JSON.stringify({ status: GoalStatus.TODO })); + }); + + it("uses the standard error renderer and exits on failure", async () => { + Renderer.configure({ format: "json" }); + controller.handle.mockRejectedValue(new Error("wrong state")); + + await expect(goalReinstate({ id: "goal_123" }, container)).rejects.toThrow("exit 1"); + expect(errorSpy).toHaveBeenCalledWith( + JSON.stringify({ error: "Failed to reinstate goal", details: "wrong state" }) + ); + }); +}); diff --git a/tests/presentation/cli/commands/goals/show/GoalShowOutputBuilder.test.ts b/tests/presentation/cli/commands/goals/show/GoalShowOutputBuilder.test.ts index af0295b6..1d377a96 100644 --- a/tests/presentation/cli/commands/goals/show/GoalShowOutputBuilder.test.ts +++ b/tests/presentation/cli/commands/goals/show/GoalShowOutputBuilder.test.ts @@ -269,7 +269,7 @@ describe("GoalShowOutputBuilder", () => { }); it("should format all status types with semantic indicators", () => { - const statuses = ["doing", "refined", "in-review", "rejected", "blocked", "done"]; + const statuses = ["doing", "refined", "in-review", "rejected", "blocked", "postponed", "done"]; for (const status of statuses) { const view = makeContextualView({ status: status as GoalView["status"] }); diff --git a/tests/presentation/cli/commands/registry/RequiresProjectMetadata.test.ts b/tests/presentation/cli/commands/registry/RequiresProjectMetadata.test.ts index 90c643ce..1719b190 100644 --- a/tests/presentation/cli/commands/registry/RequiresProjectMetadata.test.ts +++ b/tests/presentation/cli/commands/registry/RequiresProjectMetadata.test.ts @@ -62,4 +62,18 @@ describe("requiresProject metadata", () => { expect(paths).toContain("goal approve"); expect(paths).not.toContain("goal qualify"); }); + + it("registers goal postpone as explicitly project-scoped", () => { + const command = commands.find((c) => c.path === "goal postpone"); + + expect(command).toBeDefined(); + expect(command?.metadata.requiresProject).toBe(true); + }); + + it("registers goal reinstate as explicitly project-scoped", () => { + const command = commands.find((c) => c.path === "goal reinstate"); + + expect(command).toBeDefined(); + expect(command?.metadata.requiresProject).toBe(true); + }); }); diff --git a/tests/presentation/tui/goals/GoalsScreen.test.tsx b/tests/presentation/tui/goals/GoalsScreen.test.tsx index a0835535..f704143b 100644 --- a/tests/presentation/tui/goals/GoalsScreen.test.tsx +++ b/tests/presentation/tui/goals/GoalsScreen.test.tsx @@ -571,6 +571,24 @@ describe("GoalsScreen", () => { } }); + it("renders postponed goals and accepts a postponed navigation filter", async () => { + const handledRequests: GetGoalsRequest[] = []; + const { lastFrame, unmount } = renderGoalsScreen({ + statusFilter: [GoalStatus.POSTPONED], + goals: [createGoal({ + goalId: "goal_postponed", + title: "Deferred goal", + status: GoalStatus.POSTPONED, + })], + handledRequests, + }); + + const frame = stripAnsi(await waitForFrame(lastFrame, "Deferred goal")); + expect(frame).toContain("postponed"); + expect(handledRequests).toContainEqual({ statuses: [GoalStatus.POSTPONED] }); + unmount(); + }); + it("opens the goal authoring wizard from the goals screen", async () => { const { lastFrame, stdin, unmount } = renderGoalsScreen(); diff --git a/tests/presentation/tui/navigation/MegaMenuDefinitions.test.ts b/tests/presentation/tui/navigation/MegaMenuDefinitions.test.ts index cf5756ea..6a21e9e2 100644 --- a/tests/presentation/tui/navigation/MegaMenuDefinitions.test.ts +++ b/tests/presentation/tui/navigation/MegaMenuDefinitions.test.ts @@ -44,6 +44,7 @@ describe("MegaMenuDefinitions", () => { expect(goalsSection.children[0].children?.map((item) => item.goalStatusFilter)).toEqual([ MEGA_MENU_GOAL_STATUS_FILTERS.defined, MEGA_MENU_GOAL_STATUS_FILTERS.refined, + MEGA_MENU_GOAL_STATUS_FILTERS.postponed, ]); expect(goalsSection.children[1].children?.map((item) => item.goalStatusFilter)).toEqual([ MEGA_MENU_GOAL_STATUS_FILTERS.doing, @@ -108,6 +109,7 @@ describe("MegaMenuDefinitions", () => { expect(goalsSection.children[0].children?.map((item) => item.key)).toEqual([ GoalStatus.TODO, GoalStatus.REFINED, + GoalStatus.POSTPONED, ]); expect(goalsSection.children[1].children?.map((item) => item.key)).toEqual([ GoalStatus.DOING,