graphql-schema-contract
category: architecture last_updated: 2025-11-17 tags: [graphql, schema, contract, m57, m58, m70, m78, secrets-management, socratic-inquiry-engine, constraint-shift-detection, decision-freshness] title: "GraphQL Schema Contract" sidebar_label: "GraphQL Schema" author: "Gemini, Pramod Prasanth" milestone: "M78" status: "IMPLEMENTED"
import DocInfo from '@site/src/components/DocInfo';
GraphQL Schema Contract
Status: ✅ FULLY IMPLEMENTED (M57 Phase 1 + M58 Secrets Management + M70 Socratic Inquiry Engine + M78 Constraint Shift Detection)
This document outlines the GraphQL schema for the ChainAlign project, focusing on the relationships between core data entities. The TaskAlign schema (Task Management) has been fully implemented in Milestone M57 with complete resolver support. Milestone M58 adds comprehensive secrets management integration with Infisical vault. Milestone M70 adds dynamic Socratic question generation for decision-making processes. Milestone M78 adds constraint shift detection and decision freshness monitoring based on Theory of Constraints principles.
Implementation Status
- ✅ M57 Task 7: GraphQL Schema definition (
taskSchema.graphql) - COMPLETE - ✅ M57 Task 8: GraphQL Resolvers (all 16 resolvers) - COMPLETE
- ✅ M57 Test Coverage: 56/56 tests passing (100%)
- 🔄 M57 Task 9: GraphQL Server integration (Apollo setup) - PENDING
- ✅ M58 Task 1: GraphQL Resolvers for Secrets (12 resolvers) - COMPLETE
- ✅ M58 Task 2: GraphQL Type Definitions for Secrets - COMPLETE
- ✅ M58 Task 3: SecretsRepository DAL Layer - COMPLETE
- ✅ M58 Task 4: SecretsVaultService (Infisical integration) - COMPLETE
- ✅ M60 Task 27.6: SIE Workflow GraphQL mutation and REST endpoint - COMPLETE
- ✅ M60 Task 27.6:
orchestrateSIEWorkflowmutation withSIEWorkflowInputandSIEWorkflowResulttypes - COMPLETE - ✅ M60 Task 27.6: Integration tests for SIE workflow orchestration - COMPLETE
- ✅ M60 Task 1.1-1.6: OrchestratedNarrativeService Integration - COMPLETE
- Task 1.1: Integration test for narrative pipeline - COMPLETE
- Task 1.2: GraphQL Narrative types (Headline, ExecutiveSummary, NarrativeDetails, etc.) - COMPLETE
- Task 1.3: Service integration with DecisionOrchestrationService - COMPLETE
- Task 1.4: GraphQL resolvers (Query: orchestrationResult/Results, Mutation: reOrchestrate/logDecision) - COMPLETE
- Task 1.5: React hook useOrchestrateDecision with Apollo Client integration - COMPLETE
- Task 1.6: Integration test verification (4/4 tests passing) - COMPLETE
- ✅ M63 Task X.Y:
metricsOverviewQuery and associated types - COMPLETE - ✅ M63 Task X.Z:
Subscriptiontype and real-time event types (ScenarioExecuted,CycleCreated,CacheInvalidated) - COMPLETE - ✅ M70 Phase 4: GraphQL Schema Types for Socratic Inquiry Engine - COMPLETE
- ✅
SocraticQuestiontype with category, contextSnippets, and user response tracking - ✅
HumanJudgmenttype for Contextual Alignment Buffer (CAB) - ✅
ProblemStateVectortype for refined strategic priorities with vector embeddings - ✅
ContextSnippettype for source attribution and transparency - ✅
DecisionContextInputinput type for question generation - ✅
HumanJudgmentInputinput type for capturing responses - ✅
CaptureJudgmentResponseandFlagQuestionResponseresponse types - ✅ 2 queries:
socraticQuestions,problemStateVector - ✅ 3 mutations:
generateSocraticQuestions,captureHumanJudgment,flagImpactfulQuestion
- ✅
- ✅ M70 Phase 3: GraphQL Resolvers for Socratic Inquiry Engine - COMPLETE
- ✅ All 5 resolvers implemented with comprehensive error handling
- ✅ Integration with SocraticInquiryService, DAL repositories
- ✅ Snake-to-camel case field transformation for frontend compatibility
- ✅ M78 Phase 3: GraphQL Schema Types for Constraint Shift Detection & Decision Freshness - COMPLETE
- ✅
ConstraintShiftLogtype for audit trail of detected shifts - ✅
DecisionFreshnesstype for tracking decision validity - ✅
FreshnessSummarytype for health dashboard metrics - ✅
ConstraintShiftDetectionResulttype for shift analysis results - ✅ 6 queries:
unacknowledgedShifts,freshnessSummary,decisionsNeedingReview,decisionFreshness,constraintShiftHistory,constraintUtilizationHistory - ✅ 7 mutations:
detectConstraintShift,monitorAllConstraints,recordConstraintUtilization,acknowledgeConstraintShift,flagStaleDecisions,initializeFreshnessTracking,markDecisionReviewed - ✅ TOC principle integration: When constraint shifts, decisions need review
- ✅
All queries and mutations listed below have been fully implemented and tested.
I. Core Types & Sources
This section maps GraphQL types to their responsible services and underlying data sources.
| GraphQL Type | Owning Service/File | Primary Data Source(s) | Description |
|---|---|---|---|
| User | schema.graphql | users table | Represents an authenticated user, used for audit trails and ownership. |
| MLConfig | schema.graphql | ml_configs table | Stores configuration for the adaptive forecasting models. |
| Constraint | schema.graphql | constraints table | Defines operational or financial constraints (Hard, Soft, Dynamic). |
| Note | schema.graphql | notes table | Captures raw, unstructured text inputs that can be promoted to DecisionProblem. |
| Scenario | schema.graphql | scenarios table | Represents a potential solution or course of action for a DecisionProblem. |
| DecisionProblem | schema.graphql | decision_problems table | A structured problem derived from a Note, linking to potential Scenarios and Decisions. |
| Decision | schema.graphql | decisions table | An immutable record of a choice made, linking a DecisionProblem to a chosen Scenario. |
| DecisionTask | schema.graphql | decision_tasks table | An actionable task generated from a Decision, part of the Decision Loop. |
| ExternalSync | schema.graphql | external_syncs table | Tracks the synchronization of a DecisionTask with an external system like Linear or Jira. |
| Task | taskSchema.graphql | tasks table | A core task in the TaskAlign system, with support for hierarchy and dependencies. |
| TaskComment | taskSchema.graphql | task_comments table | A comment on a Task. |
| Milestone | taskSchema.graphql | milestones table | An aggregation of Tasks for progress tracking. |
| WorkSession | taskSchema.graphql | work_sessions table | A checkpoint of a user's work context for session continuity. |
| ScenarioSession | schema.graphql | In-memory/Cache | A session for real-time scenario analysis with a 4-tier pipeline. Persisted results may go to other tables. |
| SIEWorkflowInput | schema.graphql | In-Memory/Service | Input for Strategic Inquiry Engine workflow combining problem state (Tier 1) and scenario selection (Tier 2). Includes objectives, prioritization, constraints, risks, and trade-offs (M60). |
| SIEWorkflowResult | schema.graphql | PostgreSQL (telemetry) | Result of SIE orchestration including Bayesian probabilities, robustness scores, VOI analysis, optimizer recommendations, and orchestrated narrative with confidence bounds (M60). |
| Narrative | schema.graphql | Generated by OrchestratedNarrativeService | Complete narrative structure from orchestration including headline, executive summary, detailed analysis sections, caveats, and SIE prompt for audit trail (M60 Task 1). |
| Headline | schema.graphql | Narrative sub-type | Action-oriented headline with business implication and confidence score. |
| ExecutiveSummary | schema.graphql | Narrative sub-type | Summary with key risk, trade-off analysis, and data value assessment. |
| NarrativeDetails | schema.graphql | Narrative sub-type | Detailed findings from Bayesian, robustness, VOI, and optimizer analysis stages. |
| NarrativeDetail | schema.graphql | Narrative sub-type | Individual detail section with title, summary, findings, business implications, and recommendations. |
| KeyRisk | schema.graphql | Narrative sub-type | Risk assessment with title, impact, and probability. |
| TradeOff | schema.graphql | Narrative sub-type | Trade-off analysis with description and implications. |
| DataValue | schema.graphql | Narrative sub-type | Data relevance assessment with gaps and recommendations. |
| SIEPrompt | schema.graphql | Narrative sub-type | System and user prompts used to generate narrative for reproducibility and audit. |
| OrchestrationResult | schema.graphql | orchestration_results table | Complete result of decision orchestration including narrative, all analytical results, and execution metadata (M60 Task 1). |
| SecretMetadata | secretsTypeDefs.graphql | secrets_metadata table | Metadata about secrets managed via Infisical vault, including lifecycle status and rotation tracking (M58). |
| SecretAccessLog | secretsTypeDefs.graphql | secret_access_logs table | Audit trail of all secret accesses (read, update, rotate, revoke, create, delete) for compliance (M58). |
| SecretAuditTrail | secretsTypeDefs.graphql | secret_audit_trails table | Immutable change history for all secret metadata modifications, with before/after snapshots (M58). |
| Metric | schema.graphql | Calculated/Aggregated | Represents a single metric with a name, value, and unit. |
| MetricsOverview | schema.graphql | Calculated/Aggregated | Aggregates multiple metrics for a high-level overview. |
| ScenarioExecuted | schema.graphql | Real-time event stream | Real-time event indicating a scenario execution has completed. |
| CycleCreated | schema.graphql | Real-time event stream | Real-time event indicating a new SOP cycle has been created. |
| CacheInvalidated | schema.graphql | Real-time event stream | Real-time event indicating a cache entry has been invalidated. |
| MetricInput | schema.graphql | Input type | Input for recording custom metrics, including name, value, and optional tags. |
| CustomMetricResult | schema.graphql | Calculated/Aggregated | Result of recording a custom metric, including its ID, name, value, tags, and timestamp. |
| SocraticQuestion | schema.graphql | socratic_questions table | AI-generated question for decision-making, with category, context snippets, and optional user response tracking (M70). |
| HumanJudgment | schema.graphql | human_judgments table | Contextual Alignment Buffer (CAB) - immutable audit trail of user responses to Socratic questions with optional impact rating (M70). |
| ProblemStateVector | schema.graphql | problem_state_vectors table | Refined strategic priorities aggregated from human judgments, stored as vector embeddings for semantic search (M70). |
| ContextSnippet | schema.graphql | Embedded in JSONB | Source snippet from Strategic North, Historical Failures, or Constraints that informed a Socratic question (M70). |
| DecisionContextInput | schema.graphql | Input type | Input for generating Socratic questions, including decision context, type, and scope (M70). |
| HumanJudgmentInput | schema.graphql | Input type | Input for capturing human judgment/response to a Socratic question with optional impact rating (M70). |
| CaptureJudgmentResponse | schema.graphql | Response type | Response from capturing a human judgment, including success flag, audit trail ID, and judgment details (M70). |
| FlagQuestionResponse | schema.graphql | Response type | Response from flagging a question as impactful, including success flag and updated question (M70). |
| DecisionFilterPreset | decisionsTypeDefs.graphql (M71) | decision_filter_presets table | User-saved filter configurations for Decision History Feed with usage tracking (M71 Phase 1.2). |
| CounterfactualSimulation | decisionsTypeDefs.graphql (M71) | counterfactual_simulations table | "Re-Run Simulation" results for time-travel decision analysis with temporal change detection (M71 Phase 1.3). |
| ConstraintShiftLog | schema.graphql (M78) | constraint_shift_logs table | Audit trail for detected constraint shifts with acknowledgment workflow and TOC-based shift classification (M78 Phase 2). |
| ConstraintUtilizationHistory | schema.graphql (M78) | constraint_utilization_history table | Daily utilization measurements for constraint shift pattern analysis (M78 Phase 2). |
| DecisionFreshness | schema.graphql (M78) | decision_freshness table | Tracks validity status of decisions relative to constraint changes with review workflow (M78 Phase 2). |
| FreshnessSummary | schema.graphql (M78) | Calculated/Aggregated | Health dashboard metrics showing % of CURRENT decisions vs REVIEW_RECOMMENDED/STALE (M78 Phase 2). |
| ConstraintShiftDetectionResult | schema.graphql (M78) | Service result | Result of analyzing constraint for shift (utilization drop + throughput maintained = shift detected) (M78 Phase 2). |
| FlagStaleDecisionsResult | schema.graphql (M78) | Service result | Result of flagging decisions after constraint shift, includes affected decision IDs (M78 Phase 2). |
| MarkReviewedResult | schema.graphql (M78) | Service result | Result of reviewing a decision with CONFIRM or UPDATE action (M78 Phase 2). |
| MonitorConstraintsResult | schema.graphql (M78) | Service result | Batch monitoring result for all tenant constraints showing shifts detected (M78 Phase 2). |
II. Relationships & Traversal
This section explains how the core GraphQL types are interconnected.
Decision Intelligence Flow (schema.graphql)
The core workflow of the Constraint Intelligence Engine is as follows:
- A
Noteis created to capture raw input. - The
Notecan be promoted to aDecisionProblem, which formalizes the issue.DecisionProblem.sourceNote->Note
- Multiple
Scenariotypes can be linked to aDecisionProblem, representing different solutions.DecisionProblem.linkedScenarios->[Scenario]
- A
Decisionis made, immutably linking theDecisionProblemto a single, chosenScenario.Decision.problem->DecisionProblemDecision.chosenScenario->Scenario
- The
DecisiongeneratesDecisionTaskitems to be executed.Decision.executionTasks->[DecisionTask]DecisionTask.originDecision->Decision
- A
DecisionTaskcan be synced to an external system, creating anExternalSyncrecord.DecisionTask.externalSync->ExternalSyncExternalSync.task->DecisionTask
Task Management (taskSchema.graphql - M57 Phase 1)
The TaskAlign system manages tasks and their relationships with full multi-tenant support:
-
A
Taskis the core entity with hierarchical relationships.Task.parentTask->Task(optional parent for hierarchical tasks)Task.subtasks->[Task]!(list of child tasks)Task.dependencies->[Task]!(task dependencies/blockers)Task.comments->[TaskComment]!(threaded comments)- Fields:
taskId,pseudoId(human-readable ID),title,description,project,milestone,status,priority, timestamps, effort tracking - Status enum: PENDING, IN_PROGRESS, COMPLETED, BLOCKED, CANCELLED
- Priority enum: LOW, MEDIUM, HIGH, CRITICAL
-
A
TaskCommentis linked to a singleTaskfor collaboration.TaskComment.task->Task!- Fields:
commentId,user,content, timestamps
-
A
Milestoneaggregates multipleTaskitems with progress tracking.Milestone.tasks->[Task]!- Aggregates:
taskCount,completedCount,progress(percentage) - Document links:
fsdApprovedAt,fsdApprovedBy
-
A
WorkSessionis associated with aTaskto save work context for session continuity.WorkSession.task->Task(optional - session might not be tied to specific task)- Fields:
sessionId,milestone,fsdSection,filesInProgress,startedAt,endedAt,summary,tokenEstimate - Enables resume functionality (target: <30 second recovery)
III. Queries & Read Operations
This section documents the key read operations available in the GraphQL schema.
Socratic Inquiry Engine Queries (schema.graphql - M70)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
socraticQuestions | decisionId (ID!) | [SocraticQuestion!]! | Returns all Socratic questions generated for a decision, including user responses and impact ratings. | Authenticated user. Scoped to user's tenant. |
problemStateVector | decisionId (ID!) | ProblemStateVector | Returns the refined problem state vector (strategic priorities) aggregated from human judgments for a decision. Includes vector embedding for semantic search. | Authenticated user. Scoped to user's tenant. |
Orchestration Queries (schema.graphql - M60 Task 1)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
orchestrationResult | tenantId (ID!), scenarioId (ID!) | OrchestrationResult | Returns orchestration result by tenant and scenario ID, including complete narrative structure with all analysis components. | Authenticated user. Scoped to user's tenant. |
orchestrationResults | tenantId (ID!), limit (Int), offset (Int) | [OrchestrationResult!]! | Returns paginated list of orchestration results for a tenant with optional limit and offset. | Authenticated user. Scoped to user's tenant. |
metricsOverview | tenantId (ID!) | MetricsOverview | Returns an overview of key metrics for a given tenant. | Authenticated user. Scoped to user's tenant. |
metrics | tenantId (ID!), metricName (String!), filters (JSON) | [Metric!]! | Returns specific metrics by name with optional filters for a given tenant. | Authenticated user. Scoped to user's tenant. |
Task Management Queries (taskSchema.graphql - M57)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
tasks | project (String), milestone (String), status (TaskStatus) | [Task!]! | Returns filtered list of tasks. All filters are optional. Supports pagination. | Authenticated user. Scoped to user's tenant. |
task | taskId (ID!) | Task | Returns a single task by ID. | Authenticated user. Scoped to user's tenant. |
taskByPseudoId | pseudoId (String!) | Task | Returns a single task by human-readable pseudo-ID (e.g., CHA-M57-001). | Authenticated user. Scoped to user's tenant. |
milestones | project (String!) | [Milestone!]! | Returns all milestones for a project with aggregated progress. | Authenticated user. Scoped to user's tenant. |
milestone | milestoneId (String!) | Milestone | Returns a single milestone with task list and progress. | Authenticated user. Scoped to user's tenant. |
resumeContext | (none) | WorkSession | Returns the active/most recent work session for the authenticated user. Enables session recovery. | Authenticated user. |
sessionHistory | limit (Int) | [WorkSession!]! | Returns historical work sessions for the authenticated user (paginated with optional limit). | Authenticated user. |
Secrets Management Queries (secretsTypeDefs.graphql - M58)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
secret | id (ID!) | SecretMetadata | Returns a single secret by ID with full metadata. | Authenticated user. Scoped to user's tenant. Logs access for audit trail. |
secretByName | name (String!) | SecretMetadata | Returns a secret by human-readable name (tenant-scoped). | Authenticated user. Scoped to user's tenant. Logs access for audit trail. |
secrets | status (SecretStatus), environment (SecretEnvironment) | [SecretMetadata!]! | Lists all secrets for tenant, optionally filtered by status and environment. | Authenticated user. Scoped to user's tenant. |
secretsNeedingRotation | (none) | [SecretMetadata!]! | Returns secrets with rotation due (rotation_scheduled_at <= now). | Authenticated user. Scoped to user's tenant. Admin/DevOps role expected. |
secretAccessLogs | secretId (ID!), limit (Int), offset (Int) | [SecretAccessLog!]! | Returns paginated access audit trail for a secret. | Authenticated user. Scoped to user's tenant. Audit/compliance role expected. |
secretAuditTrail | secretId (ID!), limit (Int), offset (Int) | [SecretAuditTrail!]! | Returns paginated change history for a secret (immutable). | Authenticated user. Scoped to user's tenant. Audit/compliance role expected. |
Decision History Feed Queries (decisionsTypeDefs.graphql - M71)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
decisions | filters (DecisionFiltersInput), limit (Int), offset (Int) | DecisionHistoryResponse! | Returns paginated list of decisions with Ferrari Stack enrichments (Zep summaries, Graphiti context, Monte Carlo sparklines). Supports filtering by decision_mode, date_range, semantic_query, entities, status. | Authenticated user. Scoped to user's tenant. |
decision | id (ID!) | Decision | Returns a single decision with full Ferrari Stack context (related_decisions, knowledge_graph_context). | Authenticated user. Scoped to user's tenant. |
semanticSearchDecisions | query (String!), limit (Int) | [Decision!]! | Semantic search across decision history using pgvector embeddings. Query is concept-based, not keyword-based. Example: "risky supplier decisions in Q3". | Authenticated user. Scoped to user's tenant. Uses summary_embedding HNSW index. |
getFilterPresets | (none) | [DecisionFilterPreset!]! | Returns all filter presets for the authenticated user (both personal and shared team presets). | Authenticated user. Scoped to user's tenant. |
getCounterfactualAnalysis | decisionId (ID!) | CounterfactualSimulation | Returns the most recent counterfactual analysis for a decision (cached if available). | Authenticated user. Scoped to user's tenant. |
Constraint Shift Detection & Decision Freshness Queries (schema.graphql - M78)
| Query | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
unacknowledgedShifts | (none) | [ConstraintShiftLog!]! | Returns all constraint shifts that haven't been acknowledged by the user. Shows shifts needing attention. | Authenticated user. Scoped to user's tenant. |
freshnessSummary | (none) | FreshnessSummary! | Returns health dashboard metrics: counts by status (CURRENT, REVIEW_RECOMMENDED, STALE) and overall health score (% CURRENT). | Authenticated user. Scoped to user's tenant. |
decisionsNeedingReview | status (FreshnessStatus), page (Int), limit (Int) | DecisionsNeedingReviewResponse! | Returns paginated decisions needing review. Filters by REVIEW_RECOMMENDED or STALE status. Max 100 items per page. | Authenticated user. Scoped to user's tenant. |
decisionFreshness | decisionId (ID!) | DecisionFreshness | Returns freshness status for a specific decision. Includes daysSinceUpdate and requiresReview computed fields. | Authenticated user. Scoped to user's tenant. |
constraintShiftHistory | constraintId (ID!), limit (Int) | [ConstraintShiftLog!]! | Returns all detected shifts for a specific constraint with their details (old/new utilization, shift type, acknowledgment status). | Authenticated user. Scoped to user's tenant. |
constraintUtilizationHistory | constraintId (ID!), daysBack (Int) | [ConstraintUtilizationHistory!]! | Returns daily utilization measurements for a constraint. Used for trend analysis and shift detection patterns. | Authenticated user. Scoped to user's tenant. |
IV. Mutations & Write Operations
This section documents the key write operations in the GraphQL schema.
| Mutation | Input(s) | Returns | Description | Security Context |
|---|---|---|---|---|
| Socratic Inquiry Engine (M70) | ||||
generateSocraticQuestions | DecisionContextInput (decisionId!, decisionContext!, decisionType!, decisionScope!) | [SocraticQuestion!]! | Generates AI-powered Socratic questions for a decision using LLM + GraphRAG. Retrieves context from Strategic North, Historical Failures, and Constraints. Returns questions across 5 categories (assumptions, risks, trade-offs, constraints, alternatives). | Authenticated user. Scoped to user's tenant. |
captureHumanJudgment | HumanJudgmentInput (questionId!, decisionId!, responseText!, impactRating?) | CaptureJudgmentResponse | Captures user's response to a Socratic question in the Contextual Alignment Buffer (CAB). Optional impact rating (1-5). Returns success flag, audit trail ID, and judgment details. Immutable for compliance. | Authenticated user. Scoped to user's tenant. Must be the decision creator or collaborator. |
flagImpactfulQuestion | questionId! (ID!), impactRating! (Int!) | FlagQuestionResponse | Flags a Socratic question as impactful with a rating (1-5). Updates question metadata and logs who flagged it. Returns success flag and updated question. | Authenticated user. Scoped to user's tenant. |
| Orchestration & Narrative (M60 Task 1) | ||||
reOrchestrate | ReOrchestrationInput (tenantId!, scenarioId!, skipServices?, forceRecompute?) | OrchestrationResult | Re-runs orchestration for a scenario with optional service skipping and cache bypass. Returns complete orchestration result with narrative. | Authenticated user. Scoped to user's tenant. |
logDecisionToReasoningBank | LogDecisionInput (tenantId!, orchestrationId!, decision!, rationale!, outcome?) | String | Logs an executed decision to the reasoning bank for future reference and analysis. | Authenticated user. Scoped to user's tenant. |
| Decision Intelligence | ||||
recordFinalDecision | problemId, chosenScenarioId, rationale | Records a final, immutable decision, linking a problem to a chosen scenario. This is a critical step in the audit trail. | Requires AUTH_ROLE: EXECUTIVE (assumed). | |
createTaskFromDecision | decisionId, taskType, assigneeId | Creates a DecisionTask from a Decision. An LLM can be used to generate the task details based on the decision context. | Requires AUTH_ROLE: MANAGER (assumed). | |
updateTaskStatus | taskId, status | Updates the status of a DecisionTask and can trigger a sync to an external system. | Requires user to be the assignee or a manager. | |
syncTaskToExternal | taskId, system | Pushes a DecisionTask to an external system like Linear or Jira, creating an ExternalSync record. | Requires AUTH_ROLE: MANAGER (assumed). | |
createScenarioSession | parameters | Creates a new real-time scenario analysis session. | Authenticated user. | |
updateScenarioParameter | sessionId, paramKey, paramValue | Updates a parameter in a ScenarioSession and triggers a re-analysis through the 4-tier pipeline. | User must be the creator of the session. | |
orchestrateSIEWorkflow | SIEWorkflowInput (tenantId!, problemStateVector!, selectedScenarioId!, orchestrationConfig) | SIEWorkflowResult | Executes complete SIE workflow: combines Tier 1 problem state + Tier 2 scenario selection for orchestration. Runs 5-stage pipeline: Bayesian → Robustness+VOI → Optimizer → Narrative. Returns decision analysis with scores and recommendations. | Authenticated user. Scoped to user's tenant. |
| Task Management (M57) | ||||
createTask | CreateTaskInput (title!, description, project!, milestone!, priority, parentTaskId, dueDate, estimatedHours, tags) | Creates a new task in the TaskAlign system with auto-generated pseudo-ID. Supports hierarchical tasks (parentTaskId) and dependency tracking. | Authenticated user. Scoped to user's tenant. | |
updateTask | taskId!, UpdateTaskInput (title, description, status, priority, dueDate, estimatedHours, actualHours, tags) | Updates an existing task. Partial updates supported - only provided fields are modified. | User must be the creator or have edit permissions. | |
completeTask | taskId!, actualHours (Float optional) | Marks a task as COMPLETED with optional time tracking. Automatically sets completedAt timestamp. | Authenticated user. Must have edit permission on task. | |
startTask | taskId! | Transitions a task to IN_PROGRESS status. Automatically sets startedAt timestamp. | Authenticated user. Must have edit permission on task. | |
addComment | taskId!, content! (String) | Adds a comment to a task for collaboration and threaded discussions. | Authenticated user. Scoped to user's tenant. | |
checkpointSession | CheckpointInput (taskId!, summary!, files, fsdSection) | Saves the current work session context for session continuity. Enables <30 second resume. | Authenticated user. Scoped to user's tenant. | |
| Secrets Management (M58) | ||||
createSecret | CreateSecretInput (name!, secretType!, description?, tags?, environment) | SecretMetadata | Creates new secret metadata and syncs with Infisical vault. Returns metadata with generated ID. | Authenticated user. Requires SECRETS_MANAGER role. Scoped to user's tenant. |
updateSecret | secretId!, UpdateSecretInput (description, tags, environment, status) | SecretMetadata | Updates secret metadata (not the actual secret value). Logs audit trail of changes. | Authenticated user. Requires SECRETS_MANAGER role. Must be tenant admin or secret creator. |
rotateSecret | secretId!, rotationScheduledAt (DateTime!) | SecretMetadata | Schedules secret for rotation. Updates metadata and logs audit event. | Authenticated user. Requires SECRETS_MANAGER role. Typically initiated by deployment pipeline. |
revokeSecret | secretId!, reason (String!) | SecretMetadata | Revokes secret immediately (marks as revoked). Cannot be undone. Logs reason in audit trail. | Authenticated user. Requires SECRETS_ADMIN role (restricted). Logs unauthorized attempts. |
restoreSecret | secretId! | SecretMetadata | Restores a revoked secret back to active (only by SECRETS_ADMIN). Logs restoration event. | Authenticated user. Requires SECRETS_ADMIN role. Restricted operation with heavy audit logging. |
rollbackScenarioVersion | tenantId (ID!), cycleId (ID!), versionNumber (Int!) | ScenarioVersion | Rolls back a scenario to a previous version. | Authenticated user. Scoped to user's tenant. |
recordCustomMetric | tenantId (ID!), metric (MetricInput!) | CustomMetricResult | Records a custom metric for a given tenant. | Authenticated user. Scoped to user's tenant. |
| Decision History Feed (M71) | ||||
createFilterPreset | CreateFilterPresetInput (name!, description?, filterConfig!, isDefault?, isShared?) | DecisionFilterPreset! | Creates a new filter preset for Decision History Feed. Filter config includes decision_mode, status, date_range, semantic_query, entities. Only one preset can be marked as default per user. | Authenticated user. Scoped to user's tenant. |
updateFilterPreset | presetId!, UpdateFilterPresetInput (name?, description?, filterConfig?, isDefault?, isShared?) | DecisionFilterPreset! | Updates an existing filter preset. Partial updates supported. If isDefault=true, all other presets for user are set to isDefault=false. | User must be preset creator or tenant admin. |
deleteFilterPreset | presetId! | Boolean! | Deletes a filter preset. Shared presets can only be deleted by tenant admin. | User must be preset creator or tenant admin. |
runCounterfactualAnalysis | decisionId! | CounterfactualSimulation! | Triggers "Re-Run Simulation" for a decision. Calls CogneeService.detectTemporalChanges() to identify what changed, re-runs MonteCarloService with current constraints, and returns comparison with recommendation ('still_optimal', 'suboptimal', 'significantly_worse', 'reversed'). Results are cached for performance. | Authenticated user. Scoped to user's tenant. Computationally expensive operation. |
| Constraint Shift Detection & Decision Freshness (M78) | ||||
detectConstraintShift | constraintId!, historicalMetrics (JSON) | ConstraintShiftDetectionResult! | Detects if a constraint has shifted using TOC principles. Shift detected when: utilization drops >15% AND throughput maintained. Returns shift type (ELEVATED, ADDRESSED, UNKNOWN) and logs to audit trail if shift detected. | Authenticated user. Scoped to user's tenant. |
monitorAllConstraints | (none) | MonitorConstraintsResult! | Batch operation to check all active tenant constraints for shifts. Returns summary with total monitored and shifts detected. | Authenticated user. Scoped to user's tenant. Scheduled job typically. |
recordConstraintUtilization | RecordUtilizationInput (constraintId!, utilizationPercent!, throughputRate?, measurementDate?) | ConstraintUtilizationHistory! | Records daily utilization measurement for a constraint. Used to build historical patterns for shift detection. | Authenticated user. Scoped to user's tenant. Called by monitoring pipeline. |
acknowledgeConstraintShift | AcknowledgeShiftInput (shiftLogId!, notes?) | ConstraintShiftLog! | Marks a detected constraint shift as acknowledged by user. Updates acknowledgment status and logs who acknowledged. | Authenticated user. Scoped to user's tenant. User must have shift management permissions. |
flagStaleDecisions | FlagStaleDecisionsInput (oldConstraintId!, shiftLogId!, newConstraintId?) | FlagStaleDecisionsResult! | Flags all decisions based on shifted constraint as REVIEW_RECOMMENDED. TOC principle: when constraint shifts, old optimizations need review. Returns count of flagged decisions and affected IDs. | Authenticated user. Scoped to user's tenant. Triggered after shift detection. |
initializeFreshnessTracking | InitializeFreshnessInput (decisionId!, constraintId!) | DecisionFreshness! | Initializes freshness tracking when decision is created. Sets status to CURRENT. Upserts on conflict (idempotent). | Authenticated user. Scoped to user's tenant. Called at decision creation. |
markDecisionReviewed | MarkDecisionReviewedInput (decisionId!, action!, notes?) | MarkReviewedResult! | Reviews a decision after constraint shift. Action: CONFIRM (still valid) or UPDATE (changed). Updates status to CURRENT and logs review in audit trail. | Authenticated user. Scoped to user's tenant. User must have decision review permissions. |
V. Subscriptions & Real-time Operations
This section documents the real-time subscription operations available in the GraphQL schema.
| Subscription | Parameters | Returns | Description | Security Context |
|---|---|---|---|---|
scenarioExecuted | tenantId (ID!) | ScenarioExecuted | Subscribes to real-time events for scenario execution completion. | Authenticated user. Scoped to user's tenant. |
cycleCreated | tenantId (ID!) | CycleCreated | Subscribes to real-time events for new SOP cycle creation. | Authenticated user. Scoped to user's tenant. |
cacheInvalidated | tenantId (ID!) | CacheInvalidated | Subscribes to real-time events for cache invalidation. | Authenticated user. Scoped to user's tenant. |
VI. Security Context
tenantId: All root queries and mutations are implicitly scoped to the authenticated user'stenantId. The backend services are responsible for applying this filter to all database queries.- Resource Ownership: For mutations like
updateTask, the resolver must verify that the authenticated user is either the creator or the assignee of the task. - Role-Based Access: While not explicitly defined in the schema, it is assumed that certain mutations (e.g.,
recordFinalDecision) are protected by role-based access control (RBAC) enforced at the resolver level.
VI. M71 Decision History Feed - Type Definitions
This section documents the GraphQL type definitions for the M71 Decision History Feed with Ferrari Stack integration.
Enhanced Decision Type (M71)
The existing Decision type is enhanced with Ferrari Stack fields for intelligent decision cards:
type Decision {
# Existing fields
id: ID!
tenantId: ID!
decisionProblemId: ID!
chosenScenarioId: ID!
decisionMakerId: ID!
finalRationale: String!
decidedAt: DateTime!
actualOutcome: JSON
metadata: JSON
# M71 Ferrari Stack fields
decisionMode: DecisionMode! # 'AUTONOMOUS' or 'HUMAN_LED'
zepSummary: String # AI-generated concise summary (max 200 chars)
zepSessionId: String # Link to Zep session for full dialogue
summaryEmbedding: [Float!] # pgvector embedding (768-dim) - rarely queried directly
monteCarloSparklineData: [SparklinePoint!] # Visualization data for sparkline chart
# M71 Knowledge Graph enrichments (computed fields)
relatedDecisions: [Decision!]! # Related decisions via Graphiti (shared entities)
knowledgeGraphContext: KnowledgeGraphContext # Temporal context from Cognee
}
enum DecisionMode {
AUTONOMOUS # System auto-executed (green border)
HUMAN_LED # User intervention (amber border)
}
type SparklinePoint {
x: Float! # X-coordinate (simulation run index or percentile)
y: Float! # Y-coordinate (outcome value)
}
type KnowledgeGraphContext {
entities: [GraphEntity!]! # Entities connected to this decision
relationships: [GraphRelationship!]! # Relationships between entities
temporalContext: JSON # Time-based context (e.g., "2 months after supplier change")
}
type GraphEntity {
id: ID!
type: String! # 'SUPPLIER', 'PRODUCT', 'CONSTRAINT', etc.
name: String!
attributes: JSON
}
type GraphRelationship {
fromEntity: ID!
toEntity: ID!
relationshipType: String! # 'SUPPLIES', 'DEPENDS_ON', 'CONFLICTS_WITH', etc.
strength: Float # 0.0 to 1.0 (relationship strength)
}
DecisionFilterPreset Type
type DecisionFilterPreset {
presetId: ID!
tenantId: ID!
userId: ID!
presetName: String! # "Q3 Supplier Decisions", "Failed Autonomous Decisions"
description: String
isDefault: Boolean! # Only one can be true per user
isShared: Boolean! # Visible to all users in tenant
filterConfig: FilterConfig!
usageCount: Int! # Analytics: how many times used
lastUsedAt: DateTime
createdAt: DateTime!
updatedAt: DateTime!
}
type FilterConfig {
decisionMode: [DecisionMode!] # Filter by AUTONOMOUS, HUMAN_LED
status: [String!] # Filter by decision status
outcome: [String!] # Filter by outcome (positive, negative, neutral)
dateRange: DateRangeFilter
decisionType: [String!] # Filter by decision type
entities: [ID!] # Filter by related entities (suppliers, products, etc.)
semanticQuery: String # Semantic search query (uses pgvector)
}
input DateRangeFilter {
start: DateTime!
end: DateTime!
}
input CreateFilterPresetInput {
presetName: String!
description: String
filterConfig: FilterConfigInput!
isDefault: Boolean
isShared: Boolean
}
input UpdateFilterPresetInput {
presetName: String
description: String
filterConfig: FilterConfigInput
isDefault: Boolean
isShared: Boolean
}
input FilterConfigInput {
decisionMode: [DecisionMode!]
status: [String!]
outcome: [String!]
dateRange: DateRangeFilter
decisionType: [String!]
entities: [ID!]
semanticQuery: String
}
CounterfactualSimulation Type
type CounterfactualSimulation {
simulationId: ID!
tenantId: ID!
decisionId: ID!
decision: Decision! # Original decision being re-evaluated
simulatedAt: DateTime!
triggeredByUserId: ID!
triggeredByUser: User!
# Original decision context (at decision time)
originalDecisionDate: Date!
originalMonteCarloResults: MonteCarloResults!
originalConstraints: [Constraint!]!
# Current context (at counterfactual simulation time)
currentMonteCarloResults: MonteCarloResults!
currentConstraints: [Constraint!]!
# Temporal changes (from Graphiti/Cognee)
detectedChanges: TemporalChanges!
changeSummary: String # AI-generated summary
# Comparison & Recommendation
comparisonDeltas: ComparisonDeltas!
recommendation: CounterfactualRecommendation!
recommendationReasoning: String
# Caching
isCached: Boolean!
cacheExpiresAt: DateTime
}
type MonteCarloResults {
mean: Float!
stddev: Float!
percentiles: Percentiles!
riskAvoided: Float # Percentage of risk avoided (e.g., 98%)
simulationRuns: Int!
}
type Percentiles {
p10: Float!
p25: Float!
p50: Float! # Median
p75: Float!
p90: Float!
p95: Float!
p99: Float!
}
type TemporalChanges {
newEntities: [GraphEntity!]! # Entities that didn't exist at decision time
updatedEntities: [EntityChange!]! # Entities that changed since decision
removedEntities: [GraphEntity!]! # Entities that no longer exist
newConstraints: [Constraint!]! # New constraints added since decision
removedConstraints: [Constraint!]! # Constraints no longer active
}
type EntityChange {
entity: GraphEntity!
beforeState: JSON
afterState: JSON
changeType: String! # 'QUALITY_DEGRADED', 'RELIABILITY_IMPROVED', 'PRICE_INCREASED', etc.
}
type ComparisonDeltas {
riskChange: String! # "+12%" or "-5%"
confidenceChange: String! # "-15%"
meanChange: String!
stddevChange: String!
constraintViolations: [String!]! # New constraint violations
}
enum CounterfactualRecommendation {
STILL_OPTIMAL # Decision still correct with current data
SUBOPTIMAL # Decision would be different today (minor change)
SIGNIFICANTLY_WORSE # Decision significantly worse with current data
REVERSED # Recommendation would be opposite today
}
Query Response Types
type DecisionHistoryResponse {
decisions: [Decision!]!
totalCount: Int!
hasMore: Boolean!
pageInfo: PageInfo!
}
type PageInfo {
currentPage: Int!
pageSize: Int!
totalPages: Int!
}
input DecisionFiltersInput {
decisionMode: [DecisionMode!]
status: [String!]
outcome: [String!]
dateRange: DateRangeFilter
decisionType: [String!]
entities: [ID!]
semanticQuery: String
limit: Int
offset: Int
}
M71 Implementation Notes
Ferrari Stack Integration Points:
- Zep Service:
zepSummaryandzepSessionIdfields populated byZepService.summarizeDialogue() - pgvector:
summaryEmbeddingfield used bysemanticSearchDecisionsquery (HNSW index) - Graphiti/Cognee:
relatedDecisionsandknowledgeGraphContextfields populated byCogneeServicemethods - Monte Carlo:
monteCarloSparklineDatafield contains visualization coordinates for AreaChart
Performance Considerations:
summaryEmbeddingis 768-dimensional and rarely queried directly (used for search, not display)relatedDecisionsis a computed field (JOIN-heavy) - use DataLoader for batchingknowledgeGraphContextmakes external API call to Cognee service - cache aggressivelyrunCounterfactualAnalysisis computationally expensive - results are cached with TTL
Caching Strategy:
- Counterfactual simulations cached for 24 hours (configurable via
cache_expires_at) - Knowledge graph context cached for 1 hour (entities/relationships change slowly)
- Filter presets usage tracking updated asynchronously (avoid blocking queries)