Skip to main content

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: orchestrateSIEWorkflow mutation with SIEWorkflowInput and SIEWorkflowResult types - 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: metricsOverview Query and associated types - COMPLETE
  • M63 Task X.Z: Subscription type and real-time event types (ScenarioExecuted, CycleCreated, CacheInvalidated) - COMPLETE
  • M70 Phase 4: GraphQL Schema Types for Socratic Inquiry Engine - COMPLETE
    • SocraticQuestion type with category, contextSnippets, and user response tracking
    • HumanJudgment type for Contextual Alignment Buffer (CAB)
    • ProblemStateVector type for refined strategic priorities with vector embeddings
    • ContextSnippet type for source attribution and transparency
    • DecisionContextInput input type for question generation
    • HumanJudgmentInput input type for capturing responses
    • CaptureJudgmentResponse and FlagQuestionResponse response 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
    • ConstraintShiftLog type for audit trail of detected shifts
    • DecisionFreshness type for tracking decision validity
    • FreshnessSummary type for health dashboard metrics
    • ConstraintShiftDetectionResult type 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 TypeOwning Service/FilePrimary Data Source(s)Description
Userschema.graphqlusers tableRepresents an authenticated user, used for audit trails and ownership.
MLConfigschema.graphqlml_configs tableStores configuration for the adaptive forecasting models.
Constraintschema.graphqlconstraints tableDefines operational or financial constraints (Hard, Soft, Dynamic).
Noteschema.graphqlnotes tableCaptures raw, unstructured text inputs that can be promoted to DecisionProblem.
Scenarioschema.graphqlscenarios tableRepresents a potential solution or course of action for a DecisionProblem.
DecisionProblemschema.graphqldecision_problems tableA structured problem derived from a Note, linking to potential Scenarios and Decisions.
Decisionschema.graphqldecisions tableAn immutable record of a choice made, linking a DecisionProblem to a chosen Scenario.
DecisionTaskschema.graphqldecision_tasks tableAn actionable task generated from a Decision, part of the Decision Loop.
ExternalSyncschema.graphqlexternal_syncs tableTracks the synchronization of a DecisionTask with an external system like Linear or Jira.
TasktaskSchema.graphqltasks tableA core task in the TaskAlign system, with support for hierarchy and dependencies.
TaskCommenttaskSchema.graphqltask_comments tableA comment on a Task.
MilestonetaskSchema.graphqlmilestones tableAn aggregation of Tasks for progress tracking.
WorkSessiontaskSchema.graphqlwork_sessions tableA checkpoint of a user's work context for session continuity.
ScenarioSessionschema.graphqlIn-memory/CacheA session for real-time scenario analysis with a 4-tier pipeline. Persisted results may go to other tables.
SIEWorkflowInputschema.graphqlIn-Memory/ServiceInput for Strategic Inquiry Engine workflow combining problem state (Tier 1) and scenario selection (Tier 2). Includes objectives, prioritization, constraints, risks, and trade-offs (M60).
SIEWorkflowResultschema.graphqlPostgreSQL (telemetry)Result of SIE orchestration including Bayesian probabilities, robustness scores, VOI analysis, optimizer recommendations, and orchestrated narrative with confidence bounds (M60).
Narrativeschema.graphqlGenerated by OrchestratedNarrativeServiceComplete narrative structure from orchestration including headline, executive summary, detailed analysis sections, caveats, and SIE prompt for audit trail (M60 Task 1).
Headlineschema.graphqlNarrative sub-typeAction-oriented headline with business implication and confidence score.
ExecutiveSummaryschema.graphqlNarrative sub-typeSummary with key risk, trade-off analysis, and data value assessment.
NarrativeDetailsschema.graphqlNarrative sub-typeDetailed findings from Bayesian, robustness, VOI, and optimizer analysis stages.
NarrativeDetailschema.graphqlNarrative sub-typeIndividual detail section with title, summary, findings, business implications, and recommendations.
KeyRiskschema.graphqlNarrative sub-typeRisk assessment with title, impact, and probability.
TradeOffschema.graphqlNarrative sub-typeTrade-off analysis with description and implications.
DataValueschema.graphqlNarrative sub-typeData relevance assessment with gaps and recommendations.
SIEPromptschema.graphqlNarrative sub-typeSystem and user prompts used to generate narrative for reproducibility and audit.
OrchestrationResultschema.graphqlorchestration_results tableComplete result of decision orchestration including narrative, all analytical results, and execution metadata (M60 Task 1).
SecretMetadatasecretsTypeDefs.graphqlsecrets_metadata tableMetadata about secrets managed via Infisical vault, including lifecycle status and rotation tracking (M58).
SecretAccessLogsecretsTypeDefs.graphqlsecret_access_logs tableAudit trail of all secret accesses (read, update, rotate, revoke, create, delete) for compliance (M58).
SecretAuditTrailsecretsTypeDefs.graphqlsecret_audit_trails tableImmutable change history for all secret metadata modifications, with before/after snapshots (M58).
Metricschema.graphqlCalculated/AggregatedRepresents a single metric with a name, value, and unit.
MetricsOverviewschema.graphqlCalculated/AggregatedAggregates multiple metrics for a high-level overview.
ScenarioExecutedschema.graphqlReal-time event streamReal-time event indicating a scenario execution has completed.
CycleCreatedschema.graphqlReal-time event streamReal-time event indicating a new SOP cycle has been created.
CacheInvalidatedschema.graphqlReal-time event streamReal-time event indicating a cache entry has been invalidated.
MetricInputschema.graphqlInput typeInput for recording custom metrics, including name, value, and optional tags.
CustomMetricResultschema.graphqlCalculated/AggregatedResult of recording a custom metric, including its ID, name, value, tags, and timestamp.
SocraticQuestionschema.graphqlsocratic_questions tableAI-generated question for decision-making, with category, context snippets, and optional user response tracking (M70).
HumanJudgmentschema.graphqlhuman_judgments tableContextual Alignment Buffer (CAB) - immutable audit trail of user responses to Socratic questions with optional impact rating (M70).
ProblemStateVectorschema.graphqlproblem_state_vectors tableRefined strategic priorities aggregated from human judgments, stored as vector embeddings for semantic search (M70).
ContextSnippetschema.graphqlEmbedded in JSONBSource snippet from Strategic North, Historical Failures, or Constraints that informed a Socratic question (M70).
DecisionContextInputschema.graphqlInput typeInput for generating Socratic questions, including decision context, type, and scope (M70).
HumanJudgmentInputschema.graphqlInput typeInput for capturing human judgment/response to a Socratic question with optional impact rating (M70).
CaptureJudgmentResponseschema.graphqlResponse typeResponse from capturing a human judgment, including success flag, audit trail ID, and judgment details (M70).
FlagQuestionResponseschema.graphqlResponse typeResponse from flagging a question as impactful, including success flag and updated question (M70).
DecisionFilterPresetdecisionsTypeDefs.graphql (M71)decision_filter_presets tableUser-saved filter configurations for Decision History Feed with usage tracking (M71 Phase 1.2).
CounterfactualSimulationdecisionsTypeDefs.graphql (M71)counterfactual_simulations table"Re-Run Simulation" results for time-travel decision analysis with temporal change detection (M71 Phase 1.3).
ConstraintShiftLogschema.graphql (M78)constraint_shift_logs tableAudit trail for detected constraint shifts with acknowledgment workflow and TOC-based shift classification (M78 Phase 2).
ConstraintUtilizationHistoryschema.graphql (M78)constraint_utilization_history tableDaily utilization measurements for constraint shift pattern analysis (M78 Phase 2).
DecisionFreshnessschema.graphql (M78)decision_freshness tableTracks validity status of decisions relative to constraint changes with review workflow (M78 Phase 2).
FreshnessSummaryschema.graphql (M78)Calculated/AggregatedHealth dashboard metrics showing % of CURRENT decisions vs REVIEW_RECOMMENDED/STALE (M78 Phase 2).
ConstraintShiftDetectionResultschema.graphql (M78)Service resultResult of analyzing constraint for shift (utilization drop + throughput maintained = shift detected) (M78 Phase 2).
FlagStaleDecisionsResultschema.graphql (M78)Service resultResult of flagging decisions after constraint shift, includes affected decision IDs (M78 Phase 2).
MarkReviewedResultschema.graphql (M78)Service resultResult of reviewing a decision with CONFIRM or UPDATE action (M78 Phase 2).
MonitorConstraintsResultschema.graphql (M78)Service resultBatch 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:

  1. A Note is created to capture raw input.
  2. The Note can be promoted to a DecisionProblem, which formalizes the issue.
    • DecisionProblem.sourceNote -> Note
  3. Multiple Scenario types can be linked to a DecisionProblem, representing different solutions.
    • DecisionProblem.linkedScenarios -> [Scenario]
  4. A Decision is made, immutably linking the DecisionProblem to a single, chosen Scenario.
    • Decision.problem -> DecisionProblem
    • Decision.chosenScenario -> Scenario
  5. The Decision generates DecisionTask items to be executed.
    • Decision.executionTasks -> [DecisionTask]
    • DecisionTask.originDecision -> Decision
  6. A DecisionTask can be synced to an external system, creating an ExternalSync record.
    • DecisionTask.externalSync -> ExternalSync
    • ExternalSync.task -> DecisionTask

