{"version":3,"sources":["../src/bounded-contexts/project-management/domain/errors/GTDDomainError.ts","../src/bounded-contexts/inbox-management/domain/value-objects/InboxContent.ts","../src/bounded-contexts/inbox-management/domain/aggregates/InboxItem.ts","../src/bounded-contexts/inbox-management/domain/services/InboxImportExportService.ts","../src/bounded-contexts/project-management/domain/events/GTDEvents.ts","../src/bounded-contexts/project-management/domain/aggregates/NextAction.ts","../src/bounded-contexts/project-management/domain/value-objects/ActionContext.ts","../src/bounded-contexts/project-management/domain/value-objects/EnergyLevel.ts","../src/bounded-contexts/inbox-management/domain/services/GTDProcessingWorkflowService.ts","../src/bounded-contexts/inbox-management/application/commands/CompleteGTDProcessingCommand.ts","../src/bounded-contexts/inbox-management/application/services/InboxItemApplicationService.ts","../src/infrastructure/di/GTDDomainSymbols.ts","../src/bounded-contexts/inbox-management/infrastructure/repositories/InboxItemAggregateRepository.ts","../src/config/collections.ts","../src/bounded-contexts/project-management/infrastructure/repositories/NextActionAggregateRepository.ts","../src/bounded-contexts/project-management/domain/value-objects/ProcessingStatus.ts","../src/bounded-contexts/project-management/domain/aggregates/Project.ts","../src/bounded-contexts/project-management/domain/events/DomainEvent.ts","../src/bounded-contexts/project-management/infrastructure/repositories/ProjectRepository.ts","../src/bounded-contexts/project-management/application/services/ProjectApplicationService.ts","../src/types/DITypes.ts","../src/bounded-contexts/project-management/application/services/ProjectWriteService.ts","../src/bounded-contexts/project-management/application/services/ProjectReadService.ts","../src/bounded-contexts/project-management/application/services/NextActionWriteService.ts","../src/bounded-contexts/project-management/application/services/NextActionReadService.ts","../src/bounded-contexts/design-implementation-coordination/application/services/DesignImplementationFlowApplicationService.ts","../src/bounded-contexts/design-implementation-coordination/domain/value-objects/ArtifactStatus.ts","../src/bounded-contexts/design-implementation-coordination/domain/value-objects/ConformanceScore.ts","../src/bounded-contexts/design-implementation-coordination/domain/value-objects/FlowStatus.ts","../src/bounded-contexts/design-implementation-coordination/domain/errors/DesignImplementationDomainError.ts","../src/bounded-contexts/design-implementation-coordination/domain/events/DesignImplementationEvents.ts","../src/bounded-contexts/design-implementation-coordination/domain/aggregates/DesignImplementationFlow.ts","../src/bounded-contexts/design-implementation-coordination/infrastructure/repositories/DesignImplementationFlowRepository.ts","../src/bounded-contexts/design-implementation-coordination/application/services/DesignImplementationFlowReadService.ts","../src/bounded-contexts/index.ts","../src/bounded-contexts/ai-tools/infrastructure/tools/inbox-ai-tools.ts","../src/bounded-contexts/ai-tools/application/services/GTDAIToolsApplicationService.ts","../src/bounded-contexts/ai-tools/index.ts","../src/bounded-contexts/inbox-management/infrastructure/factories/createGTDQueryService.ts","../src/infrastructure/factory/GTDServiceFactory.ts","../src/integration/index.ts","../src/interface/errors/GTDFeatureError.ts","../src/infrastructure/shared-seeding/BaseDomainSeeder.ts","../src/utils/seed-gtd-data.ts","../src/infrastructure/GtdDomainSeeder.ts","../src/infrastructure/di/GTDDomainContainerModule.ts","../src/bounded-contexts/task-management/infrastructure/repositories/TaskMongoRepository.ts","../src/bounded-contexts/task-management/domain/entities/TaskAggregate.ts","../src/bounded-contexts/task-management/domain/view-models.ts","../src/bounded-contexts/task-management/domain/value-objects/TaskId.ts","../src/bounded-contexts/task-management/domain/events/TaskAssigned.ts","../src/bounded-contexts/task-management/domain/events/TaskCompleted.ts","../src/bounded-contexts/task-management/infrastructure/repositories/InboxFileRepository.ts","../src/bounded-contexts/task-management/domain/plan-view-models.ts","../src/bounded-contexts/task-management/infrastructure/repositories/NextActionsFileRepository.ts","../src/validation/GTDDomainRules.ts"],"sourcesContent":["/**\n * GTD Domain Errors following clean error handling patterns\n */\nexport class GTDDomainError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly context?: Record<string, any>\n  ) {\n    super(message);\n    this.name = 'GTDDomainError';\n  }\n}\n\nexport class ThoughtProcessingError extends GTDDomainError {\n  constructor(message: string, context?: Record<string, any>) {\n    super(message, 'THOUGHT_PROCESSING_ERROR', context);\n    this.name = 'ThoughtProcessingError';\n  }\n}\n\nexport class InvalidProcessingStatusError extends GTDDomainError {\n  constructor(currentStatus: string, requiredStatus: string) {\n    super(\n      `Cannot perform this operation. Current status: ${currentStatus}, required: ${requiredStatus}`,\n      'INVALID_PROCESSING_STATUS',\n      { currentStatus, requiredStatus }\n    );\n    this.name = 'InvalidProcessingStatusError';\n  }\n}\n\nexport class InvalidActionDurationError extends GTDDomainError {\n  constructor(duration: number) {\n    super(\n      `Action duration exceeds reasonable bounds. Duration: ${duration} minutes. Maximum allowed: 480 minutes (8 hours).`,\n      'INVALID_ACTION_DURATION',\n      { duration, maxDuration: 480 }\n    );\n    this.name = 'InvalidActionDurationError';\n  }\n}\n\nexport class ProjectStateError extends GTDDomainError {\n  constructor(message: string, projectId: string, currentState: string) {\n    super(message, 'PROJECT_STATE_ERROR', { projectId, currentState });\n    this.name = 'ProjectStateError';\n  }\n}\n\nexport class AssignmentError extends GTDDomainError {\n  constructor(message: string, actionId: string) {\n    super(message, 'ASSIGNMENT_ERROR', { actionId });\n    this.name = 'AssignmentError';\n  }\n}","import { GTDDomainError } from '../../../project-management/domain/errors/GTDDomainError';\n\n/**\n * InboxContent Value Object\n * \n * Enforces GTD capture rules:\n * - Content cannot be empty (must capture something meaningful)\n * - Minimum 3 characters to prevent accidental captures\n * - Maximum 5000 characters to maintain focus on quick capture\n * \n * Fixes data corruption by ensuring all content is validated at domain level.\n */\nexport class InboxContent {\n    private constructor(private readonly _value: string) {\n        if (!_value || _value.trim().length === 0) {\n            throw new GTDDomainError(\n                'Inbox content cannot be empty',\n                'EMPTY_INBOX_CONTENT'\n            );\n        }\n        if (_value.trim().length < 3) {\n            throw new GTDDomainError(\n                'Inbox content must be at least 3 characters',\n                'INBOX_CONTENT_TOO_SHORT',\n                { minLength: 3, actualLength: _value.trim().length }\n            );\n        }\n        if (_value.length > 5000) {\n            throw new GTDDomainError(\n                'Inbox content cannot exceed 5000 characters',\n                'INBOX_CONTENT_TOO_LONG',\n                { maxLength: 5000, actualLength: _value.length }\n            );\n        }\n    }\n    \n    static create(content: string): InboxContent {\n        return new InboxContent(content?.trim());\n    }\n    \n    get value(): string { \n        return this._value; \n    }\n}","import { InboxContent } from '../value-objects/InboxContent';\n\n/**\n * BC-035: Getting Things Done - InboxItem Aggregate\n * \n * Core GTD Principle: \"Your mind is for having ideas, not holding them\"\n * Implements David Allen's GTD capture and clarification workflow\n */\nexport class InboxItem {\n    readonly id: string;\n    private _originalContent: InboxContent;\n    readonly capturedAt: Date;\n    readonly capturedByPersonId: string;\n    \n    private _clarification?: string;\n    private _isActionable?: boolean;\n    private _processingStatus: string;\n    private _lastRefinedAt?: Date;\n    private _refinedByPersonId?: string;\n\n    private constructor(\n        id: string,\n        originalContent: InboxContent,\n        capturedAt: Date,\n        capturedByPersonId: string\n    ) {\n        this.id = id;\n        this._originalContent = originalContent;\n        this.capturedAt = capturedAt;\n        this.capturedByPersonId = capturedByPersonId;\n        this._processingStatus = 'unprocessed';\n    }\n\n    // Getters\n    get originalContent(): string {\n        return this._originalContent.value;\n    }\n\n    get clarification(): string | undefined {\n        return this._clarification;\n    }\n\n    get isActionable(): boolean | undefined {\n        return this._isActionable;\n    }\n\n    get processingStatus(): string {\n        return this._processingStatus;\n    }\n\n    get lastRefinedAt(): Date | undefined {\n        return this._lastRefinedAt;\n    }\n\n    get refinedByPersonId(): string | undefined {\n        return this._refinedByPersonId;\n    }\n\n    /**\n     * Factory method: Capture a new inbox item\n     * GTD Principle: \"Ubiquitous Capture\"\n     */\n    static capture(content: string, capturedByPersonId: string): InboxItem {\n        const id = `inbox-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n        const capturedAt = new Date();\n        const inboxContent = InboxContent.create(content);\n        \n        return new InboxItem(id, inboxContent, capturedAt, capturedByPersonId);\n    }\n\n    /**\n     * Factory method: Reconstruct from repository data\n     */\n    static fromRepository(data: {\n        id: string;\n        originalContent: string;\n        capturedAt: Date;\n        capturedByPersonId: string;\n        clarification?: string;\n        isActionable?: boolean;\n        processingStatus?: string;\n        lastRefinedAt?: Date;\n        refinedByPersonId?: string;\n    }): InboxItem {\n        const inboxContent = InboxContent.create(data.originalContent);\n        const item = new InboxItem(\n            data.id,\n            inboxContent,\n            data.capturedAt,\n            data.capturedByPersonId\n        );\n        \n        item._clarification = data.clarification;\n        item._isActionable = data.isActionable;\n        item._processingStatus = data.processingStatus || 'unprocessed';\n        item._lastRefinedAt = data.lastRefinedAt;\n        item._refinedByPersonId = data.refinedByPersonId;\n        \n        return item;\n    }\n\n    /**\n     * Refine Capture: Clean up or correct the original captured content\n     * GTD Principle: \"Your system must be current and complete\"\n     * \n     * This is NOT clarification - it's fixing typos, making the capture clearer,\n     * or adding missing context to what was hastily captured.\n     * \n     * @param refinedContent The cleaned up version of the original capture\n     * @param refinedBy Person ID who refined the content\n     */\n    refineCapture(refinedContent: string, refinedBy: string): void {\n        const newContent = InboxContent.create(refinedContent);\n        \n        this._originalContent = newContent;\n        this._lastRefinedAt = new Date();\n        this._refinedByPersonId = refinedBy;\n        // Note: Does NOT change processing status - refining is not processing\n    }\n\n    /**\n     * GTD Clarification: \"What is it? Is it actionable?\"\n     * \n     * This is the core GTD processing step where you decide what something means\n     * and whether it requires action.\n     */\n    clarify(clarification: string, isActionable: boolean, _clarifiedBy: string): void {\n        this._clarification = clarification;\n        this._isActionable = isActionable;\n        this._processingStatus = 'processed';\n    }\n\n    /**\n     * Convert to plain object for repository persistence\n     */\n    toData(): any {\n        return {\n            id: this.id,\n            originalContent: this._originalContent.value,\n            capturedAt: this.capturedAt,\n            capturedByPersonId: this.capturedByPersonId,\n            clarification: this._clarification,\n            isActionable: this._isActionable,\n            processingStatus: this._processingStatus,\n            lastRefinedAt: this._lastRefinedAt,\n            refinedByPersonId: this._refinedByPersonId\n        };\n    }\n}","import { InboxItem } from \"../aggregates/InboxItem\";\nimport { InboxItemAggregateRepository } from \"../../infrastructure/repositories/InboxItemAggregateRepository\";\n\n/**\n * Inbox Import/Export Domain Service\n * \n * Following Eric Evans Domain Service pattern for operations that don't\n * naturally belong to any single aggregate but are part of the domain.\n * \n * Import/Export is a legitimate GTD capability - not just technical migration.\n */\nexport class InboxImportExportService {\n    constructor(\n        private readonly repository: InboxItemAggregateRepository\n    ) {}\n\n    /**\n     * Export all inbox items to a portable format\n     */\n    async exportItems(filters?: {\n        status?: 'processed' | 'unprocessed';\n        limit?: number;\n    }): Promise<InboxExportData> {\n        // Get items based on filters\n        const items = await this.repository.findAll();\n\n        // Filter by status if provided\n        const filteredItems = filters?.status \n            ? items.filter((item: InboxItem) => item.processingStatus === filters.status)\n            : items;\n\n        // Apply limit\n        const limitedItems = filters?.limit \n            ? filteredItems.slice(0, filters.limit)\n            : filteredItems;\n\n        return {\n            exportDate: new Date().toISOString(),\n            version: \"1.0\",\n            source: \"swoft-gtd-inbox\",\n            totalItems: limitedItems.length,\n            items: limitedItems.map((item: InboxItem) => ({\n                originalContent: item.originalContent,\n                capturedAt: item.capturedAt.toISOString(),\n                capturedByPersonId: item.capturedByPersonId,\n                clarification: item.clarification || null,\n                isActionable: item.isActionable || null,\n                processingStatus: item.processingStatus as 'processed' | 'unprocessed'\n            }))\n        };\n    }\n\n    /**\n     * Import items from external format\n     * Supports migration from legacy formats\n     */\n    async importItems(\n        importData: InboxImportData,\n        options: {\n            skipDuplicates?: boolean;\n            capturedByPersonId?: string;\n        } = {}\n    ): Promise<InboxImportResult> {\n        this.validateImportData(importData);\n\n        const results: InboxImportResult = {\n            totalItems: importData.items.length,\n            imported: 0,\n            skipped: 0,\n            errors: []\n        };\n\n        for (const itemData of importData.items) {\n            try {\n                // Handle different input formats (legacy and new)\n                const content = itemData.originalContent || itemData.text || itemData.content;\n                if (!content) {\n                    results.errors.push(`Item missing content: ${JSON.stringify(itemData)}`);\n                    continue;\n                }\n\n                // Create domain aggregate\n                const item = InboxItem.capture(\n                    content,\n                    options.capturedByPersonId || itemData.capturedByPersonId || 'import-system'\n                );\n\n                // Apply additional properties if available (for processed items)\n                if (itemData.clarification && typeof itemData.isActionable === 'boolean') {\n                    item.clarify(itemData.clarification, itemData.isActionable, 'import-system');\n                }\n\n                // Persist via repository\n                await this.repository.save(item);\n                results.imported++;\n\n            } catch (error) {\n                if (options.skipDuplicates && error instanceof Error && error.message.includes('duplicate')) {\n                    results.skipped++;\n                } else {\n                    results.errors.push(`Failed to import item: ${error instanceof Error ? error.message : 'Unknown error'}`);\n                }\n            }\n        }\n\n        return results;\n    }\n\n    private validateImportData(data: InboxImportData): void {\n        if (!data.version) {\n            throw new Error('Import data missing version');\n        }\n        if (!data.items || !Array.isArray(data.items)) {\n            throw new Error('Import data missing or invalid items array');\n        }\n        if (data.items.length === 0) {\n            throw new Error('Import data contains no items');\n        }\n    }\n}\n\n// ============================================\n// TYPES\n// ============================================\n\nexport interface InboxExportData {\n    exportDate: string;\n    version: string;\n    source: string;\n    totalItems: number;\n    items: ExportedInboxItem[];\n}\n\nexport interface ExportedInboxItem {\n    originalContent: string;\n    capturedAt: string;\n    capturedByPersonId: string;\n    clarification: string | null;\n    isActionable: boolean | null;\n    processingStatus: 'processed' | 'unprocessed';\n}\n\nexport interface InboxImportData {\n    version: string;\n    items: ImportedInboxItem[];\n    source?: string;\n    exportDate?: string;\n}\n\nexport interface ImportedInboxItem {\n    // New format\n    originalContent?: string;\n    capturedByPersonId?: string;\n    clarification?: string | null;\n    isActionable?: boolean | null;\n    processingStatus?: 'processed' | 'unprocessed';\n    \n    // Legacy format support\n    text?: string;\n    content?: string;\n    status?: string;\n    priority?: string;\n    tags?: string[];\n    \n    // Metadata\n    capturedAt?: string;\n    createdAt?: string;\n    updatedAt?: string;\n}\n\nexport interface InboxImportResult {\n    totalItems: number;\n    imported: number;\n    skipped: number;\n    errors: string[];\n}","// TODO: DomainEvent should be imported from @swoft/core when available\n// import { DomainEvent } from '@swoft/core';\n\n/**\n * Temporary DomainEvent interface until proper import is available\n */\ninterface DomainEvent {\n  readonly eventId: string;\n  readonly aggregateId: string;\n  readonly eventType: string;\n  readonly occurredAt: Date;\n  readonly eventVersion: number;\n  getEventData(): Record<string, any>;\n}\n\n/**\n * GTD Domain Events following David Allen's methodology\n */\n\nexport class ProjectIdentified implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.ProjectIdentified';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly projectName: string,\n    public readonly desiredOutcome: string,\n    public readonly identifiedBy: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      projectName: this.projectName,\n      desiredOutcome: this.desiredOutcome,\n      identifiedBy: this.identifiedBy,\n      identifiedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class NextActionCreated implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.NextActionCreated';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly description: string,\n    public readonly context: string,\n    public readonly energyLevel: string,\n    public readonly createdBy: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      description: this.description,\n      context: this.context,\n      energyLevel: this.energyLevel,\n      createdBy: this.createdBy,\n      createdAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class TaskAssigned implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.TaskAssigned';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly assignedTo: string,\n    public readonly roleType: string,\n    public readonly assignedAt: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      assignedTo: this.assignedTo,\n      roleType: this.roleType,\n      assignedAt: this.assignedAt\n    };\n  }\n}\n\nexport class ProjectCompleted implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.ProjectCompleted';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly completedBy: string,\n    public readonly completionNotes?: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      completedBy: this.completedBy,\n      completionNotes: this.completionNotes,\n      completedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class NextActionCompleted implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.NextActionCompleted';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly completedBy: string,\n    public readonly completionNotes?: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      completedBy: this.completedBy,\n      completionNotes: this.completionNotes,\n      completedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class ReferenceDocumentAdded implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.ReferenceDocumentAdded';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly documentName: string,\n    public readonly documentType: string,\n    public readonly addedBy: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      documentName: this.documentName,\n      documentType: this.documentType,\n      addedBy: this.addedBy,\n      addedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class WeeklyReviewStarted implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.WeeklyReviewStarted';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly reviewId: string,\n    public readonly conductedBy: string\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      reviewId: this.reviewId,\n      conductedBy: this.conductedBy,\n      startedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class WeeklyReviewCompleted implements DomainEvent {\n  readonly eventId: string = crypto.randomUUID();\n  readonly aggregateId: string;\n  readonly eventType: string = 'gtd.WeeklyReviewCompleted';\n  readonly occurredAt: Date = new Date();\n  readonly eventVersion: number = 1;\n  readonly occurredOn: Date = new Date(); // For backward compatibility\n\n  constructor(\n    aggregateId: string,\n    public readonly reviewId: string,\n    public readonly reviewNotes: string,\n    public readonly nextActionsIdentified: number\n  ) {\n    this.aggregateId = aggregateId;\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      reviewId: this.reviewId,\n      reviewNotes: this.reviewNotes,\n      nextActionsIdentified: this.nextActionsIdentified,\n      completedAt: this.occurredOn.toISOString()\n    };\n  }\n}\n\nexport class NextActionEventData {\n  constructor(\n    public readonly projectName: string,\n    public readonly description: string,\n    public readonly context: string,\n    public readonly energyLevel: string,\n    public readonly estimatedDuration?: number,\n    public readonly tags?: string[]\n  ) {}\n}\n","import { ActionContext } from '../value-objects/ActionContext';\nimport { EnergyLevel } from '../value-objects/EnergyLevel';\nimport { DomainEvent } from '../events/DomainEvent';\nimport { NextActionCreated, TaskAssigned } from '../events/GTDEvents';\nimport { \n  AssignmentError, \n  ThoughtProcessingError \n} from '../errors/GTDDomainError';\n\n/**\n * GTD Next Action - the fundamental unit of actionable work\n * \"The next physical action required to move something forward\" - David Allen\n * \n * Core GTD Principle: Actions must be specific, actionable, and context-based\n */\nexport class NextAction {\n  private domainEvents: DomainEvent[] = [];\n  private _completedAt?: Date;\n  private _assignedTo?: string;\n  private _assignedAt?: Date;\n  private _roleType?: string;\n\n  constructor(\n    public readonly id: string,\n    public readonly description: string,\n    public readonly context: ActionContext,\n    public readonly energyRequired: EnergyLevel,\n    public readonly estimatedMinutes: number,\n    public readonly createdBy: string,\n    public readonly createdAt: Date = new Date(),\n    public readonly projectId?: string\n  ) {\n    this.validateAction(description, estimatedMinutes);\n    \n    this.addDomainEvent(new NextActionCreated(\n      id, \n      description, \n      context.toString(), \n      energyRequired.toString(), \n      createdBy\n    ));\n  }\n\n  /**\n   * Create a new next action with validation\n   */\n  static create(\n    description: string,\n    context: ActionContext,\n    energy: EnergyLevel,\n    minutes: number,\n    createdBy: string,\n    projectId?: string\n  ): NextAction {\n    const id = this.generateId();\n    return new NextAction(id, description, context, energy, minutes, createdBy, new Date(), projectId);\n  }\n\n  /**\n   * Reconstitute from persistence\n   */\n  static reconstitute(\n    id: string,\n    description: string,\n    context: ActionContext,\n    energy: EnergyLevel,\n    minutes: number,\n    createdBy: string,\n    createdAt: Date,\n    projectId?: string,\n    assignedTo?: string,\n    assignedAt?: Date,\n    roleType?: string,\n    completedAt?: Date\n  ): NextAction {\n    const action = new NextAction(id, description, context, energy, minutes, createdBy, createdAt, projectId);\n    \n    // Clear events from constructor\n    action.clearDomainEvents();\n    \n    // Restore state\n    if (assignedTo && assignedAt && roleType) {\n      action._assignedTo = assignedTo;\n      action._assignedAt = assignedAt;\n      action._roleType = roleType;\n    }\n    \n    if (completedAt) {\n      action._completedAt = completedAt;\n    }\n    \n    return action;\n  }\n\n  /**\n   * Assign this action to a developer/team member\n   * Integrates with Party Management domain\n   */\n  assignTo(partyId: string, roleType: string): void {\n    if (this.isCompleted()) {\n      throw new AssignmentError('Cannot assign completed actions', this.id);\n    }\n\n    if (this.isAssigned()) {\n      throw new AssignmentError(\n        `Action is already assigned to ${this._assignedTo}`, \n        this.id\n      );\n    }\n\n    if (!partyId?.trim()) {\n      throw new AssignmentError('Party ID is required for assignment', this.id);\n    }\n\n    if (!roleType?.trim()) {\n      throw new AssignmentError('Role type is required for assignment', this.id);\n    }\n\n    this._assignedTo = partyId;\n    this._roleType = roleType;\n    this._assignedAt = new Date();\n    \n    this.addDomainEvent(new TaskAssigned(\n      this.id, \n      partyId, \n      roleType, \n      this._assignedAt.toISOString()\n    ));\n  }\n\n  /**\n   * Unassign the action (return to available pool)\n   */\n  unassign(): void {\n    if (!this.isAssigned()) {\n      throw new AssignmentError('Action is not currently assigned', this.id);\n    }\n\n    if (this.isCompleted()) {\n      throw new AssignmentError('Cannot unassign completed actions', this.id);\n    }\n\n    this._assignedTo = undefined;\n    this._roleType = undefined;\n    this._assignedAt = undefined;\n  }\n\n  /**\n   * Mark action as completed\n   */\n  complete(): void {\n    if (this.isCompleted()) {\n      throw new ThoughtProcessingError('Action is already completed');\n    }\n\n    this._completedAt = new Date();\n  }\n\n  /**\n   * Check if action can be performed given current context and energy\n   * Core GTD principle: Match actions to available resources\n   */\n  canBePerformedWith(availableContext: ActionContext, availableEnergy: EnergyLevel): boolean {\n    if (this.isCompleted()) {\n      return false;\n    }\n\n    const contextMatch = this.context.equals(availableContext);\n    const energyMatch = this.energyRequired.canBePerformedWhen(availableEnergy);\n    \n    return contextMatch && energyMatch;\n  }\n\n  /**\n   * Get available actions that match criteria\n   */\n  static getAvailableActions(\n    actions: NextAction[], \n    context: ActionContext, \n    energy: EnergyLevel\n  ): NextAction[] {\n    return actions.filter(action => \n      !action.isCompleted() && \n      !action.isAssigned() && \n      action.canBePerformedWith(context, energy)\n    );\n  }\n\n  // State queries\n  isCompleted(): boolean {\n    return this._completedAt !== undefined;\n  }\n\n  isAssigned(): boolean {\n    return this._assignedTo !== undefined;\n  }\n\n  isAvailable(): boolean {\n    return !this.isCompleted() && !this.isAssigned();\n  }\n\n  // Getters\n  get assignedTo(): string | undefined {\n    return this._assignedTo;\n  }\n\n  get roleType(): string | undefined {\n    return this._roleType;\n  }\n\n  get assignedAt(): Date | undefined {\n    return this._assignedAt;\n  }\n\n  get completedAt(): Date | undefined {\n    return this._completedAt;\n  }\n\n  get status(): 'available' | 'assigned' | 'completed' {\n    if (this.isCompleted()) return 'completed';\n    if (this.isAssigned()) return 'assigned';\n    return 'available';\n  }\n\n  // Event sourcing support\n  getDomainEvents(): DomainEvent[] {\n    return [...this.domainEvents];\n  }\n\n  clearDomainEvents(): void {\n    this.domainEvents = [];\n  }\n\n  // Private methods\n  private validateAction(description: string, estimatedMinutes: number): void {\n    if (!description?.trim()) {\n      throw new ThoughtProcessingError('Action description is required');\n    }\n\n    if (estimatedMinutes <= 0) {\n      throw new ThoughtProcessingError('Estimated minutes must be positive');\n    }\n\n    // No upper limit validation - NextActions can take any reasonable duration\n    // The 2-minute rule is workflow guidance, not a domain constraint\n  }\n\n  private addDomainEvent(event: DomainEvent): void {\n    this.domainEvents.push(event);\n  }\n\n  private static generateId(): string {\n    return `action-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n  }\n}","/**\n * GTD Action Context - WHERE and HOW an action can be performed\n * Following David Allen's context-based action organization\n */\nexport class ActionContext {\n  private constructor(\n    public readonly context: string,\n    public readonly toolsRequired: string[] = [],\n    public readonly location?: string\n  ) {}\n\n  static atComputer(tools: string[] = []): ActionContext {\n    return new ActionContext('computer', tools);\n  }\n\n  static onPhone(tools: string[] = []): ActionContext {\n    return new ActionContext('phone', tools);\n  }\n\n  static atCalls(tools: string[] = []): ActionContext {\n    return new ActionContext('@calls', tools);\n  }\n\n  static atErrands(location: string = '', tools: string[] = []): ActionContext {\n    return new ActionContext('@errands', tools, location);\n  }\n\n  static anywhere(tools: string[] = []): ActionContext {\n    return new ActionContext('@anywhere', tools);\n  }\n\n  static atOffice(tools: string[] = []): ActionContext {\n    return new ActionContext('office', tools, 'office');\n  }\n\n  static atHome(tools: string[] = []): ActionContext {\n    return new ActionContext('home', tools, 'home');\n  }\n\n  static errands(location: string, tools: string[] = []): ActionContext {\n    return new ActionContext('errands', tools, location);\n  }\n\n  static agendaFor(person: string): ActionContext {\n    return new ActionContext('agenda', [], person);\n  }\n\n  static custom(context: string, tools: string[] = [], location?: string): ActionContext {\n    return new ActionContext(context, tools, location);\n  }\n\n  equals(other: ActionContext): boolean {\n    return this.context === other.context && \n           this.location === other.location &&\n           JSON.stringify(this.toolsRequired) === JSON.stringify(other.toolsRequired);\n  }\n\n  toString(): string {\n    // Return context directly if it already starts with @\n    if (this.context.startsWith('@')) {\n      return this.context;\n    }\n    // Add @ prefix for contexts that don't have it\n    const base = `@${this.context}`;\n    if (this.location) {\n      return `${base} (${this.location})`;\n    }\n    return base;\n  }\n}","/**\n * GTD Energy Level - matching actions to available energy\n * Helps optimize productivity based on current mental/physical state\n */\nexport class EnergyLevel {\n  private constructor(private readonly level: 'low' | 'medium' | 'high') {}\n\n  static low(): EnergyLevel {\n    return new EnergyLevel('low');\n  }\n\n  static medium(): EnergyLevel {\n    return new EnergyLevel('medium');\n  }\n\n  static high(): EnergyLevel {\n    return new EnergyLevel('high');\n  }\n\n  isLow(): boolean {\n    return this.level === 'low';\n  }\n\n  isMedium(): boolean {\n    return this.level === 'medium';\n  }\n\n  isHigh(): boolean {\n    return this.level === 'high';\n  }\n\n  /**\n   * Can this action be performed with the available energy level?\n   * GTD principle: Match actions to available energy\n   */\n  canBePerformedWhen(available: EnergyLevel): boolean {\n    const levels = { low: 1, medium: 2, high: 3 };\n    return levels[this.level] <= levels[available.level];\n  }\n\n  equals(other: EnergyLevel): boolean {\n    return this.level === other.level;\n  }\n\n  toString(): string {\n    return this.level;\n  }\n\n  valueOf(): string {\n    return this.level;\n  }\n}","import { InboxItem } from '../aggregates/InboxItem';\nimport { NextAction } from '../../../project-management/domain/aggregates/NextAction';\nimport { ActionContext } from '../../../project-management/domain/value-objects/ActionContext';\nimport { EnergyLevel } from '../../../project-management/domain/value-objects/EnergyLevel';\n\n/**\n * GTD Processing Workflow Service\n * \n * Implements David Allen's complete GTD methodology by orchestrating the flow\n * from inbox clarification to actionable work items (NextActions, Projects, etc.)\n * \n * Core GTD Decision Tree:\n * 1. What is it? (Clarification)\n * 2. Is it actionable? (Decision)\n * 3. If YES: What's the next action? (NextAction creation)\n * 4. If NO: Reference material, someday/maybe, or trash\n */\nexport class GTDProcessingWorkflowService {\n    \n    /**\n     * Process a clarified inbox item according to GTD methodology\n     * \n     * @param inboxItem - The clarified inbox item\n     * @param processingDecision - How the item should be processed\n     * @returns The created work items (NextActions, Projects, etc.)\n     */\n    processInboxItem(\n        inboxItem: InboxItem, \n        processingDecision: InboxProcessingDecision\n    ): GTDProcessingResult {\n        \n        if (!inboxItem.clarification) {\n            throw new Error('Inbox item must be clarified before processing');\n        }\n\n        if (inboxItem.processingStatus === 'unprocessed') {\n            throw new Error('Inbox item must be marked as processed');\n        }\n\n        // Execute GTD decision tree\n        if (inboxItem.isActionable === true) {\n            return this.handleActionableItem(inboxItem, processingDecision);\n        } else {\n            return this.handleNonActionableItem(inboxItem, processingDecision);\n        }\n    }\n\n    /**\n     * Handle actionable items (create NextActions or Projects)\n     */\n    private handleActionableItem(\n        inboxItem: InboxItem, \n        decision: InboxProcessingDecision\n    ): GTDProcessingResult {\n        \n        const result: GTDProcessingResult = {\n            success: true,\n            workflowType: 'actionable',\n            createdItems: []\n        };\n\n        // GTD Rule: If it takes less than 2 minutes, do it now\n        // Otherwise, defer it (NextAction) or delegate it\n        \n        if (decision.estimatedMinutes && decision.estimatedMinutes <= 2) {\n            // Create immediate action\n            const nextAction = this.createNextAction(inboxItem, decision);\n            result.createdItems.push({\n                type: 'next_action',\n                id: nextAction.id,\n                description: nextAction.description,\n                urgent: true,\n                reason: 'Two-minute rule: Do it now'\n            });\n        } else if (decision.isProject) {\n            // Multi-step outcomes require a project\n            result.workflowType = 'project';\n            result.createdItems.push({\n                type: 'project',\n                id: `project-${Date.now()}`,\n                description: decision.projectOutcome || inboxItem.clarification || 'New project',\n                reason: 'Multi-step outcome requires project planning'\n            });\n            \n            // Create the first next action for the project\n            const firstAction = this.createNextAction(inboxItem, decision);\n            result.createdItems.push({\n                type: 'next_action',\n                id: firstAction.id,\n                description: firstAction.description,\n                urgent: false,\n                reason: 'First action for project'\n            });\n        } else {\n            // Single next action\n            const nextAction = this.createNextAction(inboxItem, decision);\n            result.createdItems.push({\n                type: 'next_action',\n                id: nextAction.id,\n                description: nextAction.description,\n                urgent: false,\n                reason: 'Single actionable item'\n            });\n        }\n\n        return result;\n    }\n\n    /**\n     * Handle non-actionable items (reference, someday/maybe, trash)\n     */\n    private handleNonActionableItem(\n        inboxItem: InboxItem, \n        decision: InboxProcessingDecision\n    ): GTDProcessingResult {\n        \n        const result: GTDProcessingResult = {\n            success: true,\n            workflowType: 'non_actionable',\n            createdItems: []\n        };\n\n        if (decision.isReference) {\n            // Store as reference material\n            result.createdItems.push({\n                type: 'reference_material',\n                id: `ref-${Date.now()}`,\n                description: inboxItem.clarification || 'Reference material',\n                reason: 'Useful information for future reference'\n            });\n        } else if (decision.isSomedayMaybe) {\n            // Add to Someday/Maybe list\n            result.createdItems.push({\n                type: 'someday_maybe',\n                id: `someday-${Date.now()}`,\n                description: inboxItem.clarification || 'Someday/Maybe item',\n                reason: 'Potentially actionable in the future'\n            });\n        } else {\n            // Trash - no action needed\n            result.workflowType = 'trash';\n            result.reason = 'Not actionable and not worth keeping';\n        }\n\n        return result;\n    }\n\n    /**\n     * Create a NextAction from an inbox item\n     */\n    private createNextAction(\n        inboxItem: InboxItem, \n        decision: InboxProcessingDecision\n    ): NextAction {\n        \n        // Determine context - default to @computer if not specified\n        const context = decision.context \n            ? this.parseActionContext(decision.context)\n            : ActionContext.atComputer();\n\n        // Determine energy level - default to medium\n        const energyLevel = decision.energyLevel\n            ? this.parseEnergyLevel(decision.energyLevel)\n            : EnergyLevel.medium();\n\n        // Estimate time - default to 1 minute\n        const estimatedMinutes = decision.estimatedMinutes || 1;\n\n        // Create the action description\n        const actionDescription = decision.nextActionDescription \n            || this.generateActionDescription(inboxItem.clarification || '');\n\n        return NextAction.create(\n            actionDescription,\n            context,\n            energyLevel,\n            estimatedMinutes,\n            inboxItem.capturedByPersonId,\n            decision.projectId\n        );\n    }\n\n    /**\n     * Parse context string into ActionContext object\n     */\n    private parseActionContext(contextString: string): ActionContext {\n        const context = contextString.toLowerCase().replace('@', '');\n        \n        switch (context) {\n            case 'computer':\n                return ActionContext.atComputer();\n            case 'phone':\n            case 'calls':\n                return ActionContext.onPhone();\n            case 'office':\n                return ActionContext.atOffice();\n            case 'home':\n                return ActionContext.atHome();\n            case 'errands':\n                return ActionContext.errands('general');\n            default:\n                return ActionContext.custom(context);\n        }\n    }\n\n    /**\n     * Parse energy level string into EnergyLevel object\n     */\n    private parseEnergyLevel(energyString: string): EnergyLevel {\n        const level = energyString.toLowerCase();\n        \n        switch (level) {\n            case 'high':\n                return EnergyLevel.high();\n            case 'low':\n                return EnergyLevel.low();\n            case 'medium':\n            default:\n                return EnergyLevel.medium();\n        }\n    }\n\n    /**\n     * Generate a proper action description from clarification\n     * GTD Principle: Actions must be specific and physical\n     */\n    private generateActionDescription(clarification: string): string {\n        // Simple heuristic to make actions more specific\n        const actionVerbs = ['Call', 'Email', 'Write', 'Research', 'Review', 'Schedule', 'Update'];\n        \n        // If clarification already starts with an action verb, use it\n        const hasActionVerb = actionVerbs.some(verb => \n            clarification.toLowerCase().startsWith(verb.toLowerCase())\n        );\n\n        if (hasActionVerb) {\n            return clarification;\n        }\n\n        // Otherwise, prefix with a default action verb\n        return `Research: ${clarification}`;\n    }\n}\n\n/**\n * Input for processing decisions\n */\nexport interface InboxProcessingDecision {\n    // Action characteristics\n    estimatedMinutes?: number;\n    context?: string; // @calls, @computer, @errands, etc.\n    energyLevel?: string; // high, medium, low\n    nextActionDescription?: string;\n    \n    // Workflow decisions\n    isProject?: boolean;\n    projectOutcome?: string;\n    projectId?: string;\n    \n    // Non-actionable decisions\n    isReference?: boolean;\n    isSomedayMaybe?: boolean;\n}\n\n/**\n * Result of GTD processing workflow\n */\nexport interface GTDProcessingResult {\n    success: boolean;\n    workflowType: 'actionable' | 'project' | 'non_actionable' | 'trash';\n    createdItems: Array<{\n        type: 'next_action' | 'project' | 'reference_material' | 'someday_maybe';\n        id: string;\n        description: string;\n        urgent?: boolean;\n        reason: string;\n    }>;\n    reason?: string;\n    error?: string;\n}","/**\n * Complete GTD Processing Command\n * \n * Implements David Allen's full Getting Things Done methodology:\n * 1. Capture (already done - item is in inbox)\n * 2. Clarify (what is it? is it actionable?)\n * 3. Organize (create NextActions, Projects, Reference, or Someday/Maybe)\n * 4. Reflect (maintain system integrity) \n * 5. Engage (choose actions based on context and energy)\n * \n * This command bridges steps 2-3, completing the missing workflow\n * that converts inbox items into actionable work items.\n */\nexport interface CompleteGTDProcessingCommand {\n    // Core identification\n    itemId: string;\n    processedByPersonId: string;\n    \n    // GTD Clarification (Step 2)\n    clarification: string;\n    isActionable: boolean;\n    \n    // GTD Organization (Step 3) - Action Properties\n    estimatedMinutes?: number;      // GTD: If ≤2 minutes, do now\n    context?: string;               // @calls, @computer, @errands, @home, etc.\n    energyLevel?: string;           // high, medium, low (for energy-based selection)\n    nextActionDescription?: string; // Specific, physical action description\n    \n    // GTD Organization (Step 3) - Project Properties  \n    isProject?: boolean;            // Multi-step outcome requiring project\n    projectOutcome?: string;        // Desired end result for project\n    \n    // GTD Organization (Step 3) - Non-actionable Properties\n    isReference?: boolean;          // Useful information to keep\n    isSomedayMaybe?: boolean;      // Potentially actionable in future\n}\n\n/**\n * Result of complete GTD processing\n */\nexport interface CompleteGTDProcessingResult {\n    success: boolean;\n    itemId: string;\n    processedAt?: string;\n    \n    // GTD Clarification Results\n    clarification?: string;\n    isActionable?: boolean;\n    workflowType?: 'actionable' | 'project' | 'non_actionable' | 'trash';\n    \n    // GTD Organization Results\n    createdWorkItems?: Array<{\n        type: 'next_action' | 'project' | 'reference_material' | 'someday_maybe';\n        id: string;\n        description: string;\n        status: string;\n        urgent?: boolean;\n        reason?: string;\n    }>;\n    \n    // Operation Results\n    message: string;\n    error?: string;\n    \n    // GTD System Statistics (helpful for dashboard)\n    gtdMetrics?: {\n        totalInboxItems: number;\n        processedToday: number;\n        nextActionsCreated: number;\n        projectsCreated: number;\n        referencesStored: number;\n        somedayItems: number;\n    };\n}\n\n/**\n * Command Validation Helpers\n */\nexport class CompleteGTDProcessingCommandValidator {\n    \n    static validate(command: CompleteGTDProcessingCommand): ValidationResult {\n        const errors: string[] = [];\n        \n        // Required fields\n        if (!command.itemId?.trim()) {\n            errors.push('Item ID is required');\n        }\n        \n        if (!command.processedByPersonId?.trim()) {\n            errors.push('Processed by person ID is required');\n        }\n        \n        if (!command.clarification?.trim()) {\n            errors.push('Clarification is required for GTD processing');\n        }\n        \n        if (command.isActionable === undefined || command.isActionable === null) {\n            errors.push('Actionable decision is required (true/false)');\n        }\n        \n        // GTD-specific validations\n        if (command.isActionable) {\n            // Actionable items should have action context\n            if (command.estimatedMinutes && command.estimatedMinutes > 120) {\n                errors.push('Actions over 2 hours should be broken into smaller steps');\n            }\n            \n            if (command.isProject && !command.projectOutcome?.trim()) {\n                errors.push('Project outcome is required for multi-step items');\n            }\n        } else {\n            // Non-actionable items should specify disposal method\n            const hasDisposalMethod = command.isReference || command.isSomedayMaybe;\n            if (!hasDisposalMethod) {\n                errors.push('Non-actionable items must specify reference or someday/maybe');\n            }\n        }\n        \n        // Context validation\n        if (command.context) {\n            const validContexts = ['@calls', '@computer', '@errands', '@home', '@office', '@anywhere'];\n            const isValidContext = validContexts.includes(command.context.toLowerCase()) || \n                                 command.context.startsWith('@');\n            \n            if (!isValidContext) {\n                errors.push('Context must start with @ (e.g., @calls, @computer)');\n            }\n        }\n        \n        // Energy level validation\n        if (command.energyLevel) {\n            const validEnergyLevels = ['high', 'medium', 'low'];\n            if (!validEnergyLevels.includes(command.energyLevel.toLowerCase())) {\n                errors.push('Energy level must be high, medium, or low');\n            }\n        }\n        \n        return {\n            isValid: errors.length === 0,\n            errors\n        };\n    }\n}\n\ninterface ValidationResult {\n    isValid: boolean;\n    errors: string[];\n}\n\n/**\n * GTD Context Constants\n * Based on David Allen's recommended contexts\n */\nexport const GTD_CONTEXTS = {\n    CALLS: '@calls',\n    COMPUTER: '@computer', \n    ERRANDS: '@errands',\n    HOME: '@home',\n    OFFICE: '@office',\n    ANYWHERE: '@anywhere',\n    WAITING: '@waiting_for',\n    READ_REVIEW: '@read_review'\n} as const;\n\n/**\n * GTD Energy Levels\n * For matching actions to available mental/physical energy\n */\nexport const GTD_ENERGY_LEVELS = {\n    HIGH: 'high',      // Creative work, complex problem-solving\n    MEDIUM: 'medium',  // Routine tasks, administrative work\n    LOW: 'low'         // Mindless tasks, filing, organizing\n} as const;","import { injectable, inject } from 'inversify';\nimport { GTD_DOMAIN_SYMBOLS } from '../../../../infrastructure/di/GTDDomainSymbols';\nimport { InboxItem } from \"../../domain/aggregates/InboxItem\";\nimport { InboxItemAggregateRepository } from \"../../infrastructure/repositories/InboxItemAggregateRepository\";\nimport { GTDProcessingWorkflowService, InboxProcessingDecision, GTDProcessingResult } from \"../../domain/services/GTDProcessingWorkflowService\";\nimport { NextActionAggregateRepository } from \"../../../project-management/infrastructure/repositories/NextActionAggregateRepository\";\nimport {\n    CreateInboxItemCommand,\n    CreateInboxItemResult\n} from \"../commands/CreateInboxItemCommand\";\nimport {\n    DeleteInboxItemCommand,\n    DeleteInboxItemResult\n} from \"../commands/DeleteInboxItemCommand\";\nimport {\n    ProcessInboxItemCommand,\n    ProcessInboxItemResult\n} from \"../commands/ProcessInboxItemCommand\";\n\n/**\n * Unified Inbox Item Application Service\n * \n * Following Eric Evans Application Service pattern - single point of entry \n * for all inbox item operations. Coordinates domain operations and provides\n * a clean interface for external clients.\n * \n * Benefits:\n * - Single responsibility per operation\n * - Consistent error handling\n * - Transaction boundaries\n * - Clear API for MCP/UI layers\n */\n@injectable()\nexport class InboxItemApplicationService {\n    private readonly workflowService: GTDProcessingWorkflowService;\n\n    constructor(\n        @inject(GTD_DOMAIN_SYMBOLS.InboxItemAggregateRepository) \n        private readonly repository: InboxItemAggregateRepository,\n        @inject(GTD_DOMAIN_SYMBOLS.NextActionAggregateRepository)\n        _nextActionRepository: NextActionAggregateRepository\n    ) {\n        this.workflowService = new GTDProcessingWorkflowService();\n    }\n\n    /**\n     * Create a new inbox item - GTD Capture workflow\n     */\n    async createInboxItem(command: CreateInboxItemCommand): Promise<CreateInboxItemResult> {\n        try {\n            // 1. Create domain aggregate using factory\n            const item = InboxItem.capture(\n                command.originalContent,\n                command.capturedByPersonId\n            );\n\n            // 2. Persist via repository\n            await this.repository.save(item);\n\n            // 3. Return structured result\n            return {\n                success: true,\n                itemId: item.id,\n                capturedAt: item.capturedAt.toISOString(),\n                message: `GTD inbox item created successfully`\n            };\n\n        } catch (error) {\n            throw error; // Let caller handle formatting\n        }\n    }\n\n    /**\n     * Delete an inbox item\n     */\n    async deleteInboxItem(command: DeleteInboxItemCommand): Promise<DeleteInboxItemResult> {\n        try {\n            // 1. Load the aggregate\n            const item = await this.repository.findById(command.itemId);\n            if (!item) {\n                throw new Error(`Inbox item with ID ${command.itemId} not found`);\n            }\n\n            // 2. Apply domain rules (if any)\n            // TODO: Add deletion validation rules\n\n            // 3. Delete from repository\n            await this.repository.delete(command.itemId);\n\n            // 4. Return result\n            return {\n                success: true,\n                itemId: command.itemId,\n                deletedAt: new Date().toISOString(),\n                message: `GTD inbox item deleted successfully`\n            };\n\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Process an inbox item - GTD Clarification workflow\n     */\n    async processInboxItem(command: ProcessInboxItemCommand): Promise<ProcessInboxItemResult> {\n        try {\n            // 1. Load the aggregate\n            const item = await this.repository.findById(command.itemId);\n            if (!item) {\n                throw new Error(`Inbox item with ID ${command.itemId} not found`);\n            }\n\n            // 2. Apply clarification using domain method\n            if (command.clarification && command.isActionable !== undefined) {\n                item.clarify(\n                    command.clarification,\n                    command.isActionable,\n                    command.processedByPersonId\n                );\n            }\n\n            // 3. Persist changes\n            await this.repository.save(item);\n\n            // 4. Return result\n            return {\n                success: true,\n                itemId: command.itemId,\n                processedAt: new Date().toISOString(),\n                status: command.status || 'processed',\n                message: `GTD inbox item processed successfully`\n            };\n\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * List inbox items with filtering\n     */\n    async listInboxItems(filters: {\n        status?: string;\n        priority?: string;\n        limit?: number;\n        offset?: number;\n    }) {\n        try {\n            // 1. Apply filters and pagination\n            const items = await this.repository.findByFilters({\n                status: filters.status,\n                priority: filters.priority,\n                limit: Math.min(filters.limit || 20, 100),\n                offset: filters.offset || 0\n            });\n\n            // 2. Get total count\n            const totalCount = await this.repository.countByFilters({\n                status: filters.status,\n                priority: filters.priority\n            });\n\n            // 3. Transform to DTOs\n            const itemDtos = items.map((item: InboxItem) => ({\n                id: item.id,\n                originalContent: item.originalContent,\n                capturedAt: item.capturedAt.toISOString(),\n                capturedByPersonId: item.capturedByPersonId,\n                clarification: item.clarification,\n                isActionable: item.isActionable,\n                processingStatus: item.processingStatus.toString()\n            }));\n\n            return {\n                items: itemDtos,\n                totalCount,\n                hasMoreResults: (filters.offset || 0) + (filters.limit || 20) < totalCount\n            };\n\n        } catch (error) {\n            throw error;\n        }\n    }\n\n    /**\n     * Complete GTD Processing Workflow\n     * \n     * This method implements David Allen's full GTD methodology:\n     * 1. Clarify the inbox item\n     * 2. Decide if it's actionable\n     * 3. Organize into appropriate work items (NextActions, Projects, etc.)\n     * \n     * This is the MISSING PIECE that completes the GTD workflow!\n     */\n    async completeGTDProcessing(request: {\n        itemId: string;\n        clarification: string;\n        isActionable: boolean;\n        processedByPersonId: string;\n        \n        // Processing decisions\n        estimatedMinutes?: number;\n        context?: string;\n        energyLevel?: string;\n        nextActionDescription?: string;\n        isProject?: boolean;\n        projectOutcome?: string;\n        isReference?: boolean;\n        isSomedayMaybe?: boolean;\n    }): Promise<CompleteGTDProcessingResult> {\n        try {\n            // 1. Load and clarify the inbox item\n            const item = await this.repository.findById(request.itemId);\n            if (!item) {\n                throw new Error(`Inbox item with ID ${request.itemId} not found`);\n            }\n\n            // 2. Apply clarification\n            item.clarify(\n                request.clarification,\n                request.isActionable,\n                request.processedByPersonId\n            );\n\n            // 3. Save the clarified item\n            await this.repository.save(item);\n\n            // 4. Execute GTD workflow processing\n            const processingDecision: InboxProcessingDecision = {\n                estimatedMinutes: request.estimatedMinutes,\n                context: request.context,\n                energyLevel: request.energyLevel,\n                nextActionDescription: request.nextActionDescription,\n                isProject: request.isProject,\n                projectOutcome: request.projectOutcome,\n                isReference: request.isReference,\n                isSomedayMaybe: request.isSomedayMaybe\n            };\n\n            const workflowResult = this.workflowService.processInboxItem(item, processingDecision);\n\n            // 5. Persist the created work items\n            const createdWorkItems = await this.persistWorkItems(workflowResult);\n\n            // 6. Return comprehensive result\n            return {\n                success: true,\n                itemId: request.itemId,\n                processedAt: new Date().toISOString(),\n                clarification: request.clarification,\n                isActionable: request.isActionable,\n                workflowType: workflowResult.workflowType,\n                createdWorkItems,\n                message: `GTD processing completed successfully. Created ${createdWorkItems.length} work items.`\n            };\n\n        } catch (error) {\n            return {\n                success: false,\n                itemId: request.itemId,\n                error: error instanceof Error ? error.message : 'Unknown error during GTD processing',\n                message: 'GTD processing failed'\n            };\n        }\n    }\n\n    /**\n     * Persist the work items created by GTD processing\n     */\n    private async persistWorkItems(workflowResult: GTDProcessingResult): Promise<Array<{\n        type: string;\n        id: string;\n        description: string;\n        status: string;\n    }>> {\n        const persistedItems = [];\n\n        for (const item of workflowResult.createdItems) {\n            if (item.type === 'next_action') {\n                // TODO: Create and save NextAction via repository\n                // For now, we'll return the placeholder\n                persistedItems.push({\n                    type: 'next_action',\n                    id: item.id,\n                    description: item.description,\n                    status: 'created'\n                });\n            } else if (item.type === 'project') {\n                // TODO: Create and save Project via repository\n                persistedItems.push({\n                    type: 'project',\n                    id: item.id,\n                    description: item.description,\n                    status: 'created'\n                });\n            } else if (item.type === 'reference_material') {\n                // TODO: Create and save Reference Material\n                persistedItems.push({\n                    type: 'reference_material',\n                    id: item.id,\n                    description: item.description,\n                    status: 'stored'\n                });\n            } else if (item.type === 'someday_maybe') {\n                // TODO: Create and save Someday/Maybe item\n                persistedItems.push({\n                    type: 'someday_maybe',\n                    id: item.id,\n                    description: item.description,\n                    status: 'deferred'\n                });\n            }\n        }\n\n        return persistedItems;\n    }\n}\n\n/**\n * Result of complete GTD processing\n */\nexport interface CompleteGTDProcessingResult {\n    success: boolean;\n    itemId: string;\n    processedAt?: string;\n    clarification?: string;\n    isActionable?: boolean;\n    workflowType?: string;\n    createdWorkItems?: Array<{\n        type: string;\n        id: string;\n        description: string;\n        status: string;\n    }>;\n    message: string;\n    error?: string;\n}","/**\n * GTD Domain Symbols - String constants for dependency injection\n * \n * Separated from container module to avoid circular dependencies.\n * Services import symbols, container module imports services - this breaks the cycle.\n */\nexport const GTD_DOMAIN_SYMBOLS = {\n  // Inbox Management Bounded Context\n  InboxItemApplicationService: 'InboxItemApplicationService',\n  InboxItemAggregateRepository: 'InboxItemAggregateRepository',\n  GTDQueryService: 'GTDQueryService',\n  PersonLookupService: 'PersonLookupService',\n  GTDProcessingWorkflowService: 'GTDProcessingWorkflowService',\n  InboxImportExportService: 'InboxImportExportService',\n  \n  // Project Management Bounded Context\n  ProjectApplicationService: 'GTDProjectApplicationService',\n  ProjectReadService: 'ProjectReadService',\n  ProjectRepository: 'ProjectRepository',\n  NextActionAggregateRepository: 'NextActionAggregateRepository',\n  NextActionWriteService: 'NextActionWriteService',\n  NextActionReadService: 'NextActionReadService',\n  \n  // Task Management Bounded Context\n  ITaskRepository: 'ITaskRepository',\n  TaskMongoRepository: 'TaskMongoRepository',\n  GetReferenceItemService: 'GetReferenceItemService',\n  InboxFileRepository: 'InboxFileRepository',\n  NextActionsFileRepository: 'NextActionsFileRepository',\n  \n  // Cross-cutting Services\n  GtdDomainSeeder: 'GtdDomainSeeder'\n};","import { injectable } from 'inversify';\nimport { Collection, Db, getMongoDb } from \"@swoft/persistence\";\nimport { InboxItem } from '../../domain/aggregates/InboxItem';\nimport { GTD_COLLECTIONS } from '../../../../config/collections';\n\n/**\n * MongoDB Repository for InboxItem Aggregate\n * \n * PRODUCTION IMPLEMENTATION:\n * - Uses UUID as primary key (not MongoDB ObjectId)\n * - Standardized field mapping between database and domain\n * - No leaky abstractions or multiple ID formats\n * - Clean adapter pattern following Eric Evans DDD\n */\n@injectable()\nexport class InboxItemAggregateRepository {\n    private db: Db | null = null;\n    private collection: Collection | null = null;\n\n    constructor() {\n        // Lazy initialization - don't connect until needed\n    }\n\n    private ensureConnection() {\n        if (!this.db) {\n            this.db = getMongoDb();\n            this.collection = this.db.collection(GTD_COLLECTIONS.INBOX_ITEMS);\n        }\n        return this.collection!;\n    }\n\n    async save(item: InboxItem): Promise<void> {\n        const collection = this.ensureConnection();\n        const itemData = item.toData();\n        \n        // Standardized database schema - SINGLE source of truth\n        const doc = {\n            _id: item.id, // Use UUID as MongoDB _id for consistency\n            originalContent: itemData.originalContent,\n            capturedAt: item.capturedAt,\n            capturedByPersonId: itemData.capturedByPersonId,\n            clarification: itemData.clarification,\n            isActionable: itemData.isActionable,\n            processingStatus: itemData.processingStatus,\n            lastRefinedAt: itemData.lastRefinedAt,\n            refinedByPersonId: itemData.refinedByPersonId,\n            updatedAt: new Date()\n        };\n\n        await collection.replaceOne(\n            { _id: item.id as any },\n            doc,\n            { upsert: true }\n        );\n    }\n\n    async findById(id: string): Promise<InboxItem | null> {\n        const collection = this.ensureConnection();\n        const doc = await collection.findOne({ _id: id as any });\n        if (!doc) return null;\n\n        return this.mapDocumentToDomain(doc);\n    }\n\n    private mapDocumentToDomain(doc: any): InboxItem {\n        return InboxItem.fromRepository({\n            id: doc._id,\n            originalContent: doc.originalContent || '',\n            capturedAt: new Date(doc.capturedAt),\n            capturedByPersonId: doc.capturedByPersonId,\n            clarification: doc.clarification,\n            isActionable: doc.isActionable,\n            processingStatus: doc.processingStatus || 'unprocessed',\n            lastRefinedAt: doc.lastRefinedAt ? new Date(doc.lastRefinedAt) : undefined,\n            refinedByPersonId: doc.refinedByPersonId\n        });\n    }\n\n    async findAll(): Promise<InboxItem[]> {\n        const collection = this.ensureConnection();\n        const docs = await collection.find({}).toArray();\n        return docs.map(doc => this.mapDocumentToDomain(doc));\n    }\n\n    async countUnprocessed(): Promise<number> {\n        const collection = this.ensureConnection();\n        return await collection.countDocuments({\n            processingStatus: 'unprocessed'\n        });\n    }\n\n    async countAll(): Promise<number> {\n        const collection = this.ensureConnection();\n        return await collection.countDocuments({});\n    }\n\n    async delete(id: string): Promise<void> {\n        const collection = this.ensureConnection();\n        await collection.deleteOne({ _id: id as any });\n    }\n\n    async findByFilters(filters: {\n        status?: string;\n        priority?: string;\n        limit?: number;\n        offset?: number;\n    }): Promise<InboxItem[]> {\n        const query: any = {};\n\n        if (filters.status && filters.status !== 'all') {\n            query.processingStatus = filters.status === 'processed' ? 'processed' : 'unprocessed';\n        }\n        const collection = this.ensureConnection();\n        const docs = await collection\n            .find(query)\n            .sort({ capturedAt: -1 })\n            .skip(filters.offset || 0)\n            .limit(filters.limit || 20)\n            .toArray();\n\n        return docs.map(doc => this.mapDocumentToDomain(doc));\n    }\n\n    async countByFilters(filters: {\n        status?: string;\n        priority?: string;\n    }): Promise<number> {\n        const query: any = {};\n\n        if (filters.status && filters.status !== 'all') {\n            query.processingStatus = filters.status === 'processed' ? 'processed' : 'unprocessed';\n        }\n\n        const collection = this.ensureConnection();\n        return await collection.countDocuments(query);\n    }\n}\n","/**\n * @swoft/gtd-domain - MongoDB Collection Configuration\n * \n * Centralized definition of all collection names used by the GTD bounded contexts.\n * Leverages the @swoft/mongo package for database connection management.\n * \n * Following David Allen's GTD methodology with clean separation of:\n * - Inbox Management (capture)\n * - Project Management (organize/clarify)  \n * - Task Management (engage)\n * - Reference Management (reference materials)\n */\n\nimport { getMongoDb } from \"@swoft/persistence\";\nimport type { Collection, Document } from 'mongodb';\n\n\n/**\n * MongoDB Collection Names for GTD Domain Package\n * \n * Standardized naming convention: gtd_{context}_{entity}\n * Resolves inconsistencies between repositories and controllers\n */\nexport const GTD_COLLECTIONS = {\n  // Inbox Management Bounded Context\n  INBOX_ITEMS: 'gtd_inbox_items',\n  \n  // Project Management Bounded Context  \n  PROJECTS: 'gtd_projects',\n  NEXT_ACTIONS: 'gtd_next_actions',\n  \n  // Task Management Bounded Context\n  TASK_ASSIGNMENTS: 'gtd_task_assignments',\n  \n  // Design Implementation Coordination Bounded Context\n  DESIGN_IMPLEMENTATION_FLOWS: 'gtd_design_implementation_flows',\n  \n  // Reference Management Bounded Context\n  REFERENCE_ITEMS: 'gtd_reference_items',\n  AGENT_API_KEYS: 'gtd_agent_api_keys',\n  \n  // Someday/Maybe List\n  SOMEDAY_MAYBE: 'gtd_someday_maybe'\n} as const;\n\n/**\n * Type-safe collection name type\n */\nexport type GTDCollectionName = typeof GTD_COLLECTIONS[keyof typeof GTD_COLLECTIONS];\n\n/**\n * Get a MongoDB collection using the centralized @swoft/mongo package\n * \n * @param collectionName - The collection constant from GTD_COLLECTIONS\n * @returns MongoDB Collection instance\n */\nexport function getGTDCollection<T extends Document = Document>(collectionName: GTDCollectionName): Collection<T> {\n  const db = getMongoDb(); // Uses existing @swoft/mongo package\n  return db.collection<T>(collectionName);\n}\n\n/**\n * Collection metadata with bounded context mapping\n * Following David Allen's GTD methodology and DDD principles\n */\nexport const GTD_COLLECTION_METADATA = {\n  [GTD_COLLECTIONS.INBOX_ITEMS]: {\n    boundedContext: 'inbox-management',\n    description: 'Captured thoughts, ideas, and information awaiting processing (GTD Capture phase)',\n    primaryKey: 'itemId',\n    gtdPhase: 'capture',\n    aggregateRoot: 'InboxItem'\n  },\n  [GTD_COLLECTIONS.PROJECTS]: {\n    boundedContext: 'project-management', \n    description: 'Multi-step outcomes and projects with desired results (GTD Organize phase)',\n    primaryKey: 'projectId',\n    gtdPhase: 'organize',\n    aggregateRoot: 'Project'\n  },\n  [GTD_COLLECTIONS.NEXT_ACTIONS]: {\n    boundedContext: 'project-management',\n    description: 'Physical next actions with context and energy requirements (GTD Organize/Engage phase)',\n    primaryKey: 'actionId',\n    gtdPhase: 'engage',\n    aggregateRoot: 'NextAction'\n  },\n  [GTD_COLLECTIONS.TASK_ASSIGNMENTS]: {\n    boundedContext: 'task-management',\n    description: 'Task assignments and delegation tracking with status and metadata',\n    primaryKey: 'assignmentId',\n    gtdPhase: 'engage',\n    aggregateRoot: 'TaskAssignment'\n  },\n  [GTD_COLLECTIONS.DESIGN_IMPLEMENTATION_FLOWS]: {\n    boundedContext: 'design-implementation-coordination',\n    description: 'Design-to-implementation coordination flows with artifact tracking and conformance validation',\n    primaryKey: 'flowId',\n    gtdPhase: 'organize',\n    aggregateRoot: 'DesignImplementationFlow'\n  },\n  [GTD_COLLECTIONS.REFERENCE_ITEMS]: {\n    boundedContext: 'reference-management',\n    description: 'Reference materials and information for future use (GTD Reference system)',\n    primaryKey: 'referenceId',\n    gtdPhase: 'organize',\n    aggregateRoot: 'ReferenceItem'\n  },\n  [GTD_COLLECTIONS.AGENT_API_KEYS]: {\n    boundedContext: 'reference-management',\n    description: 'API keys and agent configurations for external integrations',\n    primaryKey: 'keyId',\n    gtdPhase: 'organize',\n    aggregateRoot: 'AgentApiKey'\n  }\n} as const;\n\n/**\n * Package Information (following @swoft/dev-ops pattern)\n */\nexport const GTD_DOMAIN_PACKAGE_INFO = {\n  name: '@swoft/gtd-domain',\n  version: '0.1.0',\n  description: 'Getting Things Done (GTD) methodology implementation with Domain-Driven Design',\n  architecture: 'Clean Architecture + Domain-Driven Design',\n  methodology: 'David Allen GTD (Getting Things Done)',\n  boundedContexts: [\n    'Inbox Management',\n    'Project Management', \n    'Task Management',\n    'Reference Management'\n  ],\n  gtdPhases: [\n    'Capture',\n    'Clarify', \n    'Organize',\n    'Reflect',\n    'Engage'\n  ],\n  collections: Object.values(GTD_COLLECTIONS),\n  databaseDependency: '@swoft/mongo'\n} as const;\n\n/**\n * Collection Migration Guide\n * \n * BREAKING CHANGES from previous hardcoded collection names:\n * \n * OLD → NEW (STANDARDIZED)\n * 'gtd_inbox' → 'gtd_inbox_items' (resolves controller/repository mismatch)\n * 'swoft_builder__task_assignments' → 'gtd_task_assignments' (consistent naming)\n * 'gtd_reference_store__reference_items' → 'gtd_reference_items' (simplified)\n * 'gtd_reference_store__agent_api_keys' → 'gtd_agent_api_keys' (simplified)\n * \n * CONSISTENT (no changes needed):\n * 'gtd_projects' ✓\n * 'gtd_next_actions' ✓\n */\nexport const GTD_COLLECTION_MIGRATION_GUIDE = {\n  migrations: [\n    {\n      from: 'gtd_inbox',\n      to: GTD_COLLECTIONS.INBOX_ITEMS,\n      reason: 'Resolve mismatch between InboxItemAggregateRepository and GTDSystemController',\n      affectedFiles: [\n        'InboxItemAggregateRepository.ts',\n        'GTDSharedQueryRepository.ts'\n      ]\n    },\n    {\n      from: 'swoft_builder__task_assignments', \n      to: GTD_COLLECTIONS.TASK_ASSIGNMENTS,\n      reason: 'Consistent GTD naming convention',\n      affectedFiles: [\n        'TaskMongoRepository.ts'\n      ]\n    },\n    {\n      from: 'gtd_reference_store__reference_items',\n      to: GTD_COLLECTIONS.REFERENCE_ITEMS, \n      reason: 'Simplified naming without nested prefixes',\n      affectedFiles: [\n        'collectionNames.ts'\n      ]\n    },\n    {\n      from: 'gtd_reference_store__agent_api_keys',\n      to: GTD_COLLECTIONS.AGENT_API_KEYS,\n      reason: 'Simplified naming without nested prefixes', \n      affectedFiles: [\n        'collectionNames.ts'\n      ]\n    }\n  ]\n} as const;","import { injectable } from 'inversify';\nimport { Collection, Db, getMongoDb } from \"@swoft/persistence\";\nimport { NextAction } from '../../domain/aggregates/NextAction';\nimport { ActionContext, EnergyLevel } from '../../domain/value-objects';\n\n/**\n * MongoDB Repository for NextAction Aggregate\n * \n * Handles persistence and retrieval of GTD next actions\n */\n@injectable()\nexport class NextActionAggregateRepository {\n  private db: Db | null = null;\n  private collection: Collection | null = null;\n\n  constructor() {\n    // Lazy initialization - don't connect until needed\n  }\n\n  private ensureConnection() {\n    if (!this.db) {\n      this.db = getMongoDb();\n      this.collection = this.db.collection('gtd_next_actions');\n    }\n    return this.collection!;\n  }\n\n  async save(action: NextAction): Promise<void> {\n    const collection = this.ensureConnection();\n    const doc = {\n      _id: action.id,\n      description: action.description,\n      context: action.context.toString(),\n      energyRequired: action.energyRequired.toString(),\n      estimatedMinutes: action.estimatedMinutes,\n      createdBy: action.createdBy,\n      createdAt: action.createdAt,\n      projectId: action.projectId,\n      assignedTo: action.assignedTo,\n      assignedAt: action.assignedAt,\n      completedAt: action.completedAt,\n      status: action.isCompleted() ? 'completed' : action.isAssigned() ? 'assigned' : 'available'\n    };\n\n    await collection.replaceOne(\n      { _id: action.id as any },\n      doc,\n      { upsert: true }\n    );\n  }\n\n  async findById(id: string): Promise<NextAction | null> {\n    const collection = this.ensureConnection();\n    const doc = await collection.findOne({ _id: id as any });\n    if (!doc) return null;\n\n    // Reconstruct domain object from document\n    const context = this.parseContext(doc.context);\n    const energy = this.parseEnergyLevel(doc.energyRequired);\n    \n    return NextAction.reconstitute(\n      doc._id.toString(),\n      doc.description,\n      context,\n      energy,\n      doc.estimatedMinutes,\n      doc.createdBy,\n      doc.createdAt,\n      doc.projectId,\n      doc.assignedTo,\n      doc.assignedAt,\n      doc.roleType,\n      doc.completedAt\n    );\n  }\n\n  async findAll(): Promise<NextAction[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection.find({}).toArray();\n    return docs.map(doc => {\n      const context = this.parseContext(doc.context);\n      const energy = this.parseEnergyLevel(doc.energyRequired);\n      \n      return NextAction.reconstitute(\n        doc._id.toString(),\n        doc.description,\n        context,\n        energy,\n        doc.estimatedMinutes,\n        doc.createdBy,\n        doc.createdAt,\n        doc.projectId,\n        doc.assignedTo,\n        doc.assignedAt,\n        doc.roleType,\n        doc.completedAt\n      );\n    });\n  }\n\n  async countAvailable(): Promise<number> {\n    const collection = this.ensureConnection();\n    return await collection.countDocuments({\n      status: 'available'\n    });\n  }\n\n  async countAll(): Promise<number> {\n    const collection = this.ensureConnection();\n    return await collection.countDocuments({});\n  }\n\n  async delete(id: string): Promise<void> {\n    const collection = this.ensureConnection();\n    await collection.deleteOne({ _id: id as any });\n  }\n\n  // Helper methods\n  private parseContext(contextStr: string): ActionContext {\n    switch (contextStr) {\n      case '@calls': return ActionContext.atCalls();\n      case '@computer': return ActionContext.atComputer();\n      case '@errands': return ActionContext.atErrands('');\n      case '@home': return ActionContext.atHome();\n      case '@office': return ActionContext.atOffice();\n      case '@anywhere': return ActionContext.anywhere();\n      default: return ActionContext.atComputer();\n    }\n  }\n\n  private parseEnergyLevel(energyStr: string): EnergyLevel {\n    switch (energyStr) {\n      case 'high': return EnergyLevel.high();\n      case 'medium': return EnergyLevel.medium();\n      case 'low': return EnergyLevel.low();\n      default: return EnergyLevel.medium();\n    }\n  }\n}\n","/**\n * GTD Processing Status - David Allen's workflow stages\n * Represents where an item is in the GTD clarification process\n */\nexport class ProcessingStatus {\n  private constructor(private readonly value: 'new' | 'clarified' | 'processed') {}\n\n  static new(): ProcessingStatus {\n    return new ProcessingStatus('new');\n  }\n\n  static clarified(): ProcessingStatus {\n    return new ProcessingStatus('clarified');\n  }\n\n  static processed(): ProcessingStatus {\n    return new ProcessingStatus('processed');\n  }\n\n  isNew(): boolean {\n    return this.value === 'new';\n  }\n\n  isClarified(): boolean {\n    return this.value === 'clarified';\n  }\n\n  isProcessed(): boolean {\n    return this.value === 'processed';\n  }\n\n  equals(other: ProcessingStatus): boolean {\n    return this.value === other.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n}","// NextAction is now referenced by ID only - no direct import needed\nimport { ActionContext } from '../value-objects/ActionContext';\nimport { EnergyLevel } from '../value-objects/EnergyLevel';\nimport { DomainEvent } from '../events/DomainEvent';\nimport { ProjectCompleted } from '../events/GTDEvents';\nimport { ProjectStateError, ThoughtProcessingError } from '../errors/GTDDomainError';\n\n/**\n * Plan for creating a NextAction - returned by Project.planNextAction()\n * The actual NextAction aggregate is created by the application service\n */\nexport interface NextActionPlan {\n  id: string;\n  description: string;\n  context: ActionContext;\n  energy: EnergyLevel;\n  minutes: number;\n  createdBy: string;\n  projectId: string;\n}\n\n/**\n * GTD Project - any outcome requiring more than one action step\n * \"A project is any desired result that requires more than one action step\" - David Allen\n * \n * Core GTD Principles:\n * - Every project must have at least one next action\n * - Projects need regular review to stay on track\n * - Clear desired outcome is essential\n */\nexport class Project {\n  private domainEvents: DomainEvent[] = [];\n  private _nextActionIds: string[] = [];\n  private _completedAt?: Date;\n  private _status: ProjectStatus = ProjectStatus.ACTIVE;\n\n  constructor(\n    public readonly id: string,\n    public readonly name: string,\n    public readonly desiredOutcome: string,\n    public readonly createdBy: string,\n    public readonly createdAt: Date = new Date(),\n    public readonly area?: string,\n    public readonly reviewDate?: Date\n  ) {\n    this.validateProject(name, desiredOutcome);\n  }\n\n  /**\n   * Create a new project with validation\n   */\n  static create(\n    name: string,\n    outcome: string,\n    createdBy: string,\n    area?: string,\n    reviewDate?: Date\n  ): Project {\n    const id = this.generateId();\n    return new Project(id, name, outcome, createdBy, new Date(), area, reviewDate);\n  }\n\n  /**\n   * Plan next action for this project\n   * GTD Rule: Every project must have at least one next action\n   * Returns action data to be created by application service\n   */\n  planNextAction(\n    description: string,\n    context: ActionContext,\n    energy: EnergyLevel,\n    minutes: number\n  ): NextActionPlan {\n    if (this.isCompleted() || this.isCancelled()) {\n      throw new ProjectStateError(\n        'Cannot add actions to completed or cancelled projects',\n        this.id,\n        this._status\n      );\n    }\n\n    // Generate ID for the planned action\n    const actionId = this.generateActionId();\n    \n    return {\n      id: actionId,\n      description,\n      context,\n      energy,\n      minutes,\n      createdBy: this.createdBy,\n      projectId: this.id\n    };\n  }\n\n  /**\n   * Record that a next action has been created for this project\n   */\n  recordNextActionCreated(actionId: string): void {\n    if (!this._nextActionIds.includes(actionId)) {\n      this._nextActionIds.push(actionId);\n    }\n  }\n\n  /**\n   * Record that an action within this project has been completed\n   * The actual NextAction completion is handled by NextAction aggregate\n   */\n  recordActionCompleted(actionId: string): void {\n    if (!this._nextActionIds.includes(actionId)) {\n      throw new ProjectStateError(\n        'Action not found in this project',\n        this.id,\n        this._status\n      );\n    }\n    // Action completion is handled by the NextAction aggregate itself\n    // This method just validates the action belongs to this project\n  }\n\n  /**\n   * Remove a next action from this project\n   */\n  removeAction(actionId: string): void {\n    const actionIndex = this._nextActionIds.findIndex(id => id === actionId);\n    if (actionIndex === -1) {\n      throw new ProjectStateError(\n        'Action not found in this project',\n        this.id,\n        this._status\n      );\n    }\n\n    this._nextActionIds.splice(actionIndex, 1);\n  }\n\n  /**\n   * Complete the entire project\n   */\n  complete(completedBy?: string, completionNotes?: string): void {\n    if (this.isCompleted()) {\n      throw new ProjectStateError(\n        'Project is already completed',\n        this.id,\n        this._status\n      );\n    }\n\n    this._status = ProjectStatus.COMPLETED;\n    this._completedAt = new Date();\n    \n    this.addDomainEvent(new ProjectCompleted(\n      this.id,\n      completedBy || this.createdBy,\n      completionNotes\n    ));\n  }\n\n  /**\n   * Move to Someday/Maybe list (GTD workflow)\n   */\n  defer(): void {\n    if (this.isCompleted()) {\n      throw new ProjectStateError(\n        'Cannot defer completed projects',\n        this.id,\n        this._status\n      );\n    }\n\n    this._status = ProjectStatus.SOMEDAY_MAYBE;\n  }\n\n  /**\n   * Reactivate from Someday/Maybe\n   */\n  activate(): void {\n    if (this.isCompleted()) {\n      throw new ProjectStateError(\n        'Cannot activate completed projects',\n        this.id,\n        this._status\n      );\n    }\n\n    this._status = ProjectStatus.ACTIVE;\n  }\n\n  /**\n   * Cancel the project\n   */\n  cancel(): void {\n    if (this.isCompleted()) {\n      throw new ProjectStateError(\n        'Cannot cancel completed projects',\n        this.id,\n        this._status\n      );\n    }\n\n    this._status = ProjectStatus.CANCELLED;\n  }\n\n  /**\n   * Get IDs of next actions for this project\n   * Context and energy filtering should be done at application service level\n   */\n  getNextActionIds(): string[] {\n    return [...this._nextActionIds];\n  }\n\n  /**\n   * GTD Review: Check if project needs attention\n   * A project needs attention if it has no next actions defined\n   */\n  needsAttention(): boolean {\n    if (this._status !== ProjectStatus.ACTIVE) return false;\n    \n    // Project needs attention if it has no next actions at all\n    return this._nextActionIds.length === 0;\n  }\n\n  /**\n   * Get basic project metrics (action counts must be computed at application layer)\n   */\n  getBasicProgress(): { totalActionIds: number } {\n    return {\n      totalActionIds: this._nextActionIds.length\n    };\n  }\n\n  // State queries\n  isCompleted(): boolean {\n    return this._status === ProjectStatus.COMPLETED;\n  }\n\n  isCancelled(): boolean {\n    return this._status === ProjectStatus.CANCELLED;\n  }\n\n  isActive(): boolean {\n    return this._status === ProjectStatus.ACTIVE;\n  }\n\n  isSomedayMaybe(): boolean {\n    return this._status === ProjectStatus.SOMEDAY_MAYBE;\n  }\n\n  // Getters\n  get status(): ProjectStatus {\n    return this._status;\n  }\n\n  get nextActionIds(): string[] {\n    return [...this._nextActionIds];\n  }\n\n  get completedAt(): Date | undefined {\n    return this._completedAt;\n  }\n\n  // Event sourcing support\n  getDomainEvents(): DomainEvent[] {\n    // Only return events from this aggregate\n    // NextAction events are handled by NextAction aggregates separately\n    return [...this.domainEvents];\n  }\n\n  clearDomainEvents(): void {\n    this.domainEvents = [];\n    // NextAction events are cleared by NextAction aggregates separately\n  }\n\n  // Private methods\n  private validateProject(name: string, desiredOutcome: string): void {\n    if (!name?.trim()) {\n      throw new ThoughtProcessingError('Project name is required');\n    }\n\n    if (!desiredOutcome?.trim()) {\n      throw new ThoughtProcessingError('Desired outcome is required for project clarity');\n    }\n  }\n\n  private addDomainEvent(event: DomainEvent): void {\n    this.domainEvents.push(event);\n  }\n\n  private static generateId(): string {\n    return `project-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n  }\n\n  private generateActionId(): string {\n    return `action-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n  }\n}\n\n/**\n * Project Status following GTD workflow\n */\nexport enum ProjectStatus {\n  ACTIVE = 'active',\n  SOMEDAY_MAYBE = 'someday-maybe',\n  COMPLETED = 'completed',\n  CANCELLED = 'cancelled'\n}\n\n/**\n * Project progress metrics\n */\nexport interface ProjectProgress {\n  totalActions: number;\n  completedActions: number;\n  assignedActions: number;\n  availableActions: number;\n  completionPercentage: number;\n}","/**\n * Base Domain Event for GTD productivity domain\n * Following Eric Evans event sourcing patterns\n */\nexport abstract class DomainEvent {\n  public readonly occurredOn: Date;\n  public readonly eventId: string;\n\n  constructor(\n    public readonly aggregateId: string,\n    public readonly eventType: string,\n    public readonly eventVersion: number = 1\n  ) {\n    this.occurredOn = new Date();\n    this.eventId = `${eventType}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n  }\n\n  abstract getEventData(): Record<string, any>;\n}","import { injectable } from 'inversify';\nimport { Collection, Db, getMongoDb } from \"@swoft/persistence\";\nimport { Project } from '../../domain/aggregates/Project';\nimport { GTD_COLLECTIONS } from '../../../../config/collections';\n\n/**\n * MongoDB Repository for Project Aggregate\n * \n * Following Eric Evans repository pattern - provides collection-like\n * interface for accessing projects while hiding persistence details.\n */\n@injectable()\nexport class ProjectRepository {\n  private db: Db | null = null;\n  private collection: Collection | null = null;\n\n  constructor() {\n    // Lazy initialization - don't connect until needed\n  }\n\n  private ensureConnection() {\n    if (!this.db) {\n      this.db = getMongoDb();\n      this.collection = this.db.collection(GTD_COLLECTIONS.PROJECTS);\n    }\n    return this.collection!;\n  }\n\n  async save(project: Project): Promise<void> {\n    const collection = this.ensureConnection();\n    const doc = {\n      _id: project.id,\n      name: project.name,\n      desiredOutcome: project.desiredOutcome,\n      createdBy: project.createdBy,\n      createdAt: project.createdAt,\n      area: project.area,\n      reviewDate: project.reviewDate,\n      status: project.status,\n      nextActionIds: project.nextActionIds,\n      completedAt: project.completedAt,\n      updatedAt: new Date()\n    };\n\n    await collection.replaceOne(\n      { _id: project.id as any },\n      doc,\n      { upsert: true }\n    );\n  }\n\n  async findById(id: string): Promise<Project | null> {\n    const collection = this.ensureConnection();\n    const doc = await collection.findOne({ _id: id as any });\n    if (!doc) return null;\n\n    return this.mapDocumentToDomain(doc);\n  }\n\n  async findByStatus(status: string): Promise<Project[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({ status })\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(project => project !== null) as Project[];\n  }\n\n  async findByArea(area: string): Promise<Project[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({ area })\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(project => project !== null) as Project[];\n  }\n\n  async findAll(): Promise<Project[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({})\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(project => project !== null) as Project[];\n  }\n\n  async deleteById(id: string): Promise<void> {\n    const collection = this.ensureConnection();\n    await collection.deleteOne({ _id: id as any });\n  }\n\n  private mapDocumentToDomain(doc: any): Project {\n    const project = new Project(\n      doc._id,\n      doc.name,\n      doc.desiredOutcome,\n      doc.createdBy,\n      new Date(doc.createdAt),\n      doc.area,\n      doc.reviewDate ? new Date(doc.reviewDate) : undefined\n    );\n\n    // Restore private state\n    if (doc.nextActionIds) {\n      (project as any)._nextActionIds = doc.nextActionIds;\n    }\n    if (doc.status) {\n      (project as any)._status = doc.status;\n    }\n    if (doc.completedAt) {\n      (project as any)._completedAt = new Date(doc.completedAt);\n    }\n\n    return project;\n  }\n\n  private safeMapDocumentToDomain(doc: any): Project | null {\n    try {\n      // Validate required fields before attempting to create domain object\n      if (!doc.name?.trim()) {\n        console.warn(`Skipping project document with missing name: ${doc._id}`);\n        return null;\n      }\n      if (!doc.desiredOutcome?.trim()) {\n        console.warn(`Skipping project document with missing desiredOutcome: ${doc._id}`);\n        return null;\n      }\n\n      return this.mapDocumentToDomain(doc);\n    } catch (error) {\n      console.warn(`Failed to map project document to domain object: ${doc._id}`, error);\n      return null;\n    }\n  }\n}","import { injectable, inject } from 'inversify';\nimport { Project } from \"../../domain/aggregates/Project\";\nimport { ProjectRepository } from \"../../infrastructure/repositories/ProjectRepository\";\nimport { \n  CreateProjectCommand, \n  CreateProjectResult \n} from \"../commands/CreateProjectCommand\";\nimport { TYPES } from '../../../../types/DITypes';\n\n/**\n * Project Application Service\n * \n * Following Eric Evans Application Service pattern for project management.\n * Coordinates project operations following GTD principles.\n * \n * GTD Rule: Every project must have a clear desired outcome and at least one next action.\n */\n@injectable()\nexport class ProjectApplicationService {\n  constructor(\n    @inject(TYPES.ProjectRepository) private readonly projectRepository: ProjectRepository\n  ) {}\n\n  /**\n   * Create a new GTD project\n   * \n   * GTD Principle: Projects come from processing inbox items or direct creation\n   * for multi-step outcomes.\n   */\n  async createProject(command: CreateProjectCommand): Promise<CreateProjectResult> {\n    try {\n      // Create the project aggregate\n      const project = Project.create(\n        command.name,\n        command.desiredOutcome,\n        command.createdBy,\n        command.area,\n        command.reviewDate\n      );\n\n      // Persist the project\n      await this.projectRepository.save(project);\n\n      return {\n        success: true,\n        projectId: project.id,\n        createdAt: project.createdAt.toISOString(),\n        message: `Project \"${command.name}\" created successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        projectId: '',\n        createdAt: new Date().toISOString(),\n        message: error instanceof Error ? error.message : 'Failed to create project'\n      };\n    }\n  }\n\n  /**\n   * Complete a project\n   * \n   * GTD: Mark project as completed when desired outcome is achieved\n   */\n  async completeProject(projectId: string, completedBy: string): Promise<{ success: boolean; message: string }> {\n    try {\n      const project = await this.projectRepository.findById(projectId);\n      \n      if (!project) {\n        return {\n          success: false,\n          message: `Project ${projectId} not found`\n        };\n      }\n\n      project.complete(completedBy);\n      await this.projectRepository.save(project);\n\n      return {\n        success: true,\n        message: `Project completed successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to complete project'\n      };\n    }\n  }\n\n  /**\n   * Defer project to Someday/Maybe\n   * \n   * GTD: Move project out of active list but keep for future consideration\n   */\n  async deferProject(projectId: string): Promise<{ success: boolean; message: string }> {\n    try {\n      const project = await this.projectRepository.findById(projectId);\n      \n      if (!project) {\n        return {\n          success: false,\n          message: `Project ${projectId} not found`\n        };\n      }\n\n      project.defer();\n      await this.projectRepository.save(project);\n\n      return {\n        success: true,\n        message: `Project moved to Someday/Maybe list`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to defer project'\n      };\n    }\n  }\n}","/**\n * Dependency injection symbols for GTD Domain\n * \n * Using Symbol-based identifiers to avoid circular dependencies\n * and ensure type safety in dependency injection.\n */\n\n// Inbox Management Bounded Context\nexport const TYPES = {\n  // Inbox Management Bounded Context\n  InboxItemApplicationService: Symbol.for('InboxItemApplicationService'),\n  InboxItemAggregateRepository: Symbol.for('InboxItemAggregateRepository'),\n  GTDProcessingWorkflowService: Symbol.for('GTDProcessingWorkflowService'),\n  InboxImportExportService: Symbol.for('InboxImportExportService'),\n  \n  // Project Management Bounded Context\n  ProjectApplicationService: Symbol.for('ProjectApplicationService'),\n  ProjectReadService: Symbol.for('ProjectReadService'),\n  ProjectRepository: Symbol.for('ProjectRepository'),\n  NextActionAggregateRepository: Symbol.for('NextActionAggregateRepository'),\n  NextActionWriteService: Symbol.for('NextActionWriteService'),\n  NextActionReadService: Symbol.for('NextActionReadService'),\n  \n  // Task Management Bounded Context\n  ITaskRepository: Symbol.for('ITaskRepository'),\n  TaskMongoRepository: Symbol.for('TaskMongoRepository'),\n  InboxFileRepository: Symbol.for('InboxFileRepository'),\n  NextActionsFileRepository: Symbol.for('NextActionsFileRepository'),\n  \n  // Design Implementation Coordination Bounded Context\n  DesignImplementationFlowRepository: Symbol.for('DesignImplementationFlowRepository'),\n  DesignImplementationFlowApplicationService: Symbol.for('DesignImplementationFlowApplicationService'),\n  DesignImplementationFlowReadService: Symbol.for('DesignImplementationFlowReadService')\n} as const;\n\n// Type helpers for better IntelliSense\nexport type DITypes = typeof TYPES;","import { injectable, inject } from 'inversify';\nimport { GTD_DOMAIN_SYMBOLS } from '../../../../infrastructure/di/GTDDomainSymbols';\nimport { z } from 'zod';\nimport { Project } from '../../domain/aggregates/Project';\nimport { ProjectRepository } from '../../infrastructure/repositories/ProjectRepository';\nimport { BaseApplicationError } from '@swoft/core';\n\n/**\n * Command Schemas with Zod Validation\n */\nexport const CreateProjectCommandSchema = z.object({\n  name: z.string().min(1, 'Project name cannot be empty').max(200, 'Project name too long'),\n  desiredOutcome: z.string().min(1, 'Desired outcome is required').max(1000, 'Outcome description too long'),\n  area: z.string().optional(),\n  reviewDate: z.date().optional(),\n  createdBy: z.string().min(1, 'Created by is required')\n}).strict();\n\nexport const UpdateProjectCommandSchema = z.object({\n  projectId: z.string().min(1, 'Project ID is required'),\n  name: z.string().min(1).max(200).optional(),\n  desiredOutcome: z.string().min(1).max(1000).optional(),\n  area: z.string().optional(),\n  reviewDate: z.date().optional(),\n  status: z.enum(['active', 'on-hold', 'completed', 'cancelled']).optional()\n}).strict();\n\nexport const CompleteProjectCommandSchema = z.object({\n  projectId: z.string().min(1, 'Project ID is required'),\n  completedBy: z.string().min(1, 'Completed by is required')\n}).strict();\n\n// Command Types\nexport type CreateProjectCommand = z.infer<typeof CreateProjectCommandSchema>;\nexport type UpdateProjectCommand = z.infer<typeof UpdateProjectCommandSchema>;\nexport type CompleteProjectCommand = z.infer<typeof CompleteProjectCommandSchema>;\n\n// Result Types\nexport interface CreateProjectResult {\n  readonly projectId: string;\n  readonly success: boolean;\n  readonly message: string;\n}\n\nexport interface ProjectOperationResult {\n  readonly success: boolean;\n  readonly message: string;\n}\n\n// Error classes\nexport class InvalidProjectCommandError extends BaseApplicationError {\n  readonly code = 'INVALID_PROJECT_COMMAND';\n  \n  constructor(validationErrors: string[]) {\n    super(\n      'Invalid project command data',\n      {\n        ux: [\n          'Please check the following and try again:',\n          ...validationErrors\n        ],\n        dx: [`Command validation failed: ${validationErrors.join(', ')}`]\n      }\n    );\n  }\n}\n\nexport class ProjectNotFoundError extends BaseApplicationError {\n  readonly code = 'PROJECT_NOT_FOUND';\n  \n  constructor(projectId: string) {\n    super(\n      `Project not found: ${projectId}`,\n      {\n        ux: [\n          'The requested project could not be found.',\n          'It may have been deleted or the ID is incorrect.'\n        ],\n        dx: [`Project lookup failed for ID: ${projectId}`]\n      }\n    );\n  }\n}\n\n/**\n * ProjectWriteService - Command Side (CQRS)\n * \n * Handles all write operations for GTD projects.\n * Implements the GTD principle of organizing multi-step outcomes.\n */\n@injectable()\nexport class ProjectWriteService {\n  constructor(\n    @inject(GTD_DOMAIN_SYMBOLS.ProjectRepository)\n    private readonly repository: ProjectRepository\n  ) {}\n\n  /**\n   * Create a new GTD project\n   * Core GTD principle: Any outcome requiring more than one action\n   */\n  async createProject(command: CreateProjectCommand): Promise<CreateProjectResult> {\n    // 1. Command validation\n    let validatedCommand: CreateProjectCommand;\n    try {\n      validatedCommand = CreateProjectCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidProjectCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    try {\n      // 2. Create domain aggregate\n      const project = Project.create(\n        validatedCommand.name,\n        validatedCommand.desiredOutcome,\n        validatedCommand.createdBy,\n        validatedCommand.area,\n        validatedCommand.reviewDate\n      );\n\n      // 3. Persist\n      await this.repository.save(project);\n\n      return {\n        projectId: project.id,\n        success: true,\n        message: 'Project created successfully'\n      };\n\n    } catch (error) {\n      return {\n        projectId: '',\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to create project'\n      };\n    }\n  }\n\n  /**\n   * Update project details\n   * GTD: Projects can evolve as understanding improves\n   */\n  async updateProject(command: UpdateProjectCommand): Promise<ProjectOperationResult> {\n    // 1. Command validation\n    let validatedCommand: UpdateProjectCommand;\n    try {\n      validatedCommand = UpdateProjectCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidProjectCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    // 2. Load project\n    const project = await this.repository.findById(validatedCommand.projectId);\n    if (!project) {\n      throw new ProjectNotFoundError(validatedCommand.projectId);\n    }\n\n    try {\n      // 3. Apply updates\n      // Note: The Project aggregate would need update methods for this to work properly\n      // For now, we'll return not implemented\n      throw new Error('Project update not yet implemented in domain aggregate');\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to update project'\n      };\n    }\n  }\n\n  /**\n   * Complete a project\n   * Core GTD principle: Mark as done when outcome achieved\n   */\n  async completeProject(command: CompleteProjectCommand): Promise<ProjectOperationResult> {\n    // 1. Command validation\n    let validatedCommand: CompleteProjectCommand;\n    try {\n      validatedCommand = CompleteProjectCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidProjectCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    // 2. Load project\n    const project = await this.repository.findById(validatedCommand.projectId);\n    if (!project) {\n      throw new ProjectNotFoundError(validatedCommand.projectId);\n    }\n\n    try {\n      // 3. Complete project\n      project.complete(validatedCommand.completedBy);\n\n      // 4. Persist\n      await this.repository.save(project);\n\n      return {\n        success: true,\n        message: 'Project completed successfully'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to complete project'\n      };\n    }\n  }\n\n  /**\n   * Delete a project\n   */\n  async deleteProject(projectId: string): Promise<ProjectOperationResult> {\n    try {\n      const project = await this.repository.findById(projectId);\n      if (!project) {\n        throw new ProjectNotFoundError(projectId);\n      }\n\n      await this.repository.deleteById(projectId);\n\n      return {\n        success: true,\n        message: 'Project deleted successfully'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to delete project'\n      };\n    }\n  }\n\n  /**\n   * Put project on hold\n   * GTD: Temporarily suspend active work\n   */\n  async holdProject(projectId: string): Promise<ProjectOperationResult> {\n    try {\n      const project = await this.repository.findById(projectId);\n      if (!project) {\n        throw new ProjectNotFoundError(projectId);\n      }\n\n      project.defer();\n      await this.repository.save(project);\n\n      return {\n        success: true,\n        message: 'Project put on hold'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to put project on hold'\n      };\n    }\n  }\n\n  /**\n   * Reactivate a project\n   * GTD: Resume work on held project\n   */\n  async activateProject(projectId: string): Promise<ProjectOperationResult> {\n    try {\n      const project = await this.repository.findById(projectId);\n      if (!project) {\n        throw new ProjectNotFoundError(projectId);\n      }\n\n      project.activate();\n      await this.repository.save(project);\n\n      return {\n        success: true,\n        message: 'Project reactivated'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to activate project'\n      };\n    }\n  }\n}","import { injectable, inject } from 'inversify';\nimport { GTD_DOMAIN_SYMBOLS } from '../../../../infrastructure/di/GTDDomainSymbols';\nimport { ProjectRepository } from '../../infrastructure/repositories/ProjectRepository';\nimport { getMongoDb, Collection } from \"@swoft/persistence\";\n\n/**\n * Query criteria for filtering projects\n */\nexport interface ProjectQueryCriteria {\n  readonly status?: 'active' | 'someday-maybe' | 'completed' | 'cancelled' | 'all';\n  readonly area?: string;\n  readonly assignedTo?: string;\n  readonly searchText?: string;\n  readonly needsReview?: boolean;\n  readonly createdBy?: string;\n  readonly offset?: number;\n  readonly limit?: number;\n}\n\n/**\n * Project view model for read operations\n */\nexport interface ProjectView {\n  readonly id: string;\n  readonly name: string;\n  readonly desiredOutcome: string;\n  readonly status: 'active' | 'someday-maybe' | 'completed' | 'cancelled';\n  readonly createdBy: string;\n  readonly createdAt: Date;\n  readonly area?: string;\n  readonly reviewDate?: Date;\n  readonly completedAt?: Date;\n  readonly nextActionCount: number;\n  readonly completedActionCount: number;\n  readonly needsAttention: boolean;\n  readonly progress: {\n    totalActions: number;\n    completedActions: number;\n    completionPercentage: number;\n  };\n}\n\n/**\n * Query result with pagination\n */\nexport interface ProjectQueryResult {\n  readonly projects: ProjectView[];\n  readonly total: number;\n  readonly offset: number;\n  readonly limit: number;\n  readonly hasMore: boolean;\n}\n\n/**\n * ProjectReadService - Query Side (CQRS)\n * \n * Handles all read operations for GTD projects.\n * Optimized for GTD \"Review\" phase - checking project status and progress.\n */\n@injectable()\nexport class ProjectReadService {\n  private collection: Collection;\n\n  constructor(\n    @inject(GTD_DOMAIN_SYMBOLS.ProjectRepository)\n    _repository: ProjectRepository\n  ) {\n    const db = getMongoDb();\n    this.collection = db.collection('gtd_projects');\n  }\n\n  /**\n   * Get projects matching criteria\n   * Core GTD principle: Projects need regular review to stay on track\n   */\n  async getProjects(criteria: ProjectQueryCriteria): Promise<ProjectQueryResult> {\n    const {\n      status = 'active',\n      area,\n      assignedTo,\n      searchText,\n      needsReview,\n      createdBy,\n      offset = 0,\n      limit = 20\n    } = criteria;\n\n    // Build query\n    const query: any = {};\n    \n    if (status !== 'all') {\n      query.status = status;\n    }\n    \n    if (area) {\n      query.area = area;\n    }\n    \n    if (assignedTo) {\n      query.assignedTo = assignedTo;\n    }\n    \n    if (createdBy) {\n      query.createdBy = createdBy;\n    }\n    \n    if (searchText) {\n      query.$or = [\n        { name: { $regex: searchText, $options: 'i' } },\n        { desiredOutcome: { $regex: searchText, $options: 'i' } }\n      ];\n    }\n\n    // Execute query with pagination\n    const [projects, total] = await Promise.all([\n      this.collection\n        .find(query)\n        .sort({ createdAt: -1 })\n        .skip(offset)\n        .limit(limit)\n        .toArray(),\n      this.collection.countDocuments(query)\n    ]);\n\n    // Map to view models with enhanced data\n    const projectViews: ProjectView[] = await Promise.all(\n      projects.map(async (doc) => {\n        const actionStats = await this.getActionStatisticsForProject(doc._id.toString());\n        \n        return {\n          id: doc._id.toString(),\n          name: doc.name,\n          desiredOutcome: doc.desiredOutcome,\n          status: doc.status,\n          createdBy: doc.createdBy,\n          createdAt: doc.createdAt,\n          area: doc.area,\n          reviewDate: doc.reviewDate,\n          completedAt: doc.completedAt,\n          nextActionCount: actionStats.nextActionCount,\n          completedActionCount: actionStats.completedActionCount,\n          needsAttention: actionStats.needsAttention,\n          progress: {\n            totalActions: actionStats.totalActions,\n            completedActions: actionStats.completedActions,\n            completionPercentage: actionStats.completionPercentage\n          }\n        };\n      })\n    );\n\n    // Filter by needsReview if specified\n    const filteredProjects = needsReview \n      ? projectViews.filter(p => p.needsAttention)\n      : projectViews;\n\n    return {\n      projects: filteredProjects,\n      total,\n      offset,\n      limit,\n      hasMore: total > offset + limit\n    };\n  }\n\n  /**\n   * Get a single project by ID\n   */\n  async getProjectById(projectId: string): Promise<ProjectView | null> {\n    const doc = await this.collection.findOne({ _id: projectId as any });\n    \n    if (!doc) {\n      return null;\n    }\n\n    const actionStats = await this.getActionStatisticsForProject(projectId);\n\n    return {\n      id: doc._id.toString(),\n      name: doc.name,\n      desiredOutcome: doc.desiredOutcome,\n      status: doc.status,\n      createdBy: doc.createdBy,\n      createdAt: doc.createdAt,\n      area: doc.area,\n      reviewDate: doc.reviewDate,\n      completedAt: doc.completedAt,\n      nextActionCount: actionStats.nextActionCount,\n      completedActionCount: actionStats.completedActionCount,\n      needsAttention: actionStats.needsAttention,\n      progress: {\n        totalActions: actionStats.totalActions,\n        completedActions: actionStats.completedActions,\n        completionPercentage: actionStats.completionPercentage\n      }\n    };\n  }\n\n  /**\n   * Get projects for GTD weekly review\n   */\n  async getProjectsForReview(personId: string): Promise<ProjectQueryResult> {\n    const query = {\n      createdBy: personId,\n      status: { $in: ['active', 'someday-maybe'] }\n    };\n\n    const projects = await this.collection\n      .find(query)\n      .sort({ status: 1, createdAt: -1 })\n      .toArray();\n\n    const projectViews: ProjectView[] = await Promise.all(\n      projects.map(async (doc) => {\n        const actionStats = await this.getActionStatisticsForProject(doc._id.toString());\n        \n        return {\n          id: doc._id.toString(),\n          name: doc.name,\n          desiredOutcome: doc.desiredOutcome,\n          status: doc.status,\n          createdBy: doc.createdBy,\n          createdAt: doc.createdAt,\n          area: doc.area,\n          reviewDate: doc.reviewDate,\n          completedAt: doc.completedAt,\n          nextActionCount: actionStats.nextActionCount,\n          completedActionCount: actionStats.completedActionCount,\n          needsAttention: actionStats.needsAttention,\n          progress: {\n            totalActions: actionStats.totalActions,\n            completedActions: actionStats.completedActions,\n            completionPercentage: actionStats.completionPercentage\n          }\n        };\n      })\n    );\n\n    return {\n      projects: projectViews,\n      total: projectViews.length,\n      offset: 0,\n      limit: projectViews.length,\n      hasMore: false\n    };\n  }\n\n  /**\n   * Get projects by area for organizational purposes\n   */\n  async getProjectsByArea(area: string): Promise<ProjectQueryResult> {\n    return this.getProjects({ area, status: 'active' });\n  }\n\n  /**\n   * Get project statistics\n   */\n  async getProjectStatistics(): Promise<{\n    total: number;\n    active: number;\n    somedayMaybe: number;\n    completed: number;\n    cancelled: number;\n    needingReview: number;\n    byArea: Record<string, number>;\n  }> {\n    const [\n      total,\n      active,\n      somedayMaybe,\n      completed,\n      cancelled,\n      byArea\n    ] = await Promise.all([\n      this.collection.countDocuments({}),\n      this.collection.countDocuments({ status: 'active' }),\n      this.collection.countDocuments({ status: 'someday-maybe' }),\n      this.collection.countDocuments({ status: 'completed' }),\n      this.collection.countDocuments({ status: 'cancelled' }),\n      this.getCountByField('area')\n    ]);\n\n    // Get projects needing review (active projects with no next actions)\n    const needingReview = await this.collection.countDocuments({\n      status: 'active',\n      nextActionIds: { $size: 0 }\n    });\n\n    return {\n      total,\n      active,\n      somedayMaybe,\n      completed,\n      cancelled,\n      needingReview,\n      byArea\n    };\n  }\n\n  /**\n   * Get action statistics for a specific project\n   */\n  private async getActionStatisticsForProject(projectId: string): Promise<{\n    nextActionCount: number;\n    completedActionCount: number;\n    totalActions: number;\n    completedActions: number;\n    completionPercentage: number;\n    needsAttention: boolean;\n  }> {\n    const actionsCollection = getMongoDb().collection('gtd_next_actions');\n    \n    const [\n      nextActionCount,\n      completedActionCount\n    ] = await Promise.all([\n      actionsCollection.countDocuments({ \n        projectId,\n        status: { $in: ['available', 'assigned'] }\n      }),\n      actionsCollection.countDocuments({ \n        projectId,\n        status: 'completed'\n      })\n    ]);\n\n    const totalActions = nextActionCount + completedActionCount;\n    const completionPercentage = totalActions > 0 \n      ? Math.round((completedActionCount / totalActions) * 100)\n      : 0;\n\n    // A project needs attention if it has no next actions at all\n    const needsAttention = nextActionCount === 0 && completedActionCount === 0;\n\n    return {\n      nextActionCount,\n      completedActionCount,\n      totalActions,\n      completedActions: completedActionCount,\n      completionPercentage,\n      needsAttention\n    };\n  }\n\n  /**\n   * Get counts grouped by a field\n   */\n  private async getCountByField(field: string): Promise<Record<string, number>> {\n    const results = await this.collection.aggregate([\n      {\n        $group: {\n          _id: `$${field}`,\n          count: { $sum: 1 }\n        }\n      }\n    ]).toArray();\n\n    const counts: Record<string, number> = {};\n    for (const result of results) {\n      if (result._id) {\n        counts[result._id] = result.count;\n      }\n    }\n    return counts;\n  }\n}","import { injectable, inject } from 'inversify';\nimport { GTD_DOMAIN_SYMBOLS } from '../../../../infrastructure/di/GTDDomainSymbols';\nimport { z } from 'zod';\nimport { NextAction } from '../../domain/aggregates/NextAction';\nimport { ActionContext, EnergyLevel } from '../../domain/value-objects';\nimport { NextActionAggregateRepository } from '../../infrastructure/repositories/NextActionAggregateRepository';\nimport { BaseApplicationError } from '@swoft/core';\n\n/**\n * Command Schemas with Zod Validation\n */\nexport const CreateNextActionCommandSchema = z.object({\n  description: z.string().min(1, 'Action description cannot be empty').max(500, 'Description too long'),\n  context: z.enum(['@calls', '@computer', '@errands', '@home', '@office', '@anywhere']),\n  energyLevel: z.enum(['high', 'medium', 'low']),\n  estimatedMinutes: z.number().min(1, 'Estimated time must be at least 1 minute').max(480, 'Estimated time cannot exceed 8 hours'),\n  projectId: z.string().optional(),\n  createdBy: z.string().min(1, 'Created by is required')\n}).strict();\n\nexport const AssignActionCommandSchema = z.object({\n  actionId: z.string().min(1, 'Action ID is required'),\n  assignedTo: z.string().min(1, 'Assigned to is required'),\n  roleType: z.string().min(1, 'Role type is required')\n}).strict();\n\nexport const CompleteActionCommandSchema = z.object({\n  actionId: z.string().min(1, 'Action ID is required')\n}).strict();\n\n// Command Types\nexport type CreateNextActionCommand = z.infer<typeof CreateNextActionCommandSchema>;\nexport type AssignActionCommand = z.infer<typeof AssignActionCommandSchema>;\nexport type CompleteActionCommand = z.infer<typeof CompleteActionCommandSchema>;\n\n// Result Types\nexport interface CreateNextActionResult {\n  readonly actionId: string;\n  readonly success: boolean;\n  readonly message: string;\n}\n\nexport interface ActionOperationResult {\n  readonly success: boolean;\n  readonly message: string;\n}\n\n// Error classes\nexport class InvalidActionCommandError extends BaseApplicationError {\n  readonly code = 'INVALID_ACTION_COMMAND';\n  \n  constructor(validationErrors: string[]) {\n    super(\n      'Invalid action command data',\n      {\n        ux: [\n          'Please check the following and try again:',\n          ...validationErrors\n        ],\n        dx: [`Command validation failed: ${validationErrors.join(', ')}`]\n      }\n    );\n  }\n}\n\nexport class ActionNotFoundError extends BaseApplicationError {\n  readonly code = 'ACTION_NOT_FOUND';\n  \n  constructor(actionId: string) {\n    super(\n      `Next action not found: ${actionId}`,\n      {\n        ux: [\n          'The requested action could not be found.',\n          'It may have been deleted or the ID is incorrect.'\n        ],\n        dx: [`Action lookup failed for ID: ${actionId}`]\n      }\n    );\n  }\n}\n\n/**\n * NextActionWriteService - Command Side (CQRS)\n * \n * Handles all write operations for GTD next actions.\n * Implements the GTD principle of capturing and organizing actionable items.\n */\n@injectable()\nexport class NextActionWriteService {\n  constructor(\n    @inject(GTD_DOMAIN_SYMBOLS.NextActionAggregateRepository)\n    private readonly repository: NextActionAggregateRepository\n  ) {}\n\n  /**\n   * Create a new next action\n   * Core GTD principle: Capture actionable items with context and energy\n   */\n  async createNextAction(command: CreateNextActionCommand): Promise<CreateNextActionResult> {\n    // 1. Command validation\n    let validatedCommand: CreateNextActionCommand;\n    try {\n      validatedCommand = CreateNextActionCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidActionCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    try {\n      // 2. Create domain objects\n      const context = this.parseContext(validatedCommand.context);\n      const energy = this.parseEnergyLevel(validatedCommand.energyLevel);\n\n      // 3. Create aggregate\n      const action = NextAction.create(\n        validatedCommand.description,\n        context,\n        energy,\n        validatedCommand.estimatedMinutes,\n        validatedCommand.createdBy,\n        validatedCommand.projectId\n      );\n\n      // 4. Persist\n      await this.repository.save(action);\n\n      return {\n        actionId: action.id,\n        success: true,\n        message: 'Next action created successfully'\n      };\n\n    } catch (error) {\n      return {\n        actionId: '',\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to create action'\n      };\n    }\n  }\n\n  /**\n   * Assign action to a person\n   * Integrates with Party Management for assignment\n   */\n  async assignAction(command: AssignActionCommand): Promise<ActionOperationResult> {\n    // 1. Command validation\n    let validatedCommand: AssignActionCommand;\n    try {\n      validatedCommand = AssignActionCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidActionCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    // 2. Load action\n    const action = await this.repository.findById(validatedCommand.actionId);\n    if (!action) {\n      throw new ActionNotFoundError(validatedCommand.actionId);\n    }\n\n    try {\n      // 3. Perform assignment\n      action.assignTo(validatedCommand.assignedTo, validatedCommand.roleType);\n\n      // 4. Persist\n      await this.repository.save(action);\n\n      return {\n        success: true,\n        message: 'Action assigned successfully'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to assign action'\n      };\n    }\n  }\n\n  /**\n   * Complete an action\n   * Core GTD principle: Mark actions as done when completed\n   */\n  async completeAction(command: CompleteActionCommand): Promise<ActionOperationResult> {\n    // 1. Command validation\n    let validatedCommand: CompleteActionCommand;\n    try {\n      validatedCommand = CompleteActionCommandSchema.parse(command);\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        throw new InvalidActionCommandError(error.errors.map(e => e.message));\n      }\n      throw error;\n    }\n\n    // 2. Load action\n    const action = await this.repository.findById(validatedCommand.actionId);\n    if (!action) {\n      throw new ActionNotFoundError(validatedCommand.actionId);\n    }\n\n    try {\n      // 3. Complete action\n      action.complete();\n\n      // 4. Persist\n      await this.repository.save(action);\n\n      return {\n        success: true,\n        message: 'Action completed successfully'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to complete action'\n      };\n    }\n  }\n\n  /**\n   * Delete an action\n   */\n  async deleteAction(actionId: string): Promise<ActionOperationResult> {\n    try {\n      const action = await this.repository.findById(actionId);\n      if (!action) {\n        throw new ActionNotFoundError(actionId);\n      }\n\n      await this.repository.delete(actionId);\n\n      return {\n        success: true,\n        message: 'Action deleted successfully'\n      };\n\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to delete action'\n      };\n    }\n  }\n\n  // Helper methods\n  private parseContext(context: string): ActionContext {\n    switch (context) {\n      case '@calls': return ActionContext.atCalls();\n      case '@computer': return ActionContext.atComputer();\n      case '@errands': return ActionContext.atErrands('');\n      case '@home': return ActionContext.atHome();\n      case '@office': return ActionContext.atOffice();\n      case '@anywhere': return ActionContext.anywhere();\n      default: return ActionContext.atComputer();\n    }\n  }\n\n  private parseEnergyLevel(energy: string): EnergyLevel {\n    switch (energy) {\n      case 'high': return EnergyLevel.high();\n      case 'medium': return EnergyLevel.medium();\n      case 'low': return EnergyLevel.low();\n      default: return EnergyLevel.medium();\n    }\n  }\n}","import { injectable, inject } from 'inversify';\nimport { GTD_DOMAIN_SYMBOLS } from '../../../../infrastructure/di/GTDDomainSymbols';\nimport { NextActionAggregateRepository } from '../../infrastructure/repositories/NextActionAggregateRepository';\nimport { getMongoDb, Collection } from \"@swoft/persistence\";\n\n/**\n * Query criteria for filtering actions\n */\nexport interface ActionQueryCriteria {\n  readonly context?: string;\n  readonly energyLevel?: string;\n  readonly status?: 'available' | 'assigned' | 'completed' | 'all';\n  readonly assignedTo?: string;\n  readonly projectId?: string;\n  readonly searchText?: string;\n  readonly offset?: number;\n  readonly limit?: number;\n}\n\n/**\n * Action view model for read operations\n */\nexport interface NextActionView {\n  readonly id: string;\n  readonly description: string;\n  readonly context: string;\n  readonly energyLevel: string;\n  readonly estimatedMinutes: number;\n  readonly status: 'available' | 'assigned' | 'completed';\n  readonly createdBy: string;\n  readonly createdAt: Date;\n  readonly projectId?: string;\n  readonly assignedTo?: string;\n  readonly assignedAt?: Date;\n  readonly completedAt?: Date;\n}\n\n/**\n * Query result with pagination\n */\nexport interface ActionQueryResult {\n  readonly actions: NextActionView[];\n  readonly total: number;\n  readonly offset: number;\n  readonly limit: number;\n  readonly hasMore: boolean;\n}\n\n/**\n * NextActionReadService - Query Side (CQRS)\n * \n * Handles all read operations for GTD next actions.\n * Optimized for the GTD \"Engage\" phase - choosing what to do based on context.\n */\n@injectable()\nexport class NextActionReadService {\n  private collection: Collection;\n\n  constructor(\n    @inject(GTD_DOMAIN_SYMBOLS.NextActionAggregateRepository)\n    _repository: NextActionAggregateRepository\n  ) {\n    const db = getMongoDb();\n    this.collection = db.collection('gtd_next_actions');\n  }\n\n  /**\n   * Get actions matching current context and energy\n   * Core GTD principle: Match actions to available resources\n   */\n  async getAvailableActions(criteria: ActionQueryCriteria): Promise<ActionQueryResult> {\n    const {\n      context,\n      energyLevel,\n      status = 'available',\n      assignedTo,\n      projectId,\n      searchText,\n      offset = 0,\n      limit = 20\n    } = criteria;\n\n    // Build query\n    const query: any = {};\n    \n    if (status !== 'all') {\n      query.status = status;\n    }\n    \n    if (context) {\n      query.context = context;\n    }\n    \n    if (energyLevel) {\n      query.energyLevel = energyLevel;\n    }\n    \n    if (assignedTo) {\n      query.assignedTo = assignedTo;\n    }\n    \n    if (projectId) {\n      query.projectId = projectId;\n    }\n    \n    if (searchText) {\n      query.description = { $regex: searchText, $options: 'i' };\n    }\n\n    // Execute query with pagination\n    const [actions, total] = await Promise.all([\n      this.collection\n        .find(query)\n        .sort({ createdAt: -1 })\n        .skip(offset)\n        .limit(limit)\n        .toArray(),\n      this.collection.countDocuments(query)\n    ]);\n\n    // Map to view models\n    const actionViews: NextActionView[] = actions.map(doc => ({\n      id: doc._id.toString(),\n      description: doc.description,\n      context: doc.context,\n      energyLevel: doc.energyLevel,\n      estimatedMinutes: doc.estimatedMinutes,\n      status: doc.status,\n      createdBy: doc.createdBy,\n      createdAt: doc.createdAt,\n      projectId: doc.projectId,\n      assignedTo: doc.assignedTo,\n      assignedAt: doc.assignedAt,\n      completedAt: doc.completedAt\n    }));\n\n    return {\n      actions: actionViews,\n      total,\n      offset,\n      limit,\n      hasMore: total > offset + limit\n    };\n  }\n\n  /**\n   * Get a single action by ID\n   */\n  async getActionById(actionId: string): Promise<NextActionView | null> {\n    const doc = await this.collection.findOne({ _id: actionId as any });\n    \n    if (!doc) {\n      return null;\n    }\n\n    return {\n      id: doc._id.toString(),\n      description: doc.description,\n      context: doc.context,\n      energyLevel: doc.energyLevel,\n      estimatedMinutes: doc.estimatedMinutes,\n      status: doc.status,\n      createdBy: doc.createdBy,\n      createdAt: doc.createdAt,\n      projectId: doc.projectId,\n      assignedTo: doc.assignedTo,\n      assignedAt: doc.assignedAt,\n      completedAt: doc.completedAt\n    };\n  }\n\n  /**\n   * Get actions for GTD weekly review\n   */\n  async getActionsForReview(personId: string): Promise<ActionQueryResult> {\n    const query = {\n      $or: [\n        { createdBy: personId },\n        { assignedTo: personId }\n      ]\n    };\n\n    const actions = await this.collection\n      .find(query)\n      .sort({ status: 1, createdAt: -1 })\n      .toArray();\n\n    const actionViews: NextActionView[] = actions.map(doc => ({\n      id: doc._id.toString(),\n      description: doc.description,\n      context: doc.context,\n      energyLevel: doc.energyLevel,\n      estimatedMinutes: doc.estimatedMinutes,\n      status: doc.status,\n      createdBy: doc.createdBy,\n      createdAt: doc.createdAt,\n      projectId: doc.projectId,\n      assignedTo: doc.assignedTo,\n      assignedAt: doc.assignedAt,\n      completedAt: doc.completedAt\n    }));\n\n    return {\n      actions: actionViews,\n      total: actionViews.length,\n      offset: 0,\n      limit: actionViews.length,\n      hasMore: false\n    };\n  }\n\n  /**\n   * Get action statistics\n   */\n  async getActionStatistics(): Promise<{\n    total: number;\n    available: number;\n    assigned: number;\n    completed: number;\n    byContext: Record<string, number>;\n    byEnergy: Record<string, number>;\n  }> {\n    const [\n      total,\n      available,\n      assigned,\n      completed,\n      byContext,\n      byEnergy\n    ] = await Promise.all([\n      this.collection.countDocuments({}),\n      this.collection.countDocuments({ status: 'available' }),\n      this.collection.countDocuments({ status: 'assigned' }),\n      this.collection.countDocuments({ status: 'completed' }),\n      this.getCountByField('context'),\n      this.getCountByField('energyLevel')\n    ]);\n\n    return {\n      total,\n      available,\n      assigned,\n      completed,\n      byContext,\n      byEnergy\n    };\n  }\n\n  /**\n   * Get counts grouped by a field\n   */\n  private async getCountByField(field: string): Promise<Record<string, number>> {\n    const results = await this.collection.aggregate([\n      {\n        $group: {\n          _id: `$${field}`,\n          count: { $sum: 1 }\n        }\n      }\n    ]).toArray();\n\n    const counts: Record<string, number> = {};\n    for (const result of results) {\n      if (result._id) {\n        counts[result._id] = result.count;\n      }\n    }\n    return counts;\n  }\n}","import { injectable, inject } from 'inversify';\nimport { DesignImplementationFlow } from \"../../domain/aggregates/DesignImplementationFlow\";\nimport { DesignImplementationFlowRepository } from \"../../infrastructure/repositories/DesignImplementationFlowRepository\";\nimport { \n  CreateFlowCommand, \n  CreateFlowResult \n} from \"../commands/CreateFlowCommand\";\nimport { \n  AddArtifactCommand, \n  AddArtifactResult \n} from \"../commands/AddArtifactCommand\";\nimport { TYPES } from '../../../../types/DITypes';\n\n/**\n * Design Implementation Flow Application Service\n * \n * Following Eric Evans Application Service pattern for coordination management.\n * Coordinates flow operations following DDD principles.\n * \n * Rule: Every flow must be linked to a GTD project for proper coordination.\n */\n@injectable()\nexport class DesignImplementationFlowApplicationService {\n  constructor(\n    @inject(TYPES.DesignImplementationFlowRepository) \n    private readonly flowRepository: DesignImplementationFlowRepository\n  ) {}\n\n  /**\n   * Create a new design implementation flow\n   * \n   * Principle: Flows coordinate design-to-implementation tracking\n   * for multi-artifact outcomes.\n   */\n  async createFlow(command: CreateFlowCommand): Promise<CreateFlowResult> {\n    try {\n      // Create the flow aggregate\n      const flow = DesignImplementationFlow.create(\n        command.projectId,\n        command.createdBy,\n        command.metaModelBinding,\n        command.designSpecification\n      );\n\n      // Persist the flow\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        flowId: flow.id,\n        createdAt: flow.createdAt.toISOString(),\n        message: `Design implementation flow created successfully for project ${command.projectId}`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        flowId: '',\n        createdAt: new Date().toISOString(),\n        message: error instanceof Error ? error.message : 'Failed to create flow'\n      };\n    }\n  }\n\n  /**\n   * Add artifact to existing flow\n   * \n   * Principle: Artifacts are the units of implementation being tracked\n   */\n  async addArtifact(command: AddArtifactCommand): Promise<AddArtifactResult> {\n    try {\n      const flow = await this.flowRepository.findById(command.flowId);\n      \n      if (!flow) {\n        return {\n          success: false,\n          artifactId: '',\n          flowId: command.flowId,\n          createdAt: new Date().toISOString(),\n          message: `Flow ${command.flowId} not found`\n        };\n      }\n\n      const artifactId = flow.addArtifact(\n        command.name,\n        command.type,\n        command.location,\n        command.createdBy,\n        command.version,\n        command.tags || []\n      );\n\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        artifactId,\n        flowId: command.flowId,\n        createdAt: new Date().toISOString(),\n        message: `Artifact \"${command.name}\" added to flow successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        artifactId: '',\n        flowId: command.flowId,\n        createdAt: new Date().toISOString(),\n        message: error instanceof Error ? error.message : 'Failed to add artifact'\n      };\n    }\n  }\n\n  /**\n   * Update artifact conformance score\n   */\n  async updateConformanceScore(\n    flowId: string, \n    artifactId: string,\n    metaModelScore: number,\n    designCoverageScore: number,\n    confidence: 'high' | 'medium' | 'low',\n    updatedBy: string\n  ): Promise<{ success: boolean; message: string }> {\n    try {\n      const flow = await this.flowRepository.findById(flowId);\n      \n      if (!flow) {\n        return {\n          success: false,\n          message: `Flow ${flowId} not found`\n        };\n      }\n\n      flow.updateConformanceScore(\n        artifactId, \n        metaModelScore, \n        designCoverageScore,\n        confidence, \n        updatedBy\n      );\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        message: `Conformance score updated successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to update conformance score'\n      };\n    }\n  }\n\n  /**\n   * Update artifact status\n   */\n  async updateArtifactStatus(\n    flowId: string,\n    artifactId: string,\n    newStatus: string,\n    updatedBy: string\n  ): Promise<{ success: boolean; message: string }> {\n    try {\n      const flow = await this.flowRepository.findById(flowId);\n      \n      if (!flow) {\n        return {\n          success: false,\n          message: `Flow ${flowId} not found`\n        };\n      }\n\n      flow.updateArtifactStatus(artifactId, newStatus, updatedBy);\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        message: `Artifact status updated to ${newStatus}`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to update artifact status'\n      };\n    }\n  }\n\n  /**\n   * Complete flow\n   */\n  async completeFlow(flowId: string, completedBy: string): Promise<{ success: boolean; message: string }> {\n    try {\n      const flow = await this.flowRepository.findById(flowId);\n      \n      if (!flow) {\n        return {\n          success: false,\n          message: `Flow ${flowId} not found`\n        };\n      }\n\n      flow.complete(completedBy);\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        message: `Flow completed successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to complete flow'\n      };\n    }\n  }\n\n  /**\n   * Activate flow\n   */\n  async activateFlow(flowId: string): Promise<{ success: boolean; message: string }> {\n    try {\n      const flow = await this.flowRepository.findById(flowId);\n      \n      if (!flow) {\n        return {\n          success: false,\n          message: `Flow ${flowId} not found`\n        };\n      }\n\n      flow.activate();\n      await this.flowRepository.save(flow);\n\n      return {\n        success: true,\n        message: `Flow activated successfully`\n      };\n    } catch (error) {\n      return {\n        success: false,\n        message: error instanceof Error ? error.message : 'Failed to activate flow'\n      };\n    }\n  }\n}","/**\n * Artifact Status Value Object - Following GTD Pattern\n * Represents the lifecycle state of an artifact in the design-implementation flow\n */\nexport class ArtifactStatus {\n  private constructor(\n    public readonly status: string,\n    public readonly displayName: string,\n    private readonly allowedTransitions: string[]\n  ) {}\n\n  static planning(): ArtifactStatus {\n    return new ArtifactStatus('planning', 'Planning', ['development', 'review']);\n  }\n\n  static development(): ArtifactStatus {\n    return new ArtifactStatus('development', 'Development', ['review', 'production', 'planning']);\n  }\n\n  static review(): ArtifactStatus {\n    return new ArtifactStatus('review', 'Review', ['production', 'development']);\n  }\n\n  static production(): ArtifactStatus {\n    return new ArtifactStatus('production', 'Production', ['deprecated']);\n  }\n\n  static deprecated(): ArtifactStatus {\n    return new ArtifactStatus('deprecated', 'Deprecated', []);\n  }\n\n  static fromString(status: string): ArtifactStatus {\n    switch (status) {\n      case 'planning': return ArtifactStatus.planning();\n      case 'development': return ArtifactStatus.development();\n      case 'review': return ArtifactStatus.review();\n      case 'production': return ArtifactStatus.production();\n      case 'deprecated': return ArtifactStatus.deprecated();\n      default: throw new Error(`Invalid artifact status: ${status}`);\n    }\n  }\n\n  canTransitionTo(newStatus: string): boolean {\n    return this.allowedTransitions.includes(newStatus);\n  }\n\n  equals(other: ArtifactStatus): boolean {\n    return this.status === other.status;\n  }\n\n  toString(): string {\n    return this.status;\n  }\n}","/**\n * Conformance Score Value Object - Following GTD Pattern\n * Represents the quality metrics for artifact conformance to meta-models and design\n */\nexport class ConformanceScore {\n  constructor(\n    public readonly metaModelScore: number,\n    public readonly designCoverageScore: number,\n    public readonly confidence: 'high' | 'medium' | 'low',\n    public readonly calculatedAt: Date = new Date()\n  ) {\n    this.validateScore(metaModelScore, 'metaModelScore');\n    this.validateScore(designCoverageScore, 'designCoverageScore');\n  }\n\n  private validateScore(score: number, field: string): void {\n    if (score < 0 || score > 100) {\n      throw new Error(`${field} must be between 0 and 100. Got: ${score}`);\n    }\n  }\n\n  get overallScore(): number {\n    return Math.round((this.metaModelScore + this.designCoverageScore) / 2);\n  }\n\n  isPassingGrade(): boolean {\n    return this.overallScore >= 80 && this.metaModelScore >= 70 && this.designCoverageScore >= 70;\n  }\n\n  needsImprovement(): boolean {\n    return this.overallScore < 80 || this.metaModelScore < 70 || this.designCoverageScore < 70;\n  }\n\n  static create(metaModelScore: number, designCoverageScore: number, confidence: 'high' | 'medium' | 'low'): ConformanceScore {\n    return new ConformanceScore(metaModelScore, designCoverageScore, confidence);\n  }\n\n  static zero(): ConformanceScore {\n    return new ConformanceScore(0, 0, 'low');\n  }\n\n  equals(other: ConformanceScore): boolean {\n    return this.metaModelScore === other.metaModelScore &&\n           this.designCoverageScore === other.designCoverageScore &&\n           this.confidence === other.confidence;\n  }\n\n  toString(): string {\n    return `${this.overallScore}% (Meta: ${this.metaModelScore}%, Design: ${this.designCoverageScore}%) - ${this.confidence} confidence`;\n  }\n}","/**\n * Flow Status Value Object - Following GTD Pattern\n * Represents the status of a design-implementation coordination flow\n */\nexport class FlowStatus {\n  private constructor(\n    public readonly status: string,\n    public readonly displayName: string,\n    private readonly allowedTransitions: string[]\n  ) {}\n\n  static draft(): FlowStatus {\n    return new FlowStatus('draft', 'Draft', ['active', 'abandoned']);\n  }\n\n  static active(): FlowStatus {\n    return new FlowStatus('active', 'Active', ['completed', 'abandoned']);\n  }\n\n  static completed(): FlowStatus {\n    return new FlowStatus('completed', 'Completed', []);\n  }\n\n  static abandoned(): FlowStatus {\n    return new FlowStatus('abandoned', 'Abandoned', ['draft', 'active']);\n  }\n\n  static fromString(status: string): FlowStatus {\n    switch (status) {\n      case 'draft': return FlowStatus.draft();\n      case 'active': return FlowStatus.active();\n      case 'completed': return FlowStatus.completed();\n      case 'abandoned': return FlowStatus.abandoned();\n      default: throw new Error(`Invalid flow status: ${status}`);\n    }\n  }\n\n  canTransitionTo(newStatus: string): boolean {\n    return this.allowedTransitions.includes(newStatus);\n  }\n\n  isActive(): boolean {\n    return this.status === 'active';\n  }\n\n  isCompleted(): boolean {\n    return this.status === 'completed';\n  }\n\n  equals(other: FlowStatus): boolean {\n    return this.status === other.status;\n  }\n\n  toString(): string {\n    return this.status;\n  }\n}","/**\n * Design Implementation Domain Errors following GTD clean error handling patterns\n */\nexport class DesignImplementationDomainError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly context?: Record<string, any>\n  ) {\n    super(message);\n    this.name = 'DesignImplementationDomainError';\n  }\n}\n\nexport class FlowStateError extends DesignImplementationDomainError {\n  constructor(message: string, flowId: string, currentState: string) {\n    super(message, 'FLOW_STATE_ERROR', { flowId, currentState });\n    this.name = 'FlowStateError';\n  }\n}\n\nexport class ArtifactStateError extends DesignImplementationDomainError {\n  constructor(message: string, artifactId: string, currentState: string) {\n    super(message, 'ARTIFACT_STATE_ERROR', { artifactId, currentState });\n    this.name = 'ArtifactStateError';\n  }\n}\n\nexport class ConformanceValidationError extends DesignImplementationDomainError {\n  constructor(message: string, artifactId: string, violations: string[]) {\n    super(message, 'CONFORMANCE_VALIDATION_ERROR', { artifactId, violations });\n    this.name = 'ConformanceValidationError';\n  }\n}\n\nexport class InvalidScoreError extends DesignImplementationDomainError {\n  constructor(score: number, field: string) {\n    super(\n      `Invalid score value. ${field}: ${score}. Scores must be between 0 and 100.`,\n      'INVALID_SCORE_ERROR',\n      { score, field, minScore: 0, maxScore: 100 }\n    );\n    this.name = 'InvalidScoreError';\n  }\n}\n\nexport class ArtifactNotFoundError extends DesignImplementationDomainError {\n  constructor(artifactId: string, flowId: string) {\n    super(\n      `Artifact ${artifactId} not found in flow ${flowId}`,\n      'ARTIFACT_NOT_FOUND_ERROR',\n      { artifactId, flowId }\n    );\n    this.name = 'ArtifactNotFoundError';\n  }\n}","import { DomainEvent } from '../../../project-management/domain/events/DomainEvent';\n\n/**\n * Design Implementation Flow Events - Following GTD Event Pattern\n */\n\nexport class FlowCreated extends DomainEvent {\n  constructor(\n    public readonly flowId: string,\n    public readonly projectId: string,\n    public readonly createdBy: string\n  ) {\n    super(flowId, 'FlowCreated');\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      flowId: this.flowId,\n      projectId: this.projectId,\n      createdBy: this.createdBy\n    };\n  }\n}\n\nexport class ArtifactAdded extends DomainEvent {\n  constructor(\n    public readonly flowId: string,\n    public readonly artifactId: string,\n    public readonly artifactName: string,\n    public readonly artifactType: string,\n    public readonly addedBy: string\n  ) {\n    super(flowId, 'ArtifactAdded');\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      flowId: this.flowId,\n      artifactId: this.artifactId,\n      artifactName: this.artifactName,\n      artifactType: this.artifactType,\n      addedBy: this.addedBy\n    };\n  }\n}\n\nexport class ConformanceScoreUpdated extends DomainEvent {\n  constructor(\n    public readonly flowId: string,\n    public readonly artifactId: string,\n    public readonly previousScore: number,\n    public readonly newScore: number,\n    public readonly updatedBy: string\n  ) {\n    super(flowId, 'ConformanceScoreUpdated');\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      flowId: this.flowId,\n      artifactId: this.artifactId,\n      previousScore: this.previousScore,\n      newScore: this.newScore,\n      updatedBy: this.updatedBy\n    };\n  }\n}\n\nexport class FlowCompleted extends DomainEvent {\n  constructor(\n    public readonly flowId: string,\n    public readonly projectId: string,\n    public readonly totalArtifacts: number,\n    public readonly averageConformance: number,\n    public readonly completedBy: string\n  ) {\n    super(flowId, 'FlowCompleted');\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      flowId: this.flowId,\n      projectId: this.projectId,\n      totalArtifacts: this.totalArtifacts,\n      averageConformance: this.averageConformance,\n      completedBy: this.completedBy\n    };\n  }\n}\n\nexport class ArtifactStatusChanged extends DomainEvent {\n  constructor(\n    public readonly flowId: string,\n    public readonly artifactId: string,\n    public readonly previousStatus: string,\n    public readonly newStatus: string,\n    public readonly changedBy: string\n  ) {\n    super(flowId, 'ArtifactStatusChanged');\n  }\n\n  getEventData(): Record<string, any> {\n    return {\n      flowId: this.flowId,\n      artifactId: this.artifactId,\n      previousStatus: this.previousStatus,\n      newStatus: this.newStatus,\n      changedBy: this.changedBy\n    };\n  }\n}","import { DomainEvent } from '../../../project-management/domain/events/DomainEvent';\nimport { ArtifactStatus, ConformanceScore, FlowStatus } from '../value-objects';\nimport { FlowStateError, ArtifactStateError, ArtifactNotFoundError } from '../errors/DesignImplementationDomainError';\nimport { \n  FlowCreated, \n  ArtifactAdded, \n  ConformanceScoreUpdated, \n  FlowCompleted,\n  ArtifactStatusChanged \n} from '../events/DesignImplementationEvents';\n\n/**\n * Artifact Entity within the Flow aggregate\n */\nexport interface Artifact {\n  id: string;\n  name: string;\n  type: 'Package' | 'Component' | 'Service' | 'Module' | 'Documentation';\n  version?: string;\n  location: {\n    type: 'npm' | 'file' | 'service' | 'repository';\n    path: string;\n    url?: string;\n    registry?: string;\n  };\n  status: ArtifactStatus;\n  conformanceScore?: ConformanceScore;\n  healthStatus: {\n    buildStatus: 'success' | 'failure' | 'pending' | 'not-applicable';\n    testStatus: 'passing' | 'failing' | 'partial' | 'not-applicable';\n    deploymentStatus: 'deployed' | 'pending' | 'failed' | 'not-applicable';\n    lastHealthCheck: Date;\n  };\n  createdBy: string;\n  createdAt: Date;\n  lastModified: Date;\n  tags: string[];\n}\n\n/**\n * Design Implementation Flow Aggregate - Following GTD Project Pattern\n * \n * Tracks the coordination between design specifications and their implementation\n * through artifacts, maintaining conformance scores and progress metrics.\n * \n * Core Principles:\n * - Every flow must be linked to a GTD project\n * - Artifacts track conformance to meta-models and design coverage\n * - Flow provides progress metrics back to GTD system\n */\nexport class DesignImplementationFlow {\n  private domainEvents: DomainEvent[] = [];\n  private _artifacts: Artifact[] = [];\n  private _status: FlowStatus = FlowStatus.draft();\n  private _completedAt?: Date;\n\n  constructor(\n    public readonly id: string,\n    public readonly projectId: string,\n    public readonly createdBy: string,\n    public readonly createdAt: Date = new Date(),\n    public readonly metaModelBinding?: {\n      metamodelId: string;\n      boundAt: Date;\n      validationStatus: 'valid' | 'invalid' | 'pending';\n    },\n    public readonly designSpecification?: {\n      designId: string;\n      designType: 'Component' | 'Page' | 'Pattern' | 'System';\n      domainContext: string;\n    }\n  ) {\n    this.validateFlow(projectId);\n  }\n\n  /**\n   * Create a new design implementation flow\n   */\n  static create(\n    projectId: string,\n    createdBy: string,\n    metaModelBinding?: {\n      metamodelId: string;\n      boundAt: Date;\n      validationStatus: 'valid' | 'invalid' | 'pending';\n    },\n    designSpecification?: {\n      designId: string;\n      designType: 'Component' | 'Page' | 'Pattern' | 'System';\n      domainContext: string;\n    }\n  ): DesignImplementationFlow {\n    const id = this.generateId();\n    const flow = new DesignImplementationFlow(\n      id, \n      projectId, \n      createdBy, \n      new Date(),\n      metaModelBinding,\n      designSpecification\n    );\n\n    flow.addDomainEvent(new FlowCreated(id, projectId, createdBy));\n    return flow;\n  }\n\n  /**\n   * Add artifact to the flow\n   */\n  addArtifact(\n    name: string,\n    type: 'Package' | 'Component' | 'Service' | 'Module' | 'Documentation',\n    location: {\n      type: 'npm' | 'file' | 'service' | 'repository';\n      path: string;\n      url?: string;\n      registry?: string;\n    },\n    createdBy: string,\n    version?: string,\n    tags: string[] = []\n  ): string {\n    if (this.isCompleted()) {\n      throw new FlowStateError(\n        'Cannot add artifacts to completed flows',\n        this.id,\n        this._status.toString()\n      );\n    }\n\n    const artifactId = this.generateArtifactId();\n    const artifact: Artifact = {\n      id: artifactId,\n      name,\n      type,\n      version,\n      location,\n      status: ArtifactStatus.planning(),\n      healthStatus: {\n        buildStatus: 'not-applicable',\n        testStatus: 'not-applicable',\n        deploymentStatus: 'not-applicable',\n        lastHealthCheck: new Date()\n      },\n      createdBy,\n      createdAt: new Date(),\n      lastModified: new Date(),\n      tags\n    };\n\n    this._artifacts.push(artifact);\n    \n    this.addDomainEvent(new ArtifactAdded(\n      this.id, \n      artifactId, \n      name, \n      type,\n      createdBy\n    ));\n\n    return artifactId;\n  }\n\n  /**\n   * Update artifact status\n   */\n  updateArtifactStatus(artifactId: string, newStatus: string, updatedBy: string): void {\n    const artifact = this.findArtifact(artifactId);\n    const currentStatus = artifact.status.toString();\n\n    if (!artifact.status.canTransitionTo(newStatus)) {\n      throw new ArtifactStateError(\n        `Cannot transition from ${currentStatus} to ${newStatus}`,\n        artifactId,\n        currentStatus\n      );\n    }\n\n    const previousStatus = artifact.status.toString();\n    artifact.status = ArtifactStatus.fromString(newStatus);\n    artifact.lastModified = new Date();\n\n    this.addDomainEvent(new ArtifactStatusChanged(\n      this.id,\n      artifactId,\n      previousStatus,\n      newStatus,\n      updatedBy\n    ));\n  }\n\n  /**\n   * Update conformance score for an artifact\n   */\n  updateConformanceScore(\n    artifactId: string, \n    metaModelScore: number, \n    designCoverageScore: number,\n    confidence: 'high' | 'medium' | 'low',\n    updatedBy: string\n  ): void {\n    const artifact = this.findArtifact(artifactId);\n    const previousScore = artifact.conformanceScore?.overallScore || 0;\n    \n    artifact.conformanceScore = ConformanceScore.create(\n      metaModelScore, \n      designCoverageScore, \n      confidence\n    );\n    artifact.lastModified = new Date();\n\n    const newScore = artifact.conformanceScore.overallScore;\n    \n    this.addDomainEvent(new ConformanceScoreUpdated(\n      this.id,\n      artifactId,\n      previousScore,\n      newScore,\n      updatedBy\n    ));\n  }\n\n  /**\n   * Activate the flow\n   */\n  activate(): void {\n    if (!this._status.canTransitionTo('active')) {\n      throw new FlowStateError(\n        `Cannot activate flow from ${this._status.toString()} state`,\n        this.id,\n        this._status.toString()\n      );\n    }\n\n    this._status = FlowStatus.active();\n  }\n\n  /**\n   * Complete the flow\n   */\n  complete(completedBy?: string): void {\n    if (!this._status.canTransitionTo('completed')) {\n      throw new FlowStateError(\n        `Cannot complete flow from ${this._status.toString()} state`,\n        this.id,\n        this._status.toString()\n      );\n    }\n\n    this._status = FlowStatus.completed();\n    this._completedAt = new Date();\n\n    const metrics = this.getProgressMetrics();\n    \n    this.addDomainEvent(new FlowCompleted(\n      this.id,\n      this.projectId,\n      metrics.totalArtifacts,\n      metrics.averageConformance,\n      completedBy || this.createdBy\n    ));\n  }\n\n  /**\n   * Abandon the flow\n   */\n  abandon(): void {\n    if (!this._status.canTransitionTo('abandoned')) {\n      throw new FlowStateError(\n        `Cannot abandon flow from ${this._status.toString()} state`,\n        this.id,\n        this._status.toString()\n      );\n    }\n\n    this._status = FlowStatus.abandoned();\n  }\n\n  /**\n   * Get progress metrics for GTD integration\n   */\n  getProgressMetrics(): {\n    totalArtifacts: number;\n    completedArtifacts: number;\n    artifactsInProgress: number;\n    averageConformance: number;\n    averageDesignCoverage: number;\n  } {\n    const total = this._artifacts.length;\n    const completed = this._artifacts.filter(a => a.status.toString() === 'production').length;\n    const inProgress = this._artifacts.filter(a => \n      ['development', 'review'].includes(a.status.toString())\n    ).length;\n\n    const conformanceScores = this._artifacts\n      .map(a => a.conformanceScore?.overallScore || 0)\n      .filter(score => score > 0);\n    \n    const averageConformance = conformanceScores.length > 0 \n      ? conformanceScores.reduce((sum, score) => sum + score, 0) / conformanceScores.length \n      : 0;\n\n    const designScores = this._artifacts\n      .map(a => a.conformanceScore?.designCoverageScore || 0)\n      .filter(score => score > 0);\n    \n    const averageDesignCoverage = designScores.length > 0\n      ? designScores.reduce((sum, score) => sum + score, 0) / designScores.length\n      : 0;\n\n    return {\n      totalArtifacts: total,\n      completedArtifacts: completed,\n      artifactsInProgress: inProgress,\n      averageConformance: Math.round(averageConformance),\n      averageDesignCoverage: Math.round(averageDesignCoverage)\n    };\n  }\n\n  /**\n   * Get artifacts that need attention\n   */\n  getBlockedArtifacts(): Array<{\n    artifactId: string;\n    artifactName: string;\n    blockReason: string;\n    severity: 'critical' | 'high' | 'medium' | 'low';\n  }> {\n    const blocked: Array<{\n      artifactId: string;\n      artifactName: string;\n      blockReason: string;\n      severity: 'critical' | 'high' | 'medium' | 'low';\n    }> = [];\n\n    this._artifacts.forEach(artifact => {\n      // Check for build failures\n      if (artifact.healthStatus.buildStatus === 'failure') {\n        blocked.push({\n          artifactId: artifact.id,\n          artifactName: artifact.name,\n          blockReason: 'Build failing',\n          severity: 'critical'\n        });\n      }\n\n      // Check for poor conformance\n      if (artifact.conformanceScore && artifact.conformanceScore.needsImprovement()) {\n        blocked.push({\n          artifactId: artifact.id,\n          artifactName: artifact.name,\n          blockReason: `Low conformance score: ${artifact.conformanceScore.overallScore}%`,\n          severity: artifact.conformanceScore.overallScore < 50 ? 'high' : 'medium'\n        });\n      }\n\n      // Check for stale artifacts\n      const daysSinceUpdate = Math.floor(\n        (new Date().getTime() - artifact.lastModified.getTime()) / (1000 * 60 * 60 * 24)\n      );\n      if (daysSinceUpdate > 7 && artifact.status.toString() === 'development') {\n        blocked.push({\n          artifactId: artifact.id,\n          artifactName: artifact.name,\n          blockReason: `No updates for ${daysSinceUpdate} days`,\n          severity: daysSinceUpdate > 14 ? 'medium' : 'low'\n        });\n      }\n    });\n\n    return blocked;\n  }\n\n  // State queries\n  isCompleted(): boolean {\n    return this._status.isCompleted();\n  }\n\n  isActive(): boolean {\n    return this._status.isActive();\n  }\n\n  // Getters\n  get status(): FlowStatus {\n    return this._status;\n  }\n\n  get artifacts(): Artifact[] {\n    return [...this._artifacts];\n  }\n\n  get completedAt(): Date | undefined {\n    return this._completedAt;\n  }\n\n  // Event sourcing support\n  getDomainEvents(): DomainEvent[] {\n    return [...this.domainEvents];\n  }\n\n  clearDomainEvents(): void {\n    this.domainEvents = [];\n  }\n\n  // Private methods\n  private findArtifact(artifactId: string): Artifact {\n    const artifact = this._artifacts.find(a => a.id === artifactId);\n    if (!artifact) {\n      throw new ArtifactNotFoundError(artifactId, this.id);\n    }\n    return artifact;\n  }\n\n  private validateFlow(projectId: string): void {\n    if (!projectId?.trim()) {\n      throw new FlowStateError('Project ID is required', '', 'unknown');\n    }\n  }\n\n  private addDomainEvent(event: DomainEvent): void {\n    this.domainEvents.push(event);\n  }\n\n  private static generateId(): string {\n    return `flow-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n  }\n\n  private generateArtifactId(): string {\n    return `artifact-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n  }\n}","import { injectable } from 'inversify';\nimport { Collection, Db, getMongoDb } from \"@swoft/persistence\";\nimport { DesignImplementationFlow } from '../../domain/aggregates/DesignImplementationFlow';\nimport { FlowStatus, ArtifactStatus, ConformanceScore } from '../../domain/value-objects';\nimport { GTD_COLLECTIONS } from '../../../../config/collections';\n\n/**\n * MongoDB Repository for DesignImplementationFlow Aggregate\n * \n * Following Eric Evans repository pattern - provides collection-like\n * interface for accessing flows while hiding persistence details.\n * Based on GTD Project Repository pattern.\n */\n@injectable()\nexport class DesignImplementationFlowRepository {\n  private db: Db | null = null;\n  private collection: Collection | null = null;\n\n  constructor() {\n    // Lazy initialization - don't connect until needed\n  }\n\n  private ensureConnection() {\n    if (!this.db) {\n      this.db = getMongoDb();\n      this.collection = this.db.collection(GTD_COLLECTIONS.DESIGN_IMPLEMENTATION_FLOWS);\n    }\n    return this.collection!;\n  }\n\n  async save(flow: DesignImplementationFlow): Promise<void> {\n    const collection = this.ensureConnection();\n    const doc = {\n      _id: flow.id,\n      projectId: flow.projectId,\n      createdBy: flow.createdBy,\n      createdAt: flow.createdAt,\n      metaModelBinding: flow.metaModelBinding,\n      designSpecification: flow.designSpecification,\n      status: flow.status.toString(),\n      artifacts: flow.artifacts.map(artifact => ({\n        id: artifact.id,\n        name: artifact.name,\n        type: artifact.type,\n        version: artifact.version,\n        location: artifact.location,\n        status: artifact.status.toString(),\n        conformanceScore: artifact.conformanceScore ? {\n          metaModelScore: artifact.conformanceScore.metaModelScore,\n          designCoverageScore: artifact.conformanceScore.designCoverageScore,\n          overallScore: artifact.conformanceScore.overallScore,\n          confidence: artifact.conformanceScore.confidence,\n          calculatedAt: artifact.conformanceScore.calculatedAt\n        } : null,\n        healthStatus: artifact.healthStatus,\n        createdBy: artifact.createdBy,\n        createdAt: artifact.createdAt,\n        lastModified: artifact.lastModified,\n        tags: artifact.tags\n      })),\n      completedAt: flow.completedAt,\n      updatedAt: new Date()\n    };\n\n    await collection.replaceOne(\n      { _id: flow.id as any },\n      doc,\n      { upsert: true }\n    );\n  }\n\n  async findById(id: string): Promise<DesignImplementationFlow | null> {\n    const collection = this.ensureConnection();\n    const doc = await collection.findOne({ _id: id as any });\n    if (!doc) return null;\n\n    return this.mapDocumentToDomain(doc);\n  }\n\n  async findByProjectId(projectId: string): Promise<DesignImplementationFlow[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({ projectId })\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(flow => flow !== null) as DesignImplementationFlow[];\n  }\n\n  async findByStatus(status: string): Promise<DesignImplementationFlow[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({ status })\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(flow => flow !== null) as DesignImplementationFlow[];\n  }\n\n  async findActiveFlows(): Promise<DesignImplementationFlow[]> {\n    return this.findByStatus('active');\n  }\n\n  async findAll(): Promise<DesignImplementationFlow[]> {\n    const collection = this.ensureConnection();\n    const docs = await collection\n      .find({})\n      .sort({ createdAt: -1 })\n      .toArray();\n\n    return docs\n      .map(doc => this.safeMapDocumentToDomain(doc))\n      .filter(flow => flow !== null) as DesignImplementationFlow[];\n  }\n\n  async deleteById(id: string): Promise<void> {\n    const collection = this.ensureConnection();\n    await collection.deleteOne({ _id: id as any });\n  }\n\n  private mapDocumentToDomain(doc: any): DesignImplementationFlow {\n    const flow = new DesignImplementationFlow(\n      doc._id,\n      doc.projectId,\n      doc.createdBy,\n      new Date(doc.createdAt),\n      doc.metaModelBinding,\n      doc.designSpecification\n    );\n\n    // Restore private state\n    if (doc.status) {\n      (flow as any)._status = FlowStatus.fromString(doc.status);\n    }\n    if (doc.completedAt) {\n      (flow as any)._completedAt = new Date(doc.completedAt);\n    }\n\n    // Restore artifacts\n    if (doc.artifacts && Array.isArray(doc.artifacts)) {\n      const artifacts = doc.artifacts.map((artifactDoc: any) => ({\n        id: artifactDoc.id,\n        name: artifactDoc.name,\n        type: artifactDoc.type,\n        version: artifactDoc.version,\n        location: artifactDoc.location,\n        status: ArtifactStatus.fromString(artifactDoc.status),\n        conformanceScore: artifactDoc.conformanceScore ? \n          new ConformanceScore(\n            artifactDoc.conformanceScore.metaModelScore,\n            artifactDoc.conformanceScore.designCoverageScore,\n            artifactDoc.conformanceScore.confidence,\n            new Date(artifactDoc.conformanceScore.calculatedAt)\n          ) : undefined,\n        healthStatus: {\n          buildStatus: artifactDoc.healthStatus.buildStatus,\n          testStatus: artifactDoc.healthStatus.testStatus,\n          deploymentStatus: artifactDoc.healthStatus.deploymentStatus,\n          lastHealthCheck: new Date(artifactDoc.healthStatus.lastHealthCheck)\n        },\n        createdBy: artifactDoc.createdBy,\n        createdAt: new Date(artifactDoc.createdAt),\n        lastModified: new Date(artifactDoc.lastModified),\n        tags: artifactDoc.tags || []\n      }));\n      \n      (flow as any)._artifacts = artifacts;\n    }\n\n    return flow;\n  }\n\n  private safeMapDocumentToDomain(doc: any): DesignImplementationFlow | null {\n    try {\n      // Validate required fields before attempting to create domain object\n      if (!doc.projectId?.trim()) {\n        console.warn(`Skipping flow document with missing projectId: ${doc._id}`);\n        return null;\n      }\n      if (!doc.createdBy?.trim()) {\n        console.warn(`Skipping flow document with missing createdBy: ${doc._id}`);\n        return null;\n      }\n\n      return this.mapDocumentToDomain(doc);\n    } catch (error) {\n      console.warn(`Failed to map flow document to domain object: ${doc._id}`, error);\n      return null;\n    }\n  }\n}","import { injectable, inject } from 'inversify';\nimport { DesignImplementationFlowRepository } from \"../../infrastructure/repositories/DesignImplementationFlowRepository\";\nimport { TYPES } from '../../../../types/DITypes';\n\n/**\n * Flow query criteria for filtering\n */\nexport interface FlowQueryCriteria {\n  projectId?: string;\n  status?: string;\n  createdBy?: string;\n  artifactType?: string;\n  hasConformanceIssues?: boolean;\n}\n\n/**\n * Flow view model for read operations\n */\nexport interface FlowView {\n  flowId: string;\n  projectId: string;\n  status: string;\n  createdBy: string;\n  createdAt: string;\n  completedAt?: string;\n  \n  // Meta-model binding\n  metaModelBinding?: {\n    metamodelId: string;\n    boundAt: string;\n    validationStatus: string;\n  };\n  \n  // Design specification\n  designSpecification?: {\n    designId: string;\n    designType: string;\n    domainContext: string;\n  };\n  \n  // Progress metrics\n  progressMetrics: {\n    totalArtifacts: number;\n    completedArtifacts: number;\n    artifactsInProgress: number;\n    averageConformance: number;\n    averageDesignCoverage: number;\n  };\n  \n  // Blocked artifacts summary\n  blockedArtifacts: Array<{\n    artifactId: string;\n    artifactName: string;\n    blockReason: string;\n    severity: string;\n  }>;\n  \n  // Individual artifacts\n  artifacts: Array<{\n    id: string;\n    name: string;\n    type: string;\n    version?: string;\n    status: string;\n    conformanceScore?: {\n      metaModelScore: number;\n      designCoverageScore: number;\n      overallScore: number;\n      confidence: string;\n    };\n    healthStatus: {\n      buildStatus: string;\n      testStatus: string;\n      deploymentStatus: string;\n      lastHealthCheck: string;\n    };\n    tags: string[];\n  }>;\n}\n\n/**\n * Query result with pagination\n */\nexport interface FlowQueryResult {\n  flows: FlowView[];\n  totalCount: number;\n  hasMore: boolean;\n}\n\n/**\n * Design Implementation Flow Read Service\n * \n * Following GTD CQRS pattern for read operations.\n * Provides optimized queries for flow monitoring and reporting.\n */\n@injectable()\nexport class DesignImplementationFlowReadService {\n  constructor(\n    @inject(TYPES.DesignImplementationFlowRepository) \n    private readonly flowRepository: DesignImplementationFlowRepository\n  ) {}\n\n  /**\n   * Get flow by ID with full details\n   */\n  async getFlowById(flowId: string): Promise<FlowView | null> {\n    const flow = await this.flowRepository.findById(flowId);\n    if (!flow) return null;\n\n    return this.mapToFlowView(flow);\n  }\n\n  /**\n   * Query flows with criteria and pagination\n   */\n  async queryFlows(\n    criteria: FlowQueryCriteria = {},\n    limit: number = 50,\n    offset: number = 0\n  ): Promise<FlowQueryResult> {\n    // Get all flows (in a real implementation, this would be optimized with MongoDB queries)\n    let flows = await this.flowRepository.findAll();\n\n    // Apply filters\n    if (criteria.projectId) {\n      flows = flows.filter(f => f.projectId === criteria.projectId);\n    }\n    \n    if (criteria.status) {\n      flows = flows.filter(f => f.status.toString() === criteria.status);\n    }\n    \n    if (criteria.createdBy) {\n      flows = flows.filter(f => f.createdBy === criteria.createdBy);\n    }\n    \n    if (criteria.artifactType) {\n      flows = flows.filter(f => \n        f.artifacts.some(a => a.type === criteria.artifactType)\n      );\n    }\n    \n    if (criteria.hasConformanceIssues) {\n      flows = flows.filter(f => \n        f.artifacts.some(a => \n          a.conformanceScore && a.conformanceScore.needsImprovement()\n        )\n      );\n    }\n\n    const totalCount = flows.length;\n    const paginatedFlows = flows.slice(offset, offset + limit);\n    const flowViews = paginatedFlows.map(f => this.mapToFlowView(f));\n\n    return {\n      flows: flowViews,\n      totalCount,\n      hasMore: offset + limit < totalCount\n    };\n  }\n\n  /**\n   * Get flows by project ID\n   */\n  async getFlowsByProjectId(projectId: string): Promise<FlowView[]> {\n    const flows = await this.flowRepository.findByProjectId(projectId);\n    return flows.map(f => this.mapToFlowView(f));\n  }\n\n  /**\n   * Get active flows\n   */\n  async getActiveFlows(): Promise<FlowView[]> {\n    const flows = await this.flowRepository.findActiveFlows();\n    return flows.map(f => this.mapToFlowView(f));\n  }\n\n  /**\n   * Get flows that need attention\n   */\n  async getFlowsNeedingAttention(): Promise<FlowView[]> {\n    const flows = await this.flowRepository.findActiveFlows();\n    const needingAttention = flows.filter(flow => {\n      const blocked = flow.getBlockedArtifacts();\n      return blocked.length > 0;\n    });\n    \n    return needingAttention.map(f => this.mapToFlowView(f));\n  }\n\n  /**\n   * Get conformance summary across all flows\n   */\n  async getConformanceSummary(): Promise<{\n    totalFlows: number;\n    activeFlows: number;\n    completedFlows: number;\n    totalArtifacts: number;\n    averageConformance: number;\n    artifactsNeedingAttention: number;\n  }> {\n    const flows = await this.flowRepository.findAll();\n    \n    let totalArtifacts = 0;\n    let totalConformanceSum = 0;\n    let artifactsWithScores = 0;\n    let artifactsNeedingAttention = 0;\n\n    flows.forEach(flow => {\n      const metrics = flow.getProgressMetrics();\n      totalArtifacts += metrics.totalArtifacts;\n      \n      flow.artifacts.forEach(artifact => {\n        if (artifact.conformanceScore) {\n          totalConformanceSum += artifact.conformanceScore.overallScore;\n          artifactsWithScores++;\n          \n          if (artifact.conformanceScore.needsImprovement()) {\n            artifactsNeedingAttention++;\n          }\n        }\n      });\n    });\n\n    return {\n      totalFlows: flows.length,\n      activeFlows: flows.filter(f => f.isActive()).length,\n      completedFlows: flows.filter(f => f.isCompleted()).length,\n      totalArtifacts,\n      averageConformance: artifactsWithScores > 0 \n        ? Math.round(totalConformanceSum / artifactsWithScores) \n        : 0,\n      artifactsNeedingAttention\n    };\n  }\n\n  private mapToFlowView(flow: any): FlowView {\n    const progressMetrics = flow.getProgressMetrics();\n    const blockedArtifacts = flow.getBlockedArtifacts();\n\n    return {\n      flowId: flow.id,\n      projectId: flow.projectId,\n      status: flow.status.toString(),\n      createdBy: flow.createdBy,\n      createdAt: flow.createdAt.toISOString(),\n      completedAt: flow.completedAt?.toISOString(),\n      \n      metaModelBinding: flow.metaModelBinding ? {\n        metamodelId: flow.metaModelBinding.metamodelId,\n        boundAt: flow.metaModelBinding.boundAt.toISOString(),\n        validationStatus: flow.metaModelBinding.validationStatus\n      } : undefined,\n      \n      designSpecification: flow.designSpecification,\n      \n      progressMetrics,\n      blockedArtifacts,\n      \n      artifacts: flow.artifacts.map((artifact: any) => ({\n        id: artifact.id,\n        name: artifact.name,\n        type: artifact.type,\n        version: artifact.version,\n        status: artifact.status.toString(),\n        conformanceScore: artifact.conformanceScore ? {\n          metaModelScore: artifact.conformanceScore.metaModelScore,\n          designCoverageScore: artifact.conformanceScore.designCoverageScore,\n          overallScore: artifact.conformanceScore.overallScore,\n          confidence: artifact.conformanceScore.confidence\n        } : undefined,\n        healthStatus: {\n          buildStatus: artifact.healthStatus.buildStatus,\n          testStatus: artifact.healthStatus.testStatus,\n          deploymentStatus: artifact.healthStatus.deploymentStatus,\n          lastHealthCheck: artifact.healthStatus.lastHealthCheck.toISOString()\n        },\n        tags: artifact.tags\n      }))\n    };\n  }\n}","/**\n * GTD Domain - Bounded Contexts Export\n * \n * Exports application services and domain components from all bounded contexts\n * within the GTD domain for use by MCP tools and external consumers.\n */\n\n// Inbox Management Bounded Context\nexport { InboxItemApplicationService } from './inbox-management/application/services/InboxItemApplicationService';\n\n// Project Management Bounded Context  \nexport { ProjectApplicationService } from './project-management/application/services/ProjectApplicationService';\n\n// Design Implementation Coordination Bounded Context\nexport { DesignImplementationFlowApplicationService } from './design-implementation-coordination/application/services/DesignImplementationFlowApplicationService';\nexport { DesignImplementationFlowReadService } from './design-implementation-coordination/application/services/DesignImplementationFlowReadService';\n\n// Task Management Bounded Context\n// Note: WeeklyReviewApplicationService would be part of a review management context\n// For now, we'll create a stub to satisfy the MCP exports\n\n/**\n * Placeholder Weekly Review Application Service\n * TODO: Implement proper weekly review bounded context\n */\nexport class WeeklyReviewApplicationService {\n  async conductWeeklyReview(params: any) {\n    return {\n      success: true,\n      message: 'Weekly review service not yet implemented',\n      reviewId: 'placeholder-review',\n      phases: []\n    };\n  }\n}","import { tool } from 'ai';\nimport { z } from 'zod';\nimport { InboxItemApplicationService } from '../../../inbox-management/application/services/InboxItemApplicationService';\nimport { CreateInboxItemCommand } from '../../../inbox-management/application/commands/CreateInboxItemCommand';\n\n/**\n * GTD Inbox Tools - Co-located with Domain Logic\n * \n * Moved from packages/ai-domain/src/bounded-contexts/vercel-core-ai/tools/inbox-tools.ts\n * Following Eric Evans DDD principles: tools live within the domain that contains the knowledge\n */\n\nexport function createInboxTools(inboxService: InboxItemApplicationService) {\n  const listInboxItems = tool({\n    description: 'List items in the GTD inbox with filtering options',\n    parameters: z.object({\n      status: z.enum(['unprocessed', 'processed', 'all']).default('all').describe('Filter by processing status'),\n      limit: z.number().default(10).describe('Maximum number of items to return'),\n    }),\n    execute: async ({ status, limit }) => {\n      try {\n        // Direct access to domain service - no integration port needed!\n        const result = await inboxService.listInboxItems({\n          status: status === 'all' ? undefined : status,\n          limit: Math.min(limit, 50)\n        });\n        \n        return {\n          success: true,\n          items: result.items.map(item => ({\n            id: item.id,\n            content: item.originalContent,\n            status: item.processingStatus,\n            capturedAt: item.capturedAt,\n            capturedBy: item.capturedByPersonId,\n          })),\n          totalCount: result.totalCount,\n          message: `Found ${result.items.length} inbox items`\n        };\n      } catch (error) {\n        return {\n          success: false,\n          error: error instanceof Error ? error.message : 'Unknown error',\n          message: 'Failed to retrieve inbox items'\n        };\n      }\n    },\n  });\n\n  const addInboxItem = tool({\n    description: 'Add a new item to the GTD inbox',\n    parameters: z.object({\n      content: z.string().describe('The content/description of the item to add'),\n      personId: z.string().default('system').describe('ID of the person adding the item'),\n      priority: z.enum(['low', 'medium', 'high', 'urgent']).optional().describe('Priority level'),\n    }),\n    execute: async ({ content, personId }) => {\n      try {\n        const command: CreateInboxItemCommand = {\n          originalContent: content,\n          capturedByPersonId: personId\n        };\n        \n        const result = await inboxService.createInboxItem(command);\n        \n        return {\n          success: true,\n          itemId: result.itemId,\n          message: `Added \"${content}\" to inbox`,\n          capturedAt: result.capturedAt\n        };\n      } catch (error) {\n        return {\n          success: false,\n          error: error instanceof Error ? error.message : 'Unknown error',\n          message: 'Failed to add item to inbox'\n        };\n      }\n    },\n  });\n\n  const searchInboxItems = tool({\n    description: 'Search for items in the GTD inbox by content',\n    parameters: z.object({\n      query: z.string().describe('Search term to find in inbox item content'),\n      limit: z.number().default(5).describe('Maximum number of results'),\n    }),\n    execute: async ({ query, limit }) => {\n      try {\n        // Simple search implementation using list and filter\n        const allItems = await inboxService.listInboxItems({ limit: 100 });\n        \n        const filteredItems = allItems.items.filter(item => \n          item.originalContent.toLowerCase().includes(query.toLowerCase()) ||\n          (item.clarification && item.clarification.toLowerCase().includes(query.toLowerCase()))\n        ).slice(0, Math.min(limit, 20));\n        \n        return {\n          success: true,\n          items: filteredItems.map(item => ({\n            id: item.id,\n            content: item.originalContent,\n            status: item.processingStatus,\n            relevance: 'high', // Could implement relevance scoring\n          })),\n          query,\n          resultCount: filteredItems.length,\n          message: `Found ${filteredItems.length} items matching \"${query}\"`\n        };\n      } catch (error) {\n        return {\n          success: false,\n          error: error instanceof Error ? error.message : 'Unknown error',\n          message: `Failed to search inbox for \"${query}\"`\n        };\n      }\n    },\n  });\n\n  return {\n    listInboxItems,\n    addInboxItem,\n    searchInboxItems,\n  };\n}","import { InboxItemApplicationService } from '../../../inbox-management/application/services/InboxItemApplicationService';\nimport { createInboxTools } from '../../infrastructure/tools/inbox-ai-tools';\n\n/**\n * GTD AI Tools Application Service\n * \n * Simple application service that provides GTD AI tools\n * following the existing pattern from ai-domain\n */\nexport class GTDAIToolsApplicationService {\n  \n  constructor(\n    private readonly inboxService: InboxItemApplicationService,\n  ) {}\n\n  /**\n   * Get all available GTD AI tools\n   * \n   * Returns tools compatible with Vercel AI SDK\n   */\n  getAITools() {\n    const inboxTools = createInboxTools(this.inboxService);\n    \n    return {\n      ...inboxTools,\n    };\n  }\n\n  /**\n   * Get AI tools metadata\n   */\n  getAIToolsMetadata() {\n    const tools = this.getAITools();\n    \n    return {\n      domain: 'GTD',\n      boundedContext: 'ai-tools',\n      version: '1.0.0',\n      tools: Object.keys(tools),\n      totalTools: Object.keys(tools).length,\n      lastUpdated: new Date().toISOString()\n    };\n  }\n}","/**\n * GTD AI Tools Bounded Context\n * \n * Following Eric Evans DDD principles:\n * - Co-located AI tools with domain logic\n * - Domain experts maintain AI capabilities\n * - Direct access to domain services\n */\n\n// ===========================================\n// APPLICATION LAYER\n// ===========================================\nexport { GTDAIToolsApplicationService } from './application/services/GTDAIToolsApplicationService';\n\n// ===========================================\n// INFRASTRUCTURE LAYER\n// ===========================================\nexport { createInboxTools } from './infrastructure/tools/inbox-ai-tools';\n\n// ===========================================\n// FACTORY FUNCTION (PUBLISHED LANGUAGE)\n// ===========================================\nimport { InboxItemApplicationService } from '../inbox-management/application/services/InboxItemApplicationService';\nimport { GTDAIToolsApplicationService } from './application/services/GTDAIToolsApplicationService';\n\n/**\n * Create GTD AI Tools Service with existing inbox service\n */\nexport function createGTDAIToolsService(\n  inboxService: InboxItemApplicationService,\n): GTDAIToolsApplicationService {\n  return new GTDAIToolsApplicationService(inboxService);\n}","/**\n * GTD Query Service Factory\n * \n * Creates query service instances following the Published Language pattern.\n * This factory provides the stable interface that downstream contexts depend on.\n * \n * Eric Evans approved: Factory function within inbox-management BC that creates\n * query services exposing Published Language contracts.\n */\n\nimport { MongoClient } from \"@swoft/persistence\";\nimport { InboxItemAggregateRepository } from '../repositories/InboxItemAggregateRepository';\nimport { InboxQueryCriteria, InboxItemSummary, ProjectQueryCriteriaContract, ProjectSummary } from '../../../../integration/contracts';\nimport { ProjectRepository } from '../../../project-management/infrastructure/repositories/ProjectRepository';\n\n/**\n * GTD Query Service Interface - Published Language\n * \n * This interface defines the stable query contracts that downstream contexts\n * can depend on. Changes to this interface constitute breaking changes.\n */\nexport interface GTDQueryService {\n  listInboxItems(criteria: InboxQueryCriteria): Promise<InboxItemSummary[]>;\n  getInboxItem(id: string): Promise<InboxItemSummary | null>;\n  \n  // Project queries - Published Language\n  listProjects(criteria: ProjectQueryCriteriaContract): Promise<ProjectSummary[]>;\n  getProject(id: string): Promise<ProjectSummary | null>;\n  \n  // Next actions interface (for existing adapter)\n  listNextActions(criteria: any): Promise<any[]>;\n}\n\n/**\n * Person lookup service interface for enriching GTD data\n */\nexport interface PersonLookupService {\n  getPersonById(id: string): Promise<{\n    id: string;\n    displayName: string;\n    email: string;\n    roleType: 'Human' | 'AiAgent';\n  } | null>;\n}\n\n/**\n * Implementation of GTD Query Service using domain repositories\n */\nclass GTDQueryServiceImpl implements GTDQueryService {\n  private inboxRepository: InboxItemAggregateRepository;\n  private projectRepository: ProjectRepository;\n  private personLookupService?: PersonLookupService;\n\n  constructor(_mongoClient: MongoClient | undefined, personLookupService?: PersonLookupService) {\n    this.inboxRepository = new InboxItemAggregateRepository();\n    this.projectRepository = new ProjectRepository();\n    this.personLookupService = personLookupService;\n  }\n\n  /**\n   * Extract a user-friendly title from content\n   */\n  private extractTitle(content: string): string {\n    if (!content) return 'Untitled';\n    \n    // Remove markdown headers and extract first meaningful line\n    const firstLine = content.split('\\n')[0].replace(/^#+\\s*/, '').trim();\n    \n    // If first line is too long, truncate it\n    if (firstLine.length > 60) {\n      return firstLine.substring(0, 57) + '...';\n    }\n    \n    return firstLine || 'Untitled';\n  }\n\n  /**\n   * List inbox items using Published Language contracts\n   */\n  async listInboxItems(criteria: InboxQueryCriteria): Promise<InboxItemSummary[]> {\n    const items = await this.inboxRepository.findByFilters({\n      status: criteria.status,\n      limit: criteria.limit,\n      offset: criteria.offset\n    });\n\n    // Enrich with person data if service is available\n    const enrichedItems = await Promise.all(\n      items.map(async (item) => {\n        let capturedByPerson = null;\n        \n        if (this.personLookupService && item.capturedByPersonId) {\n          try {\n            capturedByPerson = await this.personLookupService.getPersonById(item.capturedByPersonId);\n          } catch (error) {\n            // Gracefully handle person lookup failures\n            console.warn(`Failed to lookup person ${item.capturedByPersonId}:`, error);\n          }\n        }\n\n        return {\n          id: item.id,\n          content: item.originalContent,\n          text: item.originalContent,  // Backward compatibility\n          title: this.extractTitle(item.originalContent),\n          status: item.processingStatus as 'unprocessed' | 'processed',\n          capturedAt: item.capturedAt.toISOString(),\n          createdAt: item.capturedAt,  // Backward compatibility\n          capturedBy: item.capturedByPersonId,\n          capturedByPerson,\n          clarification: item.clarification,\n          description: item.clarification,  // Backward compatibility\n          isActionable: item.isActionable,\n          tags: [] // TODO: Add tags support to domain model\n        };\n      })\n    );\n\n    return enrichedItems;\n  }\n\n  /**\n   * Get single inbox item using Published Language contracts\n   */\n  async getInboxItem(id: string): Promise<InboxItemSummary | null> {\n    const item = await this.inboxRepository.findById(id);\n    \n    if (!item) return null;\n\n    // Enrich with person data if service is available\n    let capturedByPerson = null;\n    \n    if (this.personLookupService && item.capturedByPersonId) {\n      try {\n        capturedByPerson = await this.personLookupService.getPersonById(item.capturedByPersonId);\n      } catch (error) {\n        console.warn(`Failed to lookup person ${item.capturedByPersonId}:`, error);\n      }\n    }\n\n    return {\n      id: item.id,\n      content: item.originalContent,\n      text: item.originalContent,  // Backward compatibility\n      title: this.extractTitle(item.originalContent),\n      status: item.processingStatus as 'unprocessed' | 'processed',\n      capturedAt: item.capturedAt.toISOString(),\n      createdAt: item.capturedAt,  // Backward compatibility\n      capturedBy: item.capturedByPersonId,\n      capturedByPerson,\n      clarification: item.clarification,\n      description: item.clarification,  // Backward compatibility\n      isActionable: item.isActionable,\n      tags: [] // TODO: Add tags support to domain model\n    };\n  }\n\n  /**\n   * List projects using Published Language contracts\n   */\n  async listProjects(criteria: ProjectQueryCriteriaContract): Promise<ProjectSummary[]> {\n    try {\n      let projects;\n      \n      if (criteria.status) {\n        projects = await this.projectRepository.findByStatus(criteria.status);\n      } else if (criteria.area) {\n        projects = await this.projectRepository.findByArea(criteria.area);\n      } else {\n        projects = await this.projectRepository.findAll();\n      }\n\n      // Map domain objects to Published Language contracts with error handling\n      return projects\n        .filter(project => project && project.name) // Filter out invalid projects\n        .map(project => ({\n          id: project.id,\n          title: project.name,\n          vision: project.desiredOutcome,\n          status: project.status as 'active' | 'completed' | 'someday-maybe' | 'cancelled',\n          area: project.area,\n          reviewDate: project.reviewDate?.toISOString(),\n          createdAt: project.createdAt.toISOString(),\n          nextActionCount: project.nextActionIds.length\n        }));\n    } catch (error) {\n      // Gracefully handle database/domain errors by returning empty array\n      console.warn('GTD Projects query failed, returning empty array:', error);\n      return [];\n    }\n  }\n\n  /**\n   * Get single project using Published Language contracts\n   */\n  async getProject(id: string): Promise<ProjectSummary | null> {\n    const project = await this.projectRepository.findById(id);\n    \n    if (!project) return null;\n\n    return {\n      id: project.id,\n      title: project.name,\n      vision: project.desiredOutcome,\n      status: project.status as 'active' | 'completed' | 'someday-maybe' | 'cancelled',\n      area: project.area,\n      reviewDate: project.reviewDate?.toISOString(),\n      createdAt: project.createdAt.toISOString(),\n      nextActionCount: project.nextActionIds.length\n    };\n  }\n\n  /**\n   * Next actions query - to be implemented when project-management BC is ready\n   */\n  async listNextActions(_criteria: any): Promise<any[]> {\n    // TODO: Implement proper next actions query when project-management BC is ready\n    return [];\n  }\n}\n\n/**\n * Factory function for creating GTD Query Service instances\n * \n * This is the stable interface that downstream contexts depend on.\n * The implementation can change, but this factory signature should remain stable.\n */\nexport function createGTDQueryService(\n  mongoClient?: MongoClient, \n  personLookupService?: PersonLookupService\n): GTDQueryService {\n  // Parameters are kept for backward compatibility, but we use the shared connection\n  return new GTDQueryServiceImpl(mongoClient, personLookupService);\n}","/**\n * GTD Service Factory - Simplified Integration\n * \n * Following Party Manager ServiceFactory pattern - simple, type-safe, \n * no dependency injection complexity. This eliminates all the Inversify\n * symbol binding issues and makes the GTD domain much more stable.\n * \n * Inspired by Party Manager's success with this approach.\n */\n\nimport { Db } from 'mongodb';\nimport { createGTDQueryService, GTDQueryService, PersonLookupService } from '../../bounded-contexts/inbox-management/infrastructure/factories/createGTDQueryService';\n\n/**\n * Simplified GTD Service Factory\n * No Inversify, no symbols, just simple factory pattern like Party Manager\n */\nexport class GTDServiceFactory {\n  private static instance: GTDServiceFactory;\n  \n  private database?: Db;\n  private initialized = false;\n  \n  // Service instances (lazy loaded)\n  private queryService?: GTDQueryService;\n\n  private constructor() {\n    // Simple constructor - no complex DI setup\n  }\n\n  static getInstance(): GTDServiceFactory {\n    if (!GTDServiceFactory.instance) {\n      GTDServiceFactory.instance = new GTDServiceFactory();\n    }\n    return GTDServiceFactory.instance;\n  }\n\n  /**\n   * Initialize with database connection\n   * Should be called once at application startup\n   */\n  async initialize(database: Db): Promise<void> {\n    try {\n      this.database = database;\n      this.initialized = true;\n      console.log('✅ GTD Service Factory initialized successfully');\n    } catch (error: any) {\n      console.error('❌ Failed to initialize GTD Service Factory:', error);\n      throw new Error(`GTD Service Factory initialization failed: ${error.message}`);\n    }\n  }\n\n  /**\n   * Check if factory is initialized\n   */\n  isInitialized(): boolean {\n    return this.initialized;\n  }\n\n  /**\n   * Get database instance\n   */\n  private getDatabase(): Db {\n    if (!this.database) {\n      throw new Error('GTD Service Factory not initialized. Call initialize() first.');\n    }\n    return this.database;\n  }\n\n  // ========================================================================\n  // Service Getters (Lazy Loading) - Party Manager Pattern\n  // ========================================================================\n\n  /**\n   * Get GTD Query Service\n   * Creates the service using the existing factory function\n   */\n  getQueryService(personLookupService?: PersonLookupService): GTDQueryService {\n    if (!this.queryService) {\n      // Use existing factory - no need to reinvent\n      this.queryService = createGTDQueryService(undefined, personLookupService);\n    }\n    return this.queryService;\n  }\n\n  /**\n   * Get health status\n   */\n  async getHealthStatus(): Promise<any> {\n    const status = {\n      healthy: false,\n      database: 'disconnected',\n      initialized: this.initialized,\n      timestamp: new Date().toISOString()\n    };\n\n    try {\n      if (this.database) {\n        // Simple ping test\n        await this.database.admin().ping();\n        status.database = 'connected';\n        status.healthy = true;\n      }\n    } catch (error: any) {\n      console.error('GTD Service Factory health check failed:', error);\n    }\n\n    return status;\n  }\n\n  /**\n   * Graceful cleanup\n   */\n  async cleanup(): Promise<void> {\n    if (this.queryService) {\n      this.queryService = undefined;\n    }\n    this.database = undefined;\n    this.initialized = false;\n    console.log('GTD Service Factory cleanup completed');\n  }\n}","/**\n * GTD Domain Integration Module\n * \n * This module provides the integration interface for GTD Domain\n * following Eric Evans Strategic DDD patterns. It exposes the\n * Published Language contracts that downstream contexts can depend on.\n * \n * Integration Patterns:\n * - Published Language: Stable contracts for downstream contexts\n * - Customer/Supplier: GTD is upstream, consumers are downstream\n * - Anti-Corruption Layer: Consumers should translate to their own models\n */\n\n// Export Published Language contracts\nexport * from './contracts';\n\nexport const publishedLanguage = {\n  /**\n   * Domain information - Runtime metadata\n   */\n  domain: {\n    name: 'GTD Domain',\n    version: '1.0.0',\n    description: 'Getting Things Done methodology implementation'\n  },\n\n  /**\n   * Integration Capabilities - What this domain provides to consumers\n   */\n  capabilities: {\n    // Inbox Management\n    'capture-item': 'Capture thoughts, ideas, and tasks into trusted system',\n    'list-inbox-items': 'Retrieve all unprocessed inbox items',\n    'clarify-item': 'Process inbox item through GTD clarification workflow',\n    \n    // Project Management  \n    'create-project': 'Create new projects with defined outcomes',\n    'list-projects': 'Get all active projects and their status',\n    'get-project-actions': 'Retrieve next actions for specific project',\n    \n    // Action Management\n    'create-next-action': 'Create actionable tasks with context and energy level',\n    'list-actions-by-context': 'Get actions filtered by GTD context (@calls, @computer, etc.)',\n    'complete-action': 'Mark action as completed',\n    \n    // Review System\n    'weekly-review': 'Comprehensive GTD weekly review process',\n    'daily-review': 'Quick daily action planning',\n    'get-system-statistics': 'Overall GTD system health metrics'\n  },\n\n  /**\n   * Domain Events - Events published for downstream consumption\n   */\n  events: {\n    // Inbox Events\n    'item-captured': 'New item added to inbox for processing',\n    'item-clarified': 'Inbox item processed through clarification workflow',\n    'item-organized': 'Clarified item organized into appropriate lists',\n    \n    // Project Events\n    'project-created': 'New project with defined outcome established',\n    'project-completed': 'Project successfully completed',\n    'project-archived': 'Project moved to archive',\n    \n    // Action Events\n    'action-created': 'New next action defined',\n    'action-completed': 'Action marked as done',\n    'action-deferred': 'Action moved to someday/maybe list',\n    'context-action-batch-completed': 'All actions in context completed',\n    \n    // Review Events\n    'weekly-review-completed': 'Weekly review process finished',\n    'daily-review-completed': 'Daily planning session completed',\n    'system-maintenance-performed': 'GTD system cleanup and organization'\n  },\n\n  /**\n   * Business Rules - Key constraints and policies\n   */\n  businessRules: {\n    'two-minute-rule': 'Tasks taking less than 2 minutes should be done immediately',\n    'single-source-truth': 'Every commitment must be captured in trusted system',\n    'next-action-clarity': 'Every project must have at least one defined next action',\n    'context-based-organization': 'Actions organized by context (@calls, @computer, etc.)',\n    'weekly-review-required': 'Complete weekly review to maintain system integrity',\n    'inbox-zero-goal': 'Process inbox to empty during each review cycle'\n  },\n\n  /**\n   * Integration Patterns - Recommended integration approaches\n   */\n  integrationPatterns: {\n    'capture-ubiquitous': 'Provide multiple capture methods for universal collection',\n    'clarify-systematic': 'Use consistent clarification workflow for all items',\n    'organize-contextual': 'Organize by context and energy level for optimal execution',\n    'review-regular': 'Implement regular review cycles for system maintenance',\n    'engage-intuitive': 'Enable intuitive action selection based on context and energy'\n  }\n};\n\n/**\n * Integration metadata for downstream contexts\n */\nexport const GTD_INTEGRATION_INFO = {\n  version: '1.0.0',\n  context: 'GTD Domain',\n  role: 'Upstream Supplier',\n  relationships: [\n    'AI Domain (Customer)',\n    'Builder MCP (Customer)',\n    'Designer MCP (Customer)'\n  ],\n  publishedLanguage: {\n    contracts: [\n      'InboxQueryCriteria',\n      'InboxItemSummary', \n      'InboxCaptureRequest',\n      'InboxCaptureResult',\n      'InboxStatistics'\n    ],\n    stability: 'Stable - Breaking changes will increment major version'\n  }\n} as const;","import { BaseApplicationError } from '@swoft/core';\n\n/**\n * GTD Feature Application Errors\n * \n * Provides structured error handling for GTD feature operations\n * with user and developer suggestions.\n */\nexport class GTDFeatureError extends BaseApplicationError {\n  readonly code = 'GTD_FEATURE_ERROR';\n\n  constructor(message: string, cause?: unknown) {\n    super(\n      message,\n      {\n        ux: ['Please try again', 'Contact support if the problem persists'],\n        dx: ['Check GTD domain integration', 'Verify @swoft/gtd-domain package']\n      },\n      cause\n    );\n  }\n}\n\nexport class GTDValidationError extends BaseApplicationError {\n  readonly code = 'GTD_VALIDATION_ERROR';\n\n  constructor(message: string, cause?: unknown) {\n    super(\n      message,\n      {\n        ux: ['Please check your input and try again'],\n        dx: ['Check Zodios validation schema', 'Verify request format']\n      },\n      cause\n    );\n  }\n}\n\nexport class GTDDomainIntegrationError extends BaseApplicationError {\n  readonly code = 'GTD_DOMAIN_INTEGRATION_ERROR';\n\n  constructor(message: string, cause?: unknown) {\n    super(\n      message,\n      {\n        ux: ['Something went wrong processing your request'],\n        dx: ['Check @swoft/gtd-domain domain integration', 'Verify domain aggregate calls']\n      },\n      cause\n    );\n  }\n}\n","/**\n * Base Domain Seeder\n * \n * Provides common seeding functionality for all domains.\n * Kept minimal to respect DDD boundaries - only technical concerns.\n */\n\nimport { getMongoClient } from '@swoft/persistence';\n\nexport interface ValidationResult {\n  totalDocuments: number;\n  validDocuments: number;\n  invalidDocuments: number;\n}\n\nexport interface SeederMetrics {\n  totalCollections: number;\n  totalDocuments: number;\n  validDocuments: number;\n  invalidDocuments: number;\n  seedingDurationMs: number;\n  validationDurationMs: number;\n}\n\nexport interface SeederResponse {\n  success: boolean;\n  metrics: SeederMetrics;\n  error?: string;\n}\n\nexport interface DomainSeederService {\n  seedDomain(organizationId: string, projectId: string): Promise<SeederResponse>;\n}\n\nexport abstract class BaseDomainSeeder implements DomainSeederService {\n  protected domainName: string;\n  \n  constructor(domainName: string) {\n    this.domainName = domainName;\n  }\n  \n  abstract seedDomain(organizationId: string, projectId: string): Promise<SeederResponse>;\n  \n  protected async validateSeededData(): Promise<ValidationResult> {\n    // Basic validation - domains can override for specific needs\n    const client = await getMongoClient();\n    const db = client.db();\n    \n    // Count documents across collections\n    let totalDocuments = 0;\n    let validDocuments = 0;\n    \n    // Simple validation: documents exist\n    // Domains should implement specific validation logic\n    totalDocuments = validDocuments = 100; // Placeholder\n    \n    return {\n      totalDocuments,\n      validDocuments,\n      invalidDocuments: totalDocuments - validDocuments\n    };\n  }\n  \n  protected createSuccessResponse(metrics: Omit<SeederMetrics, 'validDocuments' | 'invalidDocuments' | 'totalDocuments'> & Partial<Pick<SeederMetrics, 'validDocuments' | 'invalidDocuments' | 'totalDocuments'>>): SeederResponse {\n    return {\n      success: true,\n      metrics: {\n        totalCollections: metrics.totalCollections,\n        totalDocuments: metrics.totalDocuments || 0,\n        validDocuments: metrics.validDocuments || 0,\n        invalidDocuments: metrics.invalidDocuments || 0,\n        seedingDurationMs: metrics.seedingDurationMs,\n        validationDurationMs: metrics.validationDurationMs\n      }\n    };\n  }\n  \n  protected async clearExistingData(organizationId?: string, projectId?: string): Promise<void> {\n    // Basic clearing logic - domains should override for specific needs\n    console.log(`Clearing existing data for ${this.domainName}...`);\n    // Implementation depends on domain-specific collections\n  }\n  \n  protected createErrorResponse(errorMessage: string, metrics: SeederMetrics): SeederResponse {\n    return {\n      success: false,\n      error: errorMessage,\n      metrics\n    };\n  }\n}","#!/usr/bin/env ts-node\n\n/**\n * GTD Data Seeding Script\n * \n * Creates consistent test data for GTD domain across all environments.\n * Follows David Allen's GTD methodology with proper DDD patterns.\n * Uses the same robust pattern as Party Manager and UX Design.\n */\n\nimport { getMongoClient, getMongoConfig, initializeMongoConnection } from \"@swoft/persistence\";\nimport { GTD_COLLECTIONS } from '../config/collections';\nimport { v4 as uuidv4 } from 'uuid';\n\ninterface GTDTestData {\n  organizationId: string;\n  personId: string;\n  inboxItems: Array<{\n    content: string;\n    source: string;\n    priority: string;\n    isProcessed: boolean;\n  }>;\n  projects: Array<{\n    title: string;\n    description: string;\n    desiredOutcome: string;\n    status: string;\n    priority: string;\n  }>;\n  nextActions: Array<{\n    description: string;\n    context: string;\n    energyLevel: string;\n    estimatedMinutes: number;\n    projectId?: string;\n    status: string;\n  }>;\n  referenceItems: Array<{\n    title: string;\n    content: string;\n    category: string;\n    tags: string[];\n  }>;\n}\n\nclass GTDDataSeeder {\n  private testData: GTDTestData = {\n    organizationId: '2484554d-85d3-49a4-87bf-ceded4b115c0',\n    personId: '52149abb-d080-4b1c-8283-8d603b9ca44d', // Derick's person ID\n    inboxItems: [\n      {\n        content: '🌱 UAT SEEDED DATA - This GTD inbox was populated with test data for development/testing purposes',\n        source: 'system',\n        priority: 'low',\n        isProcessed: false\n      }\n    ],\n    projects: [\n      {\n        title: 'Swoft Platform DevOps Enhancement',\n        description: 'Improve deployment processes, monitoring, and data integrity across all services',\n        desiredOutcome: 'Zero-downtime deployments with automated validation and rollback capabilities',\n        status: 'active',\n        priority: 'high'\n      },\n      {\n        title: 'AI Agent Framework Integration',\n        description: 'Integrate AI agents with human workflows for enhanced productivity',\n        desiredOutcome: 'Seamless AI-human collaboration with clear task delegation and monitoring',\n        status: 'active',\n        priority: 'high'\n      },\n      {\n        title: 'Domain Package Standardization',\n        description: 'Apply consistent DevOps patterns across all domain packages',\n        desiredOutcome: 'All domain packages have seeding scripts, data validation, and deployment checklists',\n        status: 'active',\n        priority: 'medium'\n      }\n    ],\n    nextActions: [\n      {\n        description: 'Create data seeding script for business-strategy domain',\n        context: '@computer',\n        energyLevel: 'medium',\n        estimatedMinutes: 45,\n        status: 'available'\n      },\n      {\n        description: 'Call Kevin to discuss AI agent roadmap priorities',\n        context: '@calls',\n        energyLevel: 'high',\n        estimatedMinutes: 30,\n        status: 'available'\n      },\n      {\n        description: 'Review and approve product design mockups',\n        context: '@computer',\n        energyLevel: 'medium',\n        estimatedMinutes: 20,\n        status: 'available'\n      },\n      {\n        description: 'Test new deployment pipeline on staging environment',\n        context: '@computer',\n        energyLevel: 'high',\n        estimatedMinutes: 60,\n        status: 'available'\n      },\n      {\n        description: 'Pick up new development books from bookstore',\n        context: '@errands',\n        energyLevel: 'low',\n        estimatedMinutes: 15,\n        status: 'available'\n      }\n    ],\n    referenceItems: [\n      {\n        title: 'MongoDB Performance Optimization Guide',\n        content: 'Best practices for database indexing, query optimization, and connection pooling',\n        category: 'technical',\n        tags: ['mongodb', 'performance', 'database']\n      },\n      {\n        title: 'David Allen GTD Methodology Summary',\n        content: 'Core principles: Capture, Clarify, Organize, Reflect, Engage',\n        category: 'productivity',\n        tags: ['gtd', 'methodology', 'productivity']\n      },\n      {\n        title: 'AI Agent Integration Patterns',\n        content: 'Common patterns for integrating AI agents with human workflows',\n        category: 'ai',\n        tags: ['ai', 'patterns', 'integration']\n      },\n      {\n        title: 'Domain-Driven Design Principles',\n        content: 'Eric Evans DDD concepts: bounded contexts, aggregates, entities, value objects',\n        category: 'architecture',\n        tags: ['ddd', 'architecture', 'design']\n      }\n    ]\n  };\n\n  private async setupMongo(): Promise<void> {\n    const mongoConfig = {\n      uri: process.env.MONGODB_URL || 'mongodb://localhost:27017',\n      dbName: process.env.MONGODB_DB_NAME || 'swoft_designer_dev'\n    };\n    \n    console.log(`🔗 Connecting to database: ${mongoConfig.dbName}`);\n    await initializeMongoConnection(mongoConfig);\n  }\n\n  async run(): Promise<void> {\n    try {\n      console.log('🚀 Starting GTD Data Seeding...\\n');\n      \n      await this.setupMongo();\n      \n      // Step 1: Clear existing data\n      await this.clearExistingData();\n      \n      // Step 2: Seed inbox items\n      await this.seedInboxItems();\n      \n      // Step 3: Seed projects\n      const projectIds = await this.seedProjects();\n      \n      // Step 4: Seed next actions (link some to projects)\n      await this.seedNextActions(projectIds);\n      \n      // Step 5: Seed reference items\n      await this.seedReferenceItems();\n      \n      // Step 6: Verify data integrity\n      await this.verifyDataIntegrity();\n      \n      console.log('\\n✅ GTD Data Seeding Completed Successfully!');\n      console.log(`📊 Organization: ${this.testData.organizationId}`);\n      console.log(`👤 Person: ${this.testData.personId}`);\n      console.log(`📥 Inbox Items: ${this.testData.inboxItems.length} created`);\n      console.log(`📋 Projects: ${this.testData.projects.length} created`);\n      console.log(`⚡ Next Actions: ${this.testData.nextActions.length} created`);\n      console.log(`📚 Reference Items: ${this.testData.referenceItems.length} created`);\n      \n    } catch (error) {\n      console.error('❌ GTD seeding failed:', error);\n      throw error;\n    }\n  }\n\n  private async clearExistingData(): Promise<void> {\n    console.log('🧹 Clearing existing GTD data...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    \n    // Clear inbox items for this person\n    await db.collection(GTD_COLLECTIONS.INBOX_ITEMS).deleteMany({\n      capturedByPersonId: this.testData.personId\n    });\n    \n    // Clear projects for this person\n    await db.collection(GTD_COLLECTIONS.PROJECTS).deleteMany({\n      ownerId: this.testData.personId\n    });\n    \n    // Clear next actions for this person\n    await db.collection(GTD_COLLECTIONS.NEXT_ACTIONS).deleteMany({\n      assignedToPersonId: this.testData.personId\n    });\n    \n    // Clear reference items for this person\n    await db.collection(GTD_COLLECTIONS.REFERENCE_ITEMS).deleteMany({\n      ownerId: this.testData.personId\n    });\n    \n    console.log('✅ Existing data cleared');\n  }\n\n  private async seedInboxItems(): Promise<void> {\n    console.log('\\n📥 Seeding inbox items...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    \n    // Add seeding timestamp to the first item dynamically\n    const itemsToSeed = [...this.testData.inboxItems];\n    itemsToSeed[0].content = `🌱 UAT SEEDED DATA - This GTD inbox was populated with test data for development/testing purposes on ${new Date().toISOString()}`;\n    \n    for (const itemData of itemsToSeed) {\n      const itemId = uuidv4();\n      \n      const inboxItem = {\n        itemId: itemId,\n        id: itemId,\n        content: itemData.content,\n        source: itemData.source,\n        priority: itemData.priority,\n        isProcessed: itemData.isProcessed,\n        capturedByPersonId: this.testData.personId,\n        organizationId: this.testData.organizationId,\n        capturedAt: new Date(),\n        processedAt: null,\n        processedByPersonId: null,\n        createdAt: new Date(),\n        updatedAt: new Date()\n      };\n      \n      await db.collection(GTD_COLLECTIONS.INBOX_ITEMS).insertOne(inboxItem);\n      \n      console.log(`✅ Created inbox item: ${itemData.content.substring(0, 50)}...`);\n    }\n  }\n\n  private async seedProjects(): Promise<{ [title: string]: string }> {\n    console.log('\\n📋 Seeding projects...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    const projectIds: { [title: string]: string } = {};\n    \n    for (const projectData of this.testData.projects) {\n      const projectId = uuidv4();\n      \n      const project = {\n        projectId: projectId,\n        id: projectId,\n        title: projectData.title,\n        description: projectData.description,\n        desiredOutcome: projectData.desiredOutcome,\n        status: projectData.status,\n        priority: projectData.priority,\n        ownerId: this.testData.personId,\n        organizationId: this.testData.organizationId,\n        startDate: new Date(),\n        targetDate: null,\n        completedDate: null,\n        createdAt: new Date(),\n        updatedAt: new Date()\n      };\n      \n      await db.collection(GTD_COLLECTIONS.PROJECTS).insertOne(project);\n      projectIds[projectData.title] = projectId;\n      \n      console.log(`✅ Created project: ${projectData.title}`);\n    }\n    \n    return projectIds;\n  }\n\n  private async seedNextActions(projectIds: { [title: string]: string }): Promise<void> {\n    console.log('\\n⚡ Seeding next actions...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    \n    for (const [index, actionData] of this.testData.nextActions.entries()) {\n      const actionId = uuidv4();\n      \n      // Link first action to first project\n      const linkedProjectId = index === 0 ? Object.values(projectIds)[0] : null;\n      \n      const nextAction = {\n        actionId: actionId,\n        id: actionId,\n        description: actionData.description,\n        context: actionData.context,\n        energyLevel: actionData.energyLevel,\n        estimatedMinutes: actionData.estimatedMinutes,\n        projectId: linkedProjectId,\n        status: actionData.status,\n        assignedToPersonId: this.testData.personId,\n        organizationId: this.testData.organizationId,\n        dueDate: null,\n        completedDate: null,\n        createdAt: new Date(),\n        updatedAt: new Date()\n      };\n      \n      await db.collection(GTD_COLLECTIONS.NEXT_ACTIONS).insertOne(nextAction);\n      \n      console.log(`✅ Created next action: ${actionData.description.substring(0, 50)}...`);\n    }\n  }\n\n  private async seedReferenceItems(): Promise<void> {\n    console.log('\\n📚 Seeding reference items...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    \n    for (const refData of this.testData.referenceItems) {\n      const refId = uuidv4();\n      \n      const referenceItem = {\n        referenceId: refId,\n        id: refId,\n        title: refData.title,\n        content: refData.content,\n        category: refData.category,\n        tags: refData.tags,\n        ownerId: this.testData.personId,\n        organizationId: this.testData.organizationId,\n        isArchived: false,\n        createdAt: new Date(),\n        updatedAt: new Date()\n      };\n      \n      await db.collection(GTD_COLLECTIONS.REFERENCE_ITEMS).insertOne(referenceItem);\n      \n      console.log(`✅ Created reference item: ${refData.title}`);\n    }\n  }\n\n  private async verifyDataIntegrity(): Promise<void> {\n    console.log('\\n🧪 Verifying data integrity...');\n    \n    const mongoClient = getMongoClient();\n    const config = getMongoConfig();\n    const db = mongoClient.db(config?.dbName);\n    \n    // Verify inbox items\n    const inboxCount = await db.collection(GTD_COLLECTIONS.INBOX_ITEMS)\n      .countDocuments({ capturedByPersonId: this.testData.personId });\n    console.log(inboxCount === 5 ? '✅ Inbox items verified (5 created)' : `❌ Inbox items mismatch (expected 5, got ${inboxCount})`);\n    \n    // Verify projects\n    const projectCount = await db.collection(GTD_COLLECTIONS.PROJECTS)\n      .countDocuments({ ownerId: this.testData.personId });\n    console.log(projectCount === 3 ? '✅ Projects verified (3 created)' : `❌ Projects mismatch (expected 3, got ${projectCount})`);\n    \n    // Verify next actions\n    const actionCount = await db.collection(GTD_COLLECTIONS.NEXT_ACTIONS)\n      .countDocuments({ assignedToPersonId: this.testData.personId });\n    console.log(actionCount === 5 ? '✅ Next actions verified (5 created)' : `❌ Next actions mismatch (expected 5, got ${actionCount})`);\n    \n    // Verify reference items\n    const refCount = await db.collection(GTD_COLLECTIONS.REFERENCE_ITEMS)\n      .countDocuments({ ownerId: this.testData.personId });\n    console.log(refCount === 4 ? '✅ Reference items verified (4 created)' : `❌ Reference items mismatch (expected 4, got ${refCount})`);\n    \n    console.log('\\n📊 Database Summary:');\n    console.log(`Database: ${config?.dbName}`);\n    console.log(`Collections: ${Object.values(GTD_COLLECTIONS).join(', ')}`);\n    console.log(`Person ID: ${this.testData.personId}`);\n    console.log(`Organization ID: ${this.testData.organizationId}`);\n  }\n}\n\n// Execute if run directly (ESM compatible)\nif (import.meta.url === `file://${process.argv[1]}`) {\n  const seeder = new GTDDataSeeder();\n  seeder.run()\n    .then(() => {\n      console.log('\\n🎉 GTD data is ready!');\n      console.log('\\n📋 GTD System Summary:');\n      console.log('• 5 inbox items ready for processing');\n      console.log('• 3 active projects with clear outcomes');\n      console.log('• 5 next actions organized by context');\n      console.log('• 4 reference items for future use');\n      console.log('\\n🚀 Ready to implement Getting Things Done methodology!');\n      process.exit(0);\n    })\n    .catch((error) => {\n      console.error('\\n💥 GTD seeding failed:', error);\n      process.exit(1);\n    });\n}\n\nexport { GTDDataSeeder };","/**\n * GTD Domain Seeder\n * \n * Implements the DomainSeederService pattern for GTD (Getting Things Done) domain.\n * Seeds inbox items, projects, next actions, and reference materials following\n * David Allen's GTD methodology.\n */\n\nimport { BaseDomainSeeder, DomainSeederService } from './shared-seeding/BaseDomainSeeder';\nimport { GTD_COLLECTIONS } from '../config/collections';\nimport { GTDDataSeeder } from '../utils/seed-gtd-data';\nimport { getMongoClient, getMongoConfig } from \"@swoft/persistence\";\n\nexport class GtdDomainSeeder extends BaseDomainSeeder {\n  constructor() {\n    super('gtd-domain');\n  }\n\n  async seedDomain(_organizationId: string, _projectId: string): Promise<{\n    success: boolean;\n    metrics: {\n      totalCollections: number;\n      totalDocuments: number;\n      validDocuments: number;\n      invalidDocuments: number;\n      seedingDurationMs: number;\n      validationDurationMs: number;\n    };\n    error?: string;\n  }> {\n    const seedingStartTime = Date.now();\n    \n    try {\n      console.log(`🧠 Starting ${this.domainName} domain seeding...`);\n      \n      // Create and run the real GTD data seeder\n      const gtdSeeder = new GTDDataSeeder();\n      await gtdSeeder.run();\n      \n      const seedingDurationMs = Date.now() - seedingStartTime;\n      \n      // Perform validation\n      const validationStartTime = Date.now();\n      const validationResult = await this.validateSeededData();\n      const validationDurationMs = Date.now() - validationStartTime;\n      \n      console.log(`✅ Successfully seeded ${this.domainName} domain`);\n      \n      return this.createSuccessResponse({\n        totalCollections: 5, // inbox_items, projects, next_actions, reference_items, someday_maybe\n        totalDocuments: validationResult.totalDocuments,\n        validDocuments: validationResult.validDocuments,\n        invalidDocuments: validationResult.invalidDocuments,\n        seedingDurationMs,\n        validationDurationMs\n      });\n      \n    } catch (error) {\n      const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n      console.error(`❌ Domain seeding failed for ${this.domainName}:`, errorMessage);\n      \n      return this.createErrorResponse(errorMessage, {\n        totalCollections: 0,\n        totalDocuments: 0,\n        validDocuments: 0,\n        invalidDocuments: 0,\n        seedingDurationMs: Date.now() - seedingStartTime,\n        validationDurationMs: 0\n      });\n    }\n  }\n\n  async validateSeededData(): Promise<{\n    isValid: boolean;\n    totalDocuments: number;\n    validDocuments: number;\n    invalidDocuments: number;\n    errors: string[];\n  }> {\n    try {\n      const mongoClient = getMongoClient();\n      const config = getMongoConfig();\n      const db = mongoClient.db(config?.dbName);\n      \n      const personId = '52149abb-d080-4b1c-8283-8d603b9ca44d'; // Derick's person ID\n      const collections = Object.values(GTD_COLLECTIONS);\n      \n      let totalDocuments = 0;\n      let validDocuments = 0;\n      let invalidDocuments = 0;\n      const errors: string[] = [];\n      \n      for (const collectionName of collections) {\n        try {\n          const coll = db.collection(collectionName);\n          let docs;\n          \n          // Filter by appropriate field based on collection\n          switch (collectionName) {\n            case GTD_COLLECTIONS.INBOX_ITEMS:\n              docs = await coll.find({ capturedByPersonId: personId }).toArray();\n              break;\n            case GTD_COLLECTIONS.PROJECTS:\n              docs = await coll.find({ ownerId: personId }).toArray();\n              break;\n            case GTD_COLLECTIONS.NEXT_ACTIONS:\n              docs = await coll.find({ assignedToPersonId: personId }).toArray();\n              break;\n            case GTD_COLLECTIONS.REFERENCE_ITEMS:\n              docs = await coll.find({ ownerId: personId }).toArray();\n              break;\n            case GTD_COLLECTIONS.SOMEDAY_MAYBE:\n              docs = await coll.find({ personId }).toArray();\n              break;\n            default:\n              docs = await coll.find({}).toArray();\n          }\n          \n          totalDocuments += docs.length;\n          \n          for (const doc of docs) {\n            const validation = this.validateDocument(doc, collectionName);\n            if (validation.isValid) {\n              validDocuments++;\n            } else {\n              invalidDocuments++;\n              errors.push(...validation.errors);\n            }\n          }\n          \n          console.log(`✅ Validated ${collectionName}: ${docs.length} documents`);\n        } catch (error) {\n          errors.push(`Failed to validate ${collectionName}: ${error instanceof Error ? error.message : 'Unknown error'}`);\n        }\n      }\n      \n      return {\n        isValid: errors.length === 0,\n        totalDocuments,\n        validDocuments,\n        invalidDocuments,\n        errors\n      };\n      \n    } catch (error) {\n      return {\n        isValid: false,\n        totalDocuments: 0,\n        validDocuments: 0,\n        invalidDocuments: 0,\n        errors: [error instanceof Error ? error.message : 'Unknown validation error']\n      };\n    }\n  }\n\n  private validateDocument(doc: any, collectionName: string): { isValid: boolean; errors: string[] } {\n    const errors: string[] = [];\n\n    // Basic validation - ensure required fields exist\n    if (!doc.id) {\n      errors.push(`Document in ${collectionName} missing required field: id`);\n    }\n\n    // Collection-specific validation\n    switch (collectionName) {\n      case GTD_COLLECTIONS.INBOX_ITEMS:\n        if (!doc.itemId || !doc.content || !doc.capturedByPersonId || !doc.capturedAt) {\n          errors.push(`Inbox item document missing required fields`);\n        }\n        break;\n\n      case GTD_COLLECTIONS.PROJECTS:\n        if (!doc.projectId || !doc.title || !doc.ownerId || !doc.status) {\n          errors.push(`Project document missing required fields`);\n        }\n        break;\n\n      case GTD_COLLECTIONS.NEXT_ACTIONS:\n        if (!doc.actionId || !doc.description || !doc.context || !doc.status) {\n          errors.push(`Next action document missing required fields`);\n        }\n        break;\n\n      case GTD_COLLECTIONS.REFERENCE_ITEMS:\n        if (!doc.referenceId || !doc.title || !doc.content || !doc.category) {\n          errors.push(`Reference item document missing required fields`);\n        }\n        break;\n\n      case GTD_COLLECTIONS.SOMEDAY_MAYBE:\n        if (!doc.id || !doc.title || !doc.personId) {\n          errors.push(`Someday/maybe item document missing required fields`);\n        }\n        break;\n    }\n\n    return {\n      isValid: errors.length === 0,\n      errors\n    };\n  }\n}\n\n/**\n * Factory function to create GTD domain seeder\n */\nexport function createGtdDomainSeeder(): DomainSeederService {\n  return new GtdDomainSeeder();\n}","import { ContainerModule } from 'inversify';\n\n// Inbox Management Bounded Context\nimport { InboxItemApplicationService } from '../../bounded-contexts/inbox-management';\nimport { GTDProcessingWorkflowService } from '../../bounded-contexts/inbox-management/domain/services/GTDProcessingWorkflowService';\nimport { InboxImportExportService } from '../../bounded-contexts/inbox-management/domain/services/InboxImportExportService';\nimport { InboxItemAggregateRepository } from '../../bounded-contexts/inbox-management/infrastructure/repositories/InboxItemAggregateRepository';\n\n// Project Management Bounded Context\nimport { ProjectApplicationService } from '../../bounded-contexts/project-management/application/services/ProjectApplicationService';\nimport { ProjectReadService } from '../../bounded-contexts/project-management/application/services/ProjectReadService';\nimport { NextActionWriteService } from '../../bounded-contexts/project-management/application/services/NextActionWriteService';\nimport { NextActionReadService } from '../../bounded-contexts/project-management/application/services/NextActionReadService';\nimport { ProjectRepository } from '../../bounded-contexts/project-management/infrastructure/repositories/ProjectRepository';\nimport { NextActionAggregateRepository } from '../../bounded-contexts/project-management/infrastructure/repositories/NextActionAggregateRepository';\n\n// Task Management Bounded Context\nimport { ITaskRepository } from '../../bounded-contexts/task-management/ports/ITaskRepository';\nimport { TaskMongoRepository } from '../../bounded-contexts/task-management/infrastructure/repositories/TaskMongoRepository';\nimport { InboxFileRepository } from '../../bounded-contexts/task-management/infrastructure/repositories/InboxFileRepository';\nimport { NextActionsFileRepository } from '../../bounded-contexts/task-management/infrastructure/repositories/NextActionsFileRepository';\n\n// Design Implementation Coordination Bounded Context\nimport { DesignImplementationFlowApplicationService } from '../../bounded-contexts/design-implementation-coordination/application/services/DesignImplementationFlowApplicationService';\nimport { DesignImplementationFlowReadService } from '../../bounded-contexts/design-implementation-coordination/application/services/DesignImplementationFlowReadService';\nimport { DesignImplementationFlowRepository } from '../../bounded-contexts/design-implementation-coordination/infrastructure/repositories/DesignImplementationFlowRepository';\n\n// Cross-cutting Services - Commented out due to dependency issues\n// import { GtdDomainSeeder } from '../GtdDomainSeeder';\n\n// Import DI types to avoid circular dependencies\nimport { TYPES } from '../../types/DITypes';\n\n// Note: MongoDB client now handled centrally - no direct imports needed\n\n// Export TYPES for backward compatibility\nexport const GTD_DOMAIN_SYMBOLS = TYPES;\n\n/**\n * GTD Domain Module - Following Party Manager pattern for clean DI\n * \n * This function returns a ContainerModule that configures all GTD Domain dependencies\n * following the same pattern as the working Party Manager domain.\n * Uses simple string-based bindings and avoids complex toDynamicValue patterns.\n * \n * MongoDB client is handled externally and injected where needed.\n */\nexport const createGTDDomainModule = (): ContainerModule => {\n  return new ContainerModule((bind) => {\n    // ===================================\n    // INFRASTRUCTURE - MongoDB Client\n    // ===================================\n    // Note: MongoDB client now bound centrally in application core services\n    // No need to bind here - just use injected MongoClient\n\n    // ===================================\n    // INBOX MANAGEMENT BOUNDED CONTEXT\n    // ===================================\n    \n    // Repository Layer\n    bind<InboxItemAggregateRepository>(TYPES.InboxItemAggregateRepository)\n      .to(InboxItemAggregateRepository)\n      .inSingletonScope();\n\n    // Domain Services\n    bind<GTDProcessingWorkflowService>(TYPES.GTDProcessingWorkflowService)\n      .to(GTDProcessingWorkflowService)\n      .inSingletonScope();\n\n    bind<InboxImportExportService>(TYPES.InboxImportExportService)\n      .to(InboxImportExportService)\n      .inSingletonScope();\n\n    // Application Services\n    bind<InboxItemApplicationService>(TYPES.InboxItemApplicationService)\n      .to(InboxItemApplicationService)\n      .inSingletonScope();\n\n    // ===================================\n    // PROJECT MANAGEMENT BOUNDED CONTEXT\n    // ===================================\n    \n    // Repository Layer\n    bind<ProjectRepository>(TYPES.ProjectRepository)\n      .to(ProjectRepository)\n      .inSingletonScope();\n\n    bind<NextActionAggregateRepository>(TYPES.NextActionAggregateRepository)\n      .to(NextActionAggregateRepository)\n      .inSingletonScope();\n\n    // Application Services (CQRS)\n    bind<NextActionWriteService>(TYPES.NextActionWriteService)\n      .to(NextActionWriteService)\n      .inSingletonScope();\n\n    bind<NextActionReadService>(TYPES.NextActionReadService)\n      .to(NextActionReadService)\n      .inSingletonScope();\n\n    bind<ProjectApplicationService>(TYPES.ProjectApplicationService)\n      .to(ProjectApplicationService)\n      .inSingletonScope();\n\n    bind<ProjectReadService>(TYPES.ProjectReadService)\n      .to(ProjectReadService)\n      .inSingletonScope();\n\n    // ===================================\n    // TASK MANAGEMENT BOUNDED CONTEXT\n    // ===================================\n    \n    // Repository Layer\n    bind<ITaskRepository>(TYPES.ITaskRepository)\n      .to(TaskMongoRepository)\n      .inSingletonScope();\n\n    bind<TaskMongoRepository>(TYPES.TaskMongoRepository)\n      .to(TaskMongoRepository)\n      .inSingletonScope();\n\n    // File-based Repositories\n    bind<InboxFileRepository>(TYPES.InboxFileRepository)\n      .to(InboxFileRepository)\n      .inSingletonScope();\n\n    bind<NextActionsFileRepository>(TYPES.NextActionsFileRepository)\n      .to(NextActionsFileRepository)\n      .inSingletonScope();\n\n    // ===================================\n    // DESIGN IMPLEMENTATION COORDINATION BOUNDED CONTEXT\n    // ===================================\n    \n    // Repository Layer\n    bind<DesignImplementationFlowRepository>(TYPES.DesignImplementationFlowRepository)\n      .to(DesignImplementationFlowRepository)\n      .inSingletonScope();\n\n    // Application Services\n    bind<DesignImplementationFlowApplicationService>(TYPES.DesignImplementationFlowApplicationService)\n      .to(DesignImplementationFlowApplicationService)\n      .inSingletonScope();\n\n    bind<DesignImplementationFlowReadService>(TYPES.DesignImplementationFlowReadService)\n      .to(DesignImplementationFlowReadService)\n      .inSingletonScope();\n  });\n};","import { getMongoDb } from \"@swoft/persistence\";\nimport { ITaskRepository } from '../../ports/ITaskRepository';\nimport { TaskAggregate } from '../../domain/entities/TaskAggregate';\nimport { TaskSchema } from '../../domain/view-models';\nimport { GTD_COLLECTIONS } from '../../../../config/collections';\n\n/**\n * MongoDB implementation of ITaskRepository\n */\nexport class TaskMongoRepository implements ITaskRepository {\n  private readonly collectionName = GTD_COLLECTIONS.TASK_ASSIGNMENTS;\n\n  async save(task: TaskAggregate): Promise<void> {\n    const dto = task.toDTO();\n    const assignment = {\n      productId: dto.productId,\n      taskId: dto.id,\n      partyId: dto.assignedTo,\n      roleType: dto.roleType,\n      assignedAt: dto.assignedAt,\n    };\n    const db = getMongoDb();\n    await db.collection(this.collectionName).updateOne(\n      { taskId: dto.id },\n      { $set: assignment },\n      { upsert: true }\n    );\n  }\n\n  async getById(taskId: string): Promise<TaskAggregate> {\n    const db = getMongoDb();\n    const doc: any = await db.collection(this.collectionName).findOne({ taskId });\n    if (!doc) throw new Error(`Assignment for taskId ${taskId} not found`);\n    const dto = TaskSchema.parse({\n      id: doc.taskId,\n      title: '',\n      context: [],\n      priority: 'medium',\n      status: 'in-progress',\n      inboxItemId: undefined,\n      due: undefined,\n      createdAt: new Date().toISOString(),\n      updatedAt: new Date().toISOString(),\n      assignedTo: doc.partyId,\n      roleType: doc.roleType,\n      assignedAt: doc.assignedAt,\n    });\n    return TaskAggregate.fromDTO(dto);\n  }\n\n  async listByProduct(productId: string): Promise<TaskAggregate[]> {\n    const db = getMongoDb();\n    const docs: any[] = await db.collection(this.collectionName).find({ productId }).toArray();\n    return docs.map((doc: any) => {\n      const dto = TaskSchema.parse({\n        id: doc.taskId,\n        title: '',\n        context: [],\n        priority: 'medium',\n        status: 'in-progress',\n        inboxItemId: undefined,\n        due: undefined,\n        createdAt: new Date().toISOString(),\n        updatedAt: new Date().toISOString(),\n        assignedTo: doc.partyId,\n        roleType: doc.roleType,\n        assignedAt: doc.assignedAt,\n      });\n      return TaskAggregate.fromDTO(dto);\n    });\n  }\n}\n","import { AggregateRoot } from '@swoft/core';\nimport { Task, TaskSchema } from '../view-models';\nimport { TaskId } from '../value-objects/TaskId';\nimport { TaskAssigned } from '../events/TaskAssigned';\nimport { TaskCompleted } from '../events/TaskCompleted';\n\n/**\n * Aggregate root for Task domain, encapsulating business logic and invariants.\n * \n * Manages task lifecycle, assignment rules, and completion workflow\n * following Eric Evans' DDD principles with event-driven state changes.\n */\nexport class TaskAggregate extends AggregateRoot<TaskId> {\n  constructor(\n    id: TaskId,\n    private props: Task\n  ) {\n    super(id);\n  }\n\n  /**\n   * Reconstruct aggregate from persistence layer.\n   */\n  static fromDTO(dto: Task): TaskAggregate {\n    return new TaskAggregate(\n      TaskId.fromString(dto.id),\n      dto\n    );\n  }\n\n  /**\n   * Create new task with generated ID.\n   */\n  static create(props: Omit<Task, 'id'>): TaskAggregate {\n    const id = TaskId.generate();\n    const task: Task = {\n      ...props,\n      id: id.toString()\n    };\n    return new TaskAggregate(id, task);\n  }\n\n  /**\n   * Assign this task to a developer.\n   * \n   * Business Rules:\n   * - Only 'new' or 'in-progress' tasks can be assigned\n   * - Assignment triggers workflow automation via TaskAssigned event\n   */\n  assignTo(partyId: string, roleType: string): void {\n    if (this.props.status !== 'new' && this.props.status !== 'in-progress') {\n      throw new Error(\n        `Cannot assign task ${this.props.id} in status ${this.props.status}`\n      );\n    }\n    \n    this.apply(new TaskAssigned(\n      this.getId().toString(),\n      partyId,\n      roleType,\n      new Date()\n    ));\n  }\n\n  /**\n   * Event handler: Task assignment state change.\n   */\n  onTaskAssigned(event: TaskAssigned): void {\n    this.props.assignedTo = event.partyId;\n    this.props.roleType = event.roleType;\n    this.props.assignedAt = event.assignedAt.toISOString();\n    \n    // Auto-transition to in-progress if newly assigned\n    if (this.props.status === 'new') {\n      this.props.status = 'in-progress';\n    }\n  }\n\n  /**\n   * Mark this task as completed.\n   * \n   * Business Rules:\n   * - Cannot complete already completed tasks\n   * - Cannot complete blocked tasks\n   * - Completion triggers analytics and workload rebalancing\n   */\n  complete(completedBy?: string): void {\n    if (this.props.status === 'done') {\n      throw new Error(\n        `Task ${this.props.id} is already completed`\n      );\n    }\n    if (this.props.status === 'blocked') {\n      throw new Error(\n        `Cannot complete blocked task ${this.props.id}`\n      );\n    }\n    \n    this.apply(new TaskCompleted(\n      this.getId().toString(),\n      completedBy,\n      new Date()\n    ));\n  }\n\n  /**\n   * Event handler: Task completion state change.\n   */\n  onTaskCompleted(event: TaskCompleted): void {\n    this.props.status = 'done';\n    this.props.completedAt = event.completedAt.toISOString();\n  }\n\n  /**\n   * Block this task due to dependencies or issues.\n   */\n  block(reason: string): void {\n    if (this.props.status === 'done') {\n      throw new Error(`Cannot block completed task ${this.props.id}`);\n    }\n    \n    this.props.status = 'blocked';\n    this.props.blockedReason = reason;\n    this.props.blockedAt = new Date().toISOString();\n  }\n\n  /**\n   * Unblock this task and return to previous state.\n   */\n  unblock(): void {\n    if (this.props.status !== 'blocked') {\n      throw new Error(`Task ${this.props.id} is not blocked`);\n    }\n    \n    // Return to in-progress if assigned, otherwise new\n    this.props.status = this.props.assignedTo ? 'in-progress' : 'new';\n    this.props.blockedReason = undefined;\n    this.props.blockedAt = undefined;\n  }\n\n  /** Export aggregate state as DTO */\n  toDTO(): Task {\n    return TaskSchema.parse(this.props);\n  }\n}\n","import { z } from 'zod'\n\n/**\n * GTD Lite workflow schemas using Zod\n */\nexport const InboxItemSchema = z.object({\n  id: z.string().describe('Unique identifier for the inbox item'),\n  title: z.string().describe('Short descriptive title of the item'),\n  description: z.string().describe('Detailed content of the item'),\n  context: z.string().optional().describe('Optional situational context'),\n  actionability: z\n    .enum(['actionable', 'reference', 'someday', 'delegated'])\n    .optional()\n    .describe('GTD classification'),\n  nextSteps: z.array(z.string()).optional().describe('Suggested next steps'),\n  status: z\n    .enum(['new', 'in-progress', 'done', 'blocked'])\n    .default('new')\n    .describe('Current workflow status'),\n  owner: z.string().optional().describe('Responsible person'),\n  due: z.string().optional().describe('Optional due date ISO string'),\n  processed: z.boolean().default(false).describe('Whether reviewed'),\n  createdAt: z.string().describe('Creation timestamp ISO string'),\n  updatedAt: z.string().describe('Last-modified timestamp ISO string'),\n  assignedTo: z.string().optional().describe(\"Party ID of the developer assigned to this task\"),\n  roleType: z.string().optional().describe(\"Role type of the assigned developer\"),\n  assignedAt: z.string().optional().describe(\"Timestamp when the task was assigned\"),\n})\n\nexport type InboxItem = z.infer<typeof InboxItemSchema>\nexport type InboxItemModel = InboxItem\n\nexport const TaskSchema = z.object({\n  id: z.string().describe('Unique identifier for the task'),\n  title: z.string().describe('Task title'),\n  context: z.array(z.string()).default([]).describe('Tags for categorization'),\n  priority: z.enum(['high', 'medium', 'low']).default('medium').describe('Priority level'),\n  duration: z.number().optional().describe('Estimated minutes'),\n  status: z.enum(['new', 'in-progress', 'done', 'blocked']).default('new').describe('Task status'),\n  inboxItemId: z.string().optional().describe('Origin inbox item ID'),\n  due: z.string().optional().describe('Due date ISO string'),\n  createdAt: z.string().describe('Creation timestamp ISO string'),\n  updatedAt: z.string().describe('Last-modified timestamp ISO string'),\n  assignedTo: z.string().optional().describe(\"Party ID of the developer assigned to this task\"),\n  roleType: z.string().optional().describe(\"Role type of the assigned developer\"),\n  assignedAt: z.string().optional().describe(\"Timestamp when the task was assigned\"),\n  completedAt: z.string().optional().describe(\"Timestamp when the task was completed\"),\n  productId: z.string().optional().describe(\"Product ID this task belongs to\"),\n  // Blocking support for task dependencies\n  blockedReason: z.string().optional().describe(\"Reason why the task is blocked\"),\n  blockedAt: z.string().optional().describe(\"Timestamp when the task was blocked\"),\n})\n\nexport type Task = z.infer<typeof TaskSchema>\n\nexport const ProjectSchema = z.object({\n  id: z.string().describe('Unique identifier for the project'),\n  title: z.string().describe('Project title'),\n  description: z.string().optional().describe('Project details'),\n  context: z.array(z.string()).default([]).describe('Project tags'),\n  tasks: z.array(z.string()).describe('List of task IDs'),\n  status: z.enum(['planning', 'active', 'on-hold', 'completed']).default('planning').describe('Project status'),\n  inboxItemId: z.string().optional().describe('Origin inbox item ID'),\n  due: z.string().optional().describe('Due date ISO string'),\n  progress: z.number().default(0).describe('Completion percentage'),\n  createdAt: z.string().describe('Creation timestamp ISO string'),\n  updatedAt: z.string().describe('Last-modified timestamp ISO string'),\n  assignedTo: z.string().optional().describe(\"Party ID of the developer assigned to this task\"),\n  roleType: z.string().optional().describe(\"Role type of the assigned developer\"),\n  assignedAt: z.string().optional().describe(\"Timestamp when the task was assigned\"),\n})\n\nexport type Project = z.infer<typeof ProjectSchema>\n\nexport const ContextSchema = z.object({\n  id: z.string().describe('Unique context/tag ID'),\n  name: z.string().describe('Context display name'),\n  description: z.string().optional().describe('Description of usage'),\n  color: z.string().optional().describe('UI color code'),\n})\n\nexport type Context = z.infer<typeof ContextSchema>\n\nexport const ProgressUpdateSchema = z.object({\n  projectId: z.string().optional().describe('Project ID'),\n  taskId: z.string().optional().describe('Task ID'),\n  progress: z.number().describe('Progress percentage'),\n  status: z.enum(['on-track', 'at-risk', 'blocked']).default('on-track').describe('Health status'),\n  blockers: z.array(z.string()).optional().describe('Blocker descriptions'),\n  timestamp: z.string().describe('Update timestamp ISO string'),\n})\n\nexport type ProgressUpdate = z.infer<typeof ProgressUpdateSchema>\n\nexport const TodayItemSchema = z.object({\n  id: z.string().describe('Identifier for today item'),\n  taskId: z.string().describe('Associated task ID'),\n  priority: z.enum(['high', 'medium', 'low']).describe('Today priority'),\n  scheduledTime: z.string().optional().describe('Scheduled time ISO string'),\n  completed: z.boolean().default(false).describe('Completion flag'),\n  date: z.string().describe('Date ISO string'),\n})\n\nexport type TodayItem = z.infer<typeof TodayItemSchema>\n\nexport const NudgeSchema = z.object({\n  id: z.string().describe('Unique nudge ID'),\n  taskId: z.string().describe('Associated task ID'),\n  projectId: z.string().optional().describe('Associated project ID'),\n  message: z.string().describe('Nudge message'),\n  type: z.enum(['reminder', 'suggestion', 'progress', 'blocked']).describe('Nudge type'),\n  dismissed: z.boolean().default(false).describe('Dismissed flag'),\n  timestamp: z.string().describe('Creation timestamp ISO string'),\n})\n\nexport type Nudge = z.infer<typeof NudgeSchema>\n\nexport const NextActionSchema = z.object({\n  id: z.string(),\n  text: z.string(),\n  done: z.boolean(),\n  category: z.string(),\n  fileName: z.string(),\n  fileCreatedAt: z.string(),\n  fileModifiedAt: z.string(),\n  fileSize: z.number(),\n  lineNumber: z.number(),\n})\n\nexport type NextAction = z.infer<typeof NextActionSchema>\n","import { EntityId } from \"@swoft/core\";\n\n/**\n * Strongly-typed identifier for Task aggregates.\n * \n * Provides value object semantics for task identification,\n * ensuring type safety and preventing ID confusion across aggregates.\n */\nexport class TaskId extends EntityId {\n  private readonly value: string;\n\n  constructor(value: string) {\n    super();\n    this.value = value;\n    if (!value || value.trim().length === 0) {\n      throw new Error('TaskId cannot be empty');\n    }\n  }\n\n  toString(): string {\n    return this.value;\n  }\n\n  /**\n   * Create a TaskId from a string value.\n   * Useful for deserialization and API boundaries.\n   */\n  static fromString(value: string): TaskId {\n    return new TaskId(value);\n  }\n\n  /**\n   * Generate a new unique TaskId.\n   * Uses timestamp-based generation for uniqueness.\n   */\n  static generate(): TaskId {\n    const timestamp = Date.now();\n    const random = Math.random().toString(36).substring(2, 8);\n    return new TaskId(`task-${timestamp}-${random}`);\n  }\n}","import { DomainEvent } from '@swoft/core';\n\n/**\n * Domain event raised when a task is assigned to a developer.\n * \n * This event triggers workflow automation and notification systems\n * to update project tracking and developer workload management.\n */\nexport class TaskAssigned implements DomainEvent {\n  readonly type = 'TaskAssigned';\n  readonly eventType = 'TaskAssigned';\n  readonly occurredOn: Date;\n  readonly occurredAt: Date;\n  readonly eventVersion = 1;\n\n  constructor(\n    public readonly aggregateId: string,\n    public readonly partyId: string,\n    public readonly roleType: string,\n    public readonly assignedAt: Date = new Date()\n  ) {\n    this.occurredOn = this.assignedAt;\n    this.occurredAt = this.assignedAt;\n  }\n\n  /**\n   * Create event from legacy format for migration compatibility.\n   */\n  static fromLegacy(\n    taskId: string,\n    partyId: string,\n    roleType: string,\n    assignedAt: string\n  ): TaskAssigned {\n    return new TaskAssigned(\n      taskId,\n      partyId,\n      roleType,\n      new Date(assignedAt)\n    );\n  }\n}\n","import { DomainEvent } from '@swoft/core';\n\n/**\n * Domain event raised when a task is marked as completed.\n * \n * This event triggers project progress updates, workload rebalancing,\n * and completion analytics across the development workflow.\n */\nexport class TaskCompleted implements DomainEvent {\n  readonly type = 'TaskCompleted';\n  readonly occurredAt: Date;\n  readonly eventVersion = 1;\n  readonly data: Record<string, any>;\n\n  constructor(\n    public readonly aggregateId: string,\n    public readonly completedBy?: string,\n    public readonly completedAt: Date = new Date()\n  ) {\n    this.occurredAt = this.completedAt;\n    this.data = {\n      completedBy: this.completedBy,\n      completedAt: this.completedAt\n    };\n  }\n}","import fs from 'fs/promises'\nimport path from 'path'\nimport {v4 as uuidv4} from 'uuid'\nimport {type InboxItemModel, InboxItemSchema} from '../../domain'\n\n/**\n * Filesystem-based repository for GTD Inbox Items\n */\nexport class InboxFileRepository {\n    private baseDir: string\n    private processedDir: string\n\n    constructor() {\n        this.baseDir = path.join(process.env.SWOFT_MONO_REPOS_ROOT || process.cwd(), 'gtd', 'inbox')\n        this.processedDir = path.join(this.baseDir, 'processed')\n    }\n\n    async getInboxItems(): Promise<InboxItemModel[]> {\n        await this.ensureDirs()\n        const files = await fs.readdir(this.baseDir)\n        const items: InboxItemModel[] = []\n        for (const file of files) {\n            if (!file.endsWith('.json')) continue\n            const filePath = path.join(this.baseDir, file)\n            try {\n                const content = await fs.readFile(filePath, 'utf-8')\n                const obj = JSON.parse(content)\n                items.push(InboxItemSchema.parse(obj))\n            } catch {\n                continue\n            }\n        }\n        return items\n    }\n\n    async createInboxItem(text: string, source?: string): Promise<InboxItemModel> {\n        await this.ensureDirs()\n        const now = new Date().toISOString()\n        const id = uuidv4()\n        const item = {id, text, source, processed: false, createdAt: now, updatedAt: now}\n        const filePath = path.join(this.baseDir, `${id}.json`)\n        await fs.writeFile(filePath, JSON.stringify(item, null, 2), 'utf-8')\n        return InboxItemSchema.parse(item)\n    }\n\n    private async ensureDirs() {\n        await fs.mkdir(this.baseDir, {recursive: true})\n        await fs.mkdir(this.processedDir, {recursive: true})\n    }\n}\n","import { z } from 'zod'\n\n/**\n * Summary model for listing plans.\n */\nexport const PlanSummaryViewModel = z.object({\n  id: z.string().describe('Plan ID'),\n  title: z.string().describe('Plan title'),\n  status: z.enum(['pending', 'in-progress', 'blocked', 'completed']).describe('Overall plan status'),\n  tasks: z.object({\n    total: z.number().int().min(0).describe('Total tasks count'),\n    completed: z.number().int().min(0).describe('Completed tasks count'),\n  }).describe('Task completion stats'),\n})\nexport type PlanSummaryViewModel = z.infer<typeof PlanSummaryViewModel>\n\nexport const PlanSummaryListViewModel = z.array(PlanSummaryViewModel)\nexport type PlanSummaryListViewModel = z.infer<typeof PlanSummaryListViewModel>\n\n/**\n * Model for a milestone within a plan.\n */\nexport const MilestoneViewModel = z.object({\n  name: z.string().describe('Milestone name'),\n  tasks: z.array(z.string()).describe('Associated task IDs'),\n})\nexport type MilestoneViewModel = z.infer<typeof MilestoneViewModel>\n\n/**\n * Model for a single task item in a plan.\n */\nexport const PlanTaskItemViewModel = z.object({\n  id: z.string().describe('Task ID'),\n  text: z.string().describe('Task description'),\n  status: z.enum(['pending', 'in-progress', 'blocked', 'done']).default('pending').describe('Task status'),\n  dependencies: z.array(z.string()).optional().describe('Dependent task IDs'),\n})\nexport type PlanTaskItemViewModel = z.infer<typeof PlanTaskItemViewModel>\n\n/**\n * Section of tasks in a plan.\n */\nexport const PlanTaskSectionViewModel = z.object({\n  title: z.string().describe('Section title'),\n  items: z.array(PlanTaskItemViewModel).describe('List of tasks'),\n})\nexport type PlanTaskSectionViewModel = z.infer<typeof PlanTaskSectionViewModel>\n\n/**\n * Full plan model.\n */\nexport const PlanViewModel = z.object({\n  id: z.string().describe('Plan ID'),\n  title: z.string().describe('Plan title'),\n  objective: z.string().describe('Plan objective'),\n  implementationGoals: z.array(z.string()).describe('List of goals'),\n  milestones: z.array(MilestoneViewModel).describe('Plan milestones'),\n  taskSections: z.array(PlanTaskSectionViewModel).describe('Task sections'),\n})\nexport type PlanViewModel = z.infer<typeof PlanViewModel>","import { promises as fs } from 'fs'\nimport path from 'path'\nimport { NextActionSchema, type NextAction } from '../../domain/view-models'\n\n/**\n * Repository that reads Next Actions from markdown files.\n */\nexport class NextActionsFileRepository {\n  private readonly dir: string\n\n  constructor(gtdDir?: string) {\n    const fsRoot = process.env.GTD_FILE_SYSTEM || path.resolve(process.cwd(), '..', '.gtd')\n    this.dir = gtdDir ?? path.join(fsRoot, 'next-actions')\n  }\n\n  async getNextActions(): Promise<NextAction[]> {\n    let files: string[]\n    try {\n      files = await fs.readdir(this.dir)\n    } catch {\n      return []\n    }\n    const actions: NextAction[] = []\n    for (const file of files.filter(f => f.endsWith('.md'))) {\n      const category = file.replace(/\\.md$/, '')\n      const filePath = path.join(this.dir, file)\n      const stats = await fs.stat(filePath)\n      const content = await fs.readFile(filePath, 'utf-8')\n      const lines = content.split(/\\r?\\n/)\n      for (let idx = 0; idx < lines.length; idx++) {\n        const match = lines[idx].match(/^- \\[( |x)\\] (.*)$/)\n        if (!match) continue\n        const done = match[1] === 'x'\n        const text = match[2].trim()\n        const id = `${category}-${idx}`\n        const action = NextActionSchema.parse({\n          id,\n          text,\n          done,\n          category,\n          fileName: file,\n          fileCreatedAt: stats.birthtime.toISOString(),\n          fileModifiedAt: stats.mtime.toISOString(),\n          fileSize: stats.size,\n          lineNumber: idx + 1,\n        })\n        actions.push(action)\n      }\n    }\n    return actions\n  }\n}","/**\n * GTD Domain Rules\n * \n * Domain-specific validation rules following David Allen's Getting Things Done methodology.\n * Owned and maintained by the productivity and task management domain experts.\n * \n * Follows Eric Evans DDD principle: each domain defines its own rules.\n */\n\n// TODO: These types need to be defined or imported from the correct package\n// Temporarily commenting out until the proper types are available\n/*\nimport type { \n  DomainRulesContract,\n  NamingRule,\n  IntegrationRule,\n  ArchitecturalRule,\n  DomainCapability,\n  DomainEventMetadata\n} from '@swoft/core';\n*/\n\n// Temporary type definitions to allow compilation\ntype DomainRulesContract = any;\ntype NamingRule = any;\ntype IntegrationRule = any;\ntype ArchitecturalRule = any;\ntype DomainCapability = any;\ntype DomainEventMetadata = any;\n\nexport class GTDDomainRules implements DomainRulesContract {\n  readonly domainName = 'gtd-domain';\n  readonly version = '1.0.0';\n  readonly description = 'Domain rules for Getting Things Done productivity system by David Allen';\n  readonly maintainer = 'Productivity Systems Team';\n\n  readonly namingRules: readonly NamingRule[] = [\n    {\n      pattern: 'entity',\n      examples: ['InboxItem', 'Project', 'NextAction', 'SomedayMaybeItem', 'Reference'],\n      description: 'GTD entities represent core productivity concepts from David Allen methodology'\n    },\n    {\n      pattern: 'value-object',\n      examples: ['Context', 'Priority', 'EnergyLevel', 'ProcessingStatus', 'ActionableDecision'],\n      description: 'Value objects capture GTD workflow attributes and decision points'\n    },\n    {\n      pattern: 'command',\n      examples: ['CaptureInboxItem', 'ClarifyItem', 'OrganizeAction', 'CompleteTask', 'ProcessInbox'],\n      description: 'GTD commands follow David Allen workflow verbs - capture, clarify, organize, reflect, engage'\n    },\n    {\n      pattern: 'event',\n      examples: ['ItemCaptured', 'ItemClarified', 'ProjectCompleted', 'ActionCreated', 'ItemOrganized'],\n      description: 'GTD events represent completed workflow steps - always past tense (facts that happened)'\n    }\n  ];\n\n  readonly integrationRules: readonly IntegrationRule[] = [\n    {\n      type: 'published-language',\n      description: 'Provides GTD workflow capabilities to AI agents via Published Language contracts',\n      allowedIntegrations: ['ai-domain'],\n      restrictedIntegrations: []\n    },\n    {\n      type: 'event-driven',\n      description: 'Publishes productivity events for person activity tracking',\n      allowedIntegrations: ['party-manager'],\n      restrictedIntegrations: []\n    },\n    {\n      type: 'foreign-key',\n      description: 'References persons and organizations via IDs without direct coupling',\n      allowedIntegrations: ['party-manager'],\n      restrictedIntegrations: []\n    }\n  ];\n\n  readonly architecturalRules: readonly ArchitecturalRule[] = [\n    {\n      category: 'boundary-enforcement',\n      rule: 'GTD domain must maintain pure David Allen methodology without external productivity system contamination',\n      rationale: 'Preserving the integrity of GTD methodology ensures consistent workflow behavior',\n      exceptions: []\n    },\n    {\n      category: 'aggregate-design',\n      rule: 'GTD aggregates should align with natural workflow boundaries (Inbox, Project, Action)',\n      rationale: 'Workflow boundaries provide natural consistency boundaries for aggregates',\n      exceptions: []\n    },\n    {\n      category: 'layer-separation',\n      rule: 'GTD workflow rules belong in domain layer, not application services',\n      rationale: 'David Allen methodology rules are core business logic that should be protected from infrastructure concerns',\n      exceptions: []\n    }\n  ];\n\n  readonly capabilities: readonly DomainCapability[] = [\n    { name: 'captureInboxItem', description: 'Capture thoughts/inputs into trusted inbox (David Allen Step 1)', businessValue: 'Enables ubiquitous capture for stress-free productivity', technicalComplexity: 'low' },\n    { name: 'clarifyInboxItem', description: 'Process inbox item through clarification workflow (David Allen Step 2)', businessValue: 'Transforms unclear inputs into actionable decisions', technicalComplexity: 'medium' },\n    { name: 'organizeActions', description: 'Organize clarified items into appropriate lists (David Allen Step 3)', businessValue: 'Creates trusted system for tracking commitments', technicalComplexity: 'medium' },\n    { name: 'completeAction', description: 'Mark next action as completed and update project status', businessValue: 'Maintains project momentum and progress visibility', technicalComplexity: 'low' },\n    { name: 'createProject', description: 'Define multi-step project with desired outcome', businessValue: 'Provides clarity on multi-step outcomes', technicalComplexity: 'medium' },\n    { name: 'defineNextAction', description: 'Specify concrete next physical action for project advancement', businessValue: 'Eliminates thinking about what to do next', technicalComplexity: 'low' },\n    { name: 'scheduleReview', description: 'Set up weekly/daily review cycles (David Allen Step 4)', businessValue: 'Keeps system current and trusted', technicalComplexity: 'low' },\n    { name: 'engageWithWork', description: 'Choose next action based on context, energy, time (David Allen Step 5)', businessValue: 'Optimizes productivity based on current resources', technicalComplexity: 'medium' },\n    { name: 'getInboxItems', description: 'Retrieve unprocessed and processed inbox items', businessValue: 'Provides visibility into capture pipeline', technicalComplexity: 'low' },\n    { name: 'getNextActions', description: 'List available next actions by context and energy level', businessValue: 'Enables context-appropriate action selection', technicalComplexity: 'medium' },\n    { name: 'getProjectStatus', description: 'Check project progress and next action status', businessValue: 'Maintains awareness of commitments', technicalComplexity: 'low' },\n    { name: 'validateWorkflow', description: 'Ensure GTD workflow integrity (2-minute rule, single next action)', businessValue: 'Maintains methodology consistency', technicalComplexity: 'high' }\n  ];\n\n  getNamingRules(): NamingRule[] {\n    return [...this.namingRules];\n  }\n\n  getIntegrationRules(): IntegrationRule[] {\n    return [...this.integrationRules];\n  }\n\n  getArchitecturalRules(): ArchitecturalRule[] {\n    return [...this.architecturalRules];\n  }\n\n  getCapabilities(): DomainCapability[] {\n    return [...this.capabilities];\n  }\n\n  getEventMetadata(): DomainEventMetadata[] {\n    return [...this.events];\n  }\n\n  readonly events: readonly DomainEventMetadata[] = [\n    { eventName: 'ItemCaptured', description: 'New item added to trusted inbox system', producedBy: 'InboxItem', consumedBy: ['ai-domain', 'party-manager'], schema: 'ItemCapturedEvent' },\n    { eventName: 'ItemClarified', description: 'Inbox item processed through what-is-it decision tree', producedBy: 'InboxItem', consumedBy: ['project-management'], schema: 'ItemClarifiedEvent' },\n    { eventName: 'ItemOrganized', description: 'Clarified item placed in appropriate GTD list', producedBy: 'InboxItem', consumedBy: ['project-management'], schema: 'ItemOrganizedEvent' },\n    { eventName: 'ProjectCreated', description: 'Multi-step project defined with clear outcome', producedBy: 'Project', consumedBy: ['ai-domain', 'party-manager'], schema: 'ProjectCreatedEvent' },\n    { eventName: 'ProjectCompleted', description: 'Project successfully finished and archived', producedBy: 'Project', consumedBy: ['party-manager'], schema: 'ProjectCompletedEvent' },\n    { eventName: 'NextActionDefined', description: 'Concrete next physical action specified', producedBy: 'NextAction', consumedBy: ['ai-domain'], schema: 'NextActionDefinedEvent' },\n    { eventName: 'ActionCompleted', description: 'Next action finished and project advanced', producedBy: 'NextAction', consumedBy: ['project-management', 'party-manager'], schema: 'ActionCompletedEvent' },\n    { eventName: 'ReviewScheduled', description: 'Weekly review cycle established', producedBy: 'Review', consumedBy: ['ai-domain'], schema: 'ReviewScheduledEvent' },\n    { eventName: 'ReviewCompleted', description: 'GTD review process finished with updated lists', producedBy: 'Review', consumedBy: ['party-manager'], schema: 'ReviewCompletedEvent' },\n    { eventName: 'ContextAssigned', description: 'Action tagged with appropriate context (@calls, @computer)', producedBy: 'NextAction', consumedBy: ['ai-domain'], schema: 'ContextAssignedEvent' },\n    { eventName: 'EnergyLevelSet', description: 'Action categorized by required energy level', producedBy: 'NextAction', consumedBy: ['ai-domain'], schema: 'EnergyLevelSetEvent' },\n    { eventName: 'SomedayMaybeItemCreated', description: 'Future possibility captured for review', producedBy: 'SomedayMaybeItem', consumedBy: ['ai-domain'], schema: 'SomedayMaybeItemCreatedEvent' },\n    { eventName: 'ReferenceItemStored', description: 'Information stored in reference system', producedBy: 'ReferenceItem', consumedBy: ['ai-domain'], schema: 'ReferenceItemStoredEvent' }\n  ];\n\n  validateNaming(pattern: string, name: string): { isValid: boolean; violations: string[]; suggestions: string[] } {\n    const rule = this.namingRules.find(r => r.pattern === pattern);\n    if (!rule) {\n      return { isValid: true, violations: [], suggestions: [] };\n    }\n\n    const violations: string[] = [];\n    const suggestions: string[] = [];\n\n    // GTD-specific validation\n    if (pattern === 'entity') {\n      if (!this.isGTDTerm(name)) {\n        violations.push(`Productivity concept \"${name}\" should use language from David Allen's Getting Things Done methodology`);\n        suggestions.push('Use authentic GTD terms: InboxItem, Project, NextAction, Reference, SomedayMaybe');\n      }\n    }\n\n    if (pattern === 'command') {\n      if (!this.isGTDWorkflowVerb(name)) {\n        violations.push(`Productivity action \"${name}\" should follow David Allen's 5-step GTD workflow verbs`);\n        suggestions.push('Use GTD workflow actions: Capture, Clarify, Organize, Review, Engage');\n      }\n    }\n\n    if (pattern === 'event') {\n      if (!this.isPastTense(name)) {\n        violations.push(`Productivity outcome \"${name}\" should reflect a completed GTD workflow step (facts that happened in your system)`);\n        suggestions.push('Use GTD workflow facts: ItemCaptured, ProjectCompleted, ActionDefined');\n      }\n    }\n\n    return {\n      isValid: violations.length === 0,\n      violations,\n      suggestions\n    };\n  }\n\n  validateIntegration(targetDomain: string, integrationType: string): { isValid: boolean; violations: string[]; recommendations: string[] } {\n    const rule = this.integrationRules.find(r => \n      r.allowedIntegrations.includes(targetDomain) || r.allowedIntegrations.includes('*')\n    );\n\n    if (!rule) {\n      return {\n        isValid: false,\n        violations: [`No integration rule defined for domain \"${targetDomain}\"`],\n        recommendations: ['Define explicit integration strategy maintaining GTD methodology purity']\n      };\n    }\n\n    // Special validation for GTD domain purity\n    if (integrationType === 'direct-import') {\n      return {\n        isValid: false,\n        violations: ['Direct imports violate GTD domain purity - external systems contaminate David Allen methodology'],\n        recommendations: ['Use Published Language or Anti-Corruption Layer to maintain GTD workflow integrity']\n      };\n    }\n\n    return { isValid: true, violations: [], recommendations: [] };\n  }\n\n  calculateHealthScore(): { score: number; breakdown: { naming: number; integration: number; architecture: number; capabilities: number } } {\n    const namingScore = 100; // Follows GTD naming conventions\n    const integrationScore = 100; // Proper Published Language with AI domain\n    const architectureScore = 100; // Clean domain boundaries\n    const capabilitiesScore = Math.min(100, (this.capabilities.length / 12) * 100); // 12 capabilities matches target\n\n    const totalScore = Math.round((namingScore + integrationScore + architectureScore + capabilitiesScore) / 4);\n\n    return {\n      score: totalScore,\n      breakdown: {\n        naming: namingScore,\n        integration: integrationScore,\n        architecture: architectureScore,\n        capabilities: capabilitiesScore\n      }\n    };\n  }\n\n  // Private helper methods for GTD domain validation\n  private isGTDTerm(name: string): boolean {\n    const gtdTerms = ['inbox', 'project', 'action', 'next', 'someday', 'maybe', 'reference', 'context', 'review', 'capture', 'clarify', 'organize', 'engage'];\n    return gtdTerms.some(term => name.toLowerCase().includes(term));\n  }\n\n  private isGTDWorkflowVerb(name: string): boolean {\n    const gtdVerbs = ['capture', 'clarify', 'organize', 'review', 'engage', 'complete', 'create', 'define', 'process', 'schedule'];\n    return gtdVerbs.some(verb => name.toLowerCase().startsWith(verb));\n  }\n\n  private isPastTense(name: string): boolean {\n    // Handle kebab-case events like 'item-captured'\n    if (name.includes('-')) {\n      const parts = name.split('-');\n      const lastPart = parts[parts.length - 1];\n      return this.endsWithPastTense(lastPart);\n    }\n    \n    // Handle PascalCase events like 'ItemCaptured'\n    return this.endsWithPastTense(name.toLowerCase());\n  }\n\n  private endsWithPastTense(word: string): boolean {\n    return word.endsWith('ed') || word.endsWith('d') || \n           ['captured', 'clarified', 'organized', 'completed', 'created', 'defined', 'assigned', 'stored', 'scheduled'].some(past => word.endsWith(past));\n  }\n}\n\n/**\n * Factory function for domain rules discovery\n */\nexport function createGTDDomainRules(): GTDDomainRules {\n  return new GTDDomainRules();\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,iBAAN,cAA6BC,MAAAA;EAHpC,OAGoCA;;;;;EAClC,YACEC,SACgBC,MACAC,SAChB;AACA,UAAMF,OAAAA,GAAAA,KAHUC,OAAAA,MAAAA,KACAC,UAAAA;AAGhB,SAAKC,OAAO;EACd;AACF;AAEO,IAAMC,yBAAN,cAAqCN,eAAAA;EAd5C,OAc4CA;;;EAC1C,YAAYE,SAAiBE,SAA+B;AAC1D,UAAMF,SAAS,4BAA4BE,OAAAA;AAC3C,SAAKC,OAAO;EACd;AACF;AAEO,IAAME,+BAAN,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W;MAAU;MAAW;MAAW;MAAY;;AAChJ,WAAOA,SAASC,KAAKC,CAAAA,SAAQ7C,KAAK8C,YAAW,EAAGnB,SAASkB,IAAAA,CAAAA;EAC3D;EAEQxB,kBAAkBrB,MAAuB;AAC/C,UAAM+C,WAAW;MAAC;MAAW;MAAW;MAAY;MAAU;MAAU;MAAY;MAAU;MAAU;MAAW;;AACnH,WAAOA,SAASH,KAAKI,CAAAA,SAAQhD,KAAK8C,YAAW,EAAGG,WAAWD,IAAAA,CAAAA;EAC7D;EAEQ1B,YAAYtB,MAAuB;AAEzC,QAAIA,KAAK2B,SAAS,GAAA,GAAM;AACtB,YAAMuB,QAAQlD,KAAKmD,MAAM,GAAA;AACzB,YAAMC,WAAWF,MAAMA,MAAM3B,SAAS,CAAA;AACtC,aAAO,KAAK8B,kBAAkBD,QAAAA;IAChC;AAGA,WAAO,KAAKC,kBAAkBrD,KAAK8C,YAAW,CAAA;EAChD;EAEQO,kBAAkBC,MAAuB;AAC/C,WAAOA,KAAKC,SAAS,IAAA,KAASD,KAAKC,SAAS,GAAA,KACrC;MAAC;MAAY;MAAa;MAAa;MAAa;MAAW;MAAW;MAAY;MAAU;MAAaX,KAAKY,CAAAA,SAAQF,KAAKC,SAASC,IAAAA,CAAAA;EACjJ;AACF;AAKO,SAASC,uBAAAA;AACd,SAAO,IAAI3E,eAAAA;AACb;AAFgB2E;","names":["GTDDomainError","Error","message","code","context","name","ThoughtProcessingError","InvalidProcessingStatusError","currentStatus","requiredStatus","InvalidActionDurationError","duration","maxDuration","ProjectStateError","projectId","currentState","AssignmentError","actionId","InboxContent","_value","trim","length","GTDDomainError","minLength","actualLength","maxLength","create","content","value","InboxItem","id","_originalContent","capturedAt","capturedByPersonId","_clarification","_isActionable","_processingStatus","_lastRefinedAt","_refinedByPersonId","originalContent","value","clarification","isActionable","processingStatus","lastRefinedAt","refinedByPersonId","capture","content","Date","now","Math","random","toString","substr","inboxContent","InboxContent","create","fromRepository","data","item","refineCapture","refinedContent","refinedBy","newContent","clarify","_clarifiedBy","toData","InboxImportExportService","repository","exportItems","filters","items","findAll","filteredItems","status","filter","item","processingStatus","limitedItems","limit","slice","exportDate","Date","toISOString","version","source","totalItems","length","map","originalContent","capturedAt","capturedByPersonId","clarification","isActionable","importItems","importData","options","validateImportData","results","imported","skipped","errors","itemData","content","text","push","JSON","stringify","InboxItem","capture","clarify","save","error","skipDuplicates","Error","message","includes","data","Array","isArray","ProjectIdentified","eventId","crypto","randomUUID","aggregateId","eventType","occurredAt","Date","eventVersion","occurredOn","projectName","desiredOutcome","identifiedBy","getEventData","identifiedAt","toISOString","NextActionCreated","description","context","energyLevel","createdBy","createdAt","TaskAssigned","assignedTo","roleType","assignedAt","ProjectCompleted","completedBy","completionNotes","completedAt","NextAction","domainEvents","_completedAt","_assignedTo","_assignedAt","_roleType","id","description","context","energyRequired","estimatedMinutes","createdBy","createdAt","Date","projectId","validateAction","addDomainEvent","NextActionCreated","toString","create","energy","minutes","generateId","reconstitute","assignedTo","assignedAt","roleType","completedAt","action","clearDomainEvents","assignTo","partyId","isCompleted","AssignmentError","isAssigned","trim","TaskAssigned","toISOString","unassign","undefined","complete","ThoughtProcessingError","canBePerformedWith","availableContext","availableEnergy","contextMatch","equals","energyMatch","canBePerformedWhen","getAvailableActions","actions","filter","isAvailable","status","getDomainEvents","event","push","now","Math","random","substring","ActionContext","context","toolsRequired","location","atComputer","tools","onPhone","atCalls","atErrands","anywhere","atOffice","atHome","errands","agendaFor","person","custom","equals","other","JSON","stringify","toString","startsWith","base","EnergyLevel","level","low","medium","high","isLow","isMedium","isHigh","canBePerformedWhen","available","levels","equals","other","toString","valueOf","GTDProcessingWorkflowService","processInboxItem","inboxItem","processingDecision","clarification","Error","processingStatus","isActionable","handleActionableItem","handleNonActionableItem","decision","result","success","workflowType","createdItems","estimatedMinutes","nextAction","createNextAction","push","type","id","description","urgent","reason","isProject","Date","now","projectOutcome","firstAction","isReference","isSomedayMaybe","context","parseActionContext","ActionContext","atComputer","energyLevel","parseEnergyLevel","EnergyLevel","medium","actionDescription","nextActionDescription","generateActionDescription","NextAction","create","capturedByPersonId","projectId","contextString","toLowerCase","replace","onPhone","atOffice","atHome","errands","custom","energyString","level","high","low","actionVerbs","hasActionVerb","some","verb","startsWith","CompleteGTDProcessingCommandValidator","validate","command","errors","itemId","trim","push","processedByPersonId","clarification","isActionable","undefined","estimatedMinutes","isProject","projectOutcome","hasDisposalMethod","isReference","isSomedayMaybe","context","validContexts","isValidContext","includes","toLowerCase","startsWith","energyLevel","validEnergyLevels","isValid","length","GTD_CONTEXTS","CALLS","COMPUTER","ERRANDS","HOME","OFFICE","ANYWHERE","WAITING","READ_REVIEW","GTD_ENERGY_LEVELS","HIGH","MEDIUM","LOW","injectable","inject","GTD_DOMAIN_SYMBOLS","InboxItemApplicationService","InboxItemAggregateRepository","GTDQueryService","PersonLookupService","GTDProcessingWorkflowService","InboxImportExportService","ProjectApplicationService","ProjectReadService","ProjectRepository","NextActionAggregateRepository","NextActionWriteService","NextActionReadService","ITaskRepository","TaskMongoRepository","GetReferenceItemService","InboxFileRepository","NextActionsFileRepository","GtdDomainSeeder","injectable","getMongoDb","getMongoDb","GTD_COLLECTIONS","INBOX_ITEMS","PROJECTS","NEXT_ACTIONS","TASK_ASSIGNMENTS","DESIGN_IMPLEMENTATION_FLOWS","REFERENCE_ITEMS","AGENT_API_KEYS","SOMEDAY_MAYBE","getGTDCollection","collectionName","db","getMongoDb","collection","GTD_COLLECTION_METADATA","boundedContext","description","primaryKey","gtdPhase","aggregateRoot","GTD_DOMAIN_PACKAGE_INFO","name","version","architecture","methodology","boundedContexts","gtdPhases","collections","Object","values","databaseDependency","GTD_COLLECTION_MIGRATION_GUIDE","migrations","from","to","reason","affectedFiles","InboxItemAggregateRepository","db","collection","ensureConnection","getMongoDb","GTD_COLLECTIONS","INBOX_ITEMS","save","item","itemData","toData","doc","_id","id","originalContent","capturedAt","capturedByPersonId","clarification","isActionable","processingStatus","lastRefinedAt","refinedByPersonId","updatedAt","Date","replaceOne","upsert","findById","findOne","mapDocumentToDomain","InboxItem","fromRepository","undefined","findAll","docs","find","toArray","map","countUnprocessed","countDocuments","countAll","delete","deleteOne","findByFilters","filters","query","status","sort","skip","offset","limit","countByFilters","injectable","getMongoDb","ProcessingStatus","value","new","clarified","processed","isNew","isClarified","isProcessed","equals","other","toString","NextActionAggregateRepository","db","collection","ensureConnection","getMongoDb","save","action","doc","_id","id","description","context","toString","energyRequired","estimatedMinutes","createdBy","createdAt","projectId","assignedTo","assignedAt","completedAt","status","isCompleted","isAssigned","replaceOne","upsert","findById","findOne","parseContext","energy","parseEnergyLevel","NextAction","reconstitute","roleType","findAll","docs","find","toArray","map","countAvailable","countDocuments","countAll","delete","deleteOne","contextStr","ActionContext","atCalls","atComputer","atErrands","atHome","atOffice","anywhere","energyStr","EnergyLevel","high","medium","low","InboxItemApplicationService","workflowService","repository","_nextActionRepository","GTDProcessingWorkflowService","createInboxItem","command","item","InboxItem","capture","originalContent","capturedByPersonId","save","success","itemId","id","capturedAt","toISOString","message","error","deleteInboxItem","findById","Error","delete","deletedAt","Date","processInboxItem","clarification","isActionable","undefined","clarify","processedByPersonId","processedAt","status","listInboxItems","filters","items","findByFilters","priority","limit","Math","min","offset","totalCount","countByFilters","itemDtos","map","processingStatus","toString","hasMoreResults","completeGTDProcessing","request","processingDecision","estimatedMinutes","context","energyLevel","nextActionDescription","isProject","projectOutcome","isReference","isSomedayMaybe","workflowResult","createdWorkItems","persistWorkItems","workflowType","length","persistedItems","createdItems","type","push","description","InboxItemAggregateRepository","NextActionAggregateRepository","Project","domainEvents","_nextActionIds","_completedAt","_status","id","name","desiredOutcome","createdBy","createdAt","Date","area","reviewDate","validateProject","create","outcome","generateId","planNextAction","description","context","energy","minutes","isCompleted","isCancelled","ProjectStateError","actionId","generateActionId","projectId","recordNextActionCreated","includes","push","recordActionCompleted","removeAction","actionIndex","findIndex","splice","complete","completedBy","completionNotes","addDomainEvent","ProjectCompleted","defer","activate","cancel","getNextActionIds","needsAttention","length","getBasicProgress","totalActionIds","isActive","isSomedayMaybe","status","nextActionIds","completedAt","getDomainEvents","clearDomainEvents","trim","ThoughtProcessingError","event","now","Math","random","toString","substring","ProjectStatus","DomainEvent","occurredOn","eventId","aggregateId","eventType","eventVersion","Date","now","Math","random","toString","substr","injectable","getMongoDb","ProjectRepository","db","collection","ensureConnection","getMongoDb","GTD_COLLECTIONS","PROJECTS","save","project","doc","_id","id","name","desiredOutcome","createdBy","createdAt","area","reviewDate","status","nextActionIds","completedAt","updatedAt","Date","replaceOne","upsert","findById","findOne","mapDocumentToDomain","findByStatus","docs","find","sort","toArray","map","safeMapDocumentToDomain","filter","findByArea","findAll","deleteById","deleteOne","Project","undefined","_nextActionIds","_status","_completedAt","trim","console","warn","error","injectable","inject","TYPES","InboxItemApplicationService","Symbol","for","InboxItemAggregateRepository","GTDProcessingWorkflowService","InboxImportExportService","ProjectApplicationService","ProjectReadService","ProjectRepository","NextActionAggregateRepository","NextActionWriteService","NextActionReadService","ITaskRepository","TaskMongoRepository","InboxFileRepository","NextActionsFileRepository","DesignImplementationFlowRepository","DesignImplementationFlowApplicationService","DesignImplementationFlowReadService","ProjectApplicationService","projectRepository","createProject","command","project","Project","create","name","desiredOutcome","createdBy","area","reviewDate","save","success","projectId","id","createdAt","toISOString","message","error","Date","Error","completeProject","completedBy","findById","complete","deferProject","defer","ProjectRepository","injectable","inject","z","BaseApplicationError","CreateProjectCommandSchema","z","object","name","string","min","max","desiredOutcome","area","optional","reviewDate","date","createdBy","strict","UpdateProjectCommandSchema","projectId","status","enum","CompleteProjectCommandSchema","completedBy","InvalidProjectCommandError","BaseApplicationError","code","validationErrors","ux","dx","join","ProjectNotFoundError","ProjectWriteService","repository","createProject","command","validatedCommand","parse","error","ZodError","errors","map","e","message","project","Project","create","save","id","success","Error","updateProject","findById","completeProject","complete","deleteProject","deleteById","holdProject","defer","activateProject","activate","ProjectRepository","injectable","inject","getMongoDb","ProjectReadService","collection","_repository","db","getMongoDb","getProjects","criteria","status","area","assignedTo","searchText","needsReview","createdBy","offset","limit","query","$or","name","$regex","$options","desiredOutcome","projects","total","Promise","all","find","sort","createdAt","skip","toArray","countDocuments","projectViews","map","doc","actionStats","getActionStatisticsForProject","_id","toString","id","reviewDate","completedAt","nextActionCount","completedActionCount","needsAttention","progress","totalActions","completedActions","completionPercentage","filteredProjects","filter","p","hasMore","getProjectById","projectId","findOne","getProjectsForReview","personId","$in","length","getProjectsByArea","getProjectStatistics","active","somedayMaybe","completed","cancelled","byArea","getCountByField","needingReview","nextActionIds","$size","actionsCollection","Math","round","field","results","aggregate","$group","count","$sum","counts","result","ProjectRepository","injectable","inject","z","BaseApplicationError","CreateNextActionCommandSchema","z","object","description","string","min","max","context","enum","energyLevel","estimatedMinutes","number","projectId","optional","createdBy","strict","AssignActionCommandSchema","actionId","assignedTo","roleType","CompleteActionCommandSchema","InvalidActionCommandError","BaseApplicationError","code","validationErrors","ux","dx","join","ActionNotFoundError","NextActionWriteService","repository","createNextAction","command","validatedCommand","parse","error","ZodError","errors","map","e","message","parseContext","energy","parseEnergyLevel","action","NextAction","create","save","id","success","Error","assignAction","findById","assignTo","completeAction","complete","deleteAction","delete","ActionContext","atCalls","atComputer","atErrands","atHome","atOffice","anywhere","EnergyLevel","high","medium","low","NextActionAggregateRepository","injectable","inject","getMongoDb","NextActionReadService","collection","_repository","db","getMongoDb","getAvailableActions","criteria","context","energyLevel","status","assignedTo","projectId","searchText","offset","limit","query","description","$regex","$options","actions","total","Promise","all","find","sort","createdAt","skip","toArray","countDocuments","actionViews","map","doc","id","_id","toString","estimatedMinutes","createdBy","assignedAt","completedAt","hasMore","getActionById","actionId","findOne","getActionsForReview","personId","$or","length","getActionStatistics","available","assigned","completed","byContext","byEnergy","getCountByField","field","results","aggregate","$group","count","$sum","counts","result","NextActionAggregateRepository","injectable","inject","ArtifactStatus","status","displayName","allowedTransitions","planning","development","review","production","deprecated","fromString","Error","canTransitionTo","newStatus","includes","equals","other","toString","ConformanceScore","metaModelScore","designCoverageScore","confidence","calculatedAt","Date","validateScore","score","field","Error","overallScore","Math","round","isPassingGrade","needsImprovement","create","zero","equals","other","toString","FlowStatus","status","displayName","allowedTransitions","draft","active","completed","abandoned","fromString","Error","canTransitionTo","newStatus","includes","isActive","isCompleted","equals","other","toString","DesignImplementationDomainError","Error","message","code","context","name","FlowStateError","flowId","currentState","ArtifactStateError","artifactId","ArtifactNotFoundError","DesignImplementationDomainError","artifactId","flowId","name","FlowCreated","DomainEvent","flowId","projectId","createdBy","getEventData","ArtifactAdded","artifactId","artifactName","artifactType","addedBy","ConformanceScoreUpdated","previousScore","newScore","updatedBy","FlowCompleted","totalArtifacts","averageConformance","completedBy","ArtifactStatusChanged","previousStatus","newStatus","changedBy","DesignImplementationFlow","domainEvents","_artifacts","_status","FlowStatus","draft","_completedAt","id","projectId","createdBy","createdAt","Date","metaModelBinding","designSpecification","validateFlow","create","generateId","flow","addDomainEvent","FlowCreated","addArtifact","name","type","location","version","tags","isCompleted","FlowStateError","toString","artifactId","generateArtifactId","artifact","status","ArtifactStatus","planning","healthStatus","buildStatus","testStatus","deploymentStatus","lastHealthCheck","lastModified","push","ArtifactAdded","updateArtifactStatus","newStatus","updatedBy","findArtifact","currentStatus","canTransitionTo","ArtifactStateError","previousStatus","fromString","ArtifactStatusChanged","updateConformanceScore","metaModelScore","designCoverageScore","confidence","previousScore","conformanceScore","overallScore","ConformanceScore","newScore","ConformanceScoreUpdated","activate","active","complete","completedBy","completed","metrics","getProgressMetrics","FlowCompleted","totalArtifacts","averageConformance","abandon","abandoned","total","length","filter","a","inProgress","includes","conformanceScores","map","score","reduce","sum","designScores","averageDesignCoverage","completedArtifacts","artifactsInProgress","Math","round","getBlockedArtifacts","blocked","forEach","artifactName","blockReason","severity","needsImprovement","daysSinceUpdate","floor","getTime","isActive","artifacts","completedAt","getDomainEvents","clearDomainEvents","find","ArtifactNotFoundError","trim","event","now","random","substring","injectable","getMongoDb","DesignImplementationFlowRepository","db","collection","ensureConnection","getMongoDb","GTD_COLLECTIONS","DESIGN_IMPLEMENTATION_FLOWS","save","flow","doc","_id","id","projectId","createdBy","createdAt","metaModelBinding","designSpecification","status","toString","artifacts","map","artifact","name","type","version","location","conformanceScore","metaModelScore","designCoverageScore","overallScore","confidence","calculatedAt","healthStatus","lastModified","tags","completedAt","updatedAt","Date","replaceOne","upsert","findById","findOne","mapDocumentToDomain","findByProjectId","docs","find","sort","toArray","safeMapDocumentToDomain","filter","findByStatus","findActiveFlows","findAll","deleteById","deleteOne","DesignImplementationFlow","_status","FlowStatus","fromString","_completedAt","Array","isArray","artifactDoc","ArtifactStatus","ConformanceScore","undefined","buildStatus","testStatus","deploymentStatus","lastHealthCheck","_artifacts","trim","console","warn","error","DesignImplementationFlowApplicationService","flowRepository","createFlow","command","flow","DesignImplementationFlow","create","projectId","createdBy","metaModelBinding","designSpecification","save","success","flowId","id","createdAt","toISOString","message","error","Date","Error","addArtifact","findById","artifactId","name","type","location","version","tags","updateConformanceScore","metaModelScore","designCoverageScore","confidence","updatedBy","updateArtifactStatus","newStatus","completeFlow","completedBy","complete","activateFlow","activate","DesignImplementationFlowRepository","injectable","inject","DesignImplementationFlowReadService","flowRepository","getFlowById","flowId","flow","findById","mapToFlowView","queryFlows","criteria","limit","offset","flows","findAll","projectId","filter","f","status","toString","createdBy","artifactType","artifacts","some","a","type","hasConformanceIssues","conformanceScore","needsImprovement","totalCount","length","paginatedFlows","slice","flowViews","map","hasMore","getFlowsByProjectId","findByProjectId","getActiveFlows","findActiveFlows","getFlowsNeedingAttention","needingAttention","blocked","getBlockedArtifacts","getConformanceSummary","totalArtifacts","totalConformanceSum","artifactsWithScores","artifactsNeedingAttention","forEach","metrics","getProgressMetrics","artifact","overallScore","totalFlows","activeFlows","isActive","completedFlows","isCompleted","averageConformance","Math","round","progressMetrics","blockedArtifacts","id","createdAt","toISOString","completedAt","metaModelBinding","metamodelId","boundAt","validationStatus","undefined","designSpecification","name","version","metaModelScore","designCoverageScore","confidence","healthStatus","buildStatus","testStatus","deploymentStatus","lastHealthCheck","tags","DesignImplementationFlowRepository","WeeklyReviewApplicationService","conductWeeklyReview","params","success","message","reviewId","phases","tool","z","createInboxTools","inboxService","listInboxItems","tool","description","parameters","z","object","status","enum","default","describe","limit","number","execute","result","undefined","Math","min","success","items","map","item","id","content","originalContent","processingStatus","capturedAt","capturedBy","capturedByPersonId","totalCount","message","length","error","Error","addInboxItem","string","personId","priority","optional","command","createInboxItem","itemId","searchInboxItems","query","allItems","filteredItems","filter","toLowerCase","includes","clarification","slice","relevance","resultCount","GTDAIToolsApplicationService","inboxService","getAITools","inboxTools","createInboxTools","getAIToolsMetadata","tools","domain","boundedContext","version","Object","keys","totalTools","length","lastUpdated","Date","toISOString","createGTDAIToolsService","inboxService","GTDAIToolsApplicationService","GTDQueryServiceImpl","inboxRepository","projectRepository","personLookupService","_mongoClient","InboxItemAggregateRepository","ProjectRepository","extractTitle","content","firstLine","split","replace","trim","length","substring","listInboxItems","criteria","items","findByFilters","status","limit","offset","enrichedItems","Promise","all","map","item","capturedByPerson","capturedByPersonId","getPersonById","error","console","warn","id","originalContent","text","title","processingStatus","capturedAt","toISOString","createdAt","capturedBy","clarification","description","isActionable","tags","getInboxItem","findById","listProjects","projects","findByStatus","area","findByArea","findAll","filter","project","name","vision","desiredOutcome","reviewDate","nextActionCount","nextActionIds","getProject","listNextActions","_criteria","createGTDQueryService","mongoClient","GTDServiceFactory","instance","database","initialized","queryService","getInstance","initialize","console","log","error","Error","message","isInitialized","getDatabase","getQueryService","personLookupService","createGTDQueryService","undefined","getHealthStatus","status","healthy","timestamp","Date","toISOString","admin","ping","cleanup","publishedLanguage","domain","name","version","description","capabilities","events","businessRules","integrationPatterns","GTD_INTEGRATION_INFO","context","role","relationships","contracts","stability","BaseApplicationError","GTDFeatureError","BaseApplicationError","code","message","cause","ux","dx","GTDValidationError","GTDDomainIntegrationError","getMongoClient","BaseDomainSeeder","domainName","validateSeededData","client","getMongoClient","db","totalDocuments","validDocuments","invalidDocuments","createSuccessResponse","metrics","success","totalCollections","seedingDurationMs","validationDurationMs","clearExistingData","organizationId","projectId","console","log","createErrorResponse","errorMessage","error","getMongoClient","getMongoConfig","initializeMongoConnection","v4","uuidv4","GTDDataSeeder","testData","organizationId","personId","inboxItems","content","source","priority","isProcessed","projects","title","description","desiredOutcome","status","nextActions","context","energyLevel","estimatedMinutes","referenceItems","category","tags","setupMongo","mongoConfig","uri","process","env","MONGODB_URL","dbName","MONGODB_DB_NAME","console","log","initializeMongoConnection","run","clearExistingData","seedInboxItems","projectIds","seedProjects","seedNextActions","seedReferenceItems","verifyDataIntegrity","length","error","mongoClient","getMongoClient","config","getMongoConfig","db","collection","GTD_COLLECTIONS","INBOX_ITEMS","deleteMany","capturedByPersonId","PROJECTS","ownerId","NEXT_ACTIONS","assignedToPersonId","REFERENCE_ITEMS","itemsToSeed","Date","toISOString","itemData","itemId","uuidv4","inboxItem","id","capturedAt","processedAt","processedByPersonId","createdAt","updatedAt","insertOne","substring","projectData","projectId","project","startDate","targetDate","completedDate","index","actionData","entries","actionId","linkedProjectId","Object","values","nextAction","dueDate","refData","refId","referenceItem","referenceId","isArchived","inboxCount","countDocuments","projectCount","actionCount","refCount","join","url","argv","seeder","then","exit","catch","getMongoClient","getMongoConfig","GtdDomainSeeder","BaseDomainSeeder","seedDomain","_organizationId","_projectId","seedingStartTime","Date","now","console","log","domainName","gtdSeeder","GTDDataSeeder","run","seedingDurationMs","validationStartTime","validationResult","validateSeededData","validationDurationMs","createSuccessResponse","totalCollections","totalDocuments","validDocuments","invalidDocuments","error","errorMessage","Error","message","createErrorResponse","mongoClient","getMongoClient","config","getMongoConfig","db","dbName","personId","collections","Object","values","GTD_COLLECTIONS","errors","collectionName","coll","collection","docs","INBOX_ITEMS","find","capturedByPersonId","toArray","PROJECTS","ownerId","NEXT_ACTIONS","assignedToPersonId","REFERENCE_ITEMS","SOMEDAY_MAYBE","length","doc","validation","validateDocument","isValid","push","id","itemId","content","capturedAt","projectId","title","status","actionId","description","context","referenceId","category","createGtdDomainSeeder","ContainerModule","getMongoDb","AggregateRoot","z","InboxItemSchema","object","id","string","describe","title","description","context","optional","actionability","enum","nextSteps","array","status","default","owner","due","processed","boolean","createdAt","updatedAt","assignedTo","roleType","assignedAt","TaskSchema","priority","duration","number","inboxItemId","completedAt","productId","blockedReason","blockedAt","ProjectSchema","tasks","progress","ContextSchema","name","color","ProgressUpdateSchema","projectId","taskId","blockers","timestamp","TodayItemSchema","scheduledTime","completed","date","NudgeSchema","message","type","dismissed","NextActionSchema","text","done","category","fileName","fileCreatedAt","fileModifiedAt","fileSize","lineNumber","EntityId","TaskId","EntityId","value","trim","length","Error","toString","fromString","generate","timestamp","Date","now","random","Math","substring","TaskAssigned","type","eventType","occurredOn","occurredAt","eventVersion","aggregateId","partyId","roleType","assignedAt","Date","fromLegacy","taskId","TaskCompleted","type","occurredAt","eventVersion","data","aggregateId","completedBy","completedAt","Date","TaskAggregate","AggregateRoot","id","props","fromDTO","dto","TaskId","fromString","create","generate","task","toString","assignTo","partyId","roleType","status","Error","apply","TaskAssigned","getId","Date","onTaskAssigned","event","assignedTo","assignedAt","toISOString","complete","completedBy","TaskCompleted","onTaskCompleted","completedAt","block","reason","blockedReason","blockedAt","unblock","undefined","toDTO","TaskSchema","parse","TaskMongoRepository","collectionName","GTD_COLLECTIONS","TASK_ASSIGNMENTS","save","task","dto","toDTO","assignment","productId","taskId","id","partyId","assignedTo","roleType","assignedAt","db","getMongoDb","collection","updateOne","$set","upsert","getById","doc","findOne","Error","TaskSchema","parse","title","context","priority","status","inboxItemId","undefined","due","createdAt","Date","toISOString","updatedAt","TaskAggregate","fromDTO","listByProduct","docs","find","toArray","map","fs","path","v4","uuidv4","z","PlanSummaryViewModel","object","id","string","describe","title","status","enum","tasks","total","number","int","min","completed","PlanSummaryListViewModel","array","MilestoneViewModel","name","PlanTaskItemViewModel","text","default","dependencies","optional","PlanTaskSectionViewModel","items","PlanViewModel","objective","implementationGoals","milestones","taskSections","InboxFileRepository","baseDir","processedDir","path","join","process","env","SWOFT_MONO_REPOS_ROOT","cwd","getInboxItems","ensureDirs","files","fs","readdir","items","file","endsWith","filePath","content","readFile","obj","JSON","parse","push","InboxItemSchema","createInboxItem","text","source","now","Date","toISOString","id","uuidv4","item","processed","createdAt","updatedAt","writeFile","stringify","mkdir","recursive","promises","fs","path","NextActionsFileRepository","dir","gtdDir","fsRoot","process","env","GTD_FILE_SYSTEM","path","resolve","cwd","join","getNextActions","files","fs","readdir","actions","file","filter","f","endsWith","category","replace","filePath","stats","stat","content","readFile","lines","split","idx","length","match","done","text","trim","id","action","NextActionSchema","parse","fileName","fileCreatedAt","birthtime","toISOString","fileModifiedAt","mtime","fileSize","size","lineNumber","push","GTD_DOMAIN_SYMBOLS","TYPES","createGTDDomainModule","ContainerModule","bind","InboxItemAggregateRepository","to","inSingletonScope","GTDProcessingWorkflowService","InboxImportExportService","InboxItemApplicationService","ProjectRepository","NextActionAggregateRepository","NextActionWriteService","NextActionReadService","ProjectApplicationService","ProjectReadService","ITaskRepository","TaskMongoRepository","InboxFileRepository","NextActionsFileRepository","DesignImplementationFlowRepository","DesignImplementationFlowApplicationService","DesignImplementationFlowReadService","GTDDomainRules","domainName","version","description","maintainer","namingRules","pattern","examples","integrationRules","type","allowedIntegrations","restrictedIntegrations","architecturalRules","category","rule","rationale","exceptions","capabilities","name","businessValue","technicalComplexity","getNamingRules","getIntegrationRules","getArchitecturalRules","getCapabilities","getEventMetadata","events","eventName","producedBy","consumedBy","schema","validateNaming","find","r","isValid","violations","suggestions","isGTDTerm","push","isGTDWorkflowVerb","isPastTense","length","validateIntegration","targetDomain","integrationType","includes","recommendations","calculateHealthScore","namingScore","integrationScore","architectureScore","capabilitiesScore","Math","min","totalScore","round","score","breakdown","naming","integration","architecture","gtdTerms","some","term","toLowerCase","gtdVerbs","verb","startsWith","parts","split","lastPart","endsWithPastTense","word","endsWith","past","createGTDDomainRules"]}