// Package runner executes task-shaped OpenClerk JSON requests.
package runner

import (
	"bytes"
	"encoding/json"
	"time"
)

const (
	ConfigTaskActionInspectConfig         = "inspect_config"
	ConfigTaskActionConfigureProfile      = "configure_profile"
	ConfigTaskActionClearProfile          = "clear_profile"
	ConfigTaskActionConfigureVaultIgnores = "configure_vault_ignore_paths"

	DocumentTaskActionValidate            = "validate"
	DocumentTaskActionCreate              = "create_document"
	DocumentTaskActionIngestSourceURL     = "ingest_source_url"
	DocumentTaskActionIngestVideoURL      = "ingest_video_url"
	DocumentTaskActionCompileSynthesis    = "compile_synthesis"
	DocumentTaskActionValidationSynthesis = "validation_synthesis_report"
	DocumentTaskActionList                = "list_documents"
	DocumentTaskActionGet                 = "get_document"
	DocumentTaskActionAppend              = "append_document"
	DocumentTaskActionReplaceDocument     = "replace_document"
	DocumentTaskActionReplaceSection      = "replace_section"
	DocumentTaskActionResolvePaths        = "resolve_paths"
	DocumentTaskActionInspectLayout       = "inspect_layout"
	DocumentTaskActionGitLifecycle        = "git_lifecycle_report"
	DocumentTaskActionWebSearchPlan       = "web_search_plan"
	DocumentTaskActionArtifactPlan        = "artifact_candidate_plan"
	DocumentTaskActionPlanMoveDocument    = "plan_move_document"
	DocumentTaskActionMoveDocument        = "move_document"
	DocumentTaskActionRenameDocument      = "rename_document"
	DocumentTaskActionPromoteCandidate    = "promote_candidate"
	DocumentTaskActionPlanPathCleanup     = "plan_path_cleanup"

	RetrievalTaskActionValidate                     = "validate"
	RetrievalTaskActionSearch                       = "search"
	RetrievalTaskActionDocumentLinks                = "document_links"
	RetrievalTaskActionGraph                        = "graph_neighborhood"
	RetrievalTaskActionRecordsLookup                = "records_lookup"
	RetrievalTaskActionRecordEntity                 = "record_entity"
	RetrievalTaskActionServicesLookup               = "services_lookup"
	RetrievalTaskActionServiceRecord                = "service_record"
	RetrievalTaskActionDecisionsLookup              = "decisions_lookup"
	RetrievalTaskActionDecisionRecord               = "decision_record"
	RetrievalTaskActionProvenanceEvents             = "provenance_events"
	RetrievalTaskActionProjectionStates             = "projection_states"
	RetrievalTaskActionAuditContradictions          = "audit_contradictions"
	RetrievalTaskActionMemoryRouterRecall           = "memory_router_recall_report"
	RetrievalTaskActionSourceDiscovery              = "source_discovery_report"
	RetrievalTaskActionSourceAuditReport            = "source_audit_report"
	RetrievalTaskActionEvidenceBundle               = "evidence_bundle_report"
	RetrievalTaskActionDecisionLookup               = "decision_lookup_report"
	RetrievalTaskActionDuplicateCandidate           = "duplicate_candidate_report"
	RetrievalTaskActionWorkflowGuide                = "workflow_guide_report"
	RetrievalTaskActionStructuredStore              = "structured_store_report"
	RetrievalTaskActionHybridRetrieval              = "hybrid_retrieval_report"
	RetrievalTaskActionGraphContext                 = "graph_context_report"
	RetrievalTaskActionGraphRelationship            = "graph_relationship_report"
	RetrievalTaskActionGraphRelationshipMaintenance = "graph_relationship_maintenance_plan"
	RetrievalTaskActionSemanticSearch               = "semantic_search"
	RetrievalTaskActionRetrievalEvalCapture         = "retrieval_eval_capture"
	RetrievalTaskActionRetrievalEvalReplay          = "retrieval_eval_replay"
	RetrievalTaskActionSearchDiagnostics            = "search_diagnostics_report"
	RetrievalTaskActionMaintenanceReport            = "maintenance_report"
)

type ConfigTaskRequest struct {
	Action           string        `json:"action"`
	Autonomy         AutonomyModes `json:"autonomy,omitempty"`
	Profile          AutonomyModes `json:"profile,omitempty"`
	VaultIgnorePaths *[]string     `json:"vault_ignore_paths,omitempty"`
}

type ConfigTaskResult struct {
	Rejected        bool                       `json:"rejected"`
	RejectionReason string                     `json:"rejection_reason,omitempty"`
	Paths           *Paths                     `json:"paths,omitempty"`
	Storage         *ConfigStorageSummary      `json:"storage,omitempty"`
	Profile         AutonomyModes              `json:"profile"`
	Modules         []ConfigModuleSummary      `json:"modules,omitempty"`
	GitLifecycle    *ConfigGitLifecycleSummary `json:"git_lifecycle,omitempty"`
	Summary         string                     `json:"summary"`
}

type ConfigStorageSummary struct {
	DatabasePath            string   `json:"database_path"`
	VaultRoot               string   `json:"vault_root"`
	DatabaseSource          string   `json:"database_source"`
	VaultIgnorePaths        []string `json:"vault_ignore_paths,omitempty"`
	DefaultVaultIgnorePaths []string `json:"default_vault_ignore_paths,omitempty"`
	CustomVaultIgnorePaths  []string `json:"custom_vault_ignore_paths,omitempty"`
}

type ConfigModuleSummary struct {
	Kind               string `json:"kind"`
	Provider           string `json:"provider"`
	ModuleName         string `json:"module_name"`
	Enabled            bool   `json:"enabled"`
	Command            string `json:"command,omitempty"`
	ManifestPath       string `json:"manifest_path,omitempty"`
	ManifestSHA256     string `json:"manifest_sha256,omitempty"`
	VerificationStatus string `json:"verification_status"`
	RedactionStatus    string `json:"redaction_status"`
}

type ConfigGitLifecycleSummary struct {
	CheckpointPersistence          string `json:"checkpoint_persistence"`
	CheckpointEnabledForInvocation bool   `json:"checkpoint_enabled_for_invocation"`
	CheckpointEnablementSource     string `json:"checkpoint_enablement_source"`
	CheckpointApprovalBoundary     string `json:"checkpoint_approval_boundary"`
}

type DocumentTaskRequest struct {
	Action              string                   `json:"action"`
	Autonomy            AutonomyModes            `json:"autonomy,omitempty"`
	Document            DocumentInput            `json:"document,omitempty"`
	Source              SourceURLInput           `json:"source,omitempty"`
	Video               VideoURLInput            `json:"video,omitempty"`
	Synthesis           CompileSynthesisInput    `json:"synthesis,omitempty"`
	ValidationSynthesis ValidationSynthesisInput `json:"validation_synthesis,omitempty"`
	GitLifecycle        GitLifecycleOptions      `json:"git_lifecycle,omitempty"`
	WebSearch           WebSearchPlanOptions     `json:"web_search,omitempty"`
	Artifact            ArtifactPlanOptions      `json:"artifact,omitempty"`
	Move                MoveDocumentOptions      `json:"move,omitempty"`
	PathCleanup         PathCleanupOptions       `json:"path_cleanup,omitempty"`
	Path                string                   `json:"path,omitempty"`
	Title               string                   `json:"title,omitempty"`
	Body                string                   `json:"body,omitempty"`
	Metadata            map[string]string        `json:"metadata,omitempty"`
	BodyFacts           []string                 `json:"body_facts,omitempty"`
	SourceRefs          []string                 `json:"source_refs,omitempty"`
	FreshnessNote       string                   `json:"freshness_note,omitempty"`
	Mode                string                   `json:"mode,omitempty"`
	DocID               string                   `json:"doc_id,omitempty"`
	Content             string                   `json:"content,omitempty"`
	Heading             string                   `json:"heading,omitempty"`
	IncludeHeading      bool                     `json:"include_heading,omitempty"`
	IncludeSubsections  *bool                    `json:"include_subsections,omitempty"`
	DryRun              bool                     `json:"dry_run,omitempty"`
	Diff                bool                     `json:"diff,omitempty"`
	AllowDocIDChange    bool                     `json:"allow_doc_id_change,omitempty"`
	List                DocumentListOptions      `json:"list,omitempty"`

	jsonDecoded    bool
	providedFields map[string]bool
}

func (request *DocumentTaskRequest) UnmarshalJSON(data []byte) error {
	type documentTaskRequestAlias DocumentTaskRequest
	var decoded documentTaskRequestAlias
	if err := decodeStrictJSON(data, &decoded); err != nil {
		return err
	}
	var raw map[string]json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}
	*request = DocumentTaskRequest(decoded)
	request.jsonDecoded = true
	request.providedFields = make(map[string]bool, len(raw))
	for key := range raw {
		request.providedFields[key] = true
	}
	return nil
}

func (request DocumentTaskRequest) fieldProvided(field string) bool {
	return request.providedFields[field]
}

type DocumentInput struct {
	Path  string `json:"path"`
	Title string `json:"title"`
	Body  string `json:"body"`
}

type SourceURLInput struct {
	URL           string `json:"url"`
	PathHint      string `json:"path_hint"`
	AssetPathHint string `json:"asset_path_hint"`
	Title         string `json:"title,omitempty"`
	Mode          string `json:"mode,omitempty"`
	SourceType    string `json:"source_type,omitempty"`
	Limit         int    `json:"limit,omitempty"`
}

type VideoURLInput struct {
	URL           string               `json:"url"`
	PathHint      string               `json:"path_hint"`
	AssetPathHint string               `json:"asset_path_hint,omitempty"`
	Title         string               `json:"title,omitempty"`
	Mode          string               `json:"mode,omitempty"`
	Transcript    VideoTranscriptInput `json:"transcript,omitempty"`
}

type VideoTranscriptInput struct {
	Text       string `json:"text,omitempty"`
	Policy     string `json:"policy,omitempty"`
	Origin     string `json:"origin,omitempty"`
	Language   string `json:"language,omitempty"`
	CapturedAt string `json:"captured_at,omitempty"`
	Tool       string `json:"tool,omitempty"`
	Model      string `json:"model,omitempty"`
	SHA256     string `json:"sha256,omitempty"`
}

type CompileSynthesisInput struct {
	Path          string   `json:"path"`
	Title         string   `json:"title"`
	SourceRefs    []string `json:"source_refs,omitempty"`
	Body          string   `json:"body,omitempty"`
	BodyFacts     []string `json:"body_facts,omitempty"`
	FreshnessNote string   `json:"freshness_note,omitempty"`
	Mode          string   `json:"mode,omitempty"`
}

type ValidationSynthesisInput struct {
	DocID                string   `json:"doc_id,omitempty"`
	Path                 string   `json:"path,omitempty"`
	Title                string   `json:"title,omitempty"`
	SourceRefs           []string `json:"source_refs,omitempty"`
	Body                 string   `json:"body,omitempty"`
	BodyFacts            []string `json:"body_facts,omitempty"`
	FreshnessNote        string   `json:"freshness_note,omitempty"`
	Mode                 string   `json:"mode,omitempty"`
	DisposableValidation bool     `json:"disposable_validation,omitempty"`
}

type SourcePDFMetadata struct {
	Title         string `json:"title,omitempty"`
	Author        string `json:"author,omitempty"`
	PublishedDate string `json:"published_date,omitempty"`
}

type SourceIngestionResult struct {
	DocID               string                  `json:"doc_id"`
	SourcePath          string                  `json:"source_path"`
	SourceURL           string                  `json:"source_url"`
	SourceType          string                  `json:"source_type"`
	AssetPath           string                  `json:"asset_path,omitempty"`
	DerivedPath         string                  `json:"derived_path"`
	Citations           []Citation              `json:"citations,omitempty"`
	SHA256              string                  `json:"sha256"`
	SizeBytes           int64                   `json:"size_bytes"`
	MIMEType            string                  `json:"mime_type"`
	PageCount           int                     `json:"page_count"`
	CapturedAt          time.Time               `json:"captured_at"`
	PDFMetadata         SourcePDFMetadata       `json:"pdf_metadata,omitempty"`
	UpdateStatus        string                  `json:"update_status,omitempty"`
	NormalizedSourceURL string                  `json:"normalized_source_url,omitempty"`
	SourceDocID         string                  `json:"source_doc_id,omitempty"`
	PreviousSHA256      string                  `json:"previous_sha256,omitempty"`
	NewSHA256           string                  `json:"new_sha256,omitempty"`
	Changed             *bool                   `json:"changed,omitempty"`
	DuplicateStatus     string                  `json:"duplicate_status,omitempty"`
	StaleDependents     *[]SourceStaleDependent `json:"stale_dependents,omitempty"`
	ProjectionRefs      *[]SourceProjectionRef  `json:"projection_refs,omitempty"`
	ProvenanceRefs      *[]SourceProvenanceRef  `json:"provenance_refs,omitempty"`
	SynthesisRepaired   *bool                   `json:"synthesis_repaired,omitempty"`
	NoRepairWarning     string                  `json:"no_repair_warning,omitempty"`
}

type SourcePlacementPlan struct {
	SourceURL              string           `json:"source_url"`
	SourceType             string           `json:"source_type"`
	CandidateSourcePaths   []string         `json:"candidate_source_paths"`
	CandidateAssetPaths    []string         `json:"candidate_asset_paths,omitempty"`
	CandidateSynthesisPath string           `json:"candidate_synthesis_path,omitempty"`
	ExistingSource         *DocumentSummary `json:"existing_source,omitempty"`
	DuplicateStatus        string           `json:"duplicate_status"`
	FetchStatus            string           `json:"fetch_status"`
	WriteStatus            string           `json:"write_status"`
	ApprovalBoundary       string           `json:"approval_boundary"`
	ValidationBoundaries   string           `json:"validation_boundaries"`
	AuthorityLimits        string           `json:"authority_limits"`
	AgentHandoff           *AgentHandoff    `json:"agent_handoff,omitempty"`
}

type SourceURLIntakePlan struct {
	SourceURL            string                     `json:"source_url"`
	SourceType           string                     `json:"source_type"`
	Title                string                     `json:"title,omitempty"`
	MIMEType             string                     `json:"mime_type"`
	SizeBytes            int64                      `json:"size_bytes"`
	SHA256               string                     `json:"sha256"`
	PageCount            int                        `json:"page_count,omitempty"`
	TextPreview          string                     `json:"text_preview,omitempty"`
	DiscoveredLinkCount  int                        `json:"discovered_link_count"`
	PrimaryCandidate     *SourceURLIntakeCandidate  `json:"primary_candidate,omitempty"`
	RelatedCandidates    []SourceURLIntakeCandidate `json:"related_candidates,omitempty"`
	FetchStatus          string                     `json:"fetch_status"`
	WriteStatus          string                     `json:"write_status"`
	ApprovalBoundary     string                     `json:"approval_boundary"`
	ValidationBoundaries string                     `json:"validation_boundaries"`
	AuthorityLimits      string                     `json:"authority_limits"`
	AgentHandoff         *AgentHandoff              `json:"agent_handoff,omitempty"`
}

type SourceURLIntakeCandidate struct {
	Rank                    int              `json:"rank"`
	Relation                string           `json:"relation"`
	URL                     string           `json:"url"`
	NormalizedURL           string           `json:"normalized_url"`
	Title                   string           `json:"title,omitempty"`
	LinkText                string           `json:"link_text,omitempty"`
	SourceType              string           `json:"source_type"`
	CandidateStatus         string           `json:"candidate_status"`
	DuplicateStatus         string           `json:"duplicate_status"`
	CandidateSourcePaths    []string         `json:"candidate_source_paths,omitempty"`
	CandidateAssetPaths     []string         `json:"candidate_asset_paths,omitempty"`
	CandidateSynthesisPath  string           `json:"candidate_synthesis_path,omitempty"`
	ExistingSource          *DocumentSummary `json:"existing_source,omitempty"`
	NextIngestSourceRequest string           `json:"next_ingest_source_request,omitempty"`
}

type SourceStaleDependent struct {
	Path            string   `json:"path"`
	DocID           string   `json:"doc_id"`
	Projection      string   `json:"projection"`
	Freshness       string   `json:"freshness"`
	StaleSourceRefs []string `json:"stale_source_refs,omitempty"`
}

type SourceProjectionRef struct {
	Projection string `json:"projection"`
	RefKind    string `json:"ref_kind"`
	RefID      string `json:"ref_id"`
	Freshness  string `json:"freshness"`
	SourceRef  string `json:"source_ref,omitempty"`
}

type SourceProvenanceRef struct {
	EventID   string `json:"event_id"`
	EventType string `json:"event_type"`
	RefKind   string `json:"ref_kind"`
	RefID     string `json:"ref_id"`
	SourceRef string `json:"source_ref,omitempty"`
}

type VideoIngestionResult struct {
	DocID                    string     `json:"doc_id"`
	SourcePath               string     `json:"source_path"`
	SourceURL                string     `json:"source_url"`
	AssetPath                string     `json:"asset_path,omitempty"`
	Citations                []Citation `json:"citations,omitempty"`
	TranscriptSHA256         string     `json:"transcript_sha256"`
	PreviousTranscriptSHA256 string     `json:"previous_transcript_sha256,omitempty"`
	NewTranscriptSHA256      string     `json:"new_transcript_sha256,omitempty"`
	CapturedAt               time.Time  `json:"captured_at"`
	TranscriptPolicy         string     `json:"transcript_policy"`
	TranscriptOrigin         string     `json:"transcript_origin"`
	Language                 string     `json:"language,omitempty"`
	Tool                     string     `json:"tool,omitempty"`
	Model                    string     `json:"model,omitempty"`
}

type DocumentListOptions struct {
	PathPrefix    string `json:"path_prefix,omitempty"`
	MetadataKey   string `json:"metadata_key,omitempty"`
	MetadataValue string `json:"metadata_value,omitempty"`
	Tag           string `json:"tag,omitempty"`
	Limit         int    `json:"limit,omitempty"`
	Cursor        string `json:"cursor,omitempty"`

	tagProvided bool
}

type DocumentTaskResult struct {
	Rejected            bool                    `json:"rejected"`
	RejectionReason     string                  `json:"rejection_reason,omitempty"`
	ExampleRequest      string                  `json:"example_request,omitempty"`
	Document            *Document               `json:"document,omitempty"`
	DocumentUpdate      *DocumentUpdateResult   `json:"document_update,omitempty"`
	Ingestion           *SourceIngestionResult  `json:"ingestion,omitempty"`
	SourcePlacement     *SourcePlacementPlan    `json:"source_placement_plan,omitempty"`
	SourceIntakePlan    *SourceURLIntakePlan    `json:"source_url_intake_plan,omitempty"`
	VideoIngestion      *VideoIngestionResult   `json:"video_ingestion,omitempty"`
	CompileSynthesis    *CompileSynthesisResult `json:"compile_synthesis,omitempty"`
	ValidationSynthesis *CompileSynthesisResult `json:"validation_synthesis,omitempty"`
	GitLifecycle        *GitLifecycleReport     `json:"git_lifecycle,omitempty"`
	WebSearchPlan       *WebSearchPlan          `json:"web_search_plan,omitempty"`
	ArtifactPlan        *ArtifactCandidatePlan  `json:"artifact_candidate_plan,omitempty"`
	MovePlan            *DocumentMovePlan       `json:"move_plan,omitempty"`
	MoveResult          *DocumentMoveResult     `json:"move_result,omitempty"`
	PathCleanup         *PathCleanupPlan        `json:"path_cleanup,omitempty"`
	Documents           []DocumentSummary       `json:"documents,omitempty"`
	Paths               *Paths                  `json:"paths,omitempty"`
	Layout              *KnowledgeLayout        `json:"layout,omitempty"`
	AgentHandoff        *AgentHandoff           `json:"agent_handoff,omitempty"`
	PageInfo            PageInfo                `json:"page_info,omitempty"`
	Summary             string                  `json:"summary"`
}

type DocumentUpdateResult struct {
	Action               string                 `json:"action"`
	DocID                string                 `json:"doc_id"`
	WriteStatus          string                 `json:"write_status"`
	DryRun               bool                   `json:"dry_run,omitempty"`
	Before               DocumentUpdateSnapshot `json:"before"`
	After                DocumentUpdateSnapshot `json:"after"`
	Diff                 string                 `json:"diff,omitempty"`
	PreimageSHA256       string                 `json:"preimage_sha256,omitempty"`
	RollbackRequest      string                 `json:"rollback_request,omitempty"`
	NextWriteRequest     string                 `json:"next_write_request,omitempty"`
	Heading              string                 `json:"heading,omitempty"`
	HeadingPreserved     *bool                  `json:"heading_preserved,omitempty"`
	IncludeHeading       bool                   `json:"include_heading,omitempty"`
	IncludeSubsections   bool                   `json:"include_subsections,omitempty"`
	ApprovalBoundary     string                 `json:"approval_boundary,omitempty"`
	ValidationBoundaries string                 `json:"validation_boundaries,omitempty"`
	AuthorityLimits      string                 `json:"authority_limits,omitempty"`
	AgentHandoff         *AgentHandoff          `json:"agent_handoff,omitempty"`
}

type DocumentUpdateSnapshot struct {
	Title    string   `json:"title"`
	Path     string   `json:"path"`
	Headings []string `json:"headings,omitempty"`
}

type RetrievalTaskRequest struct {
	Action                       string                              `json:"action"`
	Autonomy                     AutonomyModes                       `json:"autonomy,omitempty"`
	Search                       SearchOptions                       `json:"search,omitempty"`
	DocID                        string                              `json:"doc_id,omitempty"`
	ChunkID                      string                              `json:"chunk_id,omitempty"`
	NodeID                       string                              `json:"node_id,omitempty"`
	EntityID                     string                              `json:"entity_id,omitempty"`
	ServiceID                    string                              `json:"service_id,omitempty"`
	DecisionID                   string                              `json:"decision_id,omitempty"`
	Records                      RecordLookupOptions                 `json:"records,omitempty"`
	Services                     ServiceLookupOptions                `json:"services,omitempty"`
	Decisions                    DecisionLookupOptions               `json:"decisions,omitempty"`
	Provenance                   ProvenanceEventOptions              `json:"provenance,omitempty"`
	Projection                   ProjectionStateOptions              `json:"projection,omitempty"`
	Audit                        AuditContradictionsOptions          `json:"audit,omitempty"`
	MemoryRouterRecall           MemoryRouterRecallOptions           `json:"memory_router_recall,omitempty"`
	SourceDiscovery              SourceDiscoveryOptions              `json:"source_discovery,omitempty"`
	SourceAudit                  SourceAuditReportOptions            `json:"source_audit,omitempty"`
	EvidenceBundle               EvidenceBundleOptions               `json:"evidence_bundle,omitempty"`
	DecisionLookup               DecisionLookupReportOptions         `json:"decision_lookup,omitempty"`
	DuplicateCandidate           DuplicateCandidateOptions           `json:"duplicate_candidate,omitempty"`
	WorkflowGuide                WorkflowGuideOptions                `json:"workflow_guide,omitempty"`
	StructuredStore              StructuredStoreOptions              `json:"structured_store,omitempty"`
	HybridRetrieval              HybridRetrievalOptions              `json:"hybrid_retrieval,omitempty"`
	GraphContext                 GraphContextOptions                 `json:"graph_context,omitempty"`
	GraphRelationship            GraphRelationshipOptions            `json:"graph_relationship,omitempty"`
	GraphRelationshipMaintenance GraphRelationshipMaintenanceOptions `json:"graph_relationship_maintenance,omitempty"`
	SemanticSearch               SemanticSearchOptions               `json:"semantic_search,omitempty"`
	RetrievalEval                RetrievalEvalOptions                `json:"retrieval_eval,omitempty"`
	RetrievalReplay              RetrievalReplayOptions              `json:"retrieval_replay,omitempty"`
	SearchDiagnostics            SearchDiagnosticsOptions            `json:"search_diagnostics,omitempty"`
	Maintenance                  MaintenanceReportOptions            `json:"maintenance,omitempty"`
	Limit                        int                                 `json:"limit,omitempty"`
}

type AutonomyModes struct {
	ApprovalMode    string `json:"approval_mode,omitempty"`
	DraftingMode    string `json:"drafting_mode,omitempty"`
	WriteTargetMode string `json:"write_target_mode,omitempty"`
	CitationMode    string `json:"citation_mode,omitempty"`
	PrivacyMode     string `json:"privacy_mode,omitempty"`
	AudienceMode    string `json:"audience_mode,omitempty"`
}

type SearchOptions struct {
	Text          string `json:"text,omitempty"`
	PathPrefix    string `json:"path_prefix,omitempty"`
	MetadataKey   string `json:"metadata_key,omitempty"`
	MetadataValue string `json:"metadata_value,omitempty"`
	Tag           string `json:"tag,omitempty"`
	Limit         int    `json:"limit,omitempty"`
	Cursor        string `json:"cursor,omitempty"`

	tagProvided bool
}

type SemanticSearchOptions struct {
	Query                     string `json:"query,omitempty"`
	PathPrefix                string `json:"path_prefix,omitempty"`
	MetadataKey               string `json:"metadata_key,omitempty"`
	MetadataValue             string `json:"metadata_value,omitempty"`
	Tag                       string `json:"tag,omitempty"`
	Limit                     int    `json:"limit,omitempty"`
	Provider                  string `json:"provider,omitempty"`
	OllamaURL                 string `json:"ollama_url,omitempty"`
	EmbeddingModel            string `json:"embedding_model,omitempty"`
	GeminiAPIBase             string `json:"gemini_api_base,omitempty"`
	EmbeddingOutputDimensions int    `json:"embedding_output_dimensions,omitempty"`
	CacheDir                  string `json:"cache_dir,omitempty"`

	tagProvided bool
}

type RetrievalEvalOptions struct {
	Action         string                `json:"action,omitempty"`
	CapturePath    string                `json:"capture_path,omitempty"`
	Search         SearchOptions         `json:"search,omitempty"`
	SemanticSearch SemanticSearchOptions `json:"semantic_search,omitempty"`
}

type RetrievalReplayOptions struct {
	CapturePath string `json:"capture_path,omitempty"`
	Limit       int    `json:"limit,omitempty"`
}

type SearchDiagnosticsOptions struct {
	Query         string `json:"query,omitempty"`
	Intent        string `json:"intent,omitempty"`
	PathPrefix    string `json:"path_prefix,omitempty"`
	MetadataKey   string `json:"metadata_key,omitempty"`
	MetadataValue string `json:"metadata_value,omitempty"`
	Tag           string `json:"tag,omitempty"`
	Provider      string `json:"provider,omitempty"`
	Limit         int    `json:"limit,omitempty"`

	tagProvided bool
}

type MaintenanceReportOptions struct {
	Query          string `json:"query,omitempty"`
	DuplicateQuery string `json:"duplicate_query,omitempty"`
	DocID          string `json:"doc_id,omitempty"`
	Path           string `json:"path,omitempty"`
	PathPrefix     string `json:"path_prefix,omitempty"`
	Limit          int    `json:"limit,omitempty"`
}

func (options *DocumentListOptions) UnmarshalJSON(data []byte) error {
	type documentListOptionsAlias DocumentListOptions
	var decoded struct {
		documentListOptionsAlias
		Tag *string `json:"tag"`
	}
	if err := decodeStrictJSON(data, &decoded); err != nil {
		return err
	}
	*options = DocumentListOptions(decoded.documentListOptionsAlias)
	if decoded.Tag != nil {
		options.Tag = *decoded.Tag
		options.tagProvided = true
	}
	return nil
}

func (options *SearchOptions) UnmarshalJSON(data []byte) error {
	type searchOptionsAlias SearchOptions
	var decoded struct {
		searchOptionsAlias
		Tag *string `json:"tag"`
	}
	if err := decodeStrictJSON(data, &decoded); err != nil {
		return err
	}
	*options = SearchOptions(decoded.searchOptionsAlias)
	if decoded.Tag != nil {
		options.Tag = *decoded.Tag
		options.tagProvided = true
	}
	return nil
}

func (options *SemanticSearchOptions) UnmarshalJSON(data []byte) error {
	type semanticSearchOptionsAlias SemanticSearchOptions
	var decoded struct {
		semanticSearchOptionsAlias
		Tag *string `json:"tag"`
	}
	if err := decodeStrictJSON(data, &decoded); err != nil {
		return err
	}
	*options = SemanticSearchOptions(decoded.semanticSearchOptionsAlias)
	if decoded.Tag != nil {
		options.Tag = *decoded.Tag
		options.tagProvided = true
	}
	return nil
}

func (options *SearchDiagnosticsOptions) UnmarshalJSON(data []byte) error {
	type searchDiagnosticsOptionsAlias SearchDiagnosticsOptions
	var decoded struct {
		searchDiagnosticsOptionsAlias
		Tag *string `json:"tag"`
	}
	if err := decodeStrictJSON(data, &decoded); err != nil {
		return err
	}
	*options = SearchDiagnosticsOptions(decoded.searchDiagnosticsOptionsAlias)
	if decoded.Tag != nil {
		options.Tag = *decoded.Tag
		options.tagProvided = true
	}
	return nil
}

func decodeStrictJSON(data []byte, value any) error {
	decoder := json.NewDecoder(bytes.NewReader(data))
	decoder.DisallowUnknownFields()
	return decoder.Decode(value)
}

type RecordLookupOptions struct {
	Text       string `json:"text,omitempty"`
	EntityType string `json:"entity_type,omitempty"`
	Limit      int    `json:"limit,omitempty"`
	Cursor     string `json:"cursor,omitempty"`
}

type ServiceLookupOptions struct {
	Text      string `json:"text,omitempty"`
	Status    string `json:"status,omitempty"`
	Owner     string `json:"owner,omitempty"`
	Interface string `json:"interface,omitempty"`
	Limit     int    `json:"limit,omitempty"`
	Cursor    string `json:"cursor,omitempty"`
}

type DecisionLookupOptions struct {
	Text   string `json:"text,omitempty"`
	Status string `json:"status,omitempty"`
	Scope  string `json:"scope,omitempty"`
	Owner  string `json:"owner,omitempty"`
	Limit  int    `json:"limit,omitempty"`
	Cursor string `json:"cursor,omitempty"`
}

type ProvenanceEventOptions struct {
	RefKind   string `json:"ref_kind,omitempty"`
	RefID     string `json:"ref_id,omitempty"`
	SourceRef string `json:"source_ref,omitempty"`
	Limit     int    `json:"limit,omitempty"`
	Cursor    string `json:"cursor,omitempty"`
}

type ProjectionStateOptions struct {
	Projection string `json:"projection,omitempty"`
	RefKind    string `json:"ref_kind,omitempty"`
	RefID      string `json:"ref_id,omitempty"`
	Limit      int    `json:"limit,omitempty"`
	Cursor     string `json:"cursor,omitempty"`
}

type AuditContradictionsOptions struct {
	Query         string `json:"query,omitempty"`
	TargetPath    string `json:"target_path,omitempty"`
	Mode          string `json:"mode,omitempty"`
	ConflictQuery string `json:"conflict_query,omitempty"`
	Limit         int    `json:"limit,omitempty"`
}

type MemoryRouterRecallOptions struct {
	Query string `json:"query,omitempty"`
	Limit int    `json:"limit,omitempty"`
}

type SourceDiscoveryOptions struct {
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type SourceAuditReportOptions struct {
	Query         string `json:"query,omitempty"`
	TargetPath    string `json:"target_path,omitempty"`
	Mode          string `json:"mode,omitempty"`
	ConflictQuery string `json:"conflict_query,omitempty"`
	Limit         int    `json:"limit,omitempty"`
}

type EvidenceBundleOptions struct {
	Query      string `json:"query,omitempty"`
	EntityID   string `json:"entity_id,omitempty"`
	DecisionID string `json:"decision_id,omitempty"`
	RefKind    string `json:"ref_kind,omitempty"`
	RefID      string `json:"ref_id,omitempty"`
	Projection string `json:"projection,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type DecisionLookupReportOptions struct {
	Query      string `json:"query,omitempty"`
	DecisionID string `json:"decision_id,omitempty"`
	Status     string `json:"status,omitempty"`
	Scope      string `json:"scope,omitempty"`
	Owner      string `json:"owner,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type DuplicateCandidateOptions struct {
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type WorkflowGuideOptions struct {
	Intent string `json:"intent,omitempty"`
}

type StructuredStoreOptions struct {
	Domain     string `json:"domain,omitempty"`
	Query      string `json:"query,omitempty"`
	EntityType string `json:"entity_type,omitempty"`
	Status     string `json:"status,omitempty"`
	Owner      string `json:"owner,omitempty"`
	Interface  string `json:"interface,omitempty"`
	Scope      string `json:"scope,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type HybridRetrievalOptions struct {
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type GraphContextOptions struct {
	DocID      string `json:"doc_id,omitempty"`
	Path       string `json:"path,omitempty"`
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type GraphRelationshipOptions struct {
	DocID      string `json:"doc_id,omitempty"`
	Path       string `json:"path,omitempty"`
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type GraphRelationshipMaintenanceOptions struct {
	DocID      string `json:"doc_id,omitempty"`
	Path       string `json:"path,omitempty"`
	Query      string `json:"query,omitempty"`
	PathPrefix string `json:"path_prefix,omitempty"`
	Limit      int    `json:"limit,omitempty"`
}

type GitLifecycleOptions struct {
	Mode    string   `json:"mode,omitempty"`
	Paths   []string `json:"paths,omitempty"`
	Message string   `json:"message,omitempty"`
	Limit   int      `json:"limit,omitempty"`
}

type WebSearchPlanOptions struct {
	Query   string                 `json:"query,omitempty"`
	Results []WebSearchResultInput `json:"results,omitempty"`
	Limit   int                    `json:"limit,omitempty"`
}

type WebSearchResultInput struct {
	URL          string `json:"url,omitempty"`
	Title        string `json:"title,omitempty"`
	Snippet      string `json:"snippet,omitempty"`
	SourceType   string `json:"source_type,omitempty"`
	AccessStatus string `json:"access_status,omitempty"`
}

type ArtifactPlanOptions struct {
	Content        string            `json:"content,omitempty"`
	LocalPath      string            `json:"local_path,omitempty"`
	SourceURL      string            `json:"source_url,omitempty"`
	SourceType     string            `json:"source_type,omitempty"`
	ArtifactKind   string            `json:"artifact_kind,omitempty"`
	TextExtraction string            `json:"text_extraction,omitempty"`
	OCRProvider    string            `json:"ocr_provider,omitempty"`
	Path           string            `json:"path,omitempty"`
	Title          string            `json:"title,omitempty"`
	Body           string            `json:"body,omitempty"`
	Tags           []string          `json:"tags,omitempty"`
	Fields         map[string]string `json:"fields,omitempty"`
	DuplicateQuery string            `json:"duplicate_query,omitempty"`
	PathPrefix     string            `json:"path_prefix,omitempty"`
	Limit          int               `json:"limit,omitempty"`
}

type MoveDocumentOptions struct {
	DocID         string `json:"doc_id,omitempty"`
	Path          string `json:"path,omitempty"`
	TargetPath    string `json:"target_path,omitempty"`
	UpdateLinks   *bool  `json:"update_links,omitempty"`
	UpdateIndexes bool   `json:"update_indexes,omitempty"`
}

type PathCleanupOptions struct {
	DocID         string `json:"doc_id,omitempty"`
	Path          string `json:"path,omitempty"`
	PathPrefix    string `json:"path_prefix,omitempty"`
	Query         string `json:"query,omitempty"`
	Mode          string `json:"mode,omitempty"`
	CleanupKind   string `json:"cleanup_kind,omitempty"`
	TargetPrefix  string `json:"target_prefix,omitempty"`
	UpdateIndexes bool   `json:"update_indexes,omitempty"`
	Limit         int    `json:"limit,omitempty"`
}

type RetrievalTaskResult struct {
	Rejected                     bool                              `json:"rejected"`
	RejectionReason              string                            `json:"rejection_reason,omitempty"`
	Search                       *SearchResult                     `json:"search,omitempty"`
	Links                        *DocumentLinks                    `json:"links,omitempty"`
	Graph                        *GraphNeighborhood                `json:"graph,omitempty"`
	Records                      *RecordLookupResult               `json:"records,omitempty"`
	Entity                       *RecordEntity                     `json:"entity,omitempty"`
	Services                     *ServiceLookupResult              `json:"services,omitempty"`
	Service                      *ServiceRecord                    `json:"service,omitempty"`
	Decisions                    *DecisionLookupResult             `json:"decisions,omitempty"`
	Decision                     *DecisionRecord                   `json:"decision,omitempty"`
	Provenance                   *ProvenanceEventList              `json:"provenance,omitempty"`
	Projections                  *ProjectionStateList              `json:"projections,omitempty"`
	Audit                        *AuditContradictionsResult        `json:"audit,omitempty"`
	MemoryRouterRecall           *MemoryRouterRecallReport         `json:"memory_router_recall,omitempty"`
	SourceDiscovery              *SourceDiscoveryReport            `json:"source_discovery,omitempty"`
	SourceAudit                  *SourceAuditReport                `json:"source_audit,omitempty"`
	EvidenceBundle               *EvidenceBundleReport             `json:"evidence_bundle,omitempty"`
	DecisionLookup               *DecisionLookupReport             `json:"decision_lookup,omitempty"`
	DuplicateCandidate           *DuplicateCandidateReport         `json:"duplicate_candidate,omitempty"`
	WorkflowGuide                *WorkflowGuideReport              `json:"workflow_guide,omitempty"`
	StructuredStore              *StructuredStoreReport            `json:"structured_store,omitempty"`
	HybridRetrieval              *HybridRetrievalReport            `json:"hybrid_retrieval,omitempty"`
	GraphContext                 *GraphContextReport               `json:"graph_context,omitempty"`
	GraphRelationship            *GraphRelationshipReport          `json:"graph_relationship,omitempty"`
	GraphRelationshipMaintenance *GraphRelationshipMaintenancePlan `json:"graph_relationship_maintenance,omitempty"`
	SemanticSearch               *SemanticSearchResult             `json:"semantic_search,omitempty"`
	RetrievalEvalCapture         *RetrievalEvalCaptureReport       `json:"retrieval_eval_capture,omitempty"`
	RetrievalEvalReplay          *RetrievalEvalReplayReport        `json:"retrieval_eval_replay,omitempty"`
	SearchDiagnostics            *SearchDiagnosticsReport          `json:"search_diagnostics,omitempty"`
	Maintenance                  *MaintenanceReport                `json:"maintenance,omitempty"`
	Summary                      string                            `json:"summary"`
}

type CompileSynthesisResult struct {
	SelectedPath         string            `json:"selected_path"`
	DocumentID           string            `json:"document_id"`
	ExistingCandidate    bool              `json:"existing_candidate"`
	SourceRefs           []string          `json:"source_refs"`
	SourceEvidence       []Citation        `json:"source_evidence,omitempty"`
	CandidateStatus      string            `json:"candidate_status"`
	DuplicateStatus      string            `json:"duplicate_status"`
	ProvenanceRefs       []string          `json:"provenance_refs,omitempty"`
	ProjectionFreshness  []ProjectionState `json:"projection_freshness,omitempty"`
	WriteStatus          string            `json:"write_status"`
	ValidationBoundaries string            `json:"validation_boundaries"`
	AuthorityLimits      string            `json:"authority_limits"`
	FinalAnswer          string            `json:"final_answer,omitempty"`
	AgentHandoff         *AgentHandoff     `json:"agent_handoff,omitempty"`
}

type GitLifecycleReport struct {
	Mode                 string                   `json:"mode"`
	GitStatus            string                   `json:"git_status"`
	Branch               string                   `json:"branch,omitempty"`
	Head                 string                   `json:"head,omitempty"`
	Paths                []string                 `json:"paths,omitempty"`
	DirtyPaths           []GitLifecyclePathStatus `json:"dirty_paths,omitempty"`
	History              []GitLifecycleCommit     `json:"history,omitempty"`
	CheckpointStatus     string                   `json:"checkpoint_status,omitempty"`
	CommitID             string                   `json:"commit_id,omitempty"`
	WriteStatus          string                   `json:"write_status"`
	ApprovalBoundary     string                   `json:"approval_boundary"`
	ValidationBoundaries string                   `json:"validation_boundaries"`
	AuthorityLimits      string                   `json:"authority_limits"`
	AgentHandoff         *AgentHandoff            `json:"agent_handoff,omitempty"`
}

type GitLifecyclePathStatus struct {
	Path   string `json:"path"`
	Status string `json:"status"`
}

type GitLifecycleCommit struct {
	CommitID  string `json:"commit_id"`
	ShortID   string `json:"short_id"`
	Authored  string `json:"authored"`
	Summary   string `json:"summary"`
	PathScope string `json:"path_scope,omitempty"`
}

type WebSearchPlan struct {
	Query                string               `json:"query"`
	Candidates           []WebSearchCandidate `json:"candidates,omitempty"`
	FetchStatus          string               `json:"fetch_status"`
	WriteStatus          string               `json:"write_status"`
	ApprovalBoundary     string               `json:"approval_boundary"`
	ValidationBoundaries string               `json:"validation_boundaries"`
	AuthorityLimits      string               `json:"authority_limits"`
	AgentHandoff         *AgentHandoff        `json:"agent_handoff,omitempty"`
}

type WebSearchCandidate struct {
	Rank                    int              `json:"rank"`
	URL                     string           `json:"url"`
	NormalizedURL           string           `json:"normalized_url"`
	Title                   string           `json:"title,omitempty"`
	Snippet                 string           `json:"snippet,omitempty"`
	SourceType              string           `json:"source_type"`
	AccessStatus            string           `json:"access_status"`
	CandidateStatus         string           `json:"candidate_status"`
	DuplicateStatus         string           `json:"duplicate_status"`
	CandidateSourcePaths    []string         `json:"candidate_source_paths,omitempty"`
	CandidateAssetPaths     []string         `json:"candidate_asset_paths,omitempty"`
	CandidateSynthesisPath  string           `json:"candidate_synthesis_path,omitempty"`
	ExistingSource          *DocumentSummary `json:"existing_source,omitempty"`
	NextIngestSourceRequest string           `json:"next_ingest_source_request,omitempty"`
}

type ArtifactCandidatePlan struct {
	ArtifactKind            string            `json:"artifact_kind"`
	SourceType              string            `json:"source_type,omitempty"`
	SourceURL               string            `json:"source_url,omitempty"`
	LocalArtifact           *LocalArtifact    `json:"local_artifact,omitempty"`
	OCRExtraction           *OCRExtraction    `json:"ocr_extraction,omitempty"`
	CandidatePath           string            `json:"candidate_path,omitempty"`
	CandidateTitle          string            `json:"candidate_title,omitempty"`
	BodyPreview             string            `json:"body_preview,omitempty"`
	Tags                    []string          `json:"tags,omitempty"`
	MetadataFields          map[string]string `json:"metadata_fields,omitempty"`
	DuplicateSearch         *SearchResult     `json:"duplicate_search,omitempty"`
	LikelyDuplicate         *SearchHit        `json:"likely_duplicate,omitempty"`
	ExistingSource          *DocumentSummary  `json:"existing_source,omitempty"`
	DuplicateStatus         string            `json:"duplicate_status"`
	Confidence              string            `json:"confidence"`
	ConfidenceReasons       []string          `json:"confidence_reasons,omitempty"`
	FetchStatus             string            `json:"fetch_status"`
	WriteStatus             string            `json:"write_status"`
	ApprovalBoundary        string            `json:"approval_boundary"`
	ValidationBoundaries    string            `json:"validation_boundaries"`
	AuthorityLimits         string            `json:"authority_limits"`
	NextCreateRequest       string            `json:"next_create_document_request,omitempty"`
	NextIngestSourceRequest string            `json:"next_ingest_source_request,omitempty"`
	AgentHandoff            *AgentHandoff     `json:"agent_handoff,omitempty"`
}

type LocalArtifact struct {
	SourceRef         string `json:"source_ref"`
	FileName          string `json:"file_name"`
	MIMEType          string `json:"mime_type"`
	SizeBytes         int64  `json:"size_bytes"`
	SHA256            string `json:"sha256"`
	Parser            string `json:"parser"`
	TextStatus        string `json:"text_status"`
	Confidence        string `json:"confidence"`
	PageCount         int    `json:"page_count,omitempty"`
	UnsupportedReason string `json:"unsupported_reason,omitempty"`
}

type OCRExtraction struct {
	Provider            string   `json:"provider"`
	ModuleName          string   `json:"module_name"`
	TextStatus          string   `json:"text_status"`
	Extractor           string   `json:"extractor"`
	ExtractorVersion    string   `json:"extractor_version,omitempty"`
	PDFExtractor        string   `json:"pdf_extractor,omitempty"`
	PDFExtractorVersion string   `json:"pdf_extractor_version,omitempty"`
	Language            string   `json:"language,omitempty"`
	PageCount           int      `json:"page_count,omitempty"`
	Confidence          string   `json:"confidence"`
	PrivacyPosture      string   `json:"privacy_posture"`
	Provenance          string   `json:"provenance"`
	Warnings            []string `json:"warnings,omitempty"`
}

type AgentHandoff struct {
	AnswerSummary               string   `json:"answer_summary"`
	Evidence                    []string `json:"evidence,omitempty"`
	ValidationBoundaries        string   `json:"validation_boundaries"`
	AuthorityLimits             string   `json:"authority_limits"`
	FollowUpPrimitiveInspection string   `json:"follow_up_primitive_inspection"`
}

type MemoryRouterRecallReport struct {
	QuerySummary          string        `json:"query_summary"`
	TemporalStatus        string        `json:"temporal_status"`
	CanonicalEvidenceRefs []string      `json:"canonical_evidence_refs"`
	StaleSessionStatus    string        `json:"stale_session_status"`
	FeedbackWeighting     string        `json:"feedback_weighting"`
	RoutingRationale      string        `json:"routing_rationale"`
	ProvenanceRefs        []string      `json:"provenance_refs"`
	SynthesisFreshness    string        `json:"synthesis_freshness"`
	ValidationBoundaries  string        `json:"validation_boundaries"`
	AuthorityLimits       string        `json:"authority_limits"`
	AgentHandoff          *AgentHandoff `json:"agent_handoff,omitempty"`
}

type SourceAuditReport struct {
	Query                     string                      `json:"query"`
	TargetPath                string                      `json:"target_path"`
	Mode                      string                      `json:"mode"`
	SelectedTargetPath        string                      `json:"selected_target_path,omitempty"`
	CandidateSynthesisPaths   []string                    `json:"candidate_synthesis_paths,omitempty"`
	SourcePaths               []string                    `json:"source_paths,omitempty"`
	Citations                 []Citation                  `json:"citations,omitempty"`
	CurrentSourcePaths        []string                    `json:"current_source_paths,omitempty"`
	SupersededSourcePaths     []string                    `json:"superseded_source_paths,omitempty"`
	ProvenanceInspected       []AuditProvenanceInspection `json:"provenance_inspected,omitempty"`
	ProjectionFreshnessBefore []ProjectionState           `json:"projection_freshness_before,omitempty"`
	ProjectionFreshnessAfter  []ProjectionState           `json:"projection_freshness_after,omitempty"`
	RepairStatus              string                      `json:"repair_status"`
	RepairApplied             bool                        `json:"repair_applied"`
	DuplicatePrevention       string                      `json:"duplicate_prevention"`
	UnresolvedConflictGroups  []AuditConflictGroup        `json:"unresolved_conflict_groups,omitempty"`
	FailureClassification     string                      `json:"failure_classification"`
	ValidationBoundaries      string                      `json:"validation_boundaries"`
	AuthorityLimits           string                      `json:"authority_limits"`
	AgentHandoff              *AgentHandoff               `json:"agent_handoff,omitempty"`
}

type SourceDiscoveryCategory struct {
	Category        string `json:"category"`
	PathPrefix      string `json:"path_prefix,omitempty"`
	SearchHits      int    `json:"search_hits"`
	ListedDocuments int    `json:"listed_documents"`
}

type SourceDiscoveryReport struct {
	QueryPresent         bool                      `json:"query_present"`
	PathPrefix           string                    `json:"path_prefix,omitempty"`
	SearchHitCount       int                       `json:"search_hit_count"`
	RepresentativeCount  int                       `json:"representative_count"`
	CitationCount        int                       `json:"citation_count"`
	SourceCategories     []SourceDiscoveryCategory `json:"source_categories,omitempty"`
	SanitizedSummary     string                    `json:"sanitized_summary"`
	ValidationBoundaries string                    `json:"validation_boundaries"`
	AuthorityLimits      string                    `json:"authority_limits"`
	AgentHandoff         *AgentHandoff             `json:"agent_handoff,omitempty"`
}

type EvidenceBundleReport struct {
	QuerySummary         string                `json:"query_summary"`
	Search               *SearchResult         `json:"search,omitempty"`
	Records              *RecordLookupResult   `json:"records,omitempty"`
	Entity               *RecordEntity         `json:"entity,omitempty"`
	Decisions            *DecisionLookupResult `json:"decisions,omitempty"`
	Decision             *DecisionRecord       `json:"decision,omitempty"`
	Citations            []Citation            `json:"citations,omitempty"`
	Provenance           *ProvenanceEventList  `json:"provenance,omitempty"`
	Projections          *ProjectionStateList  `json:"projections,omitempty"`
	ValidationBoundaries string                `json:"validation_boundaries"`
	AuthorityLimits      string                `json:"authority_limits"`
	AgentHandoff         *AgentHandoff         `json:"agent_handoff,omitempty"`
}

type DecisionLookupReport struct {
	Query                string                `json:"query,omitempty"`
	DecisionID           string                `json:"decision_id,omitempty"`
	Decisions            *DecisionLookupResult `json:"decisions,omitempty"`
	Decision             *DecisionRecord       `json:"decision,omitempty"`
	Records              *RecordLookupResult   `json:"records,omitempty"`
	Search               *SearchResult         `json:"search,omitempty"`
	Provenance           *ProvenanceEventList  `json:"provenance,omitempty"`
	Projections          *ProjectionStateList  `json:"projections,omitempty"`
	Citations            []Citation            `json:"citations,omitempty"`
	LookupStatus         string                `json:"lookup_status"`
	ValidationBoundaries string                `json:"validation_boundaries"`
	AuthorityLimits      string                `json:"authority_limits"`
	AgentHandoff         *AgentHandoff         `json:"agent_handoff,omitempty"`
}

type DuplicateCandidateReport struct {
	Query                string            `json:"query"`
	PathPrefix           string            `json:"path_prefix,omitempty"`
	Search               *SearchResult     `json:"search,omitempty"`
	Documents            []DocumentSummary `json:"documents,omitempty"`
	LikelyTarget         *DocumentSummary  `json:"likely_target,omitempty"`
	EvidenceInspected    []string          `json:"evidence_inspected"`
	DuplicateStatus      string            `json:"duplicate_status"`
	WriteStatus          string            `json:"write_status"`
	ApprovalBoundary     string            `json:"approval_boundary"`
	ValidationBoundaries string            `json:"validation_boundaries"`
	AuthorityLimits      string            `json:"authority_limits"`
	AgentHandoff         *AgentHandoff     `json:"agent_handoff,omitempty"`
}

type WorkflowGuideReport struct {
	Intent               string                   `json:"intent"`
	RecommendedSurface   string                   `json:"recommended_surface"`
	RunnerDomain         string                   `json:"runner_domain"`
	RequestShape         string                   `json:"request_shape"`
	UseWhen              string                   `json:"use_when"`
	DoNotUseFor          []string                 `json:"do_not_use_for,omitempty"`
	CandidateSurfaces    []WorkflowGuideCandidate `json:"candidate_surfaces,omitempty"`
	ValidationBoundaries string                   `json:"validation_boundaries"`
	AuthorityLimits      string                   `json:"authority_limits"`
	AgentHandoff         *AgentHandoff            `json:"agent_handoff,omitempty"`
}

type WorkflowGuideCandidate struct {
	Surface        string `json:"surface"`
	Status         string `json:"status"`
	SelectionRule  string `json:"selection_rule"`
	Boundary       string `json:"boundary"`
	RequestExample string `json:"request_example,omitempty"`
}

type StructuredStoreReport struct {
	Domain               string                     `json:"domain"`
	Query                string                     `json:"query,omitempty"`
	EntityType           string                     `json:"entity_type,omitempty"`
	Status               string                     `json:"status,omitempty"`
	Owner                string                     `json:"owner,omitempty"`
	Interface            string                     `json:"interface,omitempty"`
	Scope                string                     `json:"scope,omitempty"`
	Records              *RecordLookupResult        `json:"records,omitempty"`
	Services             *ServiceLookupResult       `json:"services,omitempty"`
	Decisions            *DecisionLookupResult      `json:"decisions,omitempty"`
	Projections          *ProjectionStateList       `json:"projections,omitempty"`
	CandidateSurfaces    []StructuredStoreCandidate `json:"candidate_surfaces,omitempty"`
	Recommendation       string                     `json:"recommendation"`
	SafetyPass           string                     `json:"safety_pass"`
	CapabilityPass       string                     `json:"capability_pass"`
	UXQuality            string                     `json:"ux_quality"`
	EvidencePosture      string                     `json:"evidence_posture"`
	ValidationBoundaries string                     `json:"validation_boundaries"`
	AuthorityLimits      string                     `json:"authority_limits"`
	EvidenceInspected    []string                   `json:"evidence_inspected,omitempty"`
	AgentHandoff         *AgentHandoff              `json:"agent_handoff,omitempty"`
}

type StructuredStoreCandidate struct {
	Surface        string   `json:"surface"`
	Status         string   `json:"status"`
	Safety         string   `json:"safety"`
	Capability     string   `json:"capability"`
	UXQuality      string   `json:"ux_quality"`
	Implementation []string `json:"implementation,omitempty"`
}

type HybridRetrievalReport struct {
	Query                string                     `json:"query"`
	PathPrefix           string                     `json:"path_prefix,omitempty"`
	LexicalSearch        *SearchResult              `json:"lexical_search,omitempty"`
	CandidateSurfaces    []HybridRetrievalCandidate `json:"candidate_surfaces,omitempty"`
	Recommendation       string                     `json:"recommendation"`
	SafetyPass           string                     `json:"safety_pass"`
	CapabilityPass       string                     `json:"capability_pass"`
	UXQuality            string                     `json:"ux_quality"`
	PerformancePosture   string                     `json:"performance_posture"`
	EvidencePosture      string                     `json:"evidence_posture"`
	ValidationBoundaries string                     `json:"validation_boundaries"`
	AuthorityLimits      string                     `json:"authority_limits"`
	EvidenceInspected    []string                   `json:"evidence_inspected,omitempty"`
	AgentHandoff         *AgentHandoff              `json:"agent_handoff,omitempty"`
}

type HybridRetrievalCandidate struct {
	Surface        string   `json:"surface"`
	Status         string   `json:"status"`
	Safety         string   `json:"safety"`
	Capability     string   `json:"capability"`
	UXQuality      string   `json:"ux_quality"`
	Implementation []string `json:"implementation,omitempty"`
}

type GraphContextReport struct {
	Query                     string                      `json:"query,omitempty"`
	Path                      string                      `json:"path,omitempty"`
	DocID                     string                      `json:"doc_id,omitempty"`
	PathPrefix                string                      `json:"path_prefix,omitempty"`
	SourceDocument            *DocumentSummary            `json:"source_document,omitempty"`
	SourceSelection           string                      `json:"source_selection"`
	SourceCandidates          []SearchHit                 `json:"source_candidates,omitempty"`
	CanonicalRelationshipText []CanonicalRelationshipText `json:"canonical_relationship_text,omitempty"`
	Links                     *DocumentLinks              `json:"links,omitempty"`
	Graph                     *GraphNeighborhood          `json:"graph,omitempty"`
	GraphProjection           *ProjectionStateList        `json:"graph_projection,omitempty"`
	Provenance                *ProvenanceEventList        `json:"provenance,omitempty"`
	ProvenanceRefs            []string                    `json:"provenance_refs,omitempty"`
	CandidateSurfaces         []GraphContextCandidate     `json:"candidate_surfaces,omitempty"`
	Recommendation            string                      `json:"recommendation"`
	SafetyPass                string                      `json:"safety_pass"`
	CapabilityPass            string                      `json:"capability_pass"`
	UXQuality                 string                      `json:"ux_quality"`
	EvidencePosture           string                      `json:"evidence_posture"`
	ValidationBoundaries      string                      `json:"validation_boundaries"`
	AuthorityLimits           string                      `json:"authority_limits"`
	EvidenceInspected         []string                    `json:"evidence_inspected,omitempty"`
	AgentHandoff              *AgentHandoff               `json:"agent_handoff,omitempty"`
}

type CanonicalRelationshipText struct {
	Text     string   `json:"text"`
	Citation Citation `json:"citation"`
}

type GraphContextCandidate struct {
	Surface        string   `json:"surface"`
	Status         string   `json:"status"`
	Safety         string   `json:"safety"`
	Capability     string   `json:"capability"`
	UXQuality      string   `json:"ux_quality"`
	Implementation []string `json:"implementation,omitempty"`
}

type GraphRelationshipReport struct {
	Query                       string                           `json:"query,omitempty"`
	Path                        string                           `json:"path,omitempty"`
	DocID                       string                           `json:"doc_id,omitempty"`
	PathPrefix                  string                           `json:"path_prefix,omitempty"`
	SourceDocument              *DocumentSummary                 `json:"source_document,omitempty"`
	SourceSelection             string                           `json:"source_selection"`
	SourceCandidates            []SearchHit                      `json:"source_candidates,omitempty"`
	RelationshipPaths           []GraphRelationshipPath          `json:"relationship_paths,omitempty"`
	DirectRelationships         []GraphRelationshipEvidence      `json:"direct_relationships,omitempty"`
	DerivedRelationships        []GraphRelationshipEvidence      `json:"derived_relationships,omitempty"`
	TypedRelationshipCandidates []GraphRelationshipTypeCandidate `json:"typed_relationship_candidates,omitempty"`
	AuditFindings               []GraphRelationshipAuditFinding  `json:"audit_findings,omitempty"`
	GraphProjection             *ProjectionStateList             `json:"graph_projection,omitempty"`
	Provenance                  *ProvenanceEventList             `json:"provenance,omitempty"`
	ProvenanceRefs              []string                         `json:"provenance_refs,omitempty"`
	CandidateSurfaces           []GraphRelationshipCandidate     `json:"candidate_surfaces,omitempty"`
	Recommendation              string                           `json:"recommendation"`
	SafetyPass                  string                           `json:"safety_pass"`
	CapabilityPass              string                           `json:"capability_pass"`
	UXQuality                   string                           `json:"ux_quality"`
	EvidencePosture             string                           `json:"evidence_posture"`
	ValidationBoundaries        string                           `json:"validation_boundaries"`
	AuthorityLimits             string                           `json:"authority_limits"`
	EvidenceInspected           []string                         `json:"evidence_inspected,omitempty"`
	AgentHandoff                *AgentHandoff                    `json:"agent_handoff,omitempty"`
}

type GraphRelationshipPath struct {
	Direction string     `json:"direction"`
	DocID     string     `json:"doc_id,omitempty"`
	Path      string     `json:"path,omitempty"`
	Title     string     `json:"title,omitempty"`
	Evidence  string     `json:"evidence"`
	Citations []Citation `json:"citations,omitempty"`
}

type GraphRelationshipEvidence struct {
	Kind              string     `json:"kind"`
	RelationshipType  string     `json:"relationship_type,omitempty"`
	Direction         string     `json:"direction,omitempty"`
	Source            string     `json:"source"`
	EvidenceText      string     `json:"evidence_text,omitempty"`
	Citations         []Citation `json:"citations,omitempty"`
	Authority         string     `json:"authority"`
	InferenceBoundary string     `json:"inference_boundary,omitempty"`
}

type GraphRelationshipTypeCandidate struct {
	RelationshipType string   `json:"relationship_type"`
	EvidenceText     string   `json:"evidence_text"`
	Citation         Citation `json:"citation"`
	Status           string   `json:"status"`
	Authority        string   `json:"authority"`
}

type GraphRelationshipAuditFinding struct {
	Kind      string     `json:"kind"`
	Status    string     `json:"status"`
	Evidence  string     `json:"evidence"`
	Citations []Citation `json:"citations,omitempty"`
}

type GraphRelationshipCandidate struct {
	Surface        string   `json:"surface"`
	Status         string   `json:"status"`
	Safety         string   `json:"safety"`
	Capability     string   `json:"capability"`
	UXQuality      string   `json:"ux_quality"`
	Implementation []string `json:"implementation,omitempty"`
}

type GraphRelationshipMaintenancePlan struct {
	Query                     string                                  `json:"query,omitempty"`
	Path                      string                                  `json:"path,omitempty"`
	DocID                     string                                  `json:"doc_id,omitempty"`
	PathPrefix                string                                  `json:"path_prefix,omitempty"`
	SourceDocument            *DocumentSummary                        `json:"source_document,omitempty"`
	SourceSelection           string                                  `json:"source_selection"`
	ProposedActions           []GraphRelationshipMaintenanceAction    `json:"proposed_actions,omitempty"`
	CandidateSectionHeading   string                                  `json:"candidate_section_heading"`
	CandidateSectionContent   string                                  `json:"candidate_section_content"`
	NextReplaceSectionRequest string                                  `json:"next_replace_section_request,omitempty"`
	NextAppendDocumentRequest string                                  `json:"next_append_document_request,omitempty"`
	WriteStatus               string                                  `json:"write_status"`
	ApprovalBoundary          string                                  `json:"approval_boundary"`
	RollbackAuditPath         string                                  `json:"rollback_audit_path"`
	DuplicateHandling         string                                  `json:"duplicate_handling"`
	FailureModes              []string                                `json:"failure_modes,omitempty"`
	GraphProjection           *ProjectionStateList                    `json:"graph_projection,omitempty"`
	ProvenanceRefs            []string                                `json:"provenance_refs,omitempty"`
	CandidateSurfaces         []GraphRelationshipMaintenanceCandidate `json:"candidate_surfaces,omitempty"`
	Recommendation            string                                  `json:"recommendation"`
	SafetyPass                string                                  `json:"safety_pass"`
	CapabilityPass            string                                  `json:"capability_pass"`
	UXQuality                 string                                  `json:"ux_quality"`
	EvidencePosture           string                                  `json:"evidence_posture"`
	ValidationBoundaries      string                                  `json:"validation_boundaries"`
	AuthorityLimits           string                                  `json:"authority_limits"`
	EvidenceInspected         []string                                `json:"evidence_inspected,omitempty"`
	AgentHandoff              *AgentHandoff                           `json:"agent_handoff,omitempty"`
}

type GraphRelationshipMaintenanceAction struct {
	Kind      string     `json:"kind"`
	Status    string     `json:"status"`
	Evidence  string     `json:"evidence"`
	NextStep  string     `json:"next_step"`
	Citations []Citation `json:"citations,omitempty"`
}

type GraphRelationshipMaintenanceCandidate struct {
	Surface        string   `json:"surface"`
	Status         string   `json:"status"`
	Safety         string   `json:"safety"`
	Capability     string   `json:"capability"`
	UXQuality      string   `json:"ux_quality"`
	Implementation []string `json:"implementation,omitempty"`
}

type SemanticSearchResult struct {
	Query                string                 `json:"query"`
	PathPrefix           string                 `json:"path_prefix,omitempty"`
	Tag                  string                 `json:"tag,omitempty"`
	MetadataKey          string                 `json:"metadata_key,omitempty"`
	MetadataValue        string                 `json:"metadata_value,omitempty"`
	Provider             SemanticProviderStatus `json:"provider"`
	Cache                SemanticCacheStatus    `json:"cache"`
	Ranking              string                 `json:"ranking"`
	SearchStatus         string                 `json:"search_status"`
	DuplicateChunks      int                    `json:"duplicate_chunks"`
	Hits                 []SearchHit            `json:"hits,omitempty"`
	PrivacyDisclosure    string                 `json:"privacy_disclosure"`
	ValidationBoundaries string                 `json:"validation_boundaries"`
	AuthorityLimits      string                 `json:"authority_limits"`
	AgentHandoff         *AgentHandoff          `json:"agent_handoff,omitempty"`
}

type SemanticProviderStatus struct {
	Provider         string  `json:"provider"`
	Model            string  `json:"model"`
	Status           string  `json:"status"`
	OllamaURL        string  `json:"ollama_url,omitempty"`
	CredentialRef    string  `json:"credential_ref,omitempty"`
	EmbeddingDims    int     `json:"embedding_dimensions,omitempty"`
	RequestCount     int     `json:"request_count,omitempty"`
	RetryCount       int     `json:"retry_count,omitempty"`
	BackoffSeconds   float64 `json:"backoff_seconds,omitempty"`
	ErrorSummary     string  `json:"error_summary,omitempty"`
	FallbackProvider string  `json:"fallback_provider,omitempty"`
}

type SemanticCacheStatus struct {
	Status       string `json:"status"`
	CacheRef     string `json:"cache_ref,omitempty"`
	ChunkCount   int    `json:"chunk_count"`
	RebuiltCount int    `json:"rebuilt_count,omitempty"`
}

type RetrievalEvalCaptureReport struct {
	Case                 RetrievalEvalCase `json:"case"`
	CapturePath          string            `json:"capture_path"`
	WriteStatus          string            `json:"write_status"`
	ValidationBoundaries string            `json:"validation_boundaries"`
	AuthorityLimits      string            `json:"authority_limits"`
	AgentHandoff         *AgentHandoff     `json:"agent_handoff,omitempty"`
}

type RetrievalEvalReplayReport struct {
	CapturePath              string                    `json:"capture_path"`
	CapturedCases            int                       `json:"captured_cases"`
	ComparedCases            int                       `json:"compared_cases"`
	AverageJaccard           float64                   `json:"average_jaccard"`
	Top1MatchRate            float64                   `json:"top1_match_rate"`
	AverageCapturedLatencyMS float64                   `json:"average_captured_latency_ms"`
	AverageReplayLatencyMS   float64                   `json:"average_replay_latency_ms"`
	Cases                    []RetrievalEvalReplayCase `json:"cases,omitempty"`
	ValidationBoundaries     string                    `json:"validation_boundaries"`
	AuthorityLimits          string                    `json:"authority_limits"`
	AgentHandoff             *AgentHandoff             `json:"agent_handoff,omitempty"`
}

type RetrievalEvalCase struct {
	SchemaVersion string                      `json:"schema_version"`
	CaseID        string                      `json:"case_id"`
	Action        string                      `json:"action"`
	Query         string                      `json:"query"`
	Filters       RetrievalEvalFilters        `json:"filters"`
	Results       []RetrievalEvalResultRef    `json:"results,omitempty"`
	Provider      RetrievalEvalProviderStatus `json:"provider"`
	LatencyMS     float64                     `json:"latency_ms"`
	CapturedAt    time.Time                   `json:"captured_at"`
}

type RetrievalEvalFilters struct {
	PathPrefix    string `json:"path_prefix,omitempty"`
	MetadataKey   string `json:"metadata_key,omitempty"`
	MetadataValue string `json:"metadata_value,omitempty"`
	Tag           string `json:"tag,omitempty"`
	Limit         int    `json:"limit,omitempty"`
}

type RetrievalEvalResultRef struct {
	Rank    int    `json:"rank"`
	DocID   string `json:"doc_id"`
	ChunkID string `json:"chunk_id"`
	Path    string `json:"path"`
}

type RetrievalEvalProviderStatus struct {
	Mode         string `json:"mode"`
	Provider     string `json:"provider,omitempty"`
	Status       string `json:"status"`
	Model        string `json:"model,omitempty"`
	CacheStatus  string `json:"cache_status,omitempty"`
	SearchStatus string `json:"search_status,omitempty"`
}

type RetrievalEvalReplayCase struct {
	CaseID            string                   `json:"case_id"`
	Action            string                   `json:"action"`
	Query             string                   `json:"query"`
	CapturedAt        time.Time                `json:"captured_at"`
	CapturedResults   []RetrievalEvalResultRef `json:"captured_results,omitempty"`
	CurrentResults    []RetrievalEvalResultRef `json:"current_results,omitempty"`
	Jaccard           float64                  `json:"jaccard"`
	Top1Match         bool                     `json:"top1_match"`
	CapturedLatencyMS float64                  `json:"captured_latency_ms"`
	ReplayLatencyMS   float64                  `json:"replay_latency_ms"`
	Status            string                   `json:"status"`
}

type SearchDiagnosticsReport struct {
	Query                  string                `json:"query"`
	Intent                 string                `json:"intent,omitempty"`
	PathPrefix             string                `json:"path_prefix,omitempty"`
	Tag                    string                `json:"tag,omitempty"`
	MetadataKey            string                `json:"metadata_key,omitempty"`
	MetadataValue          string                `json:"metadata_value,omitempty"`
	LexicalSearch          *SearchResult         `json:"lexical_search,omitempty"`
	RecommendedAction      string                `json:"recommended_action"`
	RecommendationReason   string                `json:"recommendation_reason"`
	ModePostures           []SearchModePosture   `json:"mode_postures,omitempty"`
	ModulePostures         []SearchModulePosture `json:"module_postures,omitempty"`
	TuningVisibility       []SearchTuningKnob    `json:"tuning_visibility,omitempty"`
	NoDefaultRankingChange bool                  `json:"no_default_ranking_change"`
	CostPosture            string                `json:"cost_posture"`
	LatencyPosture         string                `json:"latency_posture"`
	ValidationBoundaries   string                `json:"validation_boundaries"`
	AuthorityLimits        string                `json:"authority_limits"`
	AgentHandoff           *AgentHandoff         `json:"agent_handoff,omitempty"`
}

type SearchModePosture struct {
	Mode           string `json:"mode"`
	Status         string `json:"status"`
	Ranking        string `json:"ranking"`
	UseWhen        string `json:"use_when"`
	CostPosture    string `json:"cost_posture"`
	LatencyPosture string `json:"latency_posture"`
	Boundary       string `json:"boundary"`
}

type SearchModulePosture struct {
	Provider           string `json:"provider"`
	ModuleName         string `json:"module_name,omitempty"`
	Enabled            bool   `json:"enabled"`
	Readiness          string `json:"readiness"`
	VerificationStatus string `json:"verification_status,omitempty"`
	CostPosture        string `json:"cost_posture"`
	LatencyPosture     string `json:"latency_posture"`
	ErrorSummary       string `json:"error_summary,omitempty"`
}

type SearchTuningKnob struct {
	Knob       string `json:"knob"`
	Value      string `json:"value"`
	Visibility string `json:"visibility"`
	Boundary   string `json:"boundary"`
}

type MaintenanceReport struct {
	Query                string                     `json:"query,omitempty"`
	DuplicateQuery       string                     `json:"duplicate_query,omitempty"`
	Path                 string                     `json:"path,omitempty"`
	DocID                string                     `json:"doc_id,omitempty"`
	PathPrefix           string                     `json:"path_prefix,omitempty"`
	Layout               *KnowledgeLayout           `json:"layout,omitempty"`
	Projections          *ProjectionStateList       `json:"projections,omitempty"`
	RelationshipContext  *GraphRelationshipReport   `json:"relationship_context,omitempty"`
	DuplicateCandidate   *DuplicateCandidateReport  `json:"duplicate_candidate,omitempty"`
	ModulePostures       []MaintenanceModulePosture `json:"module_postures,omitempty"`
	GitLifecycle         *GitLifecycleReport        `json:"git_lifecycle,omitempty"`
	Findings             []MaintenanceFinding       `json:"findings,omitempty"`
	WriteStatus          string                     `json:"write_status"`
	Recommendation       string                     `json:"recommendation"`
	ValidationBoundaries string                     `json:"validation_boundaries"`
	AuthorityLimits      string                     `json:"authority_limits"`
	AgentHandoff         *AgentHandoff              `json:"agent_handoff,omitempty"`
}

type MaintenanceModulePosture struct {
	Kind               string `json:"kind"`
	Provider           string `json:"provider"`
	ModuleName         string `json:"module_name,omitempty"`
	Enabled            bool   `json:"enabled"`
	VerificationStatus string `json:"verification_status,omitempty"`
	Posture            string `json:"posture"`
}

type MaintenanceFinding struct {
	Area     string   `json:"area"`
	Status   string   `json:"status"`
	Summary  string   `json:"summary"`
	Evidence []string `json:"evidence,omitempty"`
	NextStep string   `json:"next_step,omitempty"`
}

type AuditContradictionsResult struct {
	Query                     string                      `json:"query"`
	TargetPath                string                      `json:"target_path"`
	Mode                      string                      `json:"mode"`
	SelectedTargetPath        string                      `json:"selected_target_path,omitempty"`
	CandidateSynthesisPaths   []string                    `json:"candidate_synthesis_paths,omitempty"`
	SourcePaths               []string                    `json:"source_paths,omitempty"`
	Citations                 []Citation                  `json:"citations,omitempty"`
	CurrentSourcePaths        []string                    `json:"current_source_paths,omitempty"`
	SupersededSourcePaths     []string                    `json:"superseded_source_paths,omitempty"`
	ProvenanceInspected       []AuditProvenanceInspection `json:"provenance_inspected,omitempty"`
	ProjectionFreshnessBefore []ProjectionState           `json:"projection_freshness_before,omitempty"`
	ProjectionFreshnessAfter  []ProjectionState           `json:"projection_freshness_after,omitempty"`
	RepairStatus              string                      `json:"repair_status"`
	RepairApplied             bool                        `json:"repair_applied"`
	DuplicatePrevention       string                      `json:"duplicate_prevention"`
	UnresolvedConflictGroups  []AuditConflictGroup        `json:"unresolved_conflict_groups,omitempty"`
	FailureClassification     string                      `json:"failure_classification"`
}

type AuditProvenanceInspection struct {
	RefKind    string            `json:"ref_kind"`
	RefID      string            `json:"ref_id"`
	SourcePath string            `json:"source_path,omitempty"`
	EventIDs   []string          `json:"event_ids,omitempty"`
	EventTypes []string          `json:"event_types,omitempty"`
	Details    map[string]string `json:"details,omitempty"`
}

type AuditConflictGroup struct {
	Query       string   `json:"query"`
	SourcePaths []string `json:"source_paths,omitempty"`
	Claims      []string `json:"claims,omitempty"`
	Status      string   `json:"status"`
	Reason      string   `json:"reason"`
}

type Paths struct {
	DatabasePath string `json:"database_path"`
	VaultRoot    string `json:"vault_root"`
}

type KnowledgeLayout struct {
	Valid                  bool                   `json:"valid"`
	Mode                   string                 `json:"mode"`
	ConfigArtifactRequired bool                   `json:"config_artifact_required"`
	ConfigArtifact         string                 `json:"config_artifact"`
	Paths                  Paths                  `json:"paths"`
	IgnoredPathRules       []string               `json:"ignored_path_rules,omitempty"`
	IgnoredPathCount       int                    `json:"ignored_path_count"`
	IgnoredDirectoryCount  int                    `json:"ignored_directory_count"`
	IgnoredFileCount       int                    `json:"ignored_file_count"`
	IgnoredPaths           []string               `json:"ignored_paths,omitempty"`
	IgnoredPathsTruncated  bool                   `json:"ignored_paths_truncated,omitempty"`
	ConventionalPaths      []LayoutPathConvention `json:"conventional_paths,omitempty"`
	DocumentKinds          []LayoutDocumentKind   `json:"document_kinds,omitempty"`
	Checks                 []KnowledgeLayoutCheck `json:"checks,omitempty"`
}

type LayoutPathConvention struct {
	Name        string `json:"name"`
	PathPrefix  string `json:"path_prefix"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
}

type LayoutDocumentKind struct {
	Kind        string   `json:"kind"`
	Description string   `json:"description"`
	Selectors   []string `json:"selectors,omitempty"`
	Required    []string `json:"required,omitempty"`
}

type KnowledgeLayoutCheck struct {
	ID      string            `json:"id"`
	Status  string            `json:"status"`
	Message string            `json:"message"`
	Path    string            `json:"path,omitempty"`
	DocID   string            `json:"doc_id,omitempty"`
	Details map[string]string `json:"details,omitempty"`
}

type Document struct {
	DocID     string            `json:"doc_id"`
	Path      string            `json:"path"`
	Title     string            `json:"title"`
	Body      string            `json:"body"`
	Headings  []string          `json:"headings,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

type DocumentSummary struct {
	DocID     string            `json:"doc_id"`
	Path      string            `json:"path"`
	Title     string            `json:"title"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	UpdatedAt time.Time         `json:"updated_at"`
}

type Citation struct {
	DocID     string `json:"doc_id"`
	ChunkID   string `json:"chunk_id"`
	Path      string `json:"path"`
	Heading   string `json:"heading,omitempty"`
	LineStart int    `json:"line_start,omitempty"`
	LineEnd   int    `json:"line_end,omitempty"`
}

type SearchHit struct {
	Rank      int        `json:"rank"`
	Score     float64    `json:"score"`
	DocID     string     `json:"doc_id"`
	ChunkID   string     `json:"chunk_id"`
	Title     string     `json:"title"`
	Snippet   string     `json:"snippet"`
	Citations []Citation `json:"citations,omitempty"`
}

type SearchResult struct {
	Hits     []SearchHit `json:"hits,omitempty"`
	PageInfo PageInfo    `json:"page_info,omitempty"`
}

type PageInfo struct {
	NextCursor string `json:"next_cursor,omitempty"`
	HasMore    bool   `json:"has_more,omitempty"`
}

type DocumentLink struct {
	DocID     string     `json:"doc_id"`
	Path      string     `json:"path"`
	Title     string     `json:"title"`
	Citations []Citation `json:"citations,omitempty"`
}

type DocumentLinks struct {
	DocID    string         `json:"doc_id"`
	Outgoing []DocumentLink `json:"outgoing,omitempty"`
	Incoming []DocumentLink `json:"incoming,omitempty"`
}

type DocumentMovePlan struct {
	DocID                string                      `json:"doc_id"`
	SourcePath           string                      `json:"source_path"`
	TargetPath           string                      `json:"target_path"`
	Title                string                      `json:"title"`
	FrontmatterID        string                      `json:"frontmatter_id"`
	StableIDStatus       string                      `json:"stable_id_status"`
	DuplicateRisk        string                      `json:"duplicate_risk"`
	ExistingTarget       *DocumentSummary            `json:"existing_target,omitempty"`
	OutgoingLinks        []DocumentLink              `json:"outgoing_links,omitempty"`
	IncomingLinks        []DocumentLink              `json:"incoming_links,omitempty"`
	LinkUpdates          []DocumentLinkUpdate        `json:"link_updates,omitempty"`
	IndexUpdates         []DocumentIndexUpdate       `json:"index_updates,omitempty"`
	ProjectionRefresh    []DocumentProjectionRefresh `json:"projection_refresh,omitempty"`
	ValidationWarnings   []string                    `json:"validation_warnings,omitempty"`
	WriteStatus          string                      `json:"write_status"`
	ApprovalBoundary     string                      `json:"approval_boundary"`
	ValidationBoundaries string                      `json:"validation_boundaries"`
}

type DocumentMoveResult struct {
	Plan                DocumentMovePlan      `json:"plan"`
	Document            Document              `json:"document"`
	LinkUpdatesApplied  []DocumentLinkUpdate  `json:"link_updates_applied,omitempty"`
	IndexUpdatesApplied []DocumentIndexUpdate `json:"index_updates_applied,omitempty"`
	ProvenanceRefs      []string              `json:"provenance_refs,omitempty"`
	ProjectionFreshness []ProjectionState     `json:"projection_freshness,omitempty"`
	WriteStatus         string                `json:"write_status"`
}

type DocumentLinkUpdate struct {
	DocID          string `json:"doc_id"`
	Path           string `json:"path"`
	OldTarget      string `json:"old_target"`
	NewTarget      string `json:"new_target"`
	Occurrences    int    `json:"occurrences"`
	IndexCandidate bool   `json:"index_candidate,omitempty"`
}

type DocumentIndexUpdate struct {
	Path   string `json:"path"`
	Status string `json:"status"`
	Reason string `json:"reason"`
}

type DocumentProjectionRefresh struct {
	Projection string `json:"projection"`
	RefKind    string `json:"ref_kind"`
	RefID      string `json:"ref_id"`
	Status     string `json:"status"`
}

type PathCleanupPlan struct {
	Mode                 string                 `json:"mode"`
	CleanupKind          string                 `json:"cleanup_kind"`
	Scope                string                 `json:"scope"`
	Candidates           []PathCleanupCandidate `json:"candidates,omitempty"`
	AppliedCount         int                    `json:"applied_count,omitempty"`
	WriteStatus          string                 `json:"write_status"`
	ApprovalBoundary     string                 `json:"approval_boundary"`
	ValidationBoundaries string                 `json:"validation_boundaries"`
	AuthorityLimits      string                 `json:"authority_limits"`
	AgentHandoff         *AgentHandoff          `json:"agent_handoff,omitempty"`
}

type PathCleanupCandidate struct {
	Rank               int                 `json:"rank"`
	DocID              string              `json:"doc_id"`
	CurrentPath        string              `json:"current_path"`
	Title              string              `json:"title"`
	ProposedTargetPath string              `json:"proposed_target_path,omitempty"`
	RecommendedAction  string              `json:"recommended_action,omitempty"`
	Confidence         string              `json:"confidence"`
	Reason             string              `json:"reason"`
	DuplicateRisk      string              `json:"duplicate_risk"`
	MovePlan           *DocumentMovePlan   `json:"move_plan,omitempty"`
	NextRequest        string              `json:"next_request,omitempty"`
	MoveResult         *DocumentMoveResult `json:"move_result,omitempty"`
	WriteStatus        string              `json:"write_status"`
}

type GraphNode struct {
	NodeID    string     `json:"node_id"`
	Type      string     `json:"type"`
	Label     string     `json:"label"`
	Citations []Citation `json:"citations,omitempty"`
}

type GraphEdge struct {
	EdgeID     string     `json:"edge_id"`
	FromNodeID string     `json:"from_node_id"`
	ToNodeID   string     `json:"to_node_id"`
	Kind       string     `json:"kind"`
	Citations  []Citation `json:"citations,omitempty"`
}

type GraphNeighborhood struct {
	Nodes []GraphNode `json:"nodes,omitempty"`
	Edges []GraphEdge `json:"edges,omitempty"`
}

type RecordFact struct {
	Key        string     `json:"key"`
	Value      string     `json:"value"`
	ObservedAt *time.Time `json:"observed_at,omitempty"`
}

type RecordEntity struct {
	EntityID   string       `json:"entity_id"`
	EntityType string       `json:"entity_type"`
	Name       string       `json:"name"`
	Summary    string       `json:"summary"`
	Facts      []RecordFact `json:"facts,omitempty"`
	Citations  []Citation   `json:"citations,omitempty"`
	UpdatedAt  time.Time    `json:"updated_at"`
}

type RecordLookupResult struct {
	Entities []RecordEntity `json:"entities,omitempty"`
	PageInfo PageInfo       `json:"page_info,omitempty"`
}

type ServiceFact struct {
	Key        string     `json:"key"`
	Value      string     `json:"value"`
	ObservedAt *time.Time `json:"observed_at,omitempty"`
}

type ServiceRecord struct {
	ServiceID string        `json:"service_id"`
	Name      string        `json:"name"`
	Status    string        `json:"status,omitempty"`
	Owner     string        `json:"owner,omitempty"`
	Interface string        `json:"interface,omitempty"`
	Summary   string        `json:"summary"`
	Facts     []ServiceFact `json:"facts,omitempty"`
	Citations []Citation    `json:"citations,omitempty"`
	UpdatedAt time.Time     `json:"updated_at"`
}

type ServiceLookupResult struct {
	Services []ServiceRecord `json:"services,omitempty"`
	PageInfo PageInfo        `json:"page_info,omitempty"`
}

type DecisionRecord struct {
	DecisionID   string     `json:"decision_id"`
	Title        string     `json:"title"`
	Status       string     `json:"status,omitempty"`
	Scope        string     `json:"scope,omitempty"`
	Owner        string     `json:"owner,omitempty"`
	Date         string     `json:"date,omitempty"`
	Summary      string     `json:"summary"`
	Supersedes   []string   `json:"supersedes,omitempty"`
	SupersededBy []string   `json:"superseded_by,omitempty"`
	SourceRefs   []string   `json:"source_refs,omitempty"`
	Citations    []Citation `json:"citations,omitempty"`
	UpdatedAt    time.Time  `json:"updated_at"`
}

type DecisionLookupResult struct {
	Decisions []DecisionRecord `json:"decision_records,omitempty"`
	PageInfo  PageInfo         `json:"page_info,omitempty"`
}

type ProvenanceEvent struct {
	EventID    string            `json:"event_id"`
	EventType  string            `json:"event_type"`
	RefKind    string            `json:"ref_kind"`
	RefID      string            `json:"ref_id"`
	SourceRef  string            `json:"source_ref,omitempty"`
	OccurredAt time.Time         `json:"occurred_at"`
	Details    map[string]string `json:"details,omitempty"`
}

type ProvenanceEventList struct {
	Events   []ProvenanceEvent `json:"events,omitempty"`
	PageInfo PageInfo          `json:"page_info,omitempty"`
}

type ProjectionState struct {
	Projection        string            `json:"projection"`
	RefKind           string            `json:"ref_kind"`
	RefID             string            `json:"ref_id"`
	SourceRef         string            `json:"source_ref,omitempty"`
	Freshness         string            `json:"freshness"`
	ProjectionVersion string            `json:"projection_version"`
	UpdatedAt         time.Time         `json:"updated_at"`
	Details           map[string]string `json:"details,omitempty"`
}

type ProjectionStateList struct {
	Projections []ProjectionState `json:"projections,omitempty"`
	PageInfo    PageInfo          `json:"page_info,omitempty"`
}