Task Management (taskSchema.graphql - M57 Phase 1)

The TaskAlign system manages tasks and their relationships with full multi-tenant support:

  1. A Task is 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
  2. A TaskComment is linked to a single Task for collaboration.

    • TaskComment.task -> Task!
    • Fields: commentId, user, content, timestamps
  3. A Milestone aggregates multiple Task items with progress tracking.

    • Milestone.tasks -> [Task]!
    • Aggregates: taskCount, completedCount, progress (percentage)
    • Document links: fsdApprovedAt, fsdApprovedBy
  4. A WorkSession is associated with a Task to 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)

QueryParametersReturnsDescriptionSecurity Context
socraticQuestionsdecisionId (ID!)[SocraticQuestion!]!Returns all Socratic questions generated for a decision, including user responses and impact ratings.Authenticated user. Scoped to user's tenant.
problemStateVectordecisionId (ID!)ProblemStateVectorReturns 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)

QueryParametersReturnsDescriptionSecurity Context
orchestrationResulttenantId (ID!), scenarioId (ID!)OrchestrationResultReturns orchestration result by tenant and scenario ID, including complete narrative structure with all analysis components.Authenticated user. Scoped to user's tenant.
orchestrationResultstenantId (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.
metricsOverviewtenantId (ID!)MetricsOverviewReturns an overview of key metrics for a given tenant.Authenticated user. Scoped to user's tenant.
metricstenantId (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)

QueryParametersReturnsDescriptionSecurity Context
tasksproject (String), milestone (String), status (TaskStatus)[Task!]!Returns filtered list of tasks. All filters are optional. Supports pagination.Authenticated user. Scoped to user's tenant.
tasktaskId (ID!)TaskReturns a single task by ID.Authenticated user. Scoped to user's tenant.
taskByPseudoIdpseudoId (String!)TaskReturns a single task by human-readable pseudo-ID (e.g., CHA-M57-001).Authenticated user. Scoped to user's tenant.
milestonesproject (String!)[Milestone!]!Returns all milestones for a project with aggregated progress.Authenticated user. Scoped to user's tenant.
milestonemilestoneId (String!)MilestoneReturns a single milestone with task list and progress.Authenticated user. Scoped to user's tenant.
resumeContext(none)WorkSessionReturns the active/most recent work session for the authenticated user. Enables session recovery.Authenticated user.
sessionHistorylimit (Int)[WorkSession!]!Returns historical work sessions for the authenticated user (paginated with optional limit).Authenticated user.

Secrets Management Queries (secretsTypeDefs.graphql - M58)

QueryParametersReturnsDescriptionSecurity Context
secretid (ID!)SecretMetadataReturns a single secret by ID with full metadata.Authenticated user. Scoped to user's tenant. Logs access for audit trail.
secretByNamename (String!)SecretMetadataReturns a secret by human-readable name (tenant-scoped).Authenticated user. Scoped to user's tenant. Logs access for audit trail.
secretsstatus (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.
secretAccessLogssecretId (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.
secretAuditTrailsecretId (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)

QueryParametersReturnsDescriptionSecurity Context
decisionsfilters (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.
decisionid (ID!)DecisionReturns a single decision with full Ferrari Stack context (related_decisions, knowledge_graph_context).Authenticated user. Scoped to user's tenant.
semanticSearchDecisionsquery (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.
getCounterfactualAnalysisdecisionId (ID!)CounterfactualSimulationReturns 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)

QueryParametersReturnsDescriptionSecurity 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.
decisionsNeedingReviewstatus (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.
decisionFreshnessdecisionId (ID!)DecisionFreshnessReturns freshness status for a specific decision. Includes daysSinceUpdate and requiresReview computed fields.Authenticated user. Scoped to user's tenant.
constraintShiftHistoryconstraintId (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.
constraintUtilizationHistoryconstraintId (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.

MutationInput(s)ReturnsDescriptionSecurity Context
Socratic Inquiry Engine (M70)
generateSocraticQuestionsDecisionContextInput (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.
captureHumanJudgmentHumanJudgmentInput (questionId!, decisionId!, responseText!, impactRating?)CaptureJudgmentResponseCaptures 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.
flagImpactfulQuestionquestionId! (ID!), impactRating! (Int!)FlagQuestionResponseFlags 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)
reOrchestrateReOrchestrationInput (tenantId!, scenarioId!, skipServices?, forceRecompute?)OrchestrationResultRe-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.
logDecisionToReasoningBankLogDecisionInput (tenantId!, orchestrationId!, decision!, rationale!, outcome?)StringLogs an executed decision to the reasoning bank for future reference and analysis.Authenticated user. Scoped to user's tenant.
Decision Intelligence
recordFinalDecisionproblemId, chosenScenarioId, rationaleRecords 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).
createTaskFromDecisiondecisionId, taskType, assigneeIdCreates 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).
updateTaskStatustaskId, statusUpdates the status of a DecisionTask and can trigger a sync to an external system.Requires user to be the assignee or a manager.
syncTaskToExternaltaskId, systemPushes a DecisionTask to an external system like Linear or Jira, creating an ExternalSync record.Requires AUTH_ROLE: MANAGER (assumed).
createScenarioSessionparametersCreates a new real-time scenario analysis session.Authenticated user.
updateScenarioParametersessionId, paramKey, paramValueUpdates a parameter in a ScenarioSession and triggers a re-analysis through the 4-tier pipeline.User must be the creator of the session.
orchestrateSIEWorkflowSIEWorkflowInput (tenantId!, problemStateVector!, selectedScenarioId!, orchestrationConfig)SIEWorkflowResultExecutes 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)
createTaskCreateTaskInput (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.
updateTasktaskId!, 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.
completeTasktaskId!, actualHours (Float optional)Marks a task as COMPLETED with optional time tracking. Automatically sets completedAt timestamp.Authenticated user. Must have edit permission on task.
startTasktaskId!Transitions a task to IN_PROGRESS status. Automatically sets startedAt timestamp.Authenticated user. Must have edit permission on task.
addCommenttaskId!, content! (String)Adds a comment to a task for collaboration and threaded discussions.Authenticated user. Scoped to user's tenant.
checkpointSessionCheckpointInput (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)
createSecretCreateSecretInput (name!, secretType!, description?, tags?, environment)SecretMetadataCreates new secret metadata and syncs with Infisical vault. Returns metadata with generated ID.Authenticated user. Requires SECRETS_MANAGER role. Scoped to user's tenant.
updateSecretsecretId!, UpdateSecretInput (description, tags, environment, status)SecretMetadataUpdates 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.
rotateSecretsecretId!, rotationScheduledAt (DateTime!)SecretMetadataSchedules secret for rotation. Updates metadata and logs audit event.Authenticated user. Requires SECRETS_MANAGER role. Typically initiated by deployment pipeline.
revokeSecretsecretId!, reason (String!)SecretMetadataRevokes secret immediately (marks as revoked). Cannot be undone. Logs reason in audit trail.Authenticated user. Requires SECRETS_ADMIN role (restricted). Logs unauthorized attempts.
restoreSecretsecretId!SecretMetadataRestores 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.
rollbackScenarioVersiontenantId (ID!), cycleId (ID!), versionNumber (Int!)ScenarioVersionRolls back a scenario to a previous version.Authenticated user. Scoped to user's tenant.
recordCustomMetrictenantId (ID!), metric (MetricInput!)CustomMetricResultRecords a custom metric for a given tenant.Authenticated user. Scoped to user's tenant.
Decision History Feed (M71)
createFilterPresetCreateFilterPresetInput (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.
updateFilterPresetpresetId!, 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.
deleteFilterPresetpresetId!Boolean!Deletes a filter preset. Shared presets can only be deleted by tenant admin.User must be preset creator or tenant admin.
runCounterfactualAnalysisdecisionId!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)
detectConstraintShiftconstraintId!, 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.
recordConstraintUtilizationRecordUtilizationInput (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.
acknowledgeConstraintShiftAcknowledgeShiftInput (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.
flagStaleDecisionsFlagStaleDecisionsInput (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.
initializeFreshnessTrackingInitializeFreshnessInput (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.
markDecisionReviewedMarkDecisionReviewedInput (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.

SubscriptionParametersReturnsDescriptionSecurity Context
scenarioExecutedtenantId (ID!)ScenarioExecutedSubscribes to real-time events for scenario execution completion.Authenticated user. Scoped to user's tenant.
cycleCreatedtenantId (ID!)CycleCreatedSubscribes to real-time events for new SOP cycle creation.Authenticated user. Scoped to user's tenant.
cacheInvalidatedtenantId (ID!)CacheInvalidatedSubscribes 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's tenantId. 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:

  1. Zep Service: zepSummary and zepSessionId fields populated by ZepService.summarizeDialogue()
  2. pgvector: summaryEmbedding field used by semanticSearchDecisions query (HNSW index)
  3. Graphiti/Cognee: relatedDecisions and knowledgeGraphContext fields populated by CogneeService methods
  4. Monte Carlo: monteCarloSparklineData field contains visualization coordinates for AreaChart

Performance Considerations:

  • summaryEmbedding is 768-dimensional and rarely queried directly (used for search, not display)
  • relatedDecisions is a computed field (JOIN-heavy) - use DataLoader for batching
  • knowledgeGraphContext makes external API call to Cognee service - cache aggressively
  • runCounterfactualAnalysis is 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)