The Ontology
A canon of software architecture you can query: every principle with its relations and its repair, every term with its definition, every algorithm with its contract, the reasoning that derives them, the layers they live in and the resolution of every tension between them. Every reference one record makes to another is a link, so any record is a starting point.
Algorithms
agent-creation
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_evidence_before_generation["Evidence-Before-Generation"]
n_semantic_operation_boundary["Semantic Operation Boundary"]
n_capability_profile["Capability Profile"]
n_creation_history_collision["Creation History Collision"]
n_domain_cache_validation["Domain Cache Validation"]
n_scope_extraction["Scope Extraction"]
n_non_destructive_domain_investigation["Non-Destructive Domain Investigation"]
n_domain_knowledge_base["Domain Knowledge Base"]
n_risk_complexity_reversibility["Risk Complexity Reversibility"]
n_existing_pattern_extraction["Existing Pattern Extraction"]
n_knowledge_documentation_relevance["Knowledge Documentation Relevance"]
n_principle_extraction["Principle Extraction"]
n_adaptive_phase_boundary["Adaptive Phase Boundary"]
n_phase_validation_requirement["Phase Validation Requirement"]
n_portable_contract_composition["Portable Contract Composition"]
n_validation_strategy_composition["Validation Strategy Composition"]
n_replacement_safety["Replacement Safety"]
n_adapter_rendering["Adapter Rendering"]
n_audit_artifact["Audit Artifact"]
n_semantic_compliance_validation["Semantic Compliance Validation"]
n_evidence_grounding_validation["Evidence Grounding Validation"]
n_algorithmic_embodiment_validation["Algorithmic Embodiment Validation"]
n_final_generation_report["Final Generation Report"]
n_agent_generation_completion["Agent Generation Completion"]
n_agent_creator_kernel["Agent Creator Kernel"]
n_agent_generation_concern["<Agent Generation Concern>"]
n_audit_artifact --> n_capability_profile
n_agent_creator_kernel --> n_capability_profile
n_agent_creator_kernel --> n_scope_extraction
n_agent_creator_kernel --> n_domain_knowledge_base
n_agent_creator_kernel --> n_principle_extraction
n_agent_creator_kernel --> n_adapter_rendering
n_agent_creator_kernel --> n_final_generation_report
n_agent_creator_kernel --> n_agent_generation_completion
n_agent_creator_kernel --> n_evidence_before_generation
n_agent_creator_kernel --> n_risk_complexity_reversibility
n_agent_creator_kernel --> n_adaptive_phase_boundary
n_agent_creator_kernel --> n_creation_history_collision
n_agent_creator_kernel --> n_phase_validation_requirement
n_agent_creator_kernel --> n_evidence_grounding_validationEvidence-Before-Generation
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowRequest → Discover → Inspect → ExtractFacts → KnowledgeBase → Generate
ProductionsEvidenceBeforeGeneration ::= <UserRequest> "->" <ResourceDiscovery> "->" <DomainInspection> "->" <FactExtraction> "->" <KnowledgeBase> "->" <GeneratedAgent> GeneratedAgent ::= "allowed_only_if_evidence_grounded"
BeforeAn agent generated from the request text and prior model knowledge, never inspecting the target.
Afterrequest -> discover resources -> inspect domain -> extract facts -> knowledge base -> generate only from verified evidence
Semantic Operation Boundary
Details
FlowSemanticVerb → AdapterMapping → RuntimeAction → Result
ProductionsSemanticBoundary ::= <SemanticOperation> "->" <AdapterMapping> "->" <RuntimeExecution> "->" <EvidenceResult> SemanticOperation ::= "DECLARE_RESOURCE" | "DISCOVER_RESOURCES" | "READ_RESOURCE" | "SEARCH_CONTENT" | "ANALYZE_CONTENT" | "EXTRACT_FACTS" | "CALCULATE_METRIC" | "COMPOSE_ARTIFACT" | "VALIDATE_ARTIFACT" | "PERSIST_ARTIFACT" | "REPORT_RESULT" | "REQUEST_DECISION" CoreConstraint ::= "no_runtime_specific_paths_or_commands"
BeforeThe agent core hardcodes a specific search command and an absolute path, so it only runs on one runtime.
Aftersemantic op{DISCOVER/READ/SEARCH/ANALYZE} -> adapter maps to the runtime -> the core carries no runtime path or command
Capability Profile
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowCapabilitySet → Probe → Available|Unavailable|Substituted → RuntimeMode
ProductionsCapabilityProfile ::= <RequiredCapabilitySet> "->" <CapabilityProbeSet> "->" <CapabilityVerdict> CapabilityVerdict ::= "full" | "degraded" | "blocked" Capability ::= "filesystem" | "search" | "execution" | "persistence" | "validation" | "user_interaction"
BeforeThe agent assumes it can execute and write, then fails when it cannot.
Afterrequired capabilities{filesystem, search, execution, persistence, validation} -> probe each -> mode{full | degraded | blocked}
Creation History Collision
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowTargetAgent → ExistingRegistry → NameCollision? → DomainCollision? → Decision
ProductionsCreationCollision ::= <TargetAgentName> "->" <ExistingAgentMap> "->" <CollisionCheck> "->" <AgentOperationMode> AgentOperationMode ::= "CREATE" | "REFINE" | "RENAME" | "REPLACE" | "CANCEL" CollisionCheck ::= "name_collision" | "domain_collision" | "none"
BeforeA new agent silently overwrites an existing one of the same name.
Aftertarget name -> existing registry -> name/domain collision? -> user decision{CREATE|REFINE|RENAME|REPLACE|CANCEL}
Domain Cache Validation
Details
FlowDomainPath → Normalize → Hash → CacheLookup → AgeCheck → UseCache|Investigate
ProductionsDomainCache ::= <DomainPath> "->" <DomainHash> "->" <CacheEntry> "->" <CacheAge> "->" <CacheDecision> CacheDecision ::= "use_cached_domain" | "reject_stale_cache" | "no_cache_investigate"
BeforeStale cached domain intelligence reused as if it were current.
Afterdomain path -> normalize + hash -> cache lookup -> age vs TTL -> {use cached | reject stale | investigate}
Scope Extraction
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowTargetPath → InvestigationType → ScopeModel → ResourceSet → InterfaceFacts
ProductionsScopeExtraction ::= <TargetPath> "->" <InvestigationDepth> "->" <DomainScope> InvestigationDepth ::= "single-resource" | "directory" | "module" | "repository" | "auto" DomainScope ::= <ResourceScope> | <DirectoryScope> | <ModuleScope> | <RepositoryScope>
BeforeA repository investigated at single-file depth, missing every boundary.
Aftertarget -> investigation depth{single-resource|directory|module|repository} -> scope-matched facts{interfaces, deps, boundaries}
Non-Destructive Domain Investigation
Details
FlowStaticPlan + OptionalExecutablePlan → Analyze → ExtractStructure → CacheResults
ProductionsDomainInvestigation ::= <InvestigationPlan> "->" <AnalysisExecution> "->" <DomainKnowledge> InvestigationPlan ::= <StaticAnalysisPlan> "," <OptionalExecutableAnalysisPlan> ExecutionConstraint ::= "non_destructive" "," "observable_output_required" "," "source_mutation_forbidden"
BeforeInvestigation runs a script that mutates the source it is inspecting.
Afterstatic plan (+ optional safe executable) -> analyze, never mutate the source -> observable output -> domain knowledge
Domain Knowledge Base
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowDomainFacts → Statistics → EvidenceSources → KnowledgeBase
ProductionsDomainKnowledgeBase ::= <DomainScope> "," <DomainStructure> "," <PurposeSet> "," <DependencyMap> "," <InterfaceSet> "," <PatternSet> "," <Statistics> "," <EvidenceSourceSet> Statistics ::= "resource_count" "," "interface_count" "," "dependency_count" "," "resource_types" "," "architectural_patterns"
BeforeGeneration proceeds with no explicit evidence substrate to cite.
Afterdomain facts + structure + purposes + deps + interfaces + patterns + statistics + evidence sources -> reusable knowledge base
Risk Complexity Reversibility
Details
FlowKnowledgeBase → RiskFactors → ComplexityScore → Reversibility → Uncertainty
ProductionsDomainCharacteristics ::= <RiskLevel> "," <ComplexityScore> "," <Reversibility> "," <UncertaintyLevel> RiskLevel ::= "low" | "medium" | "high" Reversibility ::= "reversible" | "partially-reversible" | "irreversible" UncertaintyLevel ::= "low" | "medium" | "high"
BeforeEvery agent given the same phase count regardless of how risky its domain is.
Afterknowledge base -> risk{low|medium|high} + complexity + reversibility{reversible|partial|irreversible} + uncertainty
Existing Pattern Extraction
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowExistingSpecs → PhaseCount → GateCount → OperationUsage → ReusablePatterns
ProductionsExistingPatternExtraction ::= <ExistingAgentSpecSet> "->" <StructuralMetricSet> "->" <ReusablePatternSet> StructuralMetricSet ::= "phase_count" "," "validation_gate_count" "," "semantic_operation_count"
BeforeA new agent invented in a shape that ignores the local agent grammar.
Afterexisting specs -> count{phases, gates, semantic ops} -> reusable structures -> baseline conventions
Knowledge Documentation Relevance
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowKnowledgeDocs → RelevanceAnalysis → RelevantDocs → PrincipleInput
ProductionsKnowledgeRelevance ::= <KnowledgeDocumentSet> "->" <RelevanceScoreSet> "->" <RelevantKnowledgeSet> RelevanceDecision ::= "include" | "exclude"
BeforeEvery knowledge doc fed into reasoning, relevant or not.
Afterknowledge docs -> read descriptions -> score relevance vs domain -> include relevant, exclude the rest
Principle Extraction
Details
FlowStructuralPrinciples + DomainDocs → Applicability → CorePrinciples
ProductionsPrincipleExtraction ::= <CandidatePrincipleSet> "->" <ApplicabilityAnalysis> "->" <CorePrincipleSet> CorePrinciple ::= "phase_gated_execution" | "validation_boundaries" | "declaration_before_use" | "evidence_before_composition" | "adapter_separation" | "auditability"
BeforeRuntime-specific principles baked into the portable core.
Afterstructural candidates + domain docs -> test applicability -> core principles{phase-gated, validation-boundaries, declaration-before-use, evidence-before-composition, adapter-separation, auditability}; runtime-specific excluded
Adaptive Phase Boundary
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowRisk + Complexity + Uncertainty → PhaseCount → PhaseBoundaries
ProductionsPhaseBoundarySelection ::= <RiskLevel> "," <ComplexityScore> "," <UncertaintyLevel> "->" <PhaseStructure> PhaseStructure ::= <ThreePhase> | <FivePhase> | <SevenPhase> ThreePhase ::= "Discovery" "," "Generation" "," "Verification" FivePhase ::= "Discovery" "," "Analysis" "," "Generation" "," "Verification" "," "Finalization" SevenPhase ::= "Discovery" "," "Analysis" "," "Planning" "," "Validation" "," "Generation" "," "Verification" "," "Finalization"
BeforeA high-risk irreversible domain given a 3-phase agent.
Afterrisk + complexity + uncertainty -> phase count{3 | 5 | 7} -> validation density proportional to difficulty
Phase Validation Requirement
Details
FlowPhaseSet → RequirementDerivation → ValidationGateSet
ProductionsPhaseValidation ::= <PhaseSet> "->" <ValidationRequirementSet> "->" <ValidationGateSet> PhaseValidationGate ::= <PhaseName> ":" <RequirementSet> RequirementSet ::= <Requirement> | <Requirement> "," <RequirementSet>
BeforeA phase ends with no verifiable exit condition.
Afterphase -> derive requirements{purpose, adapter-separation, evidence-grounding, safety} -> a validation gate per phase
Portable Contract Composition
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowKnowledgeBase + Principles + Phases → PortableContract
ProductionsPortableAgentContract ::= <Identity> "," <Purpose> "," <DomainModel> "," <CapabilityRequirements> "," <PhaseSpecifications> "," <ValidationStrategy> "," <SafetyConstraints> "," <OutputContract> OutputContract ::= "portable_agent_contract" | "invocation_contract" | "audit_report" | "final_report"
BeforeThe agent authored directly as a runtime artifact, welded to one runtime.
Afterknowledge base + principles + phases -> runtime-neutral contract{identity, purpose, domain model, capabilities, phase specs, validation strategy, constraints, outputs} = the canonical artifact
Validation Strategy Composition
Details
FlowPreChecks → DuringChecks → PostChecks → ValidationStrategy
ProductionsGenerationValidationStrategy ::= <PreGenerationChecks> "," <DuringGenerationChecks> "," <PostGenerationChecks> PreGenerationChecks ::= "capabilities_detected" "," "history_checked" "," "domain_knowledge_available" DuringGenerationChecks ::= "phase_gates_enforced" "," "evidence_grounded_content" "," "adapter_separated" PostGenerationChecks ::= "schema_valid" "," "audit_complete" "," "unsupported_assumptions_absent"
BeforeThe artifact validated only after it is written, never during.
Afterpre{capabilities detected, history checked, knowledge available} + during{phase gates, evidence-grounded, adapter-separated} + post{schema valid, audit complete, no unsupported assumptions}
Replacement Safety
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowReplaceIntent → Approval → ArchiveExisting → VerifyArchive → Persist|Block
ProductionsReplacementSafety ::= <AgentOperationMode> "->" <ArchivePolicy> "->" <SafetyCheck> "->" <PersistenceDecision> ArchivePolicy ::= "archive_required_if_replace" | "archive_not_required" PersistenceDecision ::= "safe_to_persist" | "blocked"
BeforeAn existing agent overwritten with no archive — the original is lost.
AfterREPLACE -> require approval -> archive existing -> verify the archive -> persist only if recoverable, else block
Adapter Rendering
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowPortableContract → AdapterSchema → RenderedArtifact → Validate → Persist
ProductionsAdapterRendering ::= <PortableContract> "->" <AdapterConfig> "->" <ArtifactSet> "->" <AdapterValidation> "->" <Persistence> ArtifactSet ::= "agent_specification" "," "invocation_contract" "," "audit_report" AdapterConstraint ::= "adapter_may_add_metadata_but_not_alter_core_intent"
BeforeThe runtime artifact edited directly, diverging from the portable contract.
Afterportable contract -> adapter schema -> artifacts{agent spec, invocation contract, audit} -> adapter may add metadata, never alter core intent
Audit Artifact
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowGenerationState → AuditFields → AuditReport
ProductionsAuditReport ::= <AgentIdentity> "," <DomainReference> "," <AgentOperationMode> "," <RuntimeEnvironment> "," <RiskMetrics> "," <ValidationGateSet> "," <EvidenceSourceSet> "," <CapabilityProfile> "," <AdapterIdentity> "," <PortabilityStatus>
BeforeA generated agent with no provenance — no record of how or from what it was built.
Aftergeneration state -> audit{identity, domain, mode, risk metrics, gates, evidence sources, capability profile, adapter identity, portability status}
Semantic Compliance Validation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowPersistedSpec → MarkerSearch → CountMetrics → LeakageCheck → ComplianceVerdict
ProductionsSemanticCompliance ::= <PersistedArtifact> "->" <SemanticMarkerSet> "->" <MetricCheck> "->" <RuntimeLeakageCheck> "->" <ComplianceVerdict> ComplianceVerdict ::= "compliant" | "non_compliant"
BeforeThe in-memory plan judged compliant, but the STORED artifact never re-checked.
Afterre-read persisted spec -> search{semantic ops, phase markers, gates} + leakage check -> compliant only if counts pass and zero runtime leakage
Evidence Grounding Validation
- Stage: verify
- Axis: verification
- Math type: probability
- Yields: number[0,1]
Details
FlowGeneratedSpec → UnsupportedClaimSearch → EvidenceReferenceCheck → GroundingScore → Accept|Reject
ProductionsEvidenceGrounding ::= <GeneratedArtifact> "->" <ClaimAnalysis> "->" <KnowledgeBaseComparison> "->" <GroundingVerdict> GroundingVerdict ::= "grounded" | "unsupported_claims_present" | "insufficient_evidence_references"
BeforeThe generated agent asserts architecture claims that trace to nothing.
Aftergenerated spec -> find claims -> compare against the knowledge base -> grounding score -> reject below threshold
Algorithmic Embodiment Validation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowGeneratedSpec → EmbodimentMarkers → Score → Pass|Fail
ProductionsAlgorithmicEmbodiment ::= <GeneratedArtifact> "->" <EmbodimentMarkerSet> "->" <EmbodimentScore> "->" <EmbodimentVerdict> EmbodimentMarkerSet ::= "phase_gates" "," "declaration_before_use" "," "calculated_metrics" "," "thresholds" "," "iterative_discovery" EmbodimentVerdict ::= "embodied" | "insufficiently_embodied"
BeforeThe agent describes phase gates in prose but does not embody them.
Aftergenerated spec -> markers{phase gates, declaration-before-use, calculated metrics, thresholds, iterative discovery} -> embodied | insufficiently-embodied
Final Generation Report
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowValidationResults + ArtifactRefs + Limitations → FinalReport
ProductionsFinalGenerationReport ::= <GenerationSummary> "," <RiskSummary> "," <ComplianceSummary> "," <ArtifactReferences> "," <LimitationSet> ComplianceSummary ::= "semantic_operations" "," "adapter" "," "evidence_grounding" "," "algorithmic_embodiment"
BeforeA report that conflates the artifact, its validation status, and its limitations.
Aftervalidation results + artifact refs + limitations{degraded mode, unsupported capabilities} -> report distinguishing all three
Agent Generation Completion
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowValidationVerdicts → AuditPresence → Accept|Regenerate|Blocked
ProductionsAgentGenerationCompletion ::= <ValidationVerdictSet> "->" <AuditCheck> "->" <AcceptanceVerdict> AcceptanceVerdict ::= "agent_accepted" | "regenerate_required" | "blocked"
BeforeA generated agent declared ready while its evidence-grounding failed and its algorithmic embodiment was insufficient.
Aftersemantic compliance passed + evidence grounded above threshold + algorithmically embodied + audit recorded -> agent_accepted; else regenerate | blocked
Agent Creator Kernel
- Math type: computation
- Yields: procedure
Details
FlowConfig → Capabilities → History → Cache → Discovery → Knowledge → Analysis → Principles → Phases → Contract → AdapterRender → Validate → Audit → Report
ProductionsAgentCreatorKernel ::= <ConfigurationLoad> "->" <CapabilityProfile> "->" <CreationCollision> "->" <DomainCache> "->" <ScopeExtraction> "->" <DomainInvestigation> "->" <DomainKnowledgeBase> "->" <DomainCharacteristics> "->" <PrincipleExtraction> "->" <PhaseBoundarySelection> "->" <PortableAgentContract> "->" <AdapterRendering> "->" <SemanticCompliance> "->" <EvidenceGrounding> "->" <AlgorithmicEmbodiment> "->" <AuditReport> "->" <FinalGenerationReport>
Derivation map
BeforeA target domain turned straight into an agent by assumption, ungated.
Afterconfig -> capabilities -> history -> cache -> discover evidence -> knowledge -> risk analysis -> principles -> phases -> portable contract -> adapter render -> validate{semantic/grounding/embodiment} -> audit -> report
<Agent Generation Concern>
- Meta record
Details
FlowContext → Capability → History → Evidence → Knowledge → Risk → Phases → Contract → Adapter → Validation → Audit → Report
ProductionsAgentGenerationConcern ::= <ContextContract> "->" <CapabilityContract> "->" <CollisionPolicy> "->" <EvidenceModel> "->" <KnowledgeBase> "->" <PhaseDesign> "->" <PortableContract> "->" <AdapterArtifactSet> "->" <ValidationSet> "->" <AuditTrail> "->" <FinalReport> ValidationSet ::= "semantic_compliance" "," "adapter_compliance" "," "evidence_grounding" "," "algorithmic_embodiment" "," "runtime_specific_leakage_absent"
agent-workflow
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_hybrid_workflow_orchestration["Hybrid Workflow Orchestration"]
n_dsl_compliance_loading["DSL Compliance Loading"]
n_agent_workflow_file_modification_recovery["File Modification Recovery"]
n_context_forking_configuration["Context Forking Configuration"]
n_verb_based_execution_classification["Verb-Based Execution Classification"]
n_workspace_configuration_discovery["Workspace Configuration Discovery"]
n_shared_document_workspace["Shared Document Workspace"]
n_workflow_type_document_selection["Workflow Type Document Selection"]
n_agent_sequence_definition["Agent Sequence Definition"]
n_agent_document_responsibility["Agent Document Responsibility"]
n_agent_activation_invocation["Agent Activation Invocation"]
n_parallel_batch_execution["Parallel Batch Execution"]
n_sequential_agent_execution["Sequential Agent Execution"]
n_four_dimensional_agent_graph["Four-Dimensional Agent Graph"]
n_handoff_signal["Handoff Signal"]
n_orchestrator_action["Orchestrator Action"]
n_workflow_coordination_sequence["Workflow Coordination Sequence"]
n_workflow_recovery_loop["Workflow Recovery Loop"]
n_checklist_integration["Checklist Integration"]
n_phase_documentation_template["Phase Documentation Template"]
n_workflow_principles_mapping["Workflow Principles Mapping"]
n_capability_invocation_protocol["Capability Invocation Protocol"]
n_template_assembly["Template Assembly"]
n_first_time_initiation["First-Time Initiation"]
n_workflow_validation_gate["Workflow Validation Gate"]
n_workflow_creation_kernel["Workflow Creation Kernel"]
n_workflow_orchestration_concern["<Workflow Orchestration Concern>"]
n_handoff_signal --> n_orchestrator_action
n_orchestrator_action --> n_handoff_signal
n_workflow_creation_kernel --> n_dsl_compliance_loading
n_workflow_creation_kernel --> n_agent_workflow_file_modification_recovery
n_workflow_creation_kernel --> n_context_forking_configuration
n_workflow_creation_kernel --> n_workspace_configuration_discovery
n_workflow_creation_kernel --> n_shared_document_workspace
n_workflow_creation_kernel --> n_agent_sequence_definition
n_workflow_creation_kernel --> n_handoff_signal
n_workflow_creation_kernel --> n_workflow_coordination_sequence
n_workflow_creation_kernel --> n_checklist_integration
n_workflow_creation_kernel --> n_phase_documentation_template
n_workflow_creation_kernel --> n_capability_invocation_protocol
n_workflow_creation_kernel --> n_template_assembly
n_workflow_creation_kernel --> n_workflow_validation_gate
n_workflow_creation_kernel --> n_workflow_type_document_selection
n_workflow_creation_kernel --> n_agent_activation_invocation
n_workflow_creation_kernel --> n_first_time_initiationHybrid Workflow Orchestration
Details
FlowWorkflowObjective → AgentPhases → ExecutionClassification → ParallelDiscovery → SequentialAction → Handoff
ProductionsHybridWorkflowOrchestration ::= <WorkflowObjective> "->" <AgentSequence> "->" <ExecutionModeClassification> "->" <ParallelBatchSet> "->" <SequentialActionSet> "->" <WorkflowCompletion> ExecutionMode ::= "PARALLEL" | "SEQUENTIAL" ParallelPhase ::= "DISCOVERY" | "INVESTIGATION" | "RESEARCH" | "ANALYSIS" | "EXPLORATION" SequentialPhase ::= "CREATE" | "WRITE" | "EXECUTE" | "VERIFY" | "IMPLEMENT" | "REFACTOR"
BeforeEvery agent runs sequentially, even independent discovery — the workflow crawls.
Afterobjective -> agent sequence -> classify by verb -> parallel discovery (forked context) + sequential action (normal context) -> handoff
DSL Compliance Loading
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowDSLSources → Requirements → ComplianceGate → Proceed|Block
ProductionsDSLComplianceLoading ::= <DSLSpecSet> "->" <WorkflowRequirementSet> "->" <ComplianceValidationGate> WorkflowRequirementSet ::= "agent_dsl_syntax" "," "agent_oriented_content" "," "stable_filename_convention" "," "handoff_protocol" "," "hybrid_parallel_sequential" "," "context_isolation" "," "agent_spawn_mechanism" "," "capability_invocation"
BeforeWorkflow generated free-form, ignoring the DSL and handoff contracts.
Afterload DSL + keyword + workflow + checklist specs -> require{agent-DSL syntax, handoff protocol, hybrid execution, context isolation, agent spawn} -> compliance gate
File Modification Recovery
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowModificationError → RereadMerge → CompleteRewrite → Verify
ProductionsFileModificationRecovery ::= <FileModificationError> "->" <RecoveryProtocolSelection> "->" <RereadAndMerge> "->" <CompleteRewrite> "->" <RecoveryLog> RecoveryProtocol ::= "reread-merge-complete-rewrite" | "snapshot-restore-on-failure" ForbiddenRecovery ::= "retry_edit_without_recovery" | "ask_user_for_tool_error_recovery"
BeforeA stale-write conflict re-reads the file and retries the same edit, or stops to ask the user.
Aftermodification error -> re-read current -> merge the delta into full state -> write complete version -> verify -> log; never retry-without-recovery, never ask for a tool error
Context Forking Configuration
Details
FlowAgentClass → ContextMode → ParallelEligibility → ExecutionPolicy
ProductionsContextForkingConfiguration ::= <AgentClass> "->" <ContextMode> "->" <ParallelPolicy> "->" <ExecutionConfiguration> AgentClass ::= "discovery" | "investigation" | "documentation" | "action" | "validation" ContextMode ::= "fork" | "normal" ParallelPolicy ::= "parallel_true" | "parallel_false"
BeforeEvery agent shares one context — discovery pollutes the action agent's state.
Afteragent class -> discovery/investigation/documentation -> fork ; action/validation -> normal -> per-class parallel eligibility preserved
Verb-Based Execution Classification
Details
FlowAgentPurpose → PrimaryVerb → VerbClass → ExecutionMode
ProductionsVerbExecutionClassification ::= <AgentPurpose> "->" <PrimaryVerb> "->" <VerbSetMatch> "->" <AgentExecutionMode> ParallelVerb ::= "ANALYZE" | "FIND" | "EXTRACT" | "READ" | "DISCOVER" | "INVESTIGATE" | "RESEARCH" | "EXPLORE" | "TRACE" SequentialVerb ::= "CREATE" | "WRITE" | "EXECUTE" | "VERIFY" | "IMPLEMENT" | "LINK" | "ITERATE" | "REFACTOR" | "DEPLOY"
BeforeExecution mode assigned by phase number, not by what the agent does.
Afteragent purpose -> primary verb -> {ANALYZE/FIND/DISCOVER -> PARALLEL(fork)} | {CREATE/WRITE/VERIFY -> SEQUENTIAL(normal)}
Workspace Configuration Discovery
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowWorkspaceConfig → Zones → AgentDefinitions → ArtifactBasePath
ProductionsWorkspaceConfigurationDiscovery ::= <WorkspaceConfigFile> "->" <WorkspaceConfig> "->" <ZoneConfig> "->" <AgentDefinitionSet> "->" <ArtifactPathPolicy> ArtifactPathPolicy ::= "shared_zone/workflow_name" "," "workflow_zone" "," "task_zone" "," "no_hardcoded_paths"
BeforeArtifact paths hardcoded — the workflow only runs in one layout.
Afterworkspace-config -> zones + root + agent defs -> artifact base = shared_zone/workflow_name; no hardcoded paths
Shared Document Workspace
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCoreDocuments → PreCreate → AgentReadEdit → SingleSourceValidation
ProductionsSharedDocumentWorkspace ::= <CoreDocumentSet> "->" <PreCreation> "->" <SharedAccessProtocol> "->" <IterativeRefinement> "->" <SingleSourceOfTruthGate> SharedAccessProtocol ::= "all_agents_same_documents" "," "orchestrator_creates" "," "agents_refine" "," "append_mode_false"
BeforeEach agent writes its own output file; findings diverge across N versions.
Afterpre-create core documents once -> every agent reads + edits the same set -> no duplicate versions -> single source of truth
Workflow Type Document Selection
Details
FlowWorkflowObjective → WorkflowType → CoreDocuments → PurposeMap
ProductionsWorkflowDocumentSelection ::= <WorkflowObjective> "->" <WorkflowType> "->" <CoreDocumentSet> "->" <DocumentPurposeMap> WorkflowType ::= "cleanup" | "analysis" | "refactoring" | "documentation" | "implementation" | "security" | "performance" | "infrastructure" | "migration" CoreDocumentConstraint ::= "document_count_between_5_and_8" "," "distinct_logical_purpose" "," "semantic_names_only"
BeforeGeneric output.md / results.md documents with overlapping purpose.
Afterobjective -> workflow_type{cleanup|analysis|refactoring|security|migration} -> 5-8 distinct-purpose documents -> one non-overlapping purpose each
Agent Sequence Definition
Details
FlowAgentCount → AgentObjectSet → AgentSequence
ProductionsAgentSequenceDefinition ::= <AgentCount> "->" <AgentObjectSet> "->" <AgentSequence> AgentObject ::= <AgentName> "," <AgentType> "," <PhaseNumber> "," <Purpose> "," <Methodology> "," <InputArtifacts> "," <OutputArtifacts> "," <ValidationGates> "," <DocumentResponsibilities> "," <ExecutionMode> "," <Graph4D>
BeforeA plan that is just a list of agent names, no executable metadata.
Afteragent_count -> agent objects{name, type, phase, purpose, inputs, outputs, validation gates, doc responsibilities, execution mode, 4D graph}
Agent Document Responsibility
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowDocument → Read → DetectStale → Remove → Replace → Deduplicate
ProductionsAgentDocumentResponsibility ::= <CoreDocument> "->" <ReadCurrentState> "->" <ContradictionDetection> "->" <StaleContentRemoval> "->" <AccurateReplacement> "->" <SingleSourceValidation> ProhibitedDocumentOperation ::= "append_only" | "duplicate_findings" | "new_version_file"
BeforeAgents append findings, accumulating duplicates and contradictions.
Afterdocument -> read current state -> detect contradictions -> remove stale -> replace with new -> single source of truth (never append, never a new version file)
Agent Activation Invocation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowAgentObject → SpawnInvocation → AgentExecution
ProductionsAgentActivationInvocation ::= <AgentObject> "->" <SpawnCall> "->" <ExecutionResult> SpawnCall ::= "agent_type" "," "prompt" "," "description" "," "model" "," "context_if_parallel" ForbiddenOrchestration ::= "simulate_agent_execution_in_orchestrator"
BeforeThe orchestrator simulates the agent's work in its own session.
Afteragent object -> spawn primitive{agent_type, prompt, model, context-if-parallel} -> real activation; never simulate in the orchestrator
Parallel Batch Execution
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowParallelAgents → ConcurrentSpawnBatch → WaitAll → MergeFindings
ProductionsParallelBatchExecution ::= <ParallelAgentSet> "->" <ConcurrentSpawnBatch> "->" <CompletionWait> "->" <SharedDocumentMerge> ConcurrentSpawnBatch ::= "single_batch_concurrent_spawn" ParallelSafety ::= "context_fork" "," "discovery_or_investigation_only" "," "shared_artifact_refinement"
BeforeParallel agents launched in separate messages, so they run one after another anyway.
Afteradjacent parallel agents -> ONE concurrent batch of forked-context spawns -> wait for all -> merge via shared documents
Sequential Agent Execution
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowPreviousHandoff → SpawnCall → WaitCompletion → NextHandoff
ProductionsSequentialAgentExecution ::= <HandoffContext> "->" <SequentialSpawnInvocation> "->" <CompletionSignal> "->" <NextAgentActivation> SequentialConstraint ::= "one_spawn_at_a_time" "," "wait_for_completion" "," "context_normal"
BeforeTwo mutating agents launched at once, producing conflicting edits.
Afterprior handoff -> one normal-context spawn at a time -> wait for completion -> activate the next
Four-Dimensional Agent Graph
Details
FlowAgent → Z + X + Y + W Graph
ProductionsFourDAgentGraph ::= <AgentObject> "->" <SequentialAxis> "," <LateralAxis> "," <DiagonalAxis> "," <PropagationAxis> SequentialAxis ::= "Z: prior_required_agents" LateralAxis ::= "X: peer_parallel_agents" DiagonalAxis ::= "Y: cross_phase_artifact_dependencies" PropagationAxis ::= "W: superseded_state, propagated_contracts, breaks_if_changed"
BeforeAn agent records only its order, not its cross-phase data or downstream ripple.
Afteragent -> Z{prior required agents} + X{peer parallel} + Y{cross-phase artifact deps} + W{superseded state, propagated contracts, breaks-if-changed}
Handoff Signal
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowAgentCompletion → HandoffContext → OrchestratorAction
ProductionsHandoffSignal ::= <AgentCompleted> "," <PhaseStatus> "," <ArtifactsLocation> "," <NextAgent> "," <ExecutionMode> "," <ContextUsed> "," <KeyFindings> "," <CriticalFiles> "," <ValidationGatesPassed> "," <ParallelResults> "," <Graph4D> "," <OrchestratorAction> OrchestratorAction ::= "ACTIVATE_NEXT_AGENT" | "PAUSE_FOR_USER" | "WORKFLOW_COMPLETE"
BeforeAn agent finishes with a prose summary the orchestrator cannot route on.
Afteragent completion -> handoff{completed, phase status, artifacts, next agent, execution mode, context, findings, validation, 4D graph, orchestrator_action}
Orchestrator Action
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowHandoffSignal → ActionType → Execute|Pause|Complete
ProductionsOrchestratorActionHandling ::= <HandoffSignal> "->" <ActionType> "->" <OrchestrationDecision> ActionType ::= "ACTIVATE_NEXT_AGENT" | "PAUSE_FOR_USER" | "WORKFLOW_COMPLETE" ContinuationRule ::= "never_ask_should_I_continue" "," "use_orchestrator_action"
BeforeThe orchestrator asks the user 'should I continue?' after every agent.
Afterhandoff -> orchestrator_action{ACTIVATE_NEXT_AGENT | PAUSE_FOR_USER | WORKFLOW_COMPLETE} -> auto-continue unless a critical decision or repeated recovery failure
Workflow Coordination Sequence
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowPreCreateDocs → ParallelBatch|SequentialTask → Handoff → Checkpoint → Complete
ProductionsWorkflowCoordinationSequence ::= <DocumentPreCreation> "->" <AgentExecutionStepSet> "->" <CheckpointUpdateSet> "->" <WorkflowCompletionState> WorkflowCompletionState ::= "WORKFLOW_PROGRESS_100_percent" "," "core_documents_refined" "," "final_output_ready"
BeforeCoordination left implicit — no one knows the exact spawn order.
Afterpre-create docs -> parallel batches where eligible + sequential tasks one at a time -> handoffs -> checkpoint updates -> 100% complete
Workflow Recovery Loop
- Stage: act
- Axis: formalisation
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowValidationFail → Diagnose → Research → Relaunch → RetryLimit|Recover
ProductionsWorkflowRecoveryLoop ::= <FailedAgentResult> "->" <SharedDocumentRead> "->" <UnmetExpectationAnalysis> "->" <ResolutionResearch> "->" <AgentRelaunch> "->" <RecoveryDecision> RecoveryDecision ::= "continue_after_recovery" | "pause_for_user_after_limit"
BeforeA failed agent is silently skipped and the workflow continues.
Aftervalidation fail -> read shared docs -> diagnose unmet expectation -> research the error -> relaunch with adapted context -> pause for user after the bound
Checklist Integration
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowWorkflow → Checklist → AgentUpdates → ResumableProgress
ProductionsChecklistIntegration ::= <WorkflowName> "->" <ChecklistFrontmatter> "->" <PhaseStructure> "->" <TaskBreakdown> "->" <ProgressTracking> "->" <SuccessCriteria> ChecklistCoordinationRule ::= "orchestrator_precreates" "," "all_agents_edit_same_checklist" "," "phase_complete_before_handoff" "," "resume_by_reading_checklist"
BeforeWorkflow state lives only in the orchestrator context; a restart loses it.
Afterworkflow -> progress checklist{execution model, linear phases + severity metadata, task checkboxes, success criteria} -> any agent resumes by reading it
Phase Documentation Template
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowAgentPhase → DocumentationSection → InvocationExample
ProductionsPhaseDocumentationTemplate ::= <AgentObject> "->" <PhaseHeader> "->" <ExecutionModeDescription> "->" <MethodologySummary> "->" <Graph4DRendering> "->" <ArtifactSection> "->" <FocusSection> "->" <OutputSection> "->" <AgentActivationExample>
BeforeA phase documented with no execution mode, graph, or invocation example.
Afteragent phase -> header + execution mode + context + methodology + 4D graph + artifacts + focus + deliverable + agent activation example
Workflow Principles Mapping
Details
FlowAgentSequence → PrincipleSet → WorkflowValueStatement
ProductionsWorkflowPrinciplesMapping ::= <AgentSequence> "->" <AgentContributionSet> "->" <WorkflowPrincipleSet> WorkflowPrinciple ::= "grounded_in_codebase_reality" | "fully_automated" | "context_aware" | "self_recovering" | "dynamically_scalable" | "hybrid_execution" | "context_forking" | "workspace_integrated"
BeforeA workflow that never states what its structure guarantees.
Afteragent sequence -> per-agent contribution{first grounds, final guarantees quality} -> principles{grounded, automated, context-aware, self-recovering, scalable}
Capability Invocation Protocol
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCapabilityNeed → CapabilityPattern → ContextMode → Invocation
ProductionsCapabilityInvocationProtocol ::= <CapabilityNeed> "->" <CapabilitySelection> "->" <CapabilityInvocation> "->" <CapabilityResultIntegration> CapabilityInvocation ::= "invoke(capability=name, args=args)" CapabilityContextRule ::= "discovery_capability_context_fork" | "validation_capability_context_normal"
BeforeEvery capability baked into every agent instead of a shared, invocable one.
Aftercapability need -> select -> invoke(capability, args){discovery -> forked, validation -> normal} -> integrate result
Template Assembly
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowSections → FinalTemplate → OutputPath → Write
ProductionsTemplateAssembly ::= <WorkflowFrontmatter> "->" <WorkspaceConfigSection> "->" <WorkflowOverview> "->" <PhaseDocumentationSet> "->" <ChecklistRequirements> "->" <AgentOrchestrationProtocol> "->" <HandoffSignalFormat> "->" <WorkflowCoordination> "->" <CapabilityIntegrationProtocol> "->" <WorkflowPrinciples> "->" <OutputArtifact> OutputArtifact ::= "{workflow_output_dir}/{workflow_name}-WORKFLOW.{workflow_ext}"
BeforeWorkflow sections written ad hoc, missing the handoff format or coordination.
Afterassemble{frontmatter, workspace config, overview, phase docs, checklist, orchestration protocol, handoff format, coordination, capabilities, principles} -> {name}-WORKFLOW file
First-Time Initiation
- Stage: terminate
- Axis: termination
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowGeneratedWorkflow → UserChoice → Execute|Edit|Cancel
ProductionsFirstTimeInitiation ::= <GeneratedWorkflow> "->" <WorkflowSummary> "->" <UserChoice> "->" <InitialAction> UserChoice ::= "Execute Workflow" | "Edit Template" | "Cancel"
BeforeThe generated workflow auto-executes without the user's go-ahead.
Aftergenerated workflow -> summary -> user choice{Execute | Edit Template | Cancel} -> generation and first execution are separate approvals
Workflow Validation Gate
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowWorkflowTemplate → GateSet → Valid|Invalid
ProductionsWorkflowValidationGate ::= <GeneratedWorkflow> "->" <DSLComplianceCheck> "->" <WorkspaceConfigCheck> "->" <AgentSequenceCheck> "->" <ExecutionModeCheck> "->" <Graph4DCheck> "->" <HandoffProtocolCheck> "->" <ChecklistIntegrationCheck> "->" <CapabilityIntegrationCheck> "->" <ArtifactPathCheck> "->" <CompletionVerdict> CompletionVerdict ::= "workflow_template_valid" | "workflow_template_invalid"
BeforeA workflow shipped without checking its handoff, 4D graphs, or dynamic paths.
Aftertemplate -> checks{DSL, workspace, agent sequence, execution mode, 4D graph, handoff, checklist, capabilities, artifact paths} -> valid | invalid
Workflow Creation Kernel
- Math type: computation
- Yields: procedure
Details
FlowSpecs → Workspace → Documents → Agents → Graphs → Handoffs → Coordination → Checklist → Capabilities → Template → Validation
ProductionsWorkflowCreationKernel ::= <DSLComplianceLoading> "->" <FileModificationRecovery> "->" <ContextForkingConfiguration> "->" <WorkspaceConfigurationDiscovery> "->" <WorkflowDocumentSelection> "->" <SharedDocumentWorkspace> "->" <AgentSequenceDefinition> "->" <VerbExecutionClassification> "->" <FourDAgentGraph> "->" <HandoffSignal> "->" <WorkflowCoordinationSequence> "->" <ChecklistIntegration> "->" <PhaseDocumentationTemplate> "->" <CapabilityInvocationProtocol> "->" <TemplateAssembly> "->" <WorkflowValidationGate>
Derivation map
BeforeAn objective turned straight into a hardcoded, single-threaded agent script.
Afterload specs -> discover workspace -> select docs -> define agents -> classify execution -> 4D graphs -> handoffs -> coordinate -> checklist + capabilities -> assemble -> validate
<Workflow Orchestration Concern>
- Meta record
Details
FlowGrammar → Workspace → Documents → Agents → ExecutionMode → Context → Graph → Handoff → Coordination → Validation
ProductionsWorkflowOrchestrationConcern ::= <GrammarContract> "->" <WorkspaceContract> "->" <SharedArtifactContract> "->" <AgentSequenceContract> "->" <HybridExecutionContract> "->" <ContextForkingContract> "->" <Graph4DContract> "->" <HandoffContract> "->" <ChecklistContract> "->" <CapabilityContract> "->" <ValidationGate> HybridExecutionContract ::= "parallel_discovery" "," "sequential_actions" "," "spawn_primitive_required" "," "no_orchestrator_simulation" "," "single_source_of_truth_documents"
anti-patterns
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_anti_pattern_inversion["Anti-Pattern Inversion"]
n_anti_pattern_propagation_kernel["Anti-Pattern Propagation Kernel"]
n_anti_pattern_remediation_algebra["Anti-Pattern Remediation Algebra"]
n_architecture_smell_record["Architecture Smell Record"]
n_anti_pattern_rule_compiler["Anti-Pattern Rule Compiler"]
n_smell_taxonomy["Smell Taxonomy"]
n_anti_pattern_relationship_record["Anti-Pattern Relationship Record"]
n_architecture_anti_pattern["<Architecture Anti-Pattern>"]Anti-Pattern Inversion
- Math type: logic
- Yields: boolean
Details
FlowPrinciple → Invariant → Violation → Propagation → Detection → Remediation
ProductionsAntiPatternInversion ::= <HealthyPrinciple> "->" <RequiredInvariant> "->" <InvariantViolation> "->" <FailurePropagation> "->" <DetectionSignalSet> "->" <RemediationInverse> AntiPatternRecord ::= <Name> "," <TriggerCondition> "," <DegenerationPath> "," <DetectionSignals> "," <DamageModel> "," <RemediationInverse>
BeforePrinciple: Low Coupling — stated as a goal only; its violations are noticed ad hoc, named inconsistently, and caught late, with no derived failure algorithm.
AfterLow Coupling -> invariant{no bidirectional dependency} -> violation{Cyclic Dependency} -> propagation{a convenience import closes a cycle, then spreads across modules} -> detection{dependency-cycle scan} -> remediation{invert the dependency / introduce a port}
Anti-Pattern Propagation Kernel
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowShortcut → Repetition → Normalization → DependencyFormation → Institutionalization → HighCostRepair
ProductionsAntiPatternPropagation ::= <LocalShortcut> "->" <RepeatedUse> "->" <ImplicitConvention> "->" <DependentCodeFormation> "->" <ArchitecturalDebt> "->" <RemediationCostIncrease> DebtAmplifier ::= "copy_paste" | "missing_contract" | "missing_owner" | "missing_metric" | "missing_boundary" | "missing_version" | "missing_observability"
BeforeA one-off shortcut — inline a secret to ship a fix — treated as an isolated, cheap, local choice.
AfterShortcut{inline secret} -> repetition{reused under deadline} -> normalization{becomes the team convention} -> dependency-formation{configs read it directly} -> institutionalization{deploy scripts assume it} -> high-cost-repair{rotate the secret and rewire every dependent}
Anti-Pattern Remediation Algebra
- Math type: algebra
- Yields: ordered-structure
Details
FlowAntiPattern → MissingControl → InverseControl → Migration → AbsenceCheck → PreventionGate
ProductionsAntiPatternRemediationAlgebra ::= <AntiPatternRecord> "->" <MissingControl> "->" <InverseArchitecturalControl> "->" <MigrationPlan> "->" <EliminationVerification> "->" <RecurrencePrevention> MissingControl ::= "boundary" | "contract" | "owner" | "version" | "telemetry" | "schema" | "policy" | "state_isolation" | "dependency_rule" RecurrencePrevention ::= "static_check" | "contract_test" | "schema_gate" | "architecture_test" | "policy_as_code" | "review_gate" | "runtime_monitor"
BeforeThe anti-pattern is deleted at one call site; the propagation path stays open, so it reappears elsewhere next sprint.
AfterSecret Sprawl -> missing-control{no secret authority} -> inverse-control{central store + injected access} -> migration{repoint every reader} -> absence-check{scan finds zero inline secrets} -> prevention-gate{lint rule rejects new inline secrets}
Architecture Smell Record
- Math type: logic
- Yields: boolean
Details
FlowSmell → Trigger → Degeneration → Detection → Measurement → Remediation → Prevention
ProductionsArchitectureSmellRecord ::= <SmellName> "," <TriggerCondition> "," <EnablingConditionSet> "," <DegenerationPath> "," <DetectionSignalSet> "," <MetricSet> "," <DamageModel> "," <RemediationInverse> "," <PreventionGate> PreventionGate ::= "static_check" | "architecture_test" | "contract_test" | "schema_gate" | "review_gate" | "fitness_function" | "runtime_monitor"
BeforeSmell described in prose ('this class is too big') — unmeasurable, unenforceable, re-argued case by case.
AfterGod Object : trigger{unrelated methods accrete} -> degeneration{fan-in/out grows} -> detection{LCOM + responsibility count} -> measurement{cohesion score below threshold} -> remediation{Extract Class} -> prevention{architecture test on cohesion}
Anti-Pattern Rule Compiler
- Math type: computation
- Yields: procedure
Details
FlowSmellRecord → DetectionRule → MetricThreshold → Severity → RefactorHint → Gate
ProductionsAntiPatternRuleCompiler ::= <ArchitectureSmellRecordSet> "->" <DetectionRuleSet> "->" <MetricThresholdSet> "->" <SeverityPolicy> "->" <RemediationPlaybookSet> "->" <PreventionGateSet> CompiledRule ::= <RuleName> "," <Scope> "," <Detector> "," <Threshold> "," <PriorityRank> "," <FailureMessage> "," <RefactorHint> "," <PreventionGate>
BeforeA smell catalog read by humans — each entry is advice that nothing executes.
AfterSmellRecord{God Object} -> detection-rule{find unrelated method clusters} -> metric-threshold{LCOM > 0.7} -> severity{error} -> refactor-hint{Extract Class} -> gate{fails the build}
Smell Taxonomy
- Math type: set-theory
- Yields: set | boolean
Details
FlowSmell → MissingControl → RuleFamily → RemediationFamily
ProductionsSmellTaxonomy ::= <SmellSet> "->" <MissingControlClassification> "->" <RuleFamilySet> "->" <RemediationFamilySet> MissingControlClassification ::= "missing_boundary" | "missing_contract" | "missing_type" | "missing_owner" | "missing_version" | "missing_validation" | "missing_observability" | "missing_state_control" | "missing_release_control" | "missing_security_control" | "missing_evidence" | "excessive_abstraction" | "excessive_coupling" | "excessive_manual_process"
BeforeDozens of smells listed flat, each handed its own bespoke, unrelated fix.
Aftersmell-set{Magic Value, Secret Sprawl, Hardcoded Path} -> missing-control{single source of truth} -> rule-family{no-inline-authority checks} -> remediation-family{centralize then inject}
Anti-Pattern Relationship Record
- Math type: graph
- Yields: edge-list
Details
ProductionsAntiPatternRelationshipRecord ::= <AntiPatternName> ":" "Anti-Pattern" "," <scope> "," <caused_by> "," <conflicts_with> "," <degrades> "," <enables_failure> "," <detected_by> "," <measured_by> "," <refactored_by> "," <prevented_by> "," <severity>
BeforeAn anti-pattern named as free text with no typed edges — not resolvable, not gate-checkable, not linkable to the principle it violates.
AfterCyclic Dependency : Anti-Pattern, scope{module}, caused_by{convenience import}, conflicts_with{Low Coupling}, degrades{modularity}, enables_failure{build deadlock}, detected_by{cycle scan}, refactored_by{invert dependency}, prevented_by{dependency rule}, severity{mandatory}
<Architecture Anti-Pattern>
- Meta record
Details
FlowShortcut → Drift → Coupling → Fragility → Detection → Inversion
ProductionsArchitectureAntiPattern ::= <TriggerCondition> "->" <MissingControl> "->" <DegenerationPath> "->" <DamageModel> "->" <DetectionSignalSet> "->" <RemediationInverse> "->" <PreventionGate> RemediationInverse ::= "introduce_boundary" | "declare_contract" | "centralize_authority" | "assign_owner" | "version_change" | "add_observability" | "isolate_state" | "enforce_policy"
arch-relationships
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_architectural_relationship_record["Architectural Relationship Record"]
n_architecture_knowledge_graph["Architecture Knowledge Graph"]
n_architectural_force_classification["Architectural Force Classification"]
n_dependency_closure["Dependency Closure"]
n_reinforcement_propagation["Reinforcement Propagation"]
n_conflict_and_tension_resolution["Conflict and Tension Resolution"]
n_severity_policy["Severity Policy"]
n_violation_detection["Violation Detection"]
n_measurement_normalization["Measurement Normalization"]
n_refactor_selection["Refactor Selection"]
n_enforcement_gate["Enforcement Gate"]
n_architecture_assessment["Architecture Assessment"]
n_modular_boundary_compliance["Modular Boundary Compliance"]
n_contract_compatibility["Contract Compatibility"]
n_canonical_semantics["Canonical Semantics"]
n_domain_boundary_governance["Domain Boundary Governance"]
n_self_description_and_discovery["Self-Description and Discovery"]
n_runtime_extensibility["Runtime Extensibility"]
n_pattern_selection["Pattern Selection"]
n_architectural_style_selection["Architectural Style Selection"]
n_event_and_messaging_consistency["Event and Messaging Consistency"]
n_state_and_transaction_safety["State and Transaction Safety"]
n_correctness_verification["Correctness Verification"]
n_resilience_policy["Resilience Policy"]
n_observability_and_auditability["Observability and Auditability"]
n_causality_and_ordering["Causality and Ordering"]
n_performance_and_scalability["Performance and Scalability"]
n_portability_and_deployment_environment["Portability and Deployment Environment"]
n_security_governance["Security Governance"]
n_architecture_evolution_governance["Architecture Evolution Governance"]
n_control_plane_coordination["Control Plane Coordination"]
n_metaprogramming_safety["Metaprogramming Safety"]
n_streaming_dataflow["Streaming Dataflow"]
n_ai_model_architecture_governance["AI Model Architecture Governance"]
n_architectural_recommendation["Architectural Recommendation"]
n_architecture_fitness_function_generation["Architecture Fitness Function Generation"]
n_architecture_refactoring_roadmap["Architecture Refactoring Roadmap"]
n_concept_cluster_extraction["Concept Cluster Extraction"]
n_architecture_decision_support["Architecture Decision Support"]
n_relationship_schema_validation["Relationship Schema Validation"]
n_architecture_catalog_compiler["Architecture Catalog Compiler"]
n_master_architecture_governance_kernel["Master Architecture Governance Kernel"]
n_architectural_relationship_algebra["Architectural Relationship Algebra"]
n_architecture_assessment --> n_dependency_closure
n_architecture_assessment --> n_violation_detection
n_architecture_assessment --> n_measurement_normalization
n_architectural_recommendation --> n_dependency_closure
n_architecture_fitness_function_generation --> n_architectural_relationship_record
n_architecture_fitness_function_generation --> n_enforcement_gate
n_architecture_fitness_function_generation --> n_severity_policy
n_master_architecture_governance_kernel --> n_relationship_schema_validation
n_master_architecture_governance_kernel --> n_concept_cluster_extraction
n_master_architecture_governance_kernel --> n_dependency_closure
n_master_architecture_governance_kernel --> n_violation_detection
n_master_architecture_governance_kernel --> n_measurement_normalization
n_master_architecture_governance_kernel --> n_refactor_selection
n_master_architecture_governance_kernel --> n_enforcement_gate
n_master_architecture_governance_kernel --> n_architecture_decision_support
n_architectural_relationship_algebra --> n_dependency_closure
n_architectural_relationship_algebra --> n_violation_detection
n_architectural_relationship_algebra --> n_measurement_normalization
n_architectural_relationship_algebra --> n_refactor_selection
n_architectural_relationship_algebra --> n_enforcement_gate
n_architectural_relationship_algebra --> n_architecture_evolution_governanceArchitectural Relationship Record
- Math type: graph
- Yields: edge-list
Details
FlowConcept → Type → Scope → Requires → Violations → Detection → Measurement → Refactor → Enforcement → Severity
ProductionsArchitecturalRelationshipRecord ::= <ConceptName> ":" <RecordType> "," <ScopeSet> "," <RequiresSet> "," <ReinforcesSet> "," <EnablesSet> "," <ConflictSet> "," <TensionSet> "," <ViolationSet> "," <DetectionSet> "," <MetricSet> "," <RefactorSet> "," <EnforcementSet> "," <EnforcementSeverity> RecordType ::= "Principle" | "Quality Attribute" | "Contract" | "Architecture Style" | "Pattern" | "Mechanism" | "Metric" | "Practice" EnforcementSeverity ::= "mandatory" | "recommended" | "contextual" | "discouraged" | "mandatory_for_context"
Before'Low Coupling' as a bare name in a list — not measurable, not enforceable.
AfterLow Coupling : Quality-Attribute, scope{module}, requires{Abstraction}, conflicts_with{Tight Coupling}, detected_by{cycle scan}, measured_by{coupling metric}, refactored_by{invert dependency}, enforced_by{dependency rule}, severity{mandatory}
Architecture Knowledge Graph
- Math type: graph
- Yields: edge-list
Details
FlowRecords → Nodes → TypedEdges → Graph → QueryableArchitectureModel
ProductionsArchitectureGraph ::= <ConceptNodeSet> "," <RelationshipEdgeSet> ConceptNode ::= <ConceptName> "," <RecordType> "," <ScopeSet> "," <EnforcementSeverity> RelationshipEdge ::= <SourceConcept> "->" <RelationType> "->" <TargetConceptOrSignal> RelationType ::= "requires" | "reinforces" | "enables" | "conflicts_with" | "tensions_with" | "violated_by" | "detected_by" | "measured_by" | "refactored_by" | "enforced_by"
BeforeA flat list of relationship records — no way to ask 'what does Foo require, transitively?'
Afterrecords -> nodes{concepts} + typed-edges{requires, reinforces, enables, conflicts_with} -> traversable graph
Architectural Force Classification
- Math type: logic
- Yields: boolean
Details
FlowIssue → ForceFamily → CandidateConcepts → ApplicableContracts
ProductionsForceClassification ::= <DesignIssue> "->" <ForceFamily> "->" <ConceptQuery> "->" <ApplicableConceptSet> ForceFamily ::= "modularity" | "contract_compatibility" | "semantic_consistency" | "domain_boundary" | "runtime_extensibility" | "object_creation" | "structural_mediation" | "behavioral_variation" | "event_messaging" | "state_transaction" | "correctness_verification" | "resilience_recovery" | "observability_traceability" | "causality_ordering" | "performance_scaling" | "security_governance" | "architecture_evolution" | "control_coordination" | "metaprogramming_modeling" | "streaming_dataflow" | "ai_governance"
BeforeA design issue answered by pattern-name recall ('use a Factory').
Afterissue{concrete constructor everywhere} -> force{object_creation} -> concept-query -> applicable{Construction Boundary}
Dependency Closure
- Math type: graph
- Yields: edge-list
Details
FlowTargetConcept → RequiresEdges → TransitiveClosure → DependencyOrder
ProductionsDependencyClosure ::= <TargetConcept> "->" <RequiresTraversal> "->" <RequiredConceptSet> "->" <TopologicalOrder> RequiresTraversal ::= "follow requires edges until fixed point" TopologicalOrder ::= "prerequisites_before_dependents"
BeforeAdopt Foo without checking what Foo needs — its prerequisites are silently unmet.
Aftertarget{Foo} -> follow requires-edges to fixed point -> {Bar, Baz} -> topological order{Baz, Bar, Foo}
Reinforcement Propagation
- Math type: graph
- Yields: edge-list
Details
FlowImplementedConcept → Reinforces + Enables → CapabilityImpact
ProductionsReinforcementPropagation ::= <SatisfiedConcept> "->" <ReinforcesTraversal> "->" <EnablesTraversal> "->" <ImpactSet> ImpactSet ::= <QualityGainSet> "," <CapabilityGainSet> QualityGain ::= <ReinforcedConcept> "," <Confidence> "," <EvidenceRequired>
BeforeFoo implemented; its second-order gains go unnoticed and unclaimed.
Aftersatisfied{Foo} -> reinforces -> {Bar quality} -> enables -> {Baz capability} -> impact set with confidence
Conflict and Tension Resolution
- Math type: logic
- Yields: boolean
Details
FlowCandidateConcept → Conflicts + Tensions → TradeoffAnalysis → Decision
ProductionsConflictTensionResolution ::= <CandidateConceptSet> "->" <ConflictSet> "->" <TensionSet> "->" <ResolutionPolicy> ResolutionPolicy ::= "reject_combination" | "accept_with_mitigation" | "document_tradeoff" | "require_architecture_decision" | "contextual_override"
BeforeTwo chosen concepts silently conflict at runtime; nobody decided the trade-off.
Aftercandidates{Foo, Bar} -> conflict{prohibitive} -> tension{trade-off} -> policy{require architecture decision}
Severity Policy
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowSeverity → EnforcementMode → GateBehavior
ProductionsSeverityPolicy ::= <EnforcementSeverity> "->" <EnforcementMode> EnforcementMode ::= "blocking_gate" | "review_warning" | "context_required" | "exception_required" | "informational" SeverityMapping ::= "mandatory -> blocking_gate" | "recommended -> review_warning" | "contextual -> context_required" | "discouraged -> exception_required"
BeforeEvery finding treated the same — a style nit blocks like a critical flaw.
Afterseverity{mandatory} -> blocking-gate ; severity{recommended} -> review-warning ; severity{contextual} -> context-required
Violation Detection
- Math type: logic
- Yields: boolean
Details
FlowApplicableConcept → DetectionSignals → Observations → ViolationRecords
ProductionsViolationDetection ::= <ApplicableConceptSet> "->" <DetectionSignalSet> "->" <ObservedEvidenceSet> "->" <ViolationRecordSet> ViolationRecord ::= <Concept> "," <ViolationPattern> "," <EvidenceLocationSet> "," <MetricValueSet> "," <EnforcementSeverity> "," <RecommendedRefactorSet>
Before'Foo is violated' asserted from opinion, with no observable signal.
Afterconcept{Foo} -> detected_by signals run on code -> observations -> violation-record{concept, pattern, evidence, severity}
Measurement Normalization
- Math type: analysis
- Yields: operation
Details
FlowMeasuredBy → MetricDefinition → Measurement → NormalizedScore → Confidence
ProductionsMeasurementNormalization ::= <MetricDescriptorSet> "->" <MetricDefinitionSet> "->" <MetricValueSet> "->" <NormalizedScoreSet> MetricDefinition ::= <MetricName> "," <Scope> "," <CollectionMethod> "," <ThresholdPolicy> "," <ConfidencePolicy>
BeforeArchitecture judged by free-form opinion, no comparable numbers.
Aftermeasured_by{coupling} -> metric-definition{scope, method, threshold} -> values -> normalized score + confidence
Refactor Selection
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowViolation → RefactorCandidates → RiskRank → SelectedPlan
ProductionsRefactorSelection ::= <ViolationRecord> "->" <RefactorActionSet> "->" <RefactorRanking> "->" <RefactorPlan> RefactorRanking ::= "severity" "," "required_dependency_count" "," "blast_radius" "," "reinforcement_gain" "," "rollback_feasibility"
BeforeA fix chosen ad hoc, unrelated to the violated concept's remediation contract.
Afterviolation{Foo} -> refactored_by candidates -> rank{severity, blast-radius, reinforcement-gain} -> refactor plan
Enforcement Gate
- Math type: logic
- Yields: boolean
Details
FlowEnforcementDescriptor → GateType → ValidationProcedure → Pass|Fail
ProductionsEnforcementGate ::= <Concept> "->" <EnforcementDescriptorSet> "->" <GateSet> "->" <GateResultSet> GateType ::= "static_analysis" | "architecture_test" | "schema_validation" | "contract_test" | "lint_rule" | "fitness_function" | "runtime_monitor" | "policy_as_code" | "review_gate"
Before'enforced_by: review' — a human promise that erodes under deadline.
Afterenforced_by{Foo} -> gate-type{static-analysis | contract-test | fitness-function} -> pass/fail in CI
Architecture Assessment
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowScope → RelevantConcepts → DependencyClosure → Detection → Measurement → Findings
ProductionsArchitectureAssessment ::= <TargetScope> "->" <RelevantConceptSelection> "->" <DependencyClosure> "->" <ViolationDetection> "->" <MeasurementNormalization> "->" <FindingPrioritization> "->" <AssessmentReport> FindingPrioritization ::= "mandatory_first" "," "high_blast_radius" "," "high_reinforcement_gain" "," "low_refactor_cost"
Before'The architecture is fine' — an unscoped, evidence-free claim.
Afterscope -> relevant concepts -> dependency-closure -> violation-detection -> measurement -> prioritized findings
Modular Boundary Compliance
- Math type: logic
- Yields: boolean
Details
FlowModule → Responsibility → Cohesion → Coupling → Visibility → BoundaryHealth
ProductionsModularBoundaryCompliance ::= <ModuleSet> "->" <ResponsibilityAnalysis> "->" <CohesionMetric> "->" <CouplingMetric> "->" <VisibilityLeakCheck> "->" <BoundaryScore> BoundaryScore ::= <ResponsibilityScore> "," <CohesionScore> "," <CouplingScore> "," <EncapsulationScore> "," <ReplaceabilityScore>
BeforeModularity checked as one vague vibe.
Aftermodules -> responsibility + cohesion + coupling + visibility-leak -> boundary score{per-dimension}
Contract Compatibility
- Math type: logic
- Yields: boolean
Details
FlowBoundary → Contract → Version → CompatibilityMatrix → Gate
ProductionsContractCompatibility ::= <BoundaryContract> "->" <SchemaOrInterfaceValidation> "->" <SemanticValidation> "->" <VersionPolicy> "->" <CompatibilityMatrix> "->" <CompatibilityVerdict> CompatibilityMatrix ::= "producer_current_consumer_current" | "producer_new_consumer_old" | "producer_old_consumer_new" | "unknown_field_handling" | "breaking_diff_check"
BeforeA schema changed and downstreams broke — compatibility was never checked.
Afterboundary-contract -> schema/semantic validation -> version-policy -> compatibility-matrix{new-producer/old-consumer} -> verdict
Canonical Semantics
- Math type: set-theory
- Yields: set | boolean
Details
FlowConcepts → Conflicts → CanonicalAuthority → Normalization → Enforcement
ProductionsCanonicalSemantics ::= <SemanticArtifactSet> "->" <ConflictDetection> "->" <CanonicalAuthoritySelection> "->" <NormalizationPolicy> "->" <TranslationBoundary> "->" <GovernanceGate> SemanticArtifact ::= "schema" | "domain_model" | "field" | "term" | "rule" | "configuration"
BeforeThree models of 'Foo' drift apart; no single authority.
Afterartifacts{Foo-a, Foo-b} -> conflict-detection -> canonical authority -> normalize variants -> SSOT gate
Domain Boundary Governance
- Math type: logic
- Yields: boolean
Details
FlowDomain → Contexts → Language → Ownership → ContextMap → ACL
ProductionsDomainBoundaryGovernance ::= <DomainScope> "->" <BoundedContextSet> "->" <UbiquitousLanguageSet> "->" <OwnershipMap> "->" <ContextMap> "->" <AntiCorruptionBoundarySet> ContextRelationship ::= "upstream" | "downstream" | "shared_kernel" | "customer_supplier" | "anti_corruption_layer" | "separate_ways"
BeforeOne shared model spans every context; a change for Foo breaks Bar.
Afterdomain -> bounded-contexts -> ubiquitous-language -> ownership-map -> context-map -> anti-corruption boundaries
Self-Description and Discovery
- Math type: set-theory
- Yields: set | boolean
Details
FlowComponent → Manifest → CapabilityDeclaration → Discovery → ContractValidation → Binding
ProductionsSelfDescribingDiscovery ::= <RuntimeEntity> "->" <Manifest> "->" <CapabilityDeclaration> "->" <DiscoveryMechanism> "->" <ConformanceValidation> "->" <BindingDecision> Manifest ::= "identity" "," "version" "," "capabilities" "," "dependencies" "," "contracts" "," "configuration" "," "health"
BeforeA runtime component's capabilities are unknowable without reading its source.
Afterentity -> manifest{identity, capabilities, contracts} -> discovery -> conformance-validation -> bind only if it matches
Runtime Extensibility
- Math type: logic
- Yields: boolean
Details
FlowVariantPressure → ExtensionPoint → PluginContract → Registry → Discovery → Isolation
ProductionsRuntimeExtensibility ::= <VariantPressure> "->" <ExtensionPointDesign> "->" <PluginContract> "->" <RegistrationPolicy> "->" <RuntimeDiscovery> "->" <FailureIsolation> RegistrationPolicy ::= "manual_registration" | "manifest_based" | "service_registry" | "convention_based" | "configuration_based"
BeforeEvery new variant edits the core switch statement.
Aftervariant-pressure -> extension-point -> plugin-contract -> registry -> runtime-discovery -> failure-isolation
Pattern Selection
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowProblemForce → PatternFamily → CandidatePattern → ApplicabilityCheck
ProductionsPatternSelection ::= <ProblemForce> "->" <PatternFamily> "->" <CandidatePatternSet> "->" <ApplicabilityVerdict> PatternFamily ::= "creational" | "structural" | "behavioral" CandidatePattern ::= "factory" | "factory_method" | "abstract_factory" | "builder" | "prototype" | "adapter" | "facade" | "proxy" | "bridge" | "decorator" | "strategy" | "template_method" | "observer" | "mediator"
BeforeA pattern applied as decoration ('let's add a Facade') with no force to justify it.
Afterforce{interface mismatch} -> family{structural} -> candidate{Adapter} -> applicability verdict
Architectural Style Selection
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowSystemForces → StyleCandidates → TradeoffMatrix → SelectedStyle → FitnessFunctions
ProductionsArchitectureStyleSelection ::= <SystemForces> "->" <ArchitectureStyleSet> "->" <TradeoffMatrix> "->" <SelectedStyle> "->" <StyleFitnessFunctionSet> SystemForces ::= "domain_complexity" "," "team_topology" "," "deployment_autonomy" "," "consistency_requirement" "," "operational_maturity" "," "scaling_pressure"
Before'We'll do microservices' chosen before the system's forces are known.
Afterforces{domain-complexity, team-topology, deployment-autonomy} -> style-candidates -> trade-off matrix -> selected style + fitness functions
Event and Messaging Consistency
- Math type: logic
- Yields: boolean
Details
FlowStateChange → EventContract → Outbox → Broker → IdempotentConsumer → Trace
ProductionsEventMessagingConsistency ::= <StateChange> "->" <EventClassification> "->" <MessageContract> "->" <PublicationReliability> "->" <ConsumerIdempotency> "->" <OrderingPolicy> "->" <ObservabilityTrace> EventClassification ::= "domain_event" | "integration_event" | "stream_event" PublicationReliability ::= "transactional_outbox" | "append_only_log" | "broker_acknowledgement"
BeforeEvents published ad hoc; a consumer replays and double-applies.
Afterstate-change -> event-contract -> transactional-outbox -> broker -> idempotent-consumer -> ordering + trace
State and Transaction Safety
- Math type: logic
- Yields: boolean
Details
FlowCommand → TransactionBoundary → Invariants → Concurrency → Commit|Rollback → Idempotency
ProductionsStateTransactionSafety ::= <Command> "->" <TransactionBoundary> "->" <InvariantCheck> "->" <ConcurrencyControl> "->" <CommitDecision> "->" <SideEffectPolicy> ConcurrencyControl ::= "optimistic_locking" | "pessimistic_locking" | "serial_execution" | "state_isolation" SideEffectPolicy ::= "idempotent" | "outbox_published" | "compensatable" | "controlled_side_effect"
BeforeTwo mutations with no boundary; a crash between them corrupts state.
Aftercommand -> transaction-boundary -> invariant-check -> concurrency-control -> commit/rollback -> idempotent side-effect
Correctness Verification
- Math type: logic
- Yields: boolean
Details
FlowInput → Canonicalize → DeterministicCore → Spec → Verification → Evidence
ProductionsCorrectnessVerification ::= <InputSet> "->" <Canonicalization> "->" <DeterministicCore> "->" <SpecificationSet> "->" <VerificationMethodSet> "->" <CorrectnessEvidence> VerificationMethod ::= "type_check" | "static_analysis" | "schema_validation" | "contract_test" | "property_based_test" | "specification_test" | "formal_verification" | "runtime_validation"
BeforeCorrectness asserted by 'it worked on my machine'.
Afterinput -> canonicalize -> deterministic-core -> spec -> {type-check, property-test, contract-test} -> evidence
Resilience Policy
- Math type: logic
- Yields: boolean
Details
FlowFailureMode → Criticality → PolicySet → RuntimeGuard → Recovery
ProductionsResiliencePolicy ::= <FailureModeSet> "->" <CriticalityClassification> "->" <ResiliencePatternSet> "->" <RuntimeGuardSet> "->" <RecoveryActionSet> ResiliencePattern ::= "timeout" | "retry" | "circuit_breaker" | "fallback" | "bulkhead" | "backpressure" | "health_check" | "failover" | "rollback" | "auto_remediation"
BeforeA remote call with no failure policy takes the whole system down.
Afterfailure-modes -> criticality -> {timeout, retry, circuit-breaker, bulkhead} -> runtime-guard -> recovery
Observability and Auditability
- Math type: graph
- Yields: edge-list
Details
FlowOperation → Correlation → Telemetry → Audit → TraceGraph → Diagnosis
ProductionsObservabilityAuditability ::= <Operation> "->" <CorrelationId> "->" <CausationId> "->" <TelemetryEventSet> "->" <AuditRecordSet> "->" <TraceGraph> TelemetryEvent ::= "structured_log" | "metric" | "trace_span" | "alert" | "audit_log" | "health_signal"
BeforeAn incident with no correlation ids — behavior can't be reconstructed.
Afteroperation -> correlation-id + causation-id -> {logs, metrics, traces, audit} -> trace-graph -> diagnosis
Causality and Ordering
- Math type: graph
- Yields: edge-list
Details
FlowEventSet → CausalMetadata → DependencyGraph → OrderingPolicy → ConsistencyVerdict
ProductionsCausalityOrdering ::= <EventSet> "->" <CausalMetadataSet> "->" <DependencyGraph> "->" <OrderingValidation> "->" <ConsistencyVerdict> CausalMetadata ::= "correlation_id" | "causation_id" | "sequence_number" | "lamport_clock" | "vector_clock" DependencyGraph ::= "DAG"
BeforeDistributed events ordered by wall-clock; skew corrupts the sequence.
Afterevents -> causal-metadata{vector-clock} -> dependency-graph{DAG} -> happens-before validation -> consistency verdict
Performance and Scalability
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowWorkload → Profile → Benchmark → Bottleneck → Complexity → Scale|Optimize → SLO
ProductionsPerformanceScalability ::= <WorkloadModel> "->" <ProfilingEvidence> "->" <BenchmarkResultSet> "->" <BottleneckAnalysis> "->" <ComplexityAnalysis> "->" <ScalingOrOptimizationPlan> "->" <PerformanceGate> ScalingOrOptimizationPlan ::= "vertical_scale" | "horizontal_scale" | "load_balance" | "shard" | "partition" | "cache" | "stream" | "rate_limit" | "algorithm_replacement"
BeforeOptimize by guesswork; add capacity and hope.
Afterworkload -> profile -> benchmark -> bottleneck -> complexity -> scale/optimize the measured bottleneck -> SLO gate
Portability and Deployment Environment
- Math type: topology
- Yields: boolean
Details
FlowRuntimeAssumption → Abstraction → ExternalConfig → Packaging → EnvironmentParity
ProductionsPortabilityDeployment ::= <ApplicationCore> "->" <PlatformAssumptionScan> "->" <PlatformAbstraction> "->" <ConfigurationExternalization> "->" <DeploymentPackaging> "->" <EnvironmentParityValidation> Environment ::= "local" | "test" | "staging" | "production"
BeforePlatform assumptions baked in; the app only runs on one host.
Aftercore -> platform-assumption scan -> abstraction -> externalized-config -> packaging -> environment-parity
Security Governance
- Math type: logic
- Yields: boolean
Details
FlowThreatModel → ControlSet → Policy → Enforcement → Audit
ProductionsSecurityGovernance ::= <ThreatModel> "->" <SecurityControlSet> "->" <PolicySet> "->" <PolicyEnforcement> "->" <ContinuousCompliance> "->" <RiskReview> SecurityControl ::= "authentication" | "authorization" | "least_privilege" | "zero_trust" | "input_validation" | "output_encoding" | "encryption_at_rest" | "encryption_in_transit" | "secrets_management" | "audit_logging"
BeforeSecurity added as a late checklist, not a policy graph.
Afterthreat-model -> controls{authn, authz, validation, encryption, secrets} -> policy-as-code -> enforcement -> continuous audit
Architecture Evolution Governance
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowAssessment → GapAnalysis → DecisionRecord → FitnessFunction → ChangePlan → Review
ProductionsArchitectureEvolutionGovernance ::= <Assessment> "->" <GapAnalysis> "->" <ImpactAnalysis> "->" <DecisionRecord> "->" <FitnessFunctionSet> "->" <EvolutionPlan> "->" <ReviewGate> DecisionRecord ::= "ADR" "," "context" "," "decision" "," "consequences" "," "status"
BeforeArchitecture drifts; no decision memory, no fitness checks.
Afterassessment -> gap-analysis -> ADR -> fitness-functions -> change-plan -> review gate
Control Plane Coordination
- Math type: logic
- Yields: boolean
Details
FlowPolicy → ControlPlane → DataPlane → Telemetry → PolicyAdjustment
ProductionsControlPlaneCoordination ::= <PolicySet> "->" <ControlPlane> "->" <DataPlaneSet> "->" <TelemetryFeedback> "->" <GovernanceAdjustment> ControlConcern ::= "configuration" | "authentication" | "authorization" | "logging" | "orchestration" | "service_registry"
BeforeEvery service does its own config + auth; policy scatters and drifts.
Afterpolicy -> control-plane{config, authn, orchestration} -> data-planes execute -> telemetry -> governance adjustment
Metaprogramming Safety
- Math type: logic
- Yields: boolean
Details
FlowModel → Schema → Transform → Generate|Interpret → Validate → Execute
ProductionsMetaprogrammingSafety ::= <ProgramModel> "->" <ModelSchema> "->" <TransformationEngine> "->" <GeneratedOrInterpretedArtifact> "->" <SafetyValidation> "->" <ExecutionBoundary> TransformationEngine ::= "reflection" | "introspection" | "compile_time_evaluation" | "runtime_code_generation" | "DSL_interpreter" | "model_driven_generator"
BeforeCode-as-string eval'd with no schema or bound.
Aftermodel -> schema -> transform{reflection | DSL} -> generated artifact -> safety-validation -> bounded execution
Streaming Dataflow
- Math type: analysis
- Yields: operation
Details
FlowSource → Stage → Stage → Backpressure → Checkpoint → Sink
ProductionsStreamingDataflow ::= <Source> "->" <PipelineStageSet> "->" <ProcessingMode> "->" <BackpressurePolicy> "->" <CheckpointPolicy> "->" <Sink> ProcessingMode ::= "single_pass" | "lazy_evaluation" | "sequential_access" | "forward_only" | "stateless" | "stateful_with_checkpoint"
BeforeLoad everything into memory, then map/filter — unbounded.
Aftersource -> forward-only stages -> backpressure -> checkpoint -> sink (bounded memory)
AI Model Architecture Governance
- Math type: logic
- Yields: boolean
Details
FlowModelArtifact → Registry → Evaluation → Safety → InferenceTrace → Monitoring
ProductionsAIModelArchitectureGovernance ::= <AIArtifactSet> "->" <GovernanceRegistry> "->" <EvaluationSuite> "->" <InferenceContract> "->" <ExplainabilityTrace> "->" <SafetyPolicy> "->" <RuntimeMonitoring> AIArtifact ::= "model" | "prompt" | "embedding_index" | "retrieval_source" | "knowledge_graph" | "dataset" | "evaluation"
BeforeA model shipped with no registry, eval, trace, or safety gate.
Afterartifacts{model, prompt, index} -> governance-registry -> evaluation -> inference-contract -> explainability-trace -> safety + monitoring
Architectural Recommendation
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowProblemEvidence → CandidateConcepts → DependencyClosure → ConflictPrune → Rank → Roadmap
ProductionsArchitecturalRecommendation ::= <ProblemEvidenceSet> "->" <ConceptMatchSet> "->" <DependencyClosure> "->" <ConflictTensionResolution> "->" <SeverityRanking> "->" <ImplementationRoadmap> SeverityRanking ::= "mandatory_before_recommended" "," "contextual_when_scope_matches" "," "discouraged_requires_exception"
BeforeAdvice given from intuition, not from the graph or the evidence.
Afterproblem-evidence -> concept-match -> dependency-closure -> conflict-prune -> severity rank -> ordered roadmap
Architecture Fitness Function Generation
- Math type: computation
- Yields: procedure
Details
FlowRelationshipRecord → DetectionCheck → MetricThreshold → EnforcementGate → FitnessFunction
ProductionsFitnessFunctionGeneration ::= <ArchitecturalRelationshipRecord> "->" <DetectionCheck> "->" <MetricThreshold> "->" <EnforcementGate> "->" <FitnessFunction> FitnessFunction ::= <Name> "," <Scope> "," <CheckProcedure> "," <Threshold> "," <SeverityPolicy> "," <FailureMessage> "," <RefactorHintSet>
BeforeMandatory records sit as prose nobody executes.
Afterrecord -> detection-check + metric-threshold + enforcement-gate -> executable fitness function
Architecture Refactoring Roadmap
- Math type: algebra
- Yields: ordered-structure
Details
FlowViolations → SharedCause → RefactorGroup → DependencyOrder → Apply → Enforce
ProductionsRefactoringRoadmap ::= <ViolationRecordSet> "->" <SharedCauseClustering> "->" <RefactorGroupSet> "->" <DependencyOrderedPlan> "->" <ExecutionGateSet> SharedCause ::= "missing_boundary" | "missing_contract" | "semantic_drift" | "concrete_coupling" | "uncontrolled_state" | "missing_observability" | "manual_governance_only"
BeforeViolations fixed one-by-one in random order; shared causes re-fixed repeatedly.
Afterviolations -> cluster by shared-cause{missing-boundary} -> refactor-groups -> dependency-ordered plan -> enforce
Concept Cluster Extraction
- Math type: set-theory
- Yields: set | boolean
Details
FlowGraph → EdgeDensity → Cluster → ConcernFamily
ProductionsConceptClusterExtraction ::= <ArchitectureGraph> "->" <RelationshipDensityAnalysis> "->" <ClusterSet> "->" <ConcernFamilySet> ConcernFamily ::= <ClusterName> "," <CoreConceptSet> "," <SupportingConceptSet> "," <ConflictConceptSet> "," <EnforcementPolicySet>
BeforeA flat catalog of hundreds of concepts, unusable at scale.
Aftergraph -> relationship-density analysis -> clusters -> concern-families{core + supporting + conflict concepts}
Architecture Decision Support
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowDecision → GraphDelta → BenefitSet + RiskSet → ADRRequired?
ProductionsArchitectureDecisionSupport ::= <ProposedDecision> "->" <SatisfiedConceptSet> "->" <ViolatedConceptSet> "->" <TensionSet> "->" <EnabledCapabilitySet> "->" <EnforcementCost> "->" <DecisionGovernance> DecisionGovernance ::= "approve" | "approve_with_ADR" | "revise" | "reject"
BeforeA design decision judged by gut feel, not by its effect on the graph.
Afterdecision -> graph-delta{satisfied, violated, tensions, enabled} -> enforcement-cost -> approve / approve-with-ADR / revise / reject
Relationship Schema Validation
- Math type: logic
- Yields: boolean
Details
FlowRecord → SchemaCheck → ReferenceCheck → CompletenessCheck → Valid|Invalid
ProductionsRelationshipSchemaValidation ::= <ArchitecturalRelationshipRecordSet> "->" <RequiredFieldValidation> "->" <ReferenceResolution> "->" <SeverityValidation> "->" <CompletenessScore> "->" <CatalogValidity> RequiredFieldSet ::= "type" "," "scope" "," "requires" "," "reinforces" "," "enables" "," "conflicts_with" "," "tensions_with" "," "violated_by" "," "detected_by" "," "measured_by" "," "refactored_by" "," "enforced_by" "," "severity"
BeforeCatalog records with missing fields and dangling references ship unchecked.
Afterrecords -> required-field validation -> reference-resolution -> severity validation -> completeness score -> catalog validity
Architecture Catalog Compiler
- Math type: computation
- Yields: procedure
Details
FlowCatalog → Rules + Playbooks + DecisionGraph + Gates
ProductionsArchitectureCatalogCompiler ::= <ArchitectureGraph> "->" <AssessmentRuleSet> "->" <RefactorPlaybookSet> "->" <DecisionSupportModel> "->" <GovernanceGateSet> AssessmentRule ::= <Concept> "," <DetectedBy> "," <MeasuredBy> "," <EnforcementSeverity> RefactorPlaybook ::= <ViolationPattern> "," <RefactoredBy> "," <EnforcedBy>
BeforeThe catalog read only by humans — no operational output.
Aftergraph -> {assessment-rules, refactor-playbooks, decision-support-model, governance-gates}
Master Architecture Governance Kernel
- Math type: computation
- Yields: procedure
Details
FlowCatalog → Graph → Scope → Concepts → Detection → Metrics → Refactor → Enforcement → ADR
ProductionsMasterArchitectureGovernanceKernel ::= <RelationshipSchemaValidation> "->" <ArchitectureGraph> "->" <TargetScopeClassification> "->" <ConceptClusterExtraction> "->" <DependencyClosure> "->" <ViolationDetection> "->" <MeasurementNormalization> "->" <ConflictTensionResolution> "->" <RefactorSelection> "->" <EnforcementGate> "->" <ArchitectureDecisionSupport> "->" <GovernanceReport> GovernanceReport ::= <SatisfiedConceptSet> "," <ViolationRecordSet> "," <MetricEvidenceSet> "," <ConflictTensionSet> "," <RefactorRoadmap> "," <EnforcementGateSet> "," <ADRRecommendationSet> "," <ResidualRiskSet>
BeforeAssessment, remediation, and evolution done by disconnected manual steps.
Aftervalidate -> graph -> scope -> clusters -> closure -> detect -> measure -> resolve -> refactor -> enforce -> ADR -> governance report
Architectural Relationship Algebra
- Meta record
Details
FlowRecord → Graph → Force → Concept → Evidence → Refactor → Gate → Governance
ProductionsArchitecturalRelationshipAlgebra ::= <ArchitecturalRelationshipRecordSet> "->" <ArchitectureGraph> "->" <ForceClassification> "->" <ApplicableConceptSet> "->" <DependencyClosure> "->" <ViolationDetection> "->" <MeasurementNormalization> "->" <RefactorSelection> "->" <EnforcementGate> "->" <ArchitectureEvolutionGovernance> ArchitecturalRelationshipRecord ::= <ConceptName> ":" <RecordType> "," <ScopeSet> "," <RequiresSet> "," <ReinforcesSet> "," <EnablesSet> "," <ConflictSet> "," <TensionSet> "," <ViolationSet> "," <DetectionSet> "," <MetricSet> "," <RefactorSet> "," <EnforcementSet> "," <EnforcementSeverity> OperationalLifecycle ::= "define" | "select" | "detect" | "measure" | "refactor" | "enforce" | "observe" | "evolve" CompletionCondition ::= "all_mandatory_concepts_satisfied" "," "contextual_concepts_justified" "," "recommended_concepts_reported" "," "discouraged_concepts_exception_reviewed" "," "residual_risk_recorded"
Architectural Clusters
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_structural_core["Structural Core"]
n_correctness_core["Correctness Core"]
n_evolution_principles["Evolution Principles"]
n_resource_core["Resource Core"]
n_execution_core["Execution Core"]
n_computation_core["Computation Core"]
n_security_core["Security Core"]
n_performance_core["Performance Core"]
n_contracts_core["Contracts Core"]
n_causality_core["Causality Core"]
n_declarative_core["Declarative Core"]
n_extensibility_core["Extensibility Core"]
n_observability["Observability"]
n_enforcement_core["Enforcement Core"]
n_atomic_boundary["Atomic Boundary"]
n_human_factors["Human Factors"]
n_domain_modeling["Domain Modeling"]
n_design_patterns_core["Design Patterns Core"]
n_state_pattern["State Pattern"]
n_separation_of_concerns["Separation of Concerns"]
n_concurrency_correctness["Concurrency Correctness"]
n_capacity_planning["Capacity Planning"]Structural Core
- Layer: Structural Core
- Meta record
Details
FlowSingleSource → NoShortcut → NoFallback → NoOrphan
Correctness Core
- Layer: Correctness Core
- Meta record
Details
FlowSurfaceFailure → RejectInvalid → ActOnFeedback
Evolution Principles
- Layer: Evolution Principles
- Meta record
Details
FlowSupersede → Delete → NoLegacy
Resource Core
- Layer: Resource Core
- Meta record
Details
FlowAcquire → Own → Bound → Release
Execution Core
- Layer: Execution Core
- Meta record
Details
FlowSinglePath → Observe → NoDefer
Computation Core
- Layer: Computation Core
- Meta record
Details
FlowImmutable → Deterministic → Reproducible
Security Core
- Layer: Security Core
- Meta record
Details
FlowValidateInput → LeastPrivilege → NoSecretLeak
Performance Core
- Layer: Performance Core
- Meta record
Details
FlowMeasure → Optimize → Verify
Contracts Core
- Layer: Contracts Core
- Meta record
Details
FlowExplicitContract → TypedBoundary → VersionChange
Causality Core
- Layer: Causality Core
- Meta record
Details
FlowLogicalOrder → Retract → NoWallClock
Declarative Core
- Layer: Declarative Core
- Meta record
Details
FlowDeclare → Separate → NoImperativeConfig
Extensibility Core
- Layer: Extensibility Core
- Meta record
Details
FlowDeclareWiring → Discover → Extend
Observability
- Layer: Observability
- Meta record
Details
FlowEmit → Trace → NoOpaque
Enforcement Core
- Layer: Enforcement Core
- Meta record
Details
FlowGate → Automate → NoConventionOnly
Atomic Boundary
- Layer: Atomic Boundary
- Meta record
Details
FlowBegin → AllOrNothing → Commit
Human Factors
- Layer: Human Factors
- Meta record
Details
FlowBoundComplexity → Approve → ActOnFeedback
Domain Modeling
- Layer: Domain Modeling
- Meta record
Details
FlowBoundContext → NoLeak → UbiquitousLanguage
Design Patterns Core
- Layer: Design Patterns Core
- Meta record
Details
FlowObserveRecurrence → ApplyPattern → NoSpeculation
State Pattern
Details
FlowDefineStates → DelegateBehavior → Transition
BeforeState-dependent behavior scattered as if/else conditionals on a status flag.
Afterdefine state objects -> delegate behavior to the current-state object -> transition replaces the conditional branching
Separation of Concerns
Details
FlowIdentifyConcerns → Separate → IsolateChange
BeforeOne module mixes parsing, persistence, and rendering — a change in one ripples through all.
Afteridentify concerns -> separate each into one place -> each concern changes independently
Concurrency Correctness
Details
FlowModelInterleavings → PreventRaces → Verify
BeforeConcurrent access with a data race; some interleaving violates the invariant.
Aftermodel interleavings -> prevent races -> verify every interleaving preserves the invariants
Capacity Planning
Details
FlowModelLoad → Forecast → Provision
BeforeCapacity guessed, then saturates under real load.
Aftermodel load -> forecast demand -> provision from measured/modeled load, not a guess
Architectural Rules
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_no_shortcuts["Constraints Over Shortcuts"]
n_no_backward_compat["Forward Compatibility Over Backward Compatibility"]
n_no_fallback["Fail-Fast Over Fallback"]
n_no_deprecation["Explicit Removal Over Deprecation"]
n_no_legacy["Greenfield Over Legacy"]
n_no_dual_path["Single-Path Determinism Over Dual-Path"]
n_no_deferring["Immediacy Over Deferring"]
n_no_optional["Mandatory Over Optional"]
n_no_for_now["Now Over For-Now"]
n_no_unobserved["Observed Execution Over Unobserved"]
n_no_uncompressed["Compression Over Repetition"]
n_no_unapproved["Approved Evolution Over Unapproved"]
n_no_ignored_feedback["Enforced Feedback Over Ignored"]
n_no_shared_ownership["Single Owner Over Shared Ownership"]
n_no_unbounded["Bounded Lifetime Over Unbounded"]
n_no_asymmetric["Enforced Symmetry Over Asymmetric Lifecycle"]
n_no_implicit_retention["Explicit Retention Over Implicit"]
n_no_discipline_release["Structural Release Over Discipline"]
n_no_mutable["Immutable Data Over Mutable State"]
n_no_silent["Errors As Language Over Silent Errors"]
n_no_hidden_invalidity["Explicit Invalidity Over Hidden"]
n_no_callbacks["Event Emission Over Parent Callbacks"]
n_no_retraction["Monotonic Growth Over Retraction"]
n_no_location["Semantic Addressing Over Location Addressing"]
n_no_timestamps["Ordinal Time Over Timestamps"]
n_no_separation["Homoiconicity Over Separation"]
n_no_unlimited["Bounded Complexity Over Unlimited"]
n_no_metrics["Computed Health Over Metric Health"]
n_no_hardcoded_secrets["Secret Store Over Hardcoded Secrets"]
n_no_unvalidated_input["Boundary Validation Over Unvalidated Input"]
n_no_broad_privilege["Least Privilege Over Broad Privilege"]
n_no_env_fallback["Config Externalization Over Env Fallback"]
n_no_unmeasured_optimization["Profile-First Over Unmeasured Optimization"]
n_no_convention_enforcement["Rule As Code Over Convention"]
n_no_implicit_contract["Design By Contract Over Implicit Contract"]
n_no_breaking_change["Versioned Evolution Over Breaking Change"]
n_no_untyped_boundary["Schema-Validated Boundary Over Untyped"]
n_no_partial_commit["Atomic Boundary Over Partial Commit"]
n_no_distributed_2pc["Saga Compensation Over Distributed 2PC"]
n_no_sync_cross_boundary["Async Events Over Synchronous Cross-Boundary"]
n_no_opaque_runtime["Observable Signals Over Opaque Runtime"]
n_no_hidden_dependency["Injected Dependency Over Hidden"]
n_no_hardcoded_wiring["Convention Discovery Over Hardcoded Wiring"]
n_no_imperative_config["Declarative Config Over Imperative"]
n_no_leaky_context["Anti-Corruption Layer Over Cross-Context Leak"]
n_no_hidden_nondeterminism["Injected Nondeterminism Over Hidden"]
n_no_speculative_pattern["Pattern By Fit Over Speculative Pattern"]Constraints Over Shortcuts
- Math type: logic
- Yields: boolean
Details
FlowShortcutTaken → IdentifyInvariant → EncodeConstraint → RouteThroughBoundary → LeverageGained
ProductionsNoShortcuts ::= <ShortcutTaken> "->" <IdentifyInvariant> "->" <EncodeConstraint> "->" <RouteThroughBoundary> "->" <LeverageGained>
Beforetype FooId = string; function loadFoo(raw: string) { return fooStore.get(raw as FooId); }
Aftertype FooId = string & { readonly __brand: "FooId" }; function fooId(raw: string): FooId { if (!raw.startsWith("foo_") || raw.length <= 4) throw new Error(`invalid FooId: ${raw}`); return raw as FooId; } function loadFoo(id: FooId) { return fooStore.get(id); }
Forward Compatibility Over Backward Compatibility
- Math type: logic
- Yields: boolean
Details
FlowManyVariants → DefineEnvelope → MapToCanonical → OpenExtensionSlot → RemoveVariantBranches
ProductionsNoBackwardCompat ::= <ManyVariants> "->" <DefineEnvelope> "->" <MapToCanonical> "->" <OpenExtensionSlot> "->" <RemoveVariantBranches>
Beforetype FooInput = string | { name: string } | { label: string; flags?: string[] }; function readFoo(input: FooInput) { if (typeof input === "string") return { label: input, flags: [] }; if ("name" in input) return { label: input.name, flags: [] }; return { label: input.label, flags: input.flags ?? [] }; }
Aftertype FooEnvelope = { kind: "foo"; label: string; extensions: Readonly<Record<string, unknown>>; }; function readFoo(input: FooEnvelope) { return { label: input.label, extensions: input.extensions }; }
Fail-Fast Over Fallback
- Math type: logic
- Yields: boolean
Details
FlowOptionalInput → MarkRequired → ValidateAtBoundary → HaltOnAbsence → ClarityGained
ProductionsNoFallback ::= <OptionalInput> "->" <MarkRequired> "->" <ValidateAtBoundary> "->" <HaltOnAbsence> "->" <ClarityGained>
Beforefunction makeFoo(config: { mode?: "foo" | "bar" }) { const mode = config.mode ?? "foo"; return mode === "foo" ? new Foo() : new Bar(); }
Aftertype FooConfig = { mode: "foo" | "bar" }; function makeFoo(config: FooConfig) { if (!config.mode) throw new Error("FooConfig.mode is required"); return config.mode === "foo" ? new Foo() : new Bar(); }
Explicit Removal Over Deprecation
- Math type: logic
- Yields: boolean
Details
FlowDeprecatedAlias → MigrateCallsites → DeleteAlias → SinglePathRemains
ProductionsNoDeprecation ::= <DeprecatedAlias> "->" <MigrateCallsites> "->" <DeleteAlias> "->" <SinglePathRemains>
Beforeclass FooService { makeFoo() { return this.createFoo(); } createFoo() { return new Foo(); } }
Afterclass FooService { createFoo() { return new Foo(); } }
Greenfield Over Legacy
- Math type: logic
- Yields: boolean
Details
FlowLegacyBranch → ExtractCurrentPath → DeleteLegacyPath → RemoveFlag
ProductionsNoLegacy ::= <LegacyBranch> "->" <ExtractCurrentPath> "->" <DeleteLegacyPath> "->" <RemoveFlag>
Beforefunction calculateFoo(input: FooInput, legacyMode: boolean) { if (legacyMode) return oldFooAlgorithm(input); return newFooAlgorithm(input); }
Afterfunction calculateFoo(input: FooInput) { return fooAlgorithm(input); }
Single-Path Determinism Over Dual-Path
- Math type: logic
- Yields: boolean
Details
FlowDualPath → ChooseCanonical → MigrateConsumers → DeleteAlternate → DeterminismGained
ProductionsNoDualPath ::= <DualPath> "->" <ChooseCanonical> "->" <MigrateConsumers> "->" <DeleteAlternate> "->" <DeterminismGained>
Beforefunction saveFoo(foo: Foo, flags: { useNewStore: boolean }) { return flags.useNewStore ? newFooStore.save(foo) : oldFooStore.save(foo); }
Afterfunction saveFoo(foo: Foo) { return fooStore.save(foo); }
Immediacy Over Deferring
- Math type: logic
- Yields: boolean
Details
FlowPartialAction → IdentifyCoupledEffects → WrapInTransaction → CommitTogether
ProductionsNoDeferring ::= <PartialAction> "->" <IdentifyCoupledEffects> "->" <WrapInTransaction> "->" <CommitTogether>
Beforeasync function renameFoo(id: FooId, name: string) { await fooStore.rename(id, name); }
Afterasync function renameFoo(id: FooId, name: string) { await transaction(async tx => { await tx.foos.rename(id, name); await tx.search.reindex(id, name); }); }
Mandatory Over Optional
- Math type: logic
- Yields: boolean
Details
FlowOptionalDependency → MakeRequired → InjectAlways → RemoveGuards
ProductionsNoOptional ::= <OptionalDependency> "->" <MakeRequired> "->" <InjectAlways> "->" <RemoveGuards>
Beforeclass FooService { constructor(private readonly audit?: AuditSink) {} create(foo: Foo) { this.audit?.write({ type: "foo.created", foo }); return fooStore.save(foo); } }
Afterclass FooService { constructor(private readonly audit: AuditSink) {} create(foo: Foo) { this.audit.write({ type: "foo.created", foo }); return fooStore.save(foo); } }
Now Over For-Now
- Math type: logic
- Yields: boolean
Details
FlowTemporaryStub → IdentifyDurabilityNeed → WireRealStore → DeleteStub
ProductionsNoForNow ::= <TemporaryStub> "->" <IdentifyDurabilityNeed> "->" <WireRealStore> "->" <DeleteStub>
Beforeclass FooRepository { private readonly data = new Map<string, Foo>(); save(foo: Foo) { this.data.set(foo.id, foo); } }
Afterclass FooRepository { constructor(private readonly db: Database) {} save(foo: Foo) { return this.db.execute("insert into foos(id, value) values (?, ?)", foo.id, foo); } }
Observed Execution Over Unobserved
- Math type: logic
- Yields: boolean
Details
FlowBlindEffect → OpenSpan → ExecuteWithinSpan → RecordOutcome
ProductionsNoUnobserved ::= <BlindEffect> "->" <OpenSpan> "->" <ExecuteWithinSpan> "->" <RecordOutcome>
Beforefunction publishFoo(foo: Foo) { sendFoo(foo); }
Afterasync function publishFoo(foo: Foo, telemetry: Telemetry) { const span = telemetry.startSpan("foo.publish", { fooId: foo.id }); try { await sendFoo(foo); span.end({ status: "ok" }); } catch (error) { span.end({ status: "error", error }); throw error; } }
Compression Over Repetition
- Math type: logic
- Yields: boolean
Details
FlowDuplicatedPattern → IdentifyVariation → ExtractParameterized → RedirectCallsites
ProductionsNoUncompressed ::= <DuplicatedPattern> "->" <IdentifyVariation> "->" <ExtractParameterized> "->" <RedirectCallsites>
Beforefunction validateFoo(foo: Foo) { if (!foo.name) throw new Error("foo.name required"); if (foo.name.length > 40) throw new Error("foo.name too long"); } function validateBar(bar: Bar) { if (!bar.name) throw new Error("bar.name required"); if (bar.name.length > 40) throw new Error("bar.name too long"); }
Afterfunction requiredName(value: { name: string }, kind: string) { if (!value.name) throw new Error(`${kind}.name required`); if (value.name.length > 40) throw new Error(`${kind}.name too long`); } const validateFoo = (foo: Foo) => requiredName(foo, "foo"); const validateBar = (bar: Bar) => requiredName(bar, "bar");
Approved Evolution Over Unapproved
- Math type: logic
- Yields: boolean
Details
FlowUnapprovedDependency → RaiseDecision → RecordApproval → WireApprovedGateway
ProductionsNoUnapproved ::= <UnapprovedDependency> "->" <RaiseDecision> "->" <RecordApproval> "->" <WireApprovedGateway>
Beforeclass FooService { private readonly barDb = connectDirectlyToBarDatabase(); }
Aftertype ArchitectureDecision = { id: "ADR-0042"; status: "approved"; owner: "foo-platform"; allowedDependency: "BarGateway"; }; const decision: ArchitectureDecision = approvedDecision("ADR-0042"); class FooService { constructor(private readonly bars: BarGateway, readonly adr = decision.id) {} }
Enforced Feedback Over Ignored
- Math type: logic
- Yields: boolean
Details
FlowWarnAndContinue → ModelFailureResult → ReturnTypedError → HaltHappyPath
ProductionsNoIgnoredFeedback ::= <WarnAndContinue> "->" <ModelFailureResult> "->" <ReturnTypedError> "->" <HaltHappyPath>
Beforefunction ingestFoo(foo: Foo) { if (foo.score < 0) console.warn("bad foo score", foo.score); return fooStore.save(foo); }
Afterfunction ingestFoo(foo: Foo) { if (foo.score < 0) { return { ok: false, error: { code: "INVALID_SCORE", value: foo.score } } as const; } fooStore.save(foo); return { ok: true } as const; }
Single Owner Over Shared Ownership
- Math type: logic
- Yields: boolean
Details
FlowMultiWriter → AssignOwner → EmitEvent → ProjectDownstream
ProductionsNoSharedOwnership ::= <MultiWriter> "->" <AssignOwner> "->" <EmitEvent> "->" <ProjectDownstream>
Beforeasync function renameFoo(id: FooId, name: string) { await fooService.rename(id, name); await barService.patchFooName(id, name); }
Afterasync function renameFoo(id: FooId, name: string) { await fooService.rename(id, name); } fooEvents.on("FooRenamed", event => { barProjection.apply(event); });
Bounded Lifetime Over Unbounded
- Math type: logic
- Yields: boolean
Details
FlowUnboundedStore → SetCapacity → AddEviction → ExposeClear
ProductionsNoUnbounded ::= <UnboundedStore> "->" <SetCapacity> "->" <AddEviction> "->" <ExposeClear>
Beforeconst fooCache = new Map<string, Foo>(); function rememberFoo(foo: Foo) { fooCache.set(foo.id, foo); }
Afterclass FooCache { constructor(private readonly maxEntries: number) {} private readonly values = new Map<string, Foo>(); set(foo: Foo) { if (this.values.size >= this.maxEntries) { const oldest = this.values.keys().next().value; if (oldest !== undefined) this.values.delete(oldest); } this.values.set(foo.id, foo); } clear() { this.values.clear(); } }
Enforced Symmetry Over Asymmetric Lifecycle
- Math type: logic
- Yields: boolean
Details
FlowUnbalancedAcquire → WrapTryFinally → ReleaseInFinally → GuaranteedCleanup
ProductionsNoAsymmetric ::= <UnbalancedAcquire> "->" <WrapTryFinally> "->" <ReleaseInFinally> "->" <GuaranteedCleanup>
Beforeasync function readFoo() { const handle = await openFoo(); const foo = await handle.read(); await handle.close(); return foo; }
Afterasync function readFoo() { const handle = await openFoo(); try { return await handle.read(); } finally { await handle.close(); } }
Explicit Retention Over Implicit
- Math type: logic
- Yields: boolean
Details
FlowAnonymousRetention → MintToken → NameOwner → ExposeRelease
ProductionsNoImplicitRetention ::= <AnonymousRetention> "->" <MintToken> "->" <NameOwner> "->" <ExposeRelease>
Beforeconst listeners: Array<() => void> = []; function watchFoo(foo: Foo) { listeners.push(() => console.log(foo.id)); }
Aftertype Retention = { owner: string; release(): void }; function retainFoo(foo: Foo, owner: string): Retention { const token = fooRetentions.add({ foo, owner }); return { owner, release: () => fooRetentions.delete(token), }; }
Structural Release Over Discipline
- Math type: logic
- Yields: boolean
Details
FlowManualRelease → ImplementDisposable → UseScopedBinding → AutomaticCleanup
ProductionsNoDisciplineRelease ::= <ManualRelease> "->" <ImplementDisposable> "->" <UseScopedBinding> "->" <AutomaticCleanup>
Beforeasync function useFoo() { const foo = await acquireFoo(); await processFoo(foo); await foo.release(); }
Afterclass FooLease implements Disposable { [Symbol.dispose]() { releaseFoo(this); } } function useFoo() { using foo = acquireFooLease(); processFoo(foo); }
Immutable Data Over Mutable State
- Math type: logic
- Yields: boolean
Details
FlowInPlaceMutation → MarkReadonly → ReturnNewValue → ReproducibilityGained
ProductionsNoMutable ::= <InPlaceMutation> "->" <MarkReadonly> "->" <ReturnNewValue> "->" <ReproducibilityGained>
Beforetype Foo = { name: string; tags: string[] }; function addTag(foo: Foo, tag: string) { foo.tags.push(tag); return foo; }
Aftertype Foo = Readonly<{ name: string; tags: readonly string[] }>; function addTag(foo: Foo, tag: string): Foo { return { ...foo, tags: [...foo.tags, tag] }; }
Errors As Language Over Silent Errors
- Math type: logic
- Yields: boolean
Details
FlowNullOnFailure → DefineResultUnion → ReturnTypedError → ForceHandling
ProductionsNoSilent ::= <NullOnFailure> "->" <DefineResultUnion> "->" <ReturnTypedError> "->" <ForceHandling>
Beforefunction parseFoo(raw: string): Foo | null { try { return JSON.parse(raw) as Foo; } catch { return null; } }
Aftertype ParseFooResult = | { ok: true; value: Foo } | { ok: false; error: { code: "INVALID_JSON" | "INVALID_FOO"; detail: string } }; function parseFoo(raw: string): ParseFooResult { try { const value = JSON.parse(raw); return isFoo(value) ? { ok: true, value } : { ok: false, error: { code: "INVALID_FOO", detail: "schema mismatch" } }; } catch (error) { return { ok: false, error: { code: "INVALID_JSON", detail: String(error) } }; } }
Event Emission Over Parent Callbacks
- Math type: logic
- Yields: boolean
Details
FlowParentCallback → DefineEvent → EmitFact → SubscribeExternally
ProductionsNoCallbacks ::= <ParentCallback> "->" <DefineEvent> "->" <EmitFact> "->" <SubscribeExternally>
Beforeclass FooEditor { constructor(private readonly onSaved: (foo: Foo) => void) {} save(foo: Foo) { fooStore.save(foo); this.onSaved(foo); } }
Afterclass FooEditor { constructor(private readonly events: EventSink) {} save(foo: Foo) { fooStore.save(foo); this.events.emit({ type: "FooSaved", fooId: foo.id }); } } fooEvents.on("FooSaved", event => refreshFooView(event.fooId));
Monotonic Growth Over Retraction
- Math type: logic
- Yields: boolean
Details
FlowDestructiveDelete → DefineEventLog → AppendRemoval → ProjectCurrent
ProductionsNoRetraction ::= <DestructiveDelete> "->" <DefineEventLog> "->" <AppendRemoval> "->" <ProjectCurrent>
Beforetype FooIndex = Map<FooId, Foo>; function deleteFoo(index: FooIndex, id: FooId) { index.delete(id); }
Aftertype FooEvent = | { seq: number; type: "FooAdded"; foo: Foo } | { seq: number; type: "FooRemoved"; fooId: FooId }; function removeFoo(log: FooEvent[], id: FooId) { log.push({ seq: log.length + 1, type: "FooRemoved", fooId: id }); } const currentFoos = projectFoos(log);
Semantic Addressing Over Location Addressing
- Math type: logic
- Yields: boolean
Details
FlowPositionalRef → AssignIdentity → ReferenceById → ResolveByLookup
ProductionsNoLocation ::= <PositionalRef> "->" <AssignIdentity> "->" <ReferenceById> "->" <ResolveByLookup>
Beforeconst foo = document.sections[2].items[4]; const reference = "sections[2].items[4]";
Aftertype FooRef = { kind: "foo"; id: FooId }; const reference: FooRef = { kind: "foo", id: fooId("foo_primary") }; const foo = document.foosById.get(reference.id);
Ordinal Time Over Timestamps
- Math type: logic
- Yields: boolean
Details
FlowWallClockOrder → AssignOrdinal → AppendWithOrdinal → SortByOrdinal
ProductionsNoTimestamps ::= <WallClockOrder> "->" <AssignOrdinal> "->" <AppendWithOrdinal> "->" <SortByOrdinal>
Beforetype FooEvent = { at: number; value: string }; const events = received.map(value => ({ at: Date.now(), value })); events.sort((a, b) => a.at - b.at);
Aftertype FooEvent = { ordinal: bigint; value: string }; function appendFoo(value: string): FooEvent { return fooLog.append(nextOrdinal(), value); } const events = fooLog.read().sort((a, b) => Number(a.ordinal - b.ordinal));
Homoiconicity Over Separation
- Math type: logic
- Yields: boolean
Details
FlowCodeAndMetadata → DefineExprData → EvaluateData → SingleSource
ProductionsNoSeparation ::= <CodeAndMetadata> "->" <DefineExprData> "->" <EvaluateData> "->" <SingleSource>
Beforefunction calculateFoo(foo: Foo) { return foo.value * 2; } const fooRuleMetadata = { operation: "multiply", operand: 2, };
Aftertype Expr = | { op: "value"; key: keyof Foo } | { op: "const"; value: number } | { op: "multiply"; left: Expr; right: Expr }; const fooRule: Expr = { op: "multiply", left: { op: "value", key: "value" }, right: { op: "const", value: 2 }, }; const result = evaluate(fooRule, foo);
Bounded Complexity Over Unlimited
- Math type: logic
- Yields: boolean
Details
FlowOpenEndedRule → DefineBoundedGrammar → ValidateDepth → ValidateFanOut
ProductionsNoUnlimited ::= <OpenEndedRule> "->" <DefineBoundedGrammar> "->" <ValidateDepth> "->" <ValidateFanOut>
Beforetype FooRule = { run(context: unknown): unknown; }; function execute(rule: FooRule) { return rule.run(globalThis); }
Aftertype FooRule = | { op: "equals"; field: "name" | "kind"; value: string } | { op: "all"; rules: readonly FooRule[] }; function validateRule(rule: FooRule, depth = 0): void { if (depth > 5) throw new Error("FooRule depth exceeds 5"); if (rule.op === "all") { if (rule.rules.length > 10) throw new Error("FooRule fan-out exceeds 10"); rule.rules.forEach(child => validateRule(child, depth + 1)); } }
Computed Health Over Metric Health
- Math type: logic
- Yields: boolean
Details
FlowMetricThreshold → EnumerateCauses → ComputeState → NameBlockers
ProductionsNoMetrics ::= <MetricThreshold> "->" <EnumerateCauses> "->" <ComputeState> "->" <NameBlockers>
Beforefunction fooHealth(metrics: { errorRate: number; latencyMs: number }) { return metrics.errorRate < 0.01 && metrics.latencyMs < 200 ? "healthy" : "unhealthy"; }
Aftertype FooHealth = | { state: "ready" } | { state: "blocked"; causes: readonly ("STORE_UNREACHABLE" | "SCHEMA_MISMATCH")[] }; function fooHealth(status: { storeReachable: boolean; schemaCompatible: boolean }): FooHealth { const causes = [ ...(!status.storeReachable ? ["STORE_UNREACHABLE" as const] : []), ...(!status.schemaCompatible ? ["SCHEMA_MISMATCH" as const] : []), ]; return causes.length ? { state: "blocked", causes } : { state: "ready" }; }
Secret Store Over Hardcoded Secrets
- Math type: logic
- Yields: boolean
Details
FlowInlineSecret → MoveToStore → ResolveAtRuntime → FailIfMissing
ProductionsNoHardcodedSecrets ::= <InlineSecret> "->" <MoveToStore> "->" <ResolveAtRuntime> "->" <FailIfMissing>
Beforeconst fooClient = new FooClient({ apiKey: "foo_live_abc123", });
Afterasync function makeFooClient(secrets: SecretStore) { const apiKey = await secrets.read("services/foo/api-key"); if (!apiKey) throw new Error("missing services/foo/api-key"); return new FooClient({ apiKey }); }
Boundary Validation Over Unvalidated Input
- Math type: logic
- Yields: boolean
Details
FlowRawInput → ParseAtBoundary → ValidateSchema → PassTypedValue
ProductionsNoUnvalidatedInput ::= <RawInput> "->" <ParseAtBoundary> "->" <ValidateSchema> "->" <PassTypedValue>
Beforeasync function createFoo(request: Request) { const body = await request.json() as any; return fooDb.query(`insert into foo(name) values ('${body.name}')`); }
Aftertype CreateFoo = { name: string }; function parseCreateFoo(value: unknown): CreateFoo { if (!value || typeof value !== "object") throw new Error("body must be an object"); const name = (value as Record<string, unknown>).name; if (typeof name !== "string" || name.length < 1 || name.length > 40) { throw new Error("name must be 1..40 characters"); } return { name }; } async function createFoo(request: Request) { const input = parseCreateFoo(await request.json()); return fooDb.query("insert into foo(name) values (?)", input.name); }
Least Privilege Over Broad Privilege
- Math type: logic
- Yields: boolean
Details
FlowBroadCapability → DefineNarrowInterface → InjectMinimal → DenyRest
ProductionsNoBroadPrivilege ::= <BroadCapability> "->" <DefineNarrowInterface> "->" <InjectMinimal> "->" <DenyRest>
Beforeclass FooJob { constructor(private readonly admin: AdminDatabase) {} run(foo: Foo) { return this.admin.execute(`delete from bar; insert into foo values (?)`, foo); } }
Afterinterface FooWriter { insert(foo: Foo): Promise<void>; } class FooJob { constructor(private readonly foos: FooWriter) {} run(foo: Foo) { return this.foos.insert(foo); } }
Config Externalization Over Env Fallback
- Math type: logic
- Yields: boolean
Details
FlowEnvOrDefault → DefineConfigSchema → LoadAtBoot → FailIfIncomplete
ProductionsNoEnvFallback ::= <EnvOrDefault> "->" <DefineConfigSchema> "->" <LoadAtBoot> "->" <FailIfIncomplete>
Beforeconst fooUrl = process.env.FOO_URL || "http://localhost:3000"; const retryCount = Number(process.env.FOO_RETRIES || "3");
Aftertype AppConfig = Readonly<{ fooUrl: URL; retryCount: number }>; function loadConfig(env: NodeJS.ProcessEnv): AppConfig { if (!env.FOO_URL) throw new Error("FOO_URL is required"); if (!env.FOO_RETRIES) throw new Error("FOO_RETRIES is required"); const retryCount = Number(env.FOO_RETRIES); if (!Number.isInteger(retryCount) || retryCount < 0) throw new Error("invalid FOO_RETRIES"); return Object.freeze({ fooUrl: new URL(env.FOO_URL), retryCount }); } const config = loadConfig(process.env);
Profile-First Over Unmeasured Optimization
- Math type: logic
- Yields: boolean
Details
FlowSuspectedHotspot → Profile → IdentifyBottleneck → OptimizeMeasured → Verify
ProductionsNoUnmeasuredOptimization ::= <SuspectedHotspot> "->" <Profile> "->" <IdentifyBottleneck> "->" <OptimizeMeasured> "->" <Verify>
Beforeconst fooCache = new Map<string, Foo>(); function getFoo(id: string) { if (!fooCache.has(id)) fooCache.set(id, expensiveLookup(id)); return fooCache.get(id)!; }
Afterconst profile = profiler.measure("foo.batch", () => { for (const id of fooIds) expensiveLookup(id); }); if (profile.hotspot === "repeated-foo-lookup") { const foos = fooStore.getMany(fooIds); consume(foos); }
Rule As Code Over Convention
- Math type: logic
- Yields: boolean
Details
FlowWrittenConvention → EncodeCheck → WireGate → FailOnViolation
ProductionsNoConventionEnforcement ::= <WrittenConvention> "->" <EncodeCheck> "->" <WireGate> "->" <FailOnViolation>
Beforeimport { sql } from "../infrastructure/database"; export function makeFoo() { return sql("select * from foo"); }
Afterconst architectureRule = forbidImports({ from: "src/domain/**", to: "src/infrastructure/**", }); for (const violation of architectureRule.scan(projectGraph)) { throw new Error(`forbidden dependency: ${violation.from} -> ${violation.to}`); }
Design By Contract Over Implicit Contract
- Math type: logic
- Yields: boolean
Details
FlowImplicitAssumption → StatePreconditions → StatePostconditions → EnforceInvariants
ProductionsNoImplicitContract ::= <ImplicitAssumption> "->" <StatePreconditions> "->" <StatePostconditions> "->" <EnforceInvariants>
Beforefunction divideFoo(total: number, count: number) { return total / count; }
Afterfunction divideFoo(total: number, count: number): number { if (!Number.isFinite(total)) throw new Error("pre: total must be finite"); if (!Number.isInteger(count) || count <= 0) throw new Error("pre: count must be positive"); const result = total / count; if (!Number.isFinite(result)) throw new Error("post: result must be finite"); return result; }
Versioned Evolution Over Breaking Change
- Math type: logic
- Yields: boolean
Details
FlowInPlaceChange → IntroduceVersion → RunBothContracts → MigrateConsumers
ProductionsNoBreakingChange ::= <InPlaceChange> "->" <IntroduceVersion> "->" <RunBothContracts> "->" <MigrateConsumers>
Beforeapp.get("/foo", () => ({ label: "Foo", tags: [] }));
Afterapp.get("/v1/foo", () => ({ name: "Foo" })); app.get("/v2/foo", () => ({ label: "Foo", tags: [] }));
Schema-Validated Boundary Over Untyped
- Math type: logic
- Yields: boolean
Details
FlowUntypedBoundary → DefineSchema → ValidateOnEntry → PropagateTyped
ProductionsNoUntypedBoundary ::= <UntypedBoundary> "->" <DefineSchema> "->" <ValidateOnEntry> "->" <PropagateTyped>
Beforeasync function loadFoo(response: Response): Promise<Foo> { return await response.json() as Foo; }
Aftertype Foo = Readonly<{ id: string; count: number }>; function decodeFoo(value: unknown): Foo { if (!value || typeof value !== "object") throw new Error("Foo must be an object"); const record = value as Record<string, unknown>; if (typeof record.id !== "string") throw new Error("Foo.id must be a string"); if (!Number.isInteger(record.count)) throw new Error("Foo.count must be an integer"); return { id: record.id, count: record.count as number }; } async function loadFoo(response: Response): Promise<Foo> { return decodeFoo(await response.json()); }
Atomic Boundary Over Partial Commit
- Math type: logic
- Yields: boolean
Details
FlowCoupledWrites → OpenTransaction → ApplyAll → CommitOrRollback
ProductionsNoPartialCommit ::= <CoupledWrites> "->" <OpenTransaction> "->" <ApplyAll> "->" <CommitOrRollback>
Beforeasync function moveFoo(id: FooId, from: BarId, to: BarId) { await barStore.removeFoo(from, id); await barStore.addFoo(to, id); }
Afterasync function moveFoo(id: FooId, from: BarId, to: BarId) { await database.transaction(async tx => { const removed = await tx.bars.removeFoo(from, id); if (!removed) throw new Error("Foo is not owned by source Bar"); await tx.bars.addFoo(to, id); }); }
Saga Compensation Over Distributed 2PC
- Math type: logic
- Yields: boolean
Details
FlowCrossServiceLock → DefineSteps → DefineCompensations → RunSaga
ProductionsNoDistributed2pc ::= <CrossServiceLock> "->" <DefineSteps> "->" <DefineCompensations> "->" <RunSaga>
Beforeasync function createFooAndBar(foo: Foo, bar: Bar) { const tx = await coordinator.begin(); await fooService.prepare(tx.id, foo); await barService.prepare(tx.id, bar); await coordinator.commit(tx.id); }
Afterasync function createFooAndBar(foo: Foo, bar: Bar) { const fooId = await fooService.create(foo); try { await barService.create({ ...bar, fooId }); } catch (error) { await fooService.cancel(fooId); throw error; } }
Async Events Over Synchronous Cross-Boundary
- Math type: logic
- Yields: boolean
Details
FlowSyncCrossCall → DefineEvent → EmitAsync → ConsumeIndependently
ProductionsNoSyncCrossBoundary ::= <SyncCrossCall> "->" <DefineEvent> "->" <EmitAsync> "->" <ConsumeIndependently>
Beforeasync function createFoo(foo: Foo) { const bar = await barServiceHttp.get(foo.barId); await bazServiceHttp.validate(foo, bar); return fooStore.save(foo); }
Afterasync function createFoo(foo: Foo) { await fooStore.transaction(async tx => { await tx.foos.save(foo); await tx.outbox.append({ type: "FooCreated", fooId: foo.id, barId: foo.barId }); }); } fooEvents.on("FooCreated", event => bazProjection.process(event));
Observable Signals Over Opaque Runtime
- Math type: logic
- Yields: boolean
Details
FlowOpaqueRuntime → InstrumentSignals → EmitStructured → EnableReconstruction
ProductionsNoOpaqueRuntime ::= <OpaqueRuntime> "->" <InstrumentSignals> "->" <EmitStructured> "->" <EnableReconstruction>
Beforeasync function processFoo(foo: Foo) { console.log("starting foo"); await fooStore.save(foo); console.log("done"); }
Afterasync function processFoo(foo: Foo, telemetry: Telemetry) { return telemetry.trace("foo.process", { fooId: foo.id }, async span => { const started = performance.now(); try { await fooStore.save(foo); telemetry.count("foo.processed", 1, { result: "ok" }); span.event("foo.saved", { durationMs: performance.now() - started }); } catch (error) { telemetry.count("foo.processed", 1, { result: "error" }); span.fail(error); throw error; } }); }
Convention Discovery Over Hardcoded Wiring
- Math type: logic
- Yields: boolean
Details
FlowHardcodedList → DefineConvention → DiscoverAtRuntime → SelfRegister
ProductionsNoHardcodedWiring ::= <HardcodedList> "->" <DefineConvention> "->" <DiscoverAtRuntime> "->" <SelfRegister>
Beforeimport { FooHandler } from "./foo-handler"; import { BarHandler } from "./bar-handler"; import { BazHandler } from "./baz-handler"; const handlers = [new FooHandler(), new BarHandler(), new BazHandler()];
Afterinterface HandlerModule { kind: string; create(): Handler; } const modules = await discover<HandlerModule>("./handlers/*.handler.js"); const handlers = new Map(modules.map(module => [module.kind, module.create()]));
Declarative Config Over Imperative
- Math type: logic
- Yields: boolean
Details
FlowImperativeSetup → DescribeDesiredState → ApplyDeclaratively → ConvergeToState
ProductionsNoImperativeConfig ::= <ImperativeSetup> "->" <DescribeDesiredState> "->" <ApplyDeclaratively> "->" <ConvergeToState>
Beforeconst app = new FooApp(); app.enableCache(); app.setRetries(3); if (process.env.DEBUG) app.enableDebug(); app.register(new BarPlugin());
Aftertype FooConfig = Readonly<{ cache: { enabled: boolean }; retries: number; debug: boolean; plugins: readonly ["bar"]; }>; const config: FooConfig = { cache: { enabled: true }, retries: 3, debug: false, plugins: ["bar"], }; const app = FooApp.fromConfig(validateFooConfig(config));
Anti-Corruption Layer Over Cross-Context Leak
- Math type: logic
- Yields: boolean
Details
FlowForeignModelLeak → DefineTranslation → TranslateAtBoundary → ProtectLocalModel
ProductionsNoLeakyContext ::= <ForeignModelLeak> "->" <DefineTranslation> "->" <TranslateAtBoundary> "->" <ProtectLocalModel>
Beforefunction priceBar(foo: FooDatabaseRow) { return foo.status === "A" ? 10 : 0; }
Aftertype FooDatabaseRow = { id: string; status: "A" | "D" }; type BarEligibility = { fooId: string; eligible: boolean }; function toBarEligibility(row: FooDatabaseRow): BarEligibility { return { fooId: row.id, eligible: row.status === "A" }; } function priceBar(input: BarEligibility) { return input.eligible ? 10 : 0; }
Pattern By Fit Over Speculative Pattern
- Math type: logic
- Yields: boolean
Details
FlowSpeculativeAbstraction → IdentifyPresentForces → MatchPatternToForce → RemoveUnforced
ProductionsNoSpeculativePattern ::= <SpeculativeAbstraction> "->" <IdentifyPresentForces> "->" <MatchPatternToForce> "->" <RemoveUnforced>
Beforeinterface FooFactoryStrategy { create(builder: FooAbstractBuilder, provider: FooProvider): Foo; } class DefaultFooFactoryStrategy implements FooFactoryStrategy { create(builder: FooAbstractBuilder, provider: FooProvider) { return builder.withName(provider.getName()).build(); } }
Afterfunction makeFoo(name: string): Foo { return { name }; }
architecture
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_document_truth_alignment["Document Truth Alignment"]
n_architectural_contract_kernel["Architectural Contract Kernel"]
n_responsibility_boundary["Responsibility Boundary"]
n_coupling_control["Coupling Control"]
n_interface_contract["Interface Contract"]
n_substitutability["Substitutability"]
n_canonical_data["Canonical Data"]
n_domain_boundary["Domain Boundary"]
n_self_description_manifest["Self-Description Manifest"]
n_runtime_discovery["Runtime Discovery"]
n_extension_point["Extension Point"]
n_construction_boundary["Construction Boundary"]
n_structural_mediation["Structural Mediation"]
n_behavioral_dispatch["Behavioral Dispatch"]
n_architectural_style_boundary["Architectural Style Boundary"]
n_port_adapter["Port Adapter"]
n_event_messaging["Event Messaging"]
n_saga_compensation["Saga Compensation"]
n_transaction_boundary["Transaction Boundary"]
n_idempotent_side_effect["Idempotent Side Effect"]
n_deterministic_core["Deterministic Core"]
n_verification_fitness["Verification Fitness"]
n_error_boundary["Error Boundary"]
n_resilience_control["Resilience Control"]
n_recovery_deployment["Recovery Deployment"]
n_observability_trace["Observability Trace"]
n_causality_ordering["Causality Ordering"]
n_performance_scaling["Performance Scaling"]
n_cache_correctness["Cache Correctness"]
n_portability_environment["Portability Environment"]
n_security_policy["Security Policy"]
n_governance_evolution["Governance Evolution"]
n_control_plane["Control Plane"]
n_declarative_metaprogramming["Declarative Metaprogramming"]
n_architecture_streaming_dataflow["Streaming Dataflow"]
n_ai_model_governance["AI Model Governance"]
n_rag_knowledge_boundary["RAG Knowledge Boundary"]
n_architecture_selection_meta_algorithm["Architecture Selection Meta-Algorithm"]
n_universal_architectural_concern_template["Universal Architectural Concern Template"]
n_architectural_contract_algebra["Architectural Contract Algebra"]
n_manifest_driven_documentation["Manifest-Driven Documentation"]
n_consumer_config_ssot["Consumer Config SSOT"]
n_finite_state_machine["Finite State Machine"]
n_statecharts["Statecharts"]
n_petri_nets["Petri Nets"]
n_queuing_theory["Queuing Theory"]
n_architectural_contract_algebra --> n_domain_boundary
n_architectural_contract_algebra --> n_transaction_boundary
n_manifest_driven_documentation --> n_document_truth_alignment
n_manifest_driven_documentation --> n_self_description_manifest
n_manifest_driven_documentation --> n_extension_point
n_consumer_config_ssot --> n_architectural_contract_kernel
n_consumer_config_ssot --> n_responsibility_boundary
n_statecharts --> n_finite_state_machineDocument Truth Alignment
- Math type: logic
- Yields: boolean
Details
FlowConcern → Variant → Invariant → TruthKey → Deriver → Template → Compilation → DriftGate
ProductionsDocumentTruth ::= <VariantProse> "+" <InvariantSet> "->" <TruthKeyBinding> "->" <DeriverResolution> "->" <TemplateCompilation> "->" <DriftGate> InvariantBinding ::= <TruthKey> "," <TokenSlot> "," <DerivedValue> "," <DocTypeSchema>
BeforeA doc states 'the system has 12 modules' — a hand-typed count that drifts the moment a module is added.
Afterinvariant{moduleCount} -> truth-key{modules.length} -> deriver{scan workspaces} -> template{'... has {moduleCount} modules'} -> drift-gate{rendered == derived, else fail}
Architectural Contract Kernel
- Math type: computation
- Yields: procedure
Details
FlowConcern → Boundary → Contract → Implementation → Verification → Observation → Evolution
ProductionsArchitectureKernel ::= <ConcernSet> "->" <BoundarySet> "->" <ContractSet> "->" <ImplementationGraph> "->" <VerificationSet> "->" <ObservationSet> "->" <EvolutionPolicy> ConcernContract ::= <Intent> "," <Responsibility> "," <InputContract> "," <OutputContract> "," <InvariantSet> "," <FailurePolicy> "," <VersionPolicy>
Beforeclass FooService { save(f) { db.write(f); log(f); notify(f); } }
Afterinterface FooPort { save(f: Foo): Promise<void>; } class FooService implements FooPort { constructor(private repo: FooRepo, private events: EventSink) {} async save(f: Foo) { await this.repo.save(f); this.events.emit({ type: "FooSaved", f }); } }
Responsibility Boundary
- Math type: set-theory
- Yields: set | boolean
Details
FlowBehavior → Responsibility → Boundary → Interface → Encapsulation → Replaceability
ProductionsResponsibilityBoundary ::= <BehaviorSet> "->" <ResponsibilityPartition> "->" <ModuleBoundary> "->" <PublicInterface> "->" <PrivateImplementation> ModuleBoundary ::= "single_responsibility" "," "high_cohesion" "," "low_coupling" "," "information_hiding" "," "replaceable_implementation"
Beforeclass FooUtil { parse() {} save() {} render() {} notify() {} }
Afterclass FooParser { parse() {} } class FooRepository { save() {} } class FooView { render() {} }
Coupling Control
- Math type: graph
- Yields: edge-list
Details
FlowConcreteDependency → AbstractionBoundary → DependencyRule → ImportValidation
ProductionsCouplingControl ::= <DependencyGraph> "->" <AbstractionNodeSet> "->" <AllowedEdgeSet> "->" <ForbiddenEdgeSet> "->" <DependencyValidation> DependencyRule ::= "depend_on_interface" | "depend_on_port" | "same_boundary_only" | "adapter_required"
Beforeimport { SqlFooStore } from "./infra/sql"; class FooService { store = new SqlFooStore(); }
Afterinterface FooStore { save(f: Foo): Promise<void>; } class FooService { constructor(private store: FooStore) {} }
Interface Contract
- Math type: logic
- Yields: boolean
Details
FlowIntent → Interface → Preconditions → Postconditions → Compatibility → Implementation
ProductionsInterfaceContract ::= <InterfaceName> "," <OperationSet> "," <PreconditionSet> "," <PostconditionSet> "," <InvariantSet> "," <ErrorContract> "," <VersionContract> CompatibilityRule ::= "backward_compatible" | "forward_compatible" | "breaking_change_requires_new_version"
Beforefunction doFoo(a, b, n) {}
Afterinterface FooOp { (a: Foo, b: Bar, n: number): Result<FooOut, FooError>; }
Substitutability
- Math type: logic
- Yields: boolean
Details
FlowInterface → Implementation → ContractCheck → Substitute|Reject
ProductionsSubstitutability ::= <BaseContract> "->" <CandidateImplementation> "->" <BehavioralCompatibilityCheck> "->" <SubstitutionVerdict> BehavioralCompatibilityCheck ::= "preconditions_not_stronger" "," "postconditions_not_weaker" "," "invariants_preserved" "," "errors_compatible"
Beforeclass ReadOnlyFooStore extends FooStore { save() { throw new Error("unsupported"); } }
Afterinterface FooReader { find(id: FooId): Foo | undefined; } interface FooWriter extends FooReader { save(f: Foo): void; } class ReadOnlyFooStore implements FooReader { find(id: FooId) { return fooCache.get(id); } }
Canonical Data
- Math type: set-theory
- Yields: set | boolean
Details
FlowRawData → Validate → Normalize → CanonicalModel → BoundaryTranslation
ProductionsCanonicalDataFlow ::= <ExternalData> "->" <SchemaValidation> "->" <Canonicalization> "->" <CanonicalModel> "->" <BoundaryAdapter> CanonicalModel ::= <Schema> "," <TypeRules> "," <SemanticRules> "," <NormalizationRules> "," <SourceOfTruth>
Beforefunction useFoo(raw) { const name = raw.name ?? raw.Name ?? raw.title; }
Afterfunction toCanonicalFoo(raw: unknown): Foo { return { id: fooId(raw), name: pickName(raw) }; }
Domain Boundary
- Math type: topology
- Yields: boolean
Details
FlowDomain → BoundedContext → Language → ContextMap → TranslationBoundary
ProductionsDomainBoundary ::= <DomainModel> "->" <BoundedContextSet> "->" <UbiquitousLanguageSet> "->" <ContextMap> "->" <IntegrationPolicy> IntegrationPolicy ::= "shared_kernel" | "customer_supplier" | "anti_corruption_layer" | "published_language" | "separate_ways"
BeforefooContext.use(sharedBaz); barContext.use(sharedBaz);
Afterfunction toBarBaz(f: FooBaz): BarBaz { return { id: f.id }; }
Self-Description Manifest
- Math type: set-theory
- Yields: set | boolean
Details
FlowComponent → Manifest → CapabilityDeclaration → Discovery → Validation
ProductionsSelfDescription ::= <Component> "->" <Manifest> "->" <CapabilitySet> "->" <ContractReferenceSet> "->" <RuntimeRegistration> Manifest ::= "identity" "," "version" "," "capabilities" "," "dependencies" "," "contracts" "," "configuration" "," "health"
Beforeexport class FooPlugin { transform(x) { return x; } }
Afterexport const manifest = { identity: "foo-plugin", version: "1.2.0", capabilities: ["transform"], contracts: ["FooPort@1"], dependencies: [] };
Runtime Discovery
- Math type: set-theory
- Yields: set | boolean
Details
FlowDiscoverySource → CandidateSet → ContractValidation → Binding → RuntimeUse
ProductionsRuntimeDiscovery ::= <DiscoveryMechanism> "->" <CandidateComponentSet> "->" <CapabilityMatch> "->" <ContractValidation> "->" <BindingDecision> DiscoveryMechanism ::= "manifest" | "registry" | "service_discovery" | "convention" | "configuration"
Beforeconst plugin = new KnownFooPlugin();
Afterconst candidates = registry.discover({ capability: "transform" }); const bound = candidates.filter((c) => satisfies(c.contract, FooPortV1));
Extension Point
- Math type: logic
- Yields: boolean
Details
FlowExtensionContract → PluginRegistration → DependencyInjection → Isolation → Dispatch
ProductionsExtensionArchitecture ::= <ExtensionPoint> "->" <PluginContract> "->" <PluginRegistry> "->" <BindingPolicy> "->" <FailureIsolation> BindingPolicy ::= "dependency_injection" | "service_registry" | "service_locator" | "manual_registration" | "auto_discovery"
Beforeswitch (kind) { case "foo": doFoo(); break; case "bar": doBar(); break; }
Afterregistry.register("foo", fooHandler); registry.register("bar", barHandler); registry.get(kind)?.handle(input);
Construction Boundary
- Math type: computation
- Yields: procedure
Details
FlowCreationRequest → ConstructionContract → Factory|Builder|Prototype → Instance
ProductionsConstructionBoundary ::= <CreationIntent> "->" <ConstructionStrategy> "->" <InstanceContract> "->" <ConstructedObject> ConstructionStrategy ::= "factory" | "factory_method" | "abstract_factory" | "builder" | "prototype"
Beforeconst c = new FooConnection(host, port, user, pw);
Afterconst c = fooConnectionFactory.create(config);
Structural Mediation
- Math type: algebra
- Yields: ordered-structure
Details
FlowClientNeed → StructuralMismatch → MediatingPattern → CompatibleInterface
ProductionsStructuralMediation ::= <ClientContract> "->" <MismatchType> "->" <StructuralPattern> "->" <CompatibleBoundary> StructuralPattern ::= "adapter" | "facade" | "proxy" | "bridge" | "decorator"
BeforelegacyFooApi.call(new FooXmlPayload(foo));
Afterclass FooAdapter implements FooPort { constructor(private legacy: FooXmlApi) {} save(f: Foo) { return this.legacy.call(toFooXml(f)); } }
Behavioral Dispatch
- Math type: logic
- Yields: boolean
Details
FlowStableFlow → VariationPoint → DispatchPattern → RuntimeBehavior
ProductionsBehavioralDispatch ::= <StableOperation> "->" <VariationPoint> "->" <BehaviorPattern> "->" <SelectedBehavior> BehaviorPattern ::= "strategy" | "template_method" | "observer" | "mediator" | "polymorphic_dispatch"
Beforefunction handleFoo(f) { if (f.kind === "a") { return runA(f); } else if (f.kind === "b") { return runB(f); } }
Afterconst strategies: Record<FooKind, FooStrategy> = { a: fooStrategyA, b: fooStrategyB }; function handleFoo(f: Foo) { return strategies[f.kind].run(f); }
Architectural Style Boundary
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowSystemForces → StyleSelection → BoundaryRules → FitnessValidation
ProductionsArchitectureStyle ::= <SystemForces> "->" <Style> "->" <BoundaryRuleSet> "->" <FitnessFunctionSet> Style ::= "hexagonal" | "ports_and_adapters" | "clean_architecture" | "layered" | "component_based" | "package_by_feature" | "microservices" | "monolith"
Beforeimport { SqlDriver } from "../infra/sql";
Afterexport const boundaries = { ui: ["app"], app: ["domain"], domain: [] };
Port Adapter
- Math type: logic
- Yields: boolean
Details
FlowUseCase → InboundPort → DomainLogic → OutboundPort → Adapter
ProductionsPortAdapterFlow ::= <ExternalDriver> "->" <InboundAdapter> "->" <InboundPort> "->" <UseCase> "->" <OutboundPort> "->" <OutboundAdapter> DependencyDirection ::= "adapter_depends_on_port" "," "domain_depends_on_abstraction" "," "infrastructure_outside_core"
Beforeclass FooUseCase { run(f) { new FooHttpClient().send(f); } }
Afterinterface FooOutPort { send(f: Foo): Promise<void>; } class FooUseCase { constructor(private out: FooOutPort) {} }
Event Messaging
- Math type: analysis
- Yields: operation
Details
FlowStateChange → Event → Publish → Consume → IdempotentEffect → Consistency
ProductionsEventMessaging ::= <StateChange> "->" <EventClassification> "->" <MessageEnvelope> "->" <BrokerOrBus> "->" <Consumer> "->" <EffectPolicy> EventClassification ::= "domain_event" | "integration_event" | "stream_event" EffectPolicy ::= "idempotent" "," "retryable" "," "observable" "," "ordered_if_required"
Beforeasync function doFoo(f) { await stepBar(f); await stepBaz(f); await stepQux(f); }
Afterasync function doFoo(f) { await fooStore.save(f); await bus.publish({ type: "FooHappened", f }); }
Saga Compensation
- Math type: computation
- Yields: procedure
Details
FlowWorkflow → StepGraph → LocalTransaction → Event → Compensation|Continue
ProductionsSaga ::= <SagaState> "->" <Step> "->" <LocalTransaction> "->" <ProgressEvent> "->" (<NextStep> | <CompensatingTransaction>) SagaStep ::= <Command> "," <SuccessEvent> "," <FailureEvent> "," <CompensationCommand>
Beforeawait reserveFoo(x); await reserveBar(x);
Afterconst saga = [ { do: reserveFoo, undo: releaseFoo }, { do: reserveBar, undo: releaseBar } ]; runSaga(saga);
Transaction Boundary
- Math type: logic
- Yields: boolean
Details
FlowCommand → UnitOfWork → Invariants → Commit|Rollback
ProductionsTransactionBoundary ::= <Command> "->" <TransactionScope> "->" <InvariantCheck> "->" <ConcurrencyControl> "->" <CommitDecision> ConcurrencyControl ::= "optimistic_locking" | "pessimistic_locking" | "serial_execution" | "state_isolation"
BeforedecFoo(a, n); incBar(b, n);
Afterawait unitOfWork(async (tx) => { await decFoo(tx, a, n); await incBar(tx, b, n); });
Idempotent Side Effect
- Math type: logic
- Yields: boolean
Details
FlowRequest → IdempotencyKey → PriorResultCheck → ExecuteOnce → PersistOutcome
ProductionsIdempotency ::= <Request> "->" <IdempotencyKey> "->" <DeduplicationStore> "->" (<PriorResult> | <SideEffectExecution>) "->" <StableResponse> StableResponse ::= "same_key_same_effect_same_semantic_result"
Beforeasync function applyFoo(req) { await external.apply(req.value); }
Afterasync function applyFoo(req) { if (await seen(req.key)) return priorResult(req.key); const r = await external.apply(req.value); await persist(req.key, r); return r; }
Deterministic Core
- Math type: logic
- Yields: boolean
Details
FlowExternalInput → Normalize → PureCore → DeterministicOutput → ControlledEffect
ProductionsDeterministicCore ::= <Input> "->" <Canonicalization> "->" <PureFunctionSet> "->" <Output> "->" <EffectBoundary> PurityConstraint ::= "no_hidden_state" "," "no_hidden_time" "," "no_hidden_randomness" "," "referential_transparency"
Beforefunction scoreFoo(f) { return f.base * (Date.now() % 2 ? 1.1 : 1); }
Afterfunction scoreFoo(f: Foo, now: Date) { return f.base * rateAt(now); }
Verification Fitness
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowRule → Test → Evidence → Pass|Fail → Gate
ProductionsVerificationFitness ::= <SpecificationSet> "->" <VerificationMethodSet> "->" <EvidenceSet> "->" <FitnessVerdict> VerificationMethod ::= "type_check" | "static_analysis" | "schema_validation" | "contract_test" | "property_based_test" | "specification_test" | "formal_verification" | "runtime_validation"
BeforereviewChecklist.push("domain must not import infra");
Aftertest("domain imports no infra", () => expect(importsOf("domain")).not.toContain("infra"));
Error Boundary
- Math type: logic
- Yields: boolean
Details
FlowOperation → Guard → ErrorClass → BoundaryPolicy → RecoveryOrAbort
ProductionsErrorBoundary ::= <Operation> "->" <PreconditionCheck> "->" <ErrorClassification> "->" <FailurePolicy> "->" <ResultContract> FailurePolicy ::= "fail_fast" | "fail_safe" | "fail_secure" | "graceful_degradation" | "fallback"
Beforetry { doFoo(); } catch (e) { return null; }
Aftertry { return ok(doFoo()); } catch (e) { if (isProgrammerError(e)) throw e; Logger.error("doFoo failed", e); return err("foo.retry"); }
Resilience Control
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowCall → Timeout → RetryPolicy → CircuitBreaker → Bulkhead → Fallback
ProductionsResilienceControl ::= <ExternalCall> "->" <TimeoutPolicy> "->" <RetryPolicy> "->" <CircuitBreaker> "->" <Bulkhead> "->" <FallbackPolicy> "->" <BackpressurePolicy> RetryPolicy ::= "bounded_attempts" "," "jittered_backoff" "," "idempotency_required"
Beforeconst r = await callFoo(url);
Afterconst r = await breaker.run(() => withTimeout(callFoo(url), 2000), { retries: 3, backoff: jitter });
Recovery Deployment
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowDeploy → HealthCheck → TrafficShift → DetectFailure → Rollback|Promote
ProductionsRecoveryDeployment ::= <ReleaseCandidate> "->" <DeploymentStrategy> "->" <HealthSignalSet> "->" <PromotionDecision> DeploymentStrategy ::= "blue_green" | "canary" | "rolling" | "rollback" | "auto_remediation"
BeforedeployAll(fooV2);
Aftercanary(fooV2, { percent: 5, healthCheck });
Observability Trace
- Math type: graph
- Yields: edge-list
Details
FlowRequest → CorrelationID → Logs/Metrics/Traces → Audit → CausalGraph
ProductionsObservabilityTrace ::= <Operation> "->" <CorrelationId> "->" <CausationId> "->" <TelemetryEventSet> "->" <TraceGraph> "->" <AuditRecord> TelemetryEvent ::= "log" | "metric" | "trace_span" | "alert" | "audit_log"
Beforeconsole.log("processing foo");
Afterlogger.info("foo.process", { correlationId: ctx.cid, causationId: ctx.parentId, fooId: foo.id });
Causality Ordering
- Math type: graph
- Yields: edge-list
Details
FlowEvent → CausalMetadata → DependencyGraph → OrderingValidation
ProductionsCausalityOrdering ::= <EventSet> "->" <CausalMetadataSet> "->" <DependencyGraph> "->" <OrderingPolicy> CausalMetadata ::= "correlation_id" | "causation_id" | "sequence_number" | "lamport_clock" | "vector_clock" DependencyGraph ::= "DAG"
Beforeevents.sort((a, b) => a.timestamp - b.timestamp);
Afterevents.sort(byVectorClock);
Performance Scaling
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowWorkload → Profile → Bottleneck → ScaleStrategy → Benchmark → Feedback
ProductionsPerformanceScaling ::= <WorkloadModel> "->" <ProfilingResult> "->" <BottleneckAnalysis> "->" <ScalingStrategy> "->" <OptimizationPolicy> "->" <BenchmarkResult> ScalingStrategy ::= "vertical_scaling" | "horizontal_scaling" | "load_balancing" | "sharding" | "partitioning" | "caching" | "stateless_replication"
BeforeoptimizeEverywhere(app);
Afterconst hot = profile(load).topBottleneck(); scale(hot, hot.isCpuBound ? "horizontal" : "cache"); benchmark();
Cache Correctness
- Math type: logic
- Yields: boolean
Details
FlowData → CacheKey → FreshnessPolicy → Invalidation → ReadThrough|Bypass
ProductionsCacheContract ::= <CacheableData> "->" <CacheKey> "->" <FreshnessPolicy> "->" <InvalidationPolicy> "->" <ConsistencyPolicy> ConsistencyPolicy ::= "strong" | "eventual" | "read_your_writes" | "bounded_staleness"
Beforecache.set(key, value);
Aftercache.set(key, value, { ttlMs: 60_000, invalidateOn: ["FooChanged"], consistency: "read_your_writes" });
Portability Environment
- Math type: topology
- Yields: boolean
Details
FlowCode → ExternalConfig → StandardProtocol → Container|Package → EnvironmentParity
ProductionsPortabilityContract ::= <ApplicationCore> "->" <ConfigurationExternalization> "->" <ProtocolBoundary> "->" <InfrastructureAdapter> "->" <EnvironmentValidation> EnvironmentValidation ::= "dev" "," "test" "," "staging" "," "production" "," "parity_check"
Beforeconst db = connect("driver://prod-host:5432");
Afterconst db = connect(config.databaseUrl);
Security Policy
- Math type: logic
- Yields: boolean
Details
FlowThreatModel → Identity → Authorization → Validation → Protection → Audit
ProductionsSecurityPolicy ::= <ThreatModel> "->" <IdentityProof> "->" <AccessDecision> "->" <InputOutputGuard> "->" <DataProtection> "->" <PolicyEnforcement> "->" <SecurityAudit> AccessDecision ::= "RBAC" | "ABAC" | "least_privilege" | "zero_trust" DataProtection ::= "encryption_at_rest" "," "encryption_in_transit" "," "secrets_management"
Beforeif (user) allowFoo();
Afterif (!policy.can(user, "foo:write", resource)) throw forbidden(); const foo = validate(FooSchema, input);
Governance Evolution
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowAssessment → Decision → Impact → FitnessFunction → Evolution
ProductionsGovernanceEvolution ::= <ArchitectureAssessment> "->" <ReviewProcess> "->" <DecisionRecord> "->" <ImpactAnalysis> "->" <FitnessFunctionSet> "->" <EvolutionPlan> DecisionRecord ::= "ADR" "," "context" "," "decision" "," "consequences" "," "status"
BeforeArchitectural decisions live in someone's memory; nothing records why Foo was chosen over Bar.
Afterassessment{Foo vs Bar} -> ADR{context, decision, consequences, status} -> impact-analysis -> fitness-function{enforces it} -> evolution{revisit via a new ADR}
Control Plane
- Math type: logic
- Yields: boolean
Details
FlowPolicy → ControlPlane → DistributedExecution → Feedback
ProductionsControlPlane ::= <PolicySet> "->" <CentralizedCoordination> "->" <DataPlaneSet> "->" <TelemetryFeedback> "->" <PolicyAdjustment> CentralizedCoordination ::= "configuration" | "authentication" | "authorization" | "logging" | "orchestration"
BeforeEvery service reads its own ad-hoc config and does its own auth — policy is scattered and drifts.
Afterpolicy{central} -> control-plane{config, auth, orchestration} -> data-planes{Foo, Bar execute work} -> telemetry-feedback -> policy-adjustment
Declarative Metaprogramming
- Math type: computation
- Yields: procedure
Details
FlowModel → Schema → Compile|Interpret → RuntimeBehavior → SafetyCheck
ProductionsDeclarativeMetaprogramming ::= <ProgramModel> "->" <ModelSchema> "->" <TransformationEngine> "->" <GeneratedOrInterpretedBehavior> "->" <SafetyBoundary> TransformationEngine ::= "reflection" | "introspection" | "compile_time_evaluation" | "runtime_code_generation" | "DSL_interpreter"
Beforeeval(fooExpression);
Afterconst ast = parse(fooDsl, GRAMMAR); validate(ast, SCHEMA); run(compile(ast), sandbox);
Streaming Dataflow
- Math type: analysis
- Yields: operation
Details
FlowSource → Stage → Stage → Sink → Checkpoint
ProductionsStreamingDataflow ::= <Source> "->" <PipelineStageSet> "->" <BackpressurePolicy> "->" <CheckpointPolicy> "->" <Sink> PipelineStage ::= <InputStream> "->" <Transform> "->" <OutputStream> ProcessingMode ::= "single_pass" | "lazy_evaluation" | "sequential_access" | "forward_only" | "stateless" | "stateful_with_checkpoint"
Beforeconst all = await loadAllFoo(); return all.map(toBar).filter(isBaz);
AfterfooSource.pipe(mapStage(toBar)).pipe(filterStage(isBaz)).pipe(sink, { backpressure: true });
AI Model Governance
- Math type: logic
- Yields: boolean
Details
FlowModelArtifact → Registry → Evaluation → SafetyCheck → InferenceTrace → Monitoring
ProductionsAIModelGovernance ::= <ModelArtifact> "->" <ModelRegistry> "->" <EvaluationSuite> "->" <SafetyPolicy> "->" <InferenceContract> "->" <MonitoringPolicy> InferenceContract ::= "input_schema" "," "retrieval_context" "," "model_version" "," "output_schema" "," "explanation_or_trace"
Beforeconst out = model.run(prompt);
Afterconst out = registry.model("foo@2.1").run({ input, promptVersion: "p7" }); evalSuite.check(out); trace(input, out);
RAG Knowledge Boundary
- Math type: probability
- Yields: number[0,1]
Details
FlowQuery → Retrieve → Rank → Ground → Generate → Cite|Reject
ProductionsRAGBoundary ::= <UserQuery> "->" <Retriever> "->" <CandidateEvidenceSet> "->" <RelevanceValidation> "->" <GroundedGeneration> "->" <EvidenceDisclosure> EvidenceDisclosure ::= "supported" | "partially_supported" | "unsupported_reject_or_disclose"
Beforeconst answer = model.generate(query);
Afterconst ev = retrieve(query); const g = generate(query, ev); return g.supported ? cite(g, ev) : disclose("unsupported");
Architecture Selection Meta-Algorithm
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowConcern → ForceType → ContractFamily → PatternSet → ValidationGate
ProductionsArchitectureSelection ::= <Concern> "->" <ForceFamily> "->" <ContractFamily> "->" <ImplementationPatternSet> "->" <ValidationGateSet> ForceFamily ::= "modularity" | "compatibility" | "semantics" | "extension" | "state" | "correctness" | "resilience" | "security" | "scale" | "governance"
BeforeA pattern chosen by name ('let's use Foo') before the force it must resolve is even known.
Afterconcern -> force{change-isolation} -> contract-family{deployment-boundary} -> pattern{selected by force, not by name} -> validation-gate
Universal Architectural Concern Template
- Math type: logic
- Yields: boolean
Details
FlowIntent → Boundary → Contract → Invariants → Variation → Validation → Evolution
ProductionsUniversalConcern ::= <Intent> "->" <Boundary> "->" <Contract> "->" <InvariantSet> "->" <AllowedVariationSet> "->" <ForbiddenLeakageSet> "->" <ValidationStrategy> "->" <ObservabilityModel> "->" <EvolutionPolicy> Contract ::= <Input> "," <Output> "," <Preconditions> "," <Postconditions> "," <FailureModes> "," <CompatibilityRules>
BeforeA principle stated as prose ('be modular') with no operational contract.
Afterintent -> boundary -> contract{in, out, pre, post} -> invariants -> allowed-variation -> forbidden-leakage -> validation -> observability -> evolution
Architectural Contract Algebra
- Meta record
Details
FlowForce → Contract → Pattern → Implementation → Verification → Operation → Evolution
ProductionsArchitecturalContractAlgebra ::= <Force> "->" <Boundary> "->" <Contract> "->" <Pattern> "->" <Implementation> "->" <Verification> "->" <Observation> "->" <Evolution> Force ::= "change" | "dependency" | "semantic_consistency" | "runtime_extension" | "state_mutation" | "failure" | "scale" | "security" | "governance" | "intelligence" Boundary ::= <ModuleBoundary> | <DomainBoundary> | <InterfaceBoundary> | <TransactionBoundary> | <SecurityBoundary> | <DeploymentBoundary> | <ObservationBoundary> Pattern ::= <CreationalPattern> | <StructuralPattern> | <BehavioralPattern> | <ArchitecturalStyle> | <MessagingPattern> | <ResiliencePattern> | <GovernancePattern> Verification ::= <StaticCheck> | <ContractTest> | <SchemaValidation> | <PropertyTest> | <FitnessFunction> | <RuntimeHealthCheck> | <AuditReview> Evolution ::= <VersioningPolicy> | <CompatibilityPolicy> | <MigrationPolicy> | <RollbackPolicy> | <ADRPolicy> | <ContinuousCompliancePolicy>
Manifest-Driven Documentation
- Math type: computation
- Yields: procedure
Details
FlowManifest → AuthoredField → DerivedSurface → SectionDeriver → MarkerLayer → Compilation → GovernanceRouter → DriftGate
ProductionsModuleDocument ::= <ManifestAuthoredFields> "+" <DerivedSurface> "->" <SectionDeriverResolution> "->" <MarkerLayerTemplate> "->" <Compilation> "->" <DriftGate> GovernanceRouter ::= <ManifestPresent> "->" <RenderFieldToFragment> <ScanFragment> | <ManifestAbsent> "->" <ScanDocument> TypedDocument ::= <FormConcernName> "->" <LocationRouter> "->" <BodySections> "->" <Compilation> "->" <DriftGate>
BeforeA README hand-authored as prose that drifts from the exports it claims to document.
Aftermanifest.docs{authored} + derivedSurface{from .d.ts} -> section-derivers -> marker-template -> compile -> drift-gate{recompiles byte-identical, else fail}
Consumer Config SSOT
- Math type: logic
- Yields: boolean
Details
FlowConsumerValue → ConfigSection → FrameworkLoad → InjectionSurface → PackageConsumption → CouplingGate
ProductionsConsumerConfigSSOT ::= <ConsumerValueSet> "->" <ConfigSectionSet> "->" <FrameworkLoad> "->" <InjectionSurface> "->" <PackageConsumption> "+" <CouplingGate> InjectionSurface ::= <SettingsChannel> "|" <OptionsChannel> "|" <ArgvEnvChannel> "|" <FactoryOptionChannel>
Beforeconst ROOT = "my-app"; const cfg = read("../config/app.json");
Afterexport function createFoo(opts: { root: string; store: FooStore }) { return new Foo(opts); }
Finite State Machine
- Math type: graph
- Yields: edge-list
Details
FlowEnumerateStates → DefineEvents → DeclareTransitions → RejectUndeclared
ProductionsFiniteStateMachine ::= <EnumerateStates> "->" <DefineEvents> "->" <DeclareTransitions> "->" <RejectUndeclared>
Beforelet isOpen = false, isLoading = false, isError = false; function onClick() { isLoading = true; if (isOpen) isOpen = false; }
Aftertype FooState = "closed" | "loading" | "open" | "error"; const transitions: Record<FooState, Partial<Record<FooEvent, FooState>>> = { closed: { open: "loading" }, loading: { ready: "open", fail: "error" }, open: { close: "closed" }, error: { retry: "loading" }, }; function next(state: FooState, event: FooEvent): FooState { return transitions[state][event] ?? state; }
Statecharts
- Math type: graph
- Yields: edge-list
Details
FlowIdentifyIndependentConcerns → NestRelatedStates → SeparateParallelRegions → GuardTransitions
ProductionsStatecharts ::= <IdentifyIndependentConcerns> "->" <NestRelatedStates> "->" <SeparateParallelRegions> "->" <GuardTransitions>
Beforetype S = "idleMuted" | "idleLoud" | "playingMuted" | "playingLoud";
Afterconst fooChart = { initial: "idle", states: { idle: {}, playing: {} }, parallel: { volume: { states: { muted: {}, loud: {} } } }, };
Petri Nets
- Math type: graph
- Yields: edge-list
Details
FlowDefinePlaces → PlaceTokens → DefineTransitions → AnalyzeReachability → AssertNoDeadlock
ProductionsPetriNet ::= <DefinePlaces> "->" <PlaceTokens> "->" <DefineTransitions> "->" <AnalyzeReachability> "->" <AssertNoDeadlock>
Beforeacquire(a); acquire(b); work(); release(b); release(a);
Afterconst net = petriNet({ places: { idle: 1, aHeld: 0, bHeld: 0 }, transitions: [ { name: "takeA", consume: { idle: 1 }, produce: { aHeld: 1 } }, { name: "takeB", consume: { aHeld: 1 }, produce: { bHeld: 1 } }, ], }); assertNoDeadlock(reachableMarkings(net));
Queuing Theory
- Math type: probability
- Yields: number[0,1]
Details
FlowMeasureArrivalRate → MeasureServiceRate → ComputeUtilization → PredictWaitTime → SizeServers
ProductionsQueuingModel ::= <MeasureArrivalRate> "->" <MeasureServiceRate> "->" <ComputeUtilization> "->" <PredictWaitTime> "->" <SizeServers>
Beforeconst workers = 4;
Afterconst rho = arrivalRate / (workers * serviceRate); if (rho >= 1) throw new Error("unstable queue: utilization >= 1"); const avgWaitMs = mm1WaitTime({ arrivalRate, serviceRate, servers: workers });
automation
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_static_to_dynamic_readiness["Static-to-Dynamic Readiness"]
n_runtime_neutral_automation_boundary["Runtime-Neutral Automation Boundary"]
n_automation_operation_mode["Automation Operation Mode"]
n_capability_degradation["Capability Degradation"]
n_automation_opportunity_detection["Automation Opportunity Detection"]
n_intentional_static_separation["Intentional Static Separation"]
n_breaking_point_calculation["Breaking Point Calculation"]
n_automation_priority_ordering["Automation Priority Ordering"]
n_convention_strength_analysis["Convention Strength Analysis"]
n_extension_interface_discovery["Extension Interface Discovery"]
n_scalability_projection["Scalability Projection"]
n_performance_aware_discovery_design["Performance-Aware Discovery Design"]
n_dynamic_extension_architecture["Dynamic Extension Architecture"]
n_centralized_reference_resolver["Centralized Reference Resolver"]
n_cache_invalidation_strategy["Cache Invalidation Strategy"]
n_manual_fallback_preservation["Manual Fallback Preservation"]
n_dynamic_failure_isolation["Dynamic Failure Isolation"]
n_entry_point_migration["Entry Point Migration"]
n_measured_vs_estimated_validation["Measured-vs-Estimated Validation"]
n_architecture_validation_before_persistence["Architecture Validation Before Persistence"]
n_knowledge_capture["Knowledge Capture"]
n_automation_session_report["Automation Session Report"]
n_automation_completion_status["Automation Completion Status"]
n_automation_kernel["Automation Kernel"]
n_automation_concern["<Automation Concern>"]
n_automation_kernel --> n_capability_degradation
n_automation_kernel --> n_scalability_projection
n_automation_kernel --> n_dynamic_extension_architecture
n_automation_kernel --> n_knowledge_capture
n_automation_kernel --> n_entry_point_migration
n_automation_kernel --> n_automation_completion_status
n_automation_kernel --> n_automation_opportunity_detection
n_automation_kernel --> n_convention_strength_analysis
n_automation_kernel --> n_intentional_static_separation
n_automation_kernel --> n_automation_priority_ordering
n_automation_kernel --> n_automation_operation_mode
n_automation_kernel --> n_architecture_validation_before_persistence
n_automation_kernel --> n_automation_session_reportStatic-to-Dynamic Readiness
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowStaticPattern → Classification → PressureMetric → ConventionStrength → Automate|RetainStatic|DesignFallback
ProductionsAutomationReadiness ::= <StaticPattern> "->" <OpportunityClassification> "->" <MaintainabilityAssessment> "->" <ConventionAssessment> "->" <AutomationDecision> AutomationDecision ::= "automate" | "retain_static" | "formalize_convention_first" | "manual_fallback_required"
BeforeA static list rewritten as dynamic discovery on sight, adding fragility for no gain.
Afterstatic pattern -> classify intentional vs problematic -> maintainability pressure + convention strength -> {automate | retain static | formalize convention first}
Runtime-Neutral Automation Boundary
Details
FlowSemanticVerb → AdapterCapability → RuntimeAction → Evidence
ProductionsRuntimeNeutralBoundary ::= <SemanticOperation> "->" <AdapterMapping> "->" <RuntimeExecution> "->" <EvidenceResult> SemanticOperation ::= "DISCOVER_RESOURCES" | "READ_RESOURCE" | "SEARCH_CONTENT" | "ANALYZE_CONTENT" | "VALIDATE_ARTIFACT" | "PERSIST_ARTIFACT" | "REPORT_RESULT" AdapterMapping ::= <CapabilityStatus> "," <RuntimeConstraint> "," <FallbackPolicy>
BeforeAutomation logic hardcodes a runtime's glob and path, so it runs on one platform only.
Aftersemantic op{DISCOVER/READ/SEARCH/VALIDATE/PERSIST} -> adapter maps to the runtime -> portable core, no platform mechanics inside
Automation Operation Mode
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowDetectMode → BindPermissions → EnforceMutationGate → ExecuteAllowedScope → EmitArtifact
ProductionsAutomationMode ::= "analysis_only" | "analysis_and_design" | "implementation" | "validation_only" ModeExecution ::= <AutomationMode> "->" <PermissionSet> "->" <AllowedArtifact> PermissionSet ::= "read_only" | "design_only" | "write_authorized" | "validate_only"
BeforeAnalysis silently mutates source; a design run also implements.
Afterdetect mode{analysis | design | implementation | validation} -> bind permissions -> mutation only in implementation mode -> mode-legal artifact
Capability Degradation
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowCapabilityRequirement → Probe → Available|Emulated|Unavailable → ConfidencePolicy
ProductionsCapabilityDegradation ::= <RequiredCapabilitySet> "->" <CapabilityProbeSet> "->" <CapabilityVerdict> "->" <ExecutionPolicy> CapabilityVerdict ::= "full" | "degraded" | "blocked" ExecutionPolicy ::= "execute" | "emulate" | "skip_with_disclosure" | "block"
BeforeAutomation assumes it can execute and persist, then fails silently when it can't.
Afterrequired capabilities -> probe -> {full | degraded | blocked} -> execute | emulate | skip-with-disclosure | block
Automation Opportunity Detection
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowTargetScope → DetectionProcedures → PatternGroups → ClassificationRegistry
ProductionsOpportunityDetection ::= <TargetScope> "->" <DetectionProcedureSet> "->" <PatternClassificationSet> DetectionProcedureSet ::= "manual_registration" "," "hardcoded_reference" "," "static_list" "," "duplicated_discovery" OpportunityClassification ::= <Location> "," <PatternType> "," <Count> "," <MaintenanceEvidence>
BeforeAutomation targets guessed, not found from real coordination points.
Afterscope -> detect{manual registration, hardcoded reference, static list, duplicated discovery} -> classify{location, type, count, maintenance signal}
Intentional Static Separation
Details
FlowStaticFinding → ScaleCheck → ChangeFrequencyCheck → RiskCheck → IntentionalStatic|AutomationCandidate
ProductionsStaticSeparation ::= <StaticFinding> "->" <ScaleMetric> "->" <MutationEvidence> "->" <RiskAssessment> "->" <StaticVerdict> StaticVerdict ::= "intentionally_static_candidate" | "automation_candidate" | "needs_more_evidence"
BeforeA small, stable, bounded static list flagged as debt and automated away.
Afterstatic finding -> scale + change-frequency + risk -> {intentionally-static candidate | automation candidate | needs more evidence}
Breaking Point Calculation
Details
FlowCurrentScale + GrowthRate + Limits → BreakingPoint → Severity
ProductionsBreakingPoint ::= <CurrentCount> "," <GrowthRate> "," <LimitSet> "->" <ThresholdProjection> "->" <PriorityRank> LimitSet ::= "cognitive_limit" "," "maintenance_limit" "," "duplication_limit" PriorityRank ::= "critical" | "high" | "medium" | "low"
BeforeAutomation prioritized by aesthetic preference, not scale pressure.
Aftercurrent count + growth rate + limits{cognitive, maintenance, duplication} -> time until breach -> severity
Automation Priority Ordering
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowBreakingPoints → UrgencyMetric → ImpactMetric → PriorityOrder
ProductionsPriorityOrdering ::= <BreakingPointSet> "->" <PriorityScoreSet> "->" <SortedAutomationBacklog> PriorityScore ::= <PriorityRank> "+" <TimeToBreak> "+" <AffectedScope> "+" <MaintenanceCost>
BeforeMigrations tackled in arbitrary order, low-impact first.
Afterbreaking points -> urgency{severity + time-to-break + scope + maintenance cost} -> sorted backlog
Convention Strength Analysis
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowRelatedResources → TokenExtraction → ConsistencyMetric → Strength → Readiness
ProductionsConventionStrength ::= <ResourceSet> "->" <ConventionSignalSet> "->" <ConsistencyScore> "->" <StrengthVerdict> StrengthVerdict ::= "strong" | "moderate" | "weak" ReadinessRule ::= "strong -> auto_discovery_ready" | "moderate -> formalize_first" | "weak -> establish_convention_first"
BeforeAuto-discovery built on a naming convention only 60% of files follow.
Afterrelated resources -> naming tokens + organization -> consistency % -> {strong -> auto-ready | moderate -> formalize | weak -> establish convention first}
Extension Interface Discovery
Details
FlowImplementationSet → ContractSignals → InterfaceCandidate → ExtensionContract
ProductionsExtensionInterfaceDiscovery ::= <ImplementationPatternSet> "->" <ContractEvidence> "->" <InterfaceCandidateSet> ContractEvidence ::= "inheritance" | "composition" | "common_methods" | "common_schema" InterfaceCandidate ::= <InterfaceName> "," <ImplementationCount> "," <RequiredContractEvidence>
BeforeDynamic discovery attempted with no contract boundary to validate against.
Afterimplementations -> contract signals{inheritance, composition, common methods, common schema} -> interface candidate when count exceeds threshold
Scalability Projection
Details
FlowCurrentScale → 10xProjection → 100xProjection → ManualFeasibility → DiscoveryNeed
ProductionsScalabilityProjection ::= <CurrentScale> "->" <GrowthScenarioSet> "->" <MaintenanceFeasibilitySet> "->" <AutomationNeed> GrowthScenarioSet ::= "10x" | "100x" AutomationNeed ::= "manual_ok" | "dynamic_recommended" | "dynamic_required"
BeforeAutomation judged against today's 5 items, not tomorrow's 500.
Aftercurrent scale -> 10x + 100x projection -> manual feasibility -> {manual ok | dynamic recommended | dynamic required}
Performance-Aware Discovery Design
Details
FlowItemCount → DiscoveryCost → LoadingCost → CacheNeed → PerformanceVerdict
ProductionsDiscoveryPerformanceDesign ::= <ScaleMetric> "->" <CostEstimateSet> "->" <CacheDecision> "->" <FailureModeSet> CostEstimateSet ::= "discovery_cost" "," "loading_cost" "," "memory_overhead" CacheDecision ::= "cache_required" | "cache_not_required"
BeforeDynamic discovery ships, hiding a per-startup scan cost that grows with scale.
Afteritem count -> {discovery cost, loading cost, memory} vs targets -> cache only when justified -> failure modes recorded
Dynamic Extension Architecture
Details
FlowContract → Discovery → Filter → Validate → Load|Skip → Report
ProductionsDynamicExtensionArchitecture ::= <ExtensionContract> "->" <DiscoveryMechanism> "->" <ContractValidation> "->" <LoadingPolicy> "->" <ObservabilityReport> LoadingPolicy ::= "load_valid" | "skip_invalid" | "manual_override" | "isolate_failure" ObservabilityReport ::= "discovered_count" "," "manual_count" "," "skipped_count" "," "failed_count"
BeforeImplementations loaded dynamically with no contract validation, unobservable.
Aftercontract -> discovery -> contract-validate -> {load valid | skip invalid | manual override | isolate failure} -> report{discovered, manual, skipped, failed}
Centralized Reference Resolver
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowHardcodedReferenceGroup → Resolver → ScopeValidation → OverrideFallback → MigrationMap
ProductionsReferenceResolver ::= <ReferenceGroup> "->" <ResolverDefinition> "->" <ScopePolicy> "->" <FallbackOverride> "->" <ReplacementMap> ScopePolicy ::= "reject_outside_allowed_scope" | "require_explicit_approval_for_escape" FallbackOverride ::= "configuration_override"
BeforeThe same hardcoded path duplicated at a dozen call sites.
Afterreference group -> resolver -> scope-safe rule -> config override fallback -> map each old reference to the resolver
Cache Invalidation Strategy
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowCacheSubject → CacheKey → Duration → InvalidationTrigger → Refresh
ProductionsCacheStrategy ::= <CacheSubject> "->" <CacheKey> "->" <CacheDuration> "->" <InvalidationPolicy> CacheSubject ::= "discovery_results" | "loaded_extensions" | "reference_resolution" InvalidationPolicy ::= "resource_change" | "explicit_invalidation" | "time_expiry" | "implementation_change"
BeforeDiscovery results cached with no invalidation, serving stale data forever.
Aftercache subject -> key{scope, convention, adapter version, identity} -> invalidate on{resource change, explicit, time, implementation change}
Manual Fallback Preservation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowAutoDiscovery → NonConformingItem → ManualRegistration → DeterministicMerge → Observability
ProductionsManualFallback ::= <DiscoveredSet> "," <ManualSet> "->" <Validation> "->" <DeterministicMerge> "->" <FallbackReport> ManualSet ::= <ExplicitRegistration> | <ExplicitRegistration> "," <ManualSet> FallbackReport ::= "manual_items_listed_separately"
BeforeAuto-discovery removes the escape hatch — a non-conforming item can't be registered.
Afterauto-discovery + manual registration for exceptions -> deterministic merge -> manual items reported separately
Dynamic Failure Isolation
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowItemFailure → Isolate → ContinueSafeSubset → ReportFailure
ProductionsFailureIsolation ::= <ExtensionItem> "->" <FailureType> "->" <IsolationPolicy> "->" <ContinuationPolicy> "->" <FailureReport> FailureType ::= "discovery_failure" | "loading_failure" | "validation_failure" | "execution_failure" ContinuationPolicy ::= "continue" | "continue_with_warning" | "halt_if_systemic_or_critical"
BeforeOne bad extension crashes the whole dynamic system.
Afteritem failure{discovery | loading | validation} -> isolate the item -> continue with valid ones -> report the failure; halt only if systemic or critical
Entry Point Migration
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCompositionRoot → StaticPatternScan → UpdatePlan → Validate → ApplyOrPlan
ProductionsEntryPointMigration ::= <CompositionRootSet> "->" <StaticPatternSet> "->" <EntryPointUpdate> "->" <Validation> "->" <PersistencePolicy> PersistencePolicy ::= "persist_only_in_implementation_mode" | "emit_plan_only"
BeforeDiscovery registries built but the composition root still hardcodes registrations.
Aftercomposition roots -> scan static patterns -> update to discovery + resolver -> validate -> persist only in implementation mode
Measured-vs-Estimated Validation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowValidationNeed → CanMeasure? → MeasuredResult|EstimatedResult → ProvenanceLabel
ProductionsValidationProvenance ::= <ValidationCheck> "->" <CapabilityCheck> "->" <ValidationResult> "->" <Provenance> Provenance ::= "measured" | "estimated" | "unavailable" Rule ::= "estimated != measured"
BeforeAn estimated performance number reported as if it were measured.
Aftervalidation need -> can measure? -> {measured | estimated (labeled)} -> estimated is never reported as measured
Architecture Validation Before Persistence
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowGeneratedArtifact → SchemaValidation → ArchitectureValidation → Persist|Reject
ProductionsPrePersistenceValidation ::= <GeneratedArtifact> "->" <SchemaCheck> "->" <ArchitectureCheck> "->" <PersistenceDecision> PersistenceDecision ::= "persist" | "reject" | "emit_unpersisted_artifact"
BeforeA generated resolver saved before it is checked against the architecture rules.
Aftergenerated artifact -> schema check -> architecture check -> {persist | reject | emit unpersisted}
Knowledge Capture
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowSessionFindings → KnowledgeMerge → PersistenceCheck → Store|ReportPreparedUpdate
ProductionsKnowledgeCapture ::= <KnowledgeBase> "," <SessionFindings> "->" <MergedKnowledge> "->" <KnowledgePersistenceStatus> SessionFindings ::= <PatternClassifications> "," <ConventionReport> "," <ScalabilityReport> "," <ArchitectureDesign> "," <MigrationStatus> KnowledgePersistenceStatus ::= "persisted" | "prepared_not_persisted"
BeforeEach automation session forgets the last — the same analysis re-run.
Afterknowledge base + session findings -> merge{detections, conventions, scale, designs, migration, validation} -> persist when capability exists
Automation Session Report
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowSessionArtifacts → Metrics → ValidationProvenance → Limitations → UserReport
ProductionsAutomationReport ::= <DetectionSummary> "," <ConventionSummary> "," <ScalabilitySummary> "," <ArchitectureSummary> "," <ImplementationSummary> "," <PerformanceValidationSummary> "," <KnowledgeUpdateSummary> "," <Limitations>
BeforeA report that conflates the design intent with what was actually applied.
Aftersession -> {detection, convention, scale, architecture, implementation, measured-vs-estimated validation, limitations} -> report separating design from applied
Automation Completion Status
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowCompletionCriteria → EvidenceCheck → CapabilityDisclosure → Complete|PlannedOnly|Blocked
ProductionsAutomationCompletionStatus ::= <CompletionCriteriaSet> "->" <EvidenceSet> "->" <CompletionVerdict> CompletionVerdict ::= "automation_complete" | "planned_only" | "blocked"
Before'Automated' declared while the convention was never formalized, no fallback was preserved, and the validation was estimated not measured.
Afterconvention strong + fallback preserved + performance validated + architecture validated + capability disclosed -> complete; else planned_only | blocked
Automation Kernel
- Math type: computation
- Yields: procedure
Details
FlowInit → Capabilities → Detect → Classify → Conventions → Scale → Design → Implement? → Validate → Knowledge → Report
ProductionsAutomationKernel ::= <Initialization> "->" <CapabilityDegradation> "->" <OpportunityDetection> "->" <StaticSeparation> "->" <BreakingPoint> "->" <ConventionStrength> "->" <ScalabilityProjection> "->" <DynamicExtensionArchitecture> "->" <ReferenceResolver> "->" <OptionalImplementation> "->" <ValidationProvenance> "->" <KnowledgeCapture> "->" <AutomationReport> OptionalImplementation ::= "skip_unless_implementation_mode" | <EntryPointMigration>
Derivation map
BeforeA static pattern rewritten dynamic by intuition, with no convention, fallback, or validation.
Afterinit -> capabilities -> detect -> classify -> conventions -> scale -> design -> optional implement -> validate -> knowledge -> report
<Automation Concern>
- Meta record
Details
FlowStatic → Evidence → Convention → Contract → Discovery → Fallback → Validation → Memory
ProductionsAutomationConcern ::= <StaticPattern> "->" <EvidenceClassification> "->" <ConventionReadiness> "->" <DynamicArchitecture> "->" <FallbackPolicy> "->" <PerformanceValidation> "->" <KnowledgeUpdate> "->" <Report> DynamicArchitecture ::= <ExtensionContract> "," <DiscoveryMechanism> "," <CentralizedResolver> "," <CachingPolicy> "," <FailureIsolation>
centralization
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_runtime_agnostic_adapter_boundary["Runtime-Agnostic Adapter Boundary"]
n_operation_mode_gating["Operation Mode Gating"]
n_capability_disclosure["Capability Disclosure"]
n_pattern_classification["Pattern Classification"]
n_refactor_intent_classification["Refactor Intent Classification"]
n_research_guidance["Research Guidance"]
n_iterative_variation_discovery["Iterative Variation Discovery"]
n_detection_registry["Detection Registry"]
n_canonical_variation_selection["Canonical Variation Selection"]
n_architecture_compliance_targeting["Architecture Compliance Targeting"]
n_existing_solution_conflict["Existing Solution Conflict"]
n_migration_action_mapping["Migration Action Mapping"]
n_atomic_refactor_phase["Atomic Refactor Phase"]
n_replacement_refactor["Replacement Refactor"]
n_additive_debt_gate["Additive Debt Gate"]
n_rollback_centered_execution["Rollback-Centered Execution"]
n_pattern_specific_validation["Pattern-Specific Validation"]
n_zero_duplication_verification["Zero-Duplication Verification"]
n_validation_score["Validation Score"]
n_user_decision_gate["User Decision Gate"]
n_completion_truthfulness["Completion Truthfulness"]
n_centralization_report["Centralization Report"]
n_centralization_kernel["Centralization Kernel"]
n_centralization_concern["<Centralization Concern>"]
n_canonical_variation_selection --> n_detection_registry
n_migration_action_mapping --> n_detection_registry
n_centralization_kernel --> n_pattern_classification
n_centralization_kernel --> n_research_guidance
n_centralization_kernel --> n_runtime_agnostic_adapter_boundary
n_centralization_kernel --> n_canonical_variation_selection
n_centralization_kernel --> n_operation_mode_gating
n_centralization_kernel --> n_migration_action_mapping
n_centralization_kernel --> n_replacement_refactor
n_centralization_kernel --> n_zero_duplication_verification
n_centralization_kernel --> n_centralization_report
n_centralization_kernel --> n_completion_truthfulnessRuntime-Agnostic Adapter Boundary
Details
FlowSemanticOperation → AdapterMapping → ConcreteExecution → EvidenceResult
ProductionsAdapterBoundary ::= <SemanticOperation> "->" <AdapterMapping> "->" <RuntimeAction> "->" <Result> SemanticOperation ::= "DISCOVER_RESOURCES" | "READ_RESOURCE" | "SEARCH_CONTENT" | "APPLY_MIGRATION" | "VALIDATE_ARTIFACT" | "REPORT_RESULT" AdapterMapping ::= <CapabilityStatus> "," <RuntimeConstraint> "," <FallbackPolicy>
BeforeCentralization logic hardcodes a repo path and shell command, so it runs on one setup only.
Aftersemantic op{DISCOVER/READ/SEARCH/APPLY_MIGRATION/VALIDATE} -> adapter maps to the runtime -> core carries no repo/shell/path/model
Operation Mode Gating
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowDetectMode → BindPermissions → EnforceMutationPolicy → ExecuteModeScope → EmitModeArtifact
ProductionsMutationMode ::= "analysis_only" | "analysis_and_plan" | "execute_migration" | "validation_only" ModeGate ::= <MutationMode> "->" <PermissionSet> "->" <ForbiddenActionSet> "->" <AllowedOutput> ForbiddenActionSet ::= "NoSourceMutationUnlessExecuteMigration"
BeforeAn analysis run silently migrates source; a plan run also executes.
Afterdetect mode{analysis | plan | execute-migration | validation} -> bind permissions -> source mutation only in execute mode -> mode-legal artifact
Capability Disclosure
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowRequiredCapability → Probe → Available|Unavailable|Emulated → ConfidenceImpact
ProductionsCapabilityModel ::= <CapabilitySet> "->" <CapabilityStatusSet> "->" <CapabilityVerdict> CapabilityStatus ::= "available" | "unavailable" | "emulated" CapabilityVerdict ::= "full" | "degraded" | "blocked"
BeforeCentralization assumes it can search and write, failing silently when it can't.
Afterrequired capabilities -> probe/emulate -> {available | unavailable | emulated} -> confidence downgraded on a gap
Pattern Classification
Details
FlowPatternDescription → ClassificationEvidence → PatternType → StrategySet
ProductionsPatternClassification ::= <PatternDescription> "->" <PatternType> "->" <SearchStrategy> "->" <ValidationStrategy> PatternType ::= "STYLE_PATTERN" | "UTILITY" | "CONSTANT" | "CONFIGURATION" | "STRUCTURAL_CODE" | "CROSS_RESOURCE_DEPENDENCY" | "UNKNOWN" StrategySet ::= <SearchStrategy> "," <RefactorApproach> "," <ValidationStrategy>
BeforeBroad discovery launched before knowing what kind of pattern it is.
Afterpattern description -> type{style | utility | constant | config | structural | cross-resource} -> search strategy + validation strategy
Refactor Intent Classification
Details
FlowOccurrenceCount + PatternIntent → RefactorType → DebtPolicy
ProductionsRefactorIntent ::= <DuplicationEvidence> "->" <RefactorType> "->" <DebtPolicy> RefactorType ::= "REPLACEMENT_REFACTOR" | "ADDITIVE_ENHANCEMENT" | "CONFIGURATION_UPDATE" | "DOCUMENTATION_ONLY" | "REQUIRES_ANALYSIS" DebtPolicy ::= "zero_duplication_required" | "explicit_retained_debt_required" | "documentation_sufficient"
BeforeA scattered pattern 'centralized' by adding an abstraction beside the old copies.
Afteroccurrences + intent -> refactor type{replacement | additive | config | doc} -> replacement default; additive needs explicit debt justification
Research Guidance
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowGuidanceNeed → ExternalOrLocalResearch → ExtractPrinciples → ScoreConfidence → ReportLimitations
ProductionsResearchGuidance ::= <ResearchQuerySet> "->" <SourceSet> "->" <BestPracticeSet> "->" <AntiPatternSet> "->" <ConfidenceScore> SourceSet ::= <ExternalCurrentSources> | <LocalKnowledgeSources> | <Unavailable> ConfidenceScore ::= <SourceCount> "+" <SourceQuality> "+" <Recency> "+" <ArchitectureAlignment>
BeforeA plan built on local inference presented as best practice.
Afterguidance need -> external or local research -> best practices + anti-patterns -> confidence score -> disclose local-only limitation
Iterative Variation Discovery
- Stage: orient
- Axis: ontology
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowPrimaryPattern → Search → ContextRead → VariationExtract → ExpandedSearch → FixedPoint
ProductionsVariationDiscovery ::= <SearchPatternSet> "->" <MatchSet> "->" <ContextSet> "->" <VariationSet> "->" <SearchPatternSet> SearchLoop ::= <VariationDiscovery> "until" ("NoNewVariations" | "IterationCapReached") VariationSet ::= <PrimaryVariation> | <PrimaryVariation> "," <DerivedVariationSet>
BeforeOne exact form of the duplicate found; its variants missed.
Afterprimary pattern -> search -> read context -> infer variants -> expand the search set -> repeat until no new variations (or cap)
Detection Registry
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowMatch → Context → OccurrenceRecord → Registry
ProductionsDetectionRegistry ::= <OccurrenceRecord> | <OccurrenceRecord> "," <DetectionRegistry> OccurrenceRecord ::= <Resource> "," <Location> "," <Pattern> "," <Snippet> "," <ContextBefore> "," <ContextAfter> "," <Value> "," <OccurrenceRole> "," <VariationType> "," <Iteration> VariationType ::= "primary" | "variant"
BeforeOccurrences half-tracked, so migration misses sites.
Aftereach match + context -> occurrence record{resource, location, matched pattern, value, role, variation type, iteration} -> complete ledger
Canonical Variation Selection
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowDetectionRegistry → VariationMetrics → CanonicalCandidate → CanonicalVariation
ProductionsCanonicalSelection ::= <DetectionRegistry> "->" <VariationMetricSet> "->" <CanonicalVariation> VariationMetricSet ::= "frequency" "," "structural_completeness" "," "semantic_coverage" "," "architecture_fit" CanonicalVariation ::= <EvidenceDerivedImplementationForm>
BeforeThe centralized form chosen by preference, not by observed project semantics.
Afterdetection registry -> metrics{frequency, completeness, semantic coverage, architecture fit} -> canonical form derived from evidence
Architecture Compliance Targeting
Details
FlowPatternType → ArchitectureRules → ExistingPatternScan → ConflictCheck → TargetSelection
ProductionsArchitectureTargeting ::= <PatternType> "->" <GuidanceSet> "->" <ExistingCentralizationSet> "->" <ComplianceCheckSet> "->" <CentralizationTarget> ComplianceCheckSet ::= "naming" "," "artifact_size" "," "folder_capacity" "," "dependency_direction" "," "single_responsibility" CentralizationTarget ::= <Category> "," <LocationPolicy> "," <NamingConvention> "," <ReferenceMethod>
BeforeA single source of truth placed in the wrong architectural boundary.
Afterpattern type -> guidance -> existing centralized patterns -> checks{naming, size, capacity, dependency direction, SRP} -> justified target
Existing Solution Conflict
Details
FlowExistingPatternSearch → ConflictDetected → ResolutionOptions → Decision
ProductionsConflictResolution ::= <DuplicateCheck> "->" <ConflictState> "->" <Resolution> ConflictState ::= "none" | "overlap" | "duplicate" | "ambiguous" Resolution ::= "reuse_existing" | "extend_existing" | "create_distinct_target" | "cancel"
BeforeA second source of truth created because an existing one was never searched.
Aftersearch existing centralized locations -> conflict{none | overlap | duplicate | ambiguous} -> {reuse | extend | distinct | cancel}
Migration Action Mapping
Details
FlowDetectionRegistry → MigrationActionSet → CoverageCheck
ProductionsMigrationMapping ::= <DetectionRegistry> "->" <MigrationActionSet> MigrationAction ::= <Resource> "," <Location> "," <OccurrenceRole> "," <OldContent> "," <NewContentStrategy> "," <MigrationStatus> "," <SkipJustificationPolicy> MigrationStatus ::= "pending" | "migrated" | "skipped_with_justification"
BeforeSome occurrences migrated, others silently left behind.
Afterdetection registry -> a migration action per occurrence{old content, replacement strategy, skip policy + justification} -> every occurrence migrated or justified
Atomic Refactor Phase
Details
FlowPhase → Actions → Verification → Pass|Rollback → NextPhase
ProductionsRefactorPhase ::= <PhaseNumber> "," <PhaseName> "," <ActionSet> "," <VerificationSet> "," <RollbackStrategy> PhaseTransition ::= <RefactorPhase> "->" ("NextPhase" | "RollbackAndStop") VerificationSet ::= <Check> | <Check> "," <VerificationSet>
BeforeA broad unverified edit across all sites at once.
Afterphases -> actions + verification + rollback per phase -> no progression until the phase verification passes
Replacement Refactor
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCentralize → Reference → Migrate → DeleteOld → VerifyZeroDuplication → Validate
ProductionsReplacementRefactor ::= <CreateCentralImplementation> "->" <UpdateReferenceInfrastructure> "->" <MigrateOccurrences> "->" <DeleteOldDefinitions> "->" <ZeroDuplicationCheck> "->" <FinalValidation> CompletionCondition ::= "all_occurrences_migrated_or_justified" "," "no_unapproved_old_patterns" "," "validation_passed"
BeforeAn abstraction created but the old copies remain — two sources of truth.
Aftercentralize -> reference infra -> migrate all -> delete old definitions -> verify zero duplication -> final validation
Additive Debt Gate
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowAdditivePlan → DebtDisclosure → Approval → DeprecationPlan → IncompleteOrDebtAcceptedStatus
ProductionsAdditiveDebtGate ::= <AdditiveEnhancement> "->" <DebtRecord> "->" <UserApproval> "->" <DeprecationPlan> DebtRecord ::= <RetainedPatternSet> "," <Reason> "," <OwnerOrTrigger> "," <ExpirationOrReviewCondition> CentralizationStatus ::= "not_zero_debt" | "approved_debt" | "cancelled"
Before'Centralized' declared while the old patterns are still live and unowned.
Afteradditive enhancement -> disclose retained debt -> approval -> deprecation plan -> never called complete centralization
Rollback-Centered Execution
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCheckpoint → ExecutePhase → VerifyPhase → Commit|Rollback
ProductionsRollbackExecution ::= <Checkpoint> "->" <ActionExecution> "->" <Verification> "->" <PhaseOutcome> PhaseOutcome ::= "commit_phase" | "rollback_and_halt" RollbackTrigger ::= "action_failure" | "verification_failure" | "critical_invariant_failure"
BeforeA destructive migration phase runs with no recovery path.
Afterbefore each risky phase -> checkpoint -> execute -> verify -> commit | rollback on{action | verification | critical-invariant} failure
Pattern-Specific Validation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowPatternType → ValidationSet → ExecuteChecks → DuplicationScan → Score → Status
ProductionsPatternValidation ::= <PatternType> "->" <ValidationCheckSet> "->" <ValidationResultSet> "->" <RemainingIssueSet> "->" <FinalStatus> ValidationCheckSet ::= <PrimaryValidation> "," <SecondaryValidationSet> "," <ArchitectureCompliance> "," <ZeroDuplicationCheck> FinalStatus ::= "complete" | "incomplete"
BeforeValidation runs generic checks unrelated to what was centralized.
Afterpattern type -> matched validation set -> execute -> scan every known variation for orphans -> validation score
Zero-Duplication Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowSearchPatterns → ExcludeCentralTarget → RemainingMatches → Approved?|Issue
ProductionsZeroDuplication ::= <KnownVariationSet> "->" <ProjectSearch> "->" <RemainingMatchSet> "->" <DuplicationVerdict> ProjectSearch ::= "search_all_modules_except_approved_central_location" DuplicationVerdict ::= "zero_unapproved_duplication" | "remaining_duplicate_or_orphan"
BeforeA single source of truth declared while old sources still exist elsewhere.
Afterknown primary + variant patterns -> search all modules except the approved central location -> zero unapproved matches required
Validation Score
- Stage: verify
- Axis: verification
- Math type: probability
- Yields: number[0,1]
Details
FlowChecks → PassedChecks → SafeDivide → Score → Complete|Incomplete
ProductionsValidationScore ::= <TotalChecks> "," <PassedChecks> "->" <SafeDivide> "->" <ScorePercent> CompletionRule ::= "ScorePercent == 100" "AND" "RemainingIssues == 0" Status ::= "complete" | "incomplete"
BeforeA 90% score reported as complete while issues remain.
Aftertotal checks + passed -> safe divide -> score; complete only when score == 100 AND remaining issues == 0
User Decision Gate
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowRiskCondition → DecisionOptions → UserDecision → BoundPlanState
ProductionsUserDecisionGate ::= <DecisionTrigger> "->" <OptionSet> "->" <SelectedOption> "->" <PlanUpdate> DecisionTrigger ::= "ambiguous_classification" | "existing_solution_conflict" | "additive_debt" | "destructive_action" | "high_risk_refactor" OptionSet ::= <Option> | <Option> "," <OptionSet>
BeforeA destructive or ambiguous action taken without governance.
Afterrisk{ambiguous | conflict | additive-debt | destructive | high-risk} -> options -> user decision -> bound into plan state
Completion Truthfulness
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowCriteriaSet → EvidenceSet → RemainingIssuesCheck → Complete|Incomplete
ProductionsCompletionContract ::= <CriticalCriteriaSet> "->" <EvidenceSet> "->" <RemainingIssueSet> "->" <CompletionVerdict> CompletionVerdict ::= "centralization_complete" | "planned_only" | "incomplete" | "blocked" CentralizationComplete ::= "single_source_of_truth_verified" "," "zero_unapproved_duplication" "," "validation_passed" "," "limitations_disclosed"
Before'Done' asserted while duplication and validation evidence are missing.
Aftercritical criteria + old patterns removed/justified + zero duplication + validation evidence + no remaining issues -> complete; else planned/incomplete/blocked
Centralization Report
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowWorkflowArtifacts → Metrics → Limitations → Status → UserReport
ProductionsUserReport ::= <ClassificationSummary> "," <ResearchSummary> "," <DetectionSummary> "," <ArchitectureSummary> "," <PlanSummary> "," <ExecutionSummary> "," <ValidationSummary> "," <ArtifactReferences> "," <Limitations> ExecutionSummary ::= "executed" | "not_executed_planned_only"
BeforeA report that conflates planned work with executed work.
Afterartifacts -> {classification, research confidence, detection metrics, architecture decision, plan, execution status, validation score, limitations} -> planned vs executed distinguished
Centralization Kernel
- Math type: computation
- Yields: procedure
Details
FlowInit → Classify → Research → DetectVariations → AnalyzeArchitecture → Plan → Execute? → Validate → Report
ProductionsCentralizationKernel ::= <Initialization> "->" <PatternClassification> "->" <ResearchGuidance> "->" <VariationDiscovery> "->" <ArchitectureTargeting> "->" <MigrationMapping> "->" <RefactorPlan> "->" <OptionalExecution> "->" <PatternValidation> "->" <UserReport> OptionalExecution ::= "skip_unless_execute_migration" | <RollbackExecution> RefactorPlan ::= <RefactorPhaseSet> "," <MigrationActionSet> "," <VerificationChecklist> "," <RollbackStrategy>
Derivation map
BeforeScattered code merged by intuition, old copies left, never verified.
Afterinit -> classify -> research -> discover variations -> analyze architecture -> plan -> optional execute -> validate zero duplication -> report
<Centralization Concern>
- Meta record
Details
FlowContext → Pattern → Registry → Canonical → Plan → ExecutionGate → Validation → Report
ProductionsCentralizationConcern ::= <ContextContract> "->" <PatternContract> "->" <OccurrenceRegistry> "->" <CanonicalSource> "->" <MigrationPlan> "->" <ExecutionPolicy> "->" <ZeroDebtValidation> "->" <EvidenceReport> ZeroDebtValidation ::= "all_variants_checked" "," "old_patterns_removed_or_justified" "," "single_source_of_truth_verified"
checklist-creation
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_orientation_stage["Orientation Stage"]
n_authoritative_source_loading["Authoritative Source Loading"]
n_trust_anchor["Trust Anchor"]
n_intent_directionality_normalization["Intent & Directionality Normalization"]
n_skeptical_context_acquisition["Skeptical Context Acquisition"]
n_dynamic_discovery_pattern_generation["Dynamic Discovery Pattern Generation"]
n_teleological_intent_gate["Teleological Intent Gate"]
n_planning_stage["Planning Stage"]
n_principle_activation["Principle Activation"]
n_protocol_semantic_selection["Protocol Semantic Selection"]
n_phase_decomposition["Phase Decomposition"]
n_four_dimensional_phase_graph["Four-Dimensional Phase Graph"]
n_dependency_linearization["Dependency Linearization"]
n_severity_assignment["Severity Assignment"]
n_loop_class_labeling["Loop Class Labeling"]
n_compilation_stage["Compilation Stage"]
n_codebase_pattern_enforcement["Codebase Pattern Enforcement"]
n_verb_template_binding["Verb Template Binding"]
n_task_atomization["Task Atomization"]
n_ripple_chain_analysis["Ripple Chain Analysis"]
n_validator_coverage["Validator Coverage"]
n_structured_observability_context["Structured Observability Context"]
n_cross_cutting_surface_coverage["Cross-Cutting Surface Coverage"]
n_legacy_elimination["Legacy Elimination"]
n_hierarchical_numbering["Hierarchical Numbering"]
n_admissibility_constraint_stage["Admissibility Constraint Gate"]
n_validation_stage["Validation Stage"]
n_semantic_debt_policy["Semantic Debt Policy"]
n_evidence_based_claim_verification["Evidence-Based Claim Verification"]
n_validation_suite_battery["Validation Suite Battery"]
n_repair_stage["Repair Stage"]
n_bounded_repair_loop["Bounded Repair Loop"]
n_severity_failure_routing["Severity Failure Routing"]
n_rendering_stage["Rendering Stage"]
n_checklist_output_rendering["Checklist Output Rendering"]
n_explicit_termination["Explicit Termination"]
n_cross_stage_invariants["Cross-Stage Invariants"]
n_checklist_creation_kernel["Checklist Creation Kernel"]
n_checklist_governance_concern["<Checklist Governance Concern>"]
n_orientation_stage --> n_authoritative_source_loading
n_orientation_stage --> n_trust_anchor
n_orientation_stage --> n_intent_directionality_normalization
n_orientation_stage --> n_skeptical_context_acquisition
n_orientation_stage --> n_dynamic_discovery_pattern_generation
n_skeptical_context_acquisition --> n_dynamic_discovery_pattern_generation
n_planning_stage --> n_principle_activation
n_planning_stage --> n_protocol_semantic_selection
n_planning_stage --> n_phase_decomposition
n_planning_stage --> n_four_dimensional_phase_graph
n_planning_stage --> n_dependency_linearization
n_planning_stage --> n_severity_assignment
n_planning_stage --> n_loop_class_labeling
n_phase_decomposition --> n_four_dimensional_phase_graph
n_phase_decomposition --> n_severity_assignment
n_phase_decomposition --> n_loop_class_labeling
n_compilation_stage --> n_verb_template_binding
n_compilation_stage --> n_codebase_pattern_enforcement
n_compilation_stage --> n_task_atomization
n_compilation_stage --> n_ripple_chain_analysis
n_compilation_stage --> n_validator_coverage
n_compilation_stage --> n_structured_observability_context
n_compilation_stage --> n_cross_cutting_surface_coverage
n_compilation_stage --> n_legacy_elimination
n_compilation_stage --> n_hierarchical_numbering
n_task_atomization --> n_codebase_pattern_enforcement
n_validation_stage --> n_validation_suite_battery
n_validation_stage --> n_evidence_based_claim_verification
n_validation_stage --> n_semantic_debt_policy
n_repair_stage --> n_severity_failure_routing
n_repair_stage --> n_bounded_repair_loop
n_rendering_stage --> n_checklist_output_rendering
n_rendering_stage --> n_explicit_termination
n_checklist_creation_kernel --> n_orientation_stage
n_checklist_creation_kernel --> n_teleological_intent_gate
n_checklist_creation_kernel --> n_planning_stage
n_checklist_creation_kernel --> n_compilation_stage
n_checklist_creation_kernel --> n_admissibility_constraint_stage
n_checklist_creation_kernel --> n_validation_stage
n_checklist_creation_kernel --> n_repair_stage
n_checklist_creation_kernel --> n_rendering_stage
n_checklist_creation_kernel --> n_cross_stage_invariants
n_checklist_creation_kernel --> n_phase_decomposition
n_checklist_creation_kernel --> n_explicit_terminationOrientation Stage
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowRawTask + GoverningDocs → AuthorityLoad → ContextDiscovery → IntentNormalization → ContextBundle|RepairRoute
ProductionsOrientationStage ::= <RawTaskText> "," <HostGoverningDocs> "->" <AuthorityLoad> "->" <CurrentSystemDiscovery> "->" <IntentDirectionalityNormalization> "->" <ContextBundle> ContextBundle ::= <NormalizedIntent> "," <ChangeRelation> "," <AuthoritativeSourceSet> "," <TrustAnchor> "," <PriorityStack> "," <DiscoveredArtifacts> "," <EvidenceInventory> "," <UnresolvedQuestions> OrientationHandoff ::= "authority_loaded" "," "intent_and_change_direction_resolved" "," "evidence_inventory_non_empty" "->" "pass_to_planning" | "repair_owner_orientation"
BeforePlanning starts from the task text alone — prior model knowledge treated as current system truth.
Afterraw task + governing docs -> load authority -> discover current system -> normalize intent + change_relation -> context_bundle{evidence_inventory non-empty}
Authoritative Source Loading
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowTaskDescription → CoreSources + TriggeredSources → SourceRead → LoadedContext|BlockMissing
ProductionsAuthoritativeSourceLoading ::= <TaskDescription> "->" <CoreSourceSet> "," <TriggeredSourceSet> "->" <SourceReadSet> "->" <SourceValidationGate> SourceSelection ::= "always_read_core" "," "read_conditional_source_when_trigger_present" SourceValidationGate ::= "all_required_sources_loaded" | "blocked_missing_source"
BeforeDecomposition grounded in memory, not the host's rules; a missing source is discovered too late.
Aftertask -> always-read core{governance, principle-ontology} + triggered{architecture, design, component} -> read before analysis -> block on a missing required source
Trust Anchor
Details
FlowInputSource → TrustClassification → UsagePolicy
ProductionsTrustAnchor ::= <InputSourceSet> "->" <TrustedSourceSet> "," <UntrustedSourceSet> "->" <UsagePolicy> UsagePolicy ::= "trusted_can_ground_tasks" | "untrusted_requires_verification"
BeforeEvery input trusted equally — a narrative doc grounds a task the same as a build result.
Afterinputs -> trusted{source files, schema/config, build/validator output, tool output} vs untrusted{narrative docs, comments, prior knowledge} -> untrusted requires verification before it grounds a task
Intent & Directionality Normalization
Details
FlowTaskDescription → IntentExtraction → DirectionalityAnalysis → NormalizedIntent + Ambiguity
ProductionsIntentDirectionalityNormalization ::= <TaskDescription> "," <ExplicitConstraints> "->" <RequestedOutcome> "," <RequestedActions> "," <Entities> "->" <ChangeRelation> "," <AmbiguitySet> ChangeRelation ::= "introduce" | "retain" | "remove" | "analyze" | "mention" | "unknown"
Before'update Foo' planned without resolving whether Foo is introduced, retained, or removed.
Aftertask -> outcome + actions + entities -> change_relation{introduce|retain|remove|analyze|mention} -> unknown direction recorded as an unresolved question, never assumed
Skeptical Context Acquisition
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowNormalizedIntent → Keywords → DiscoveryProbes → DiscoveredArtifacts + Evidence
ProductionsSkepticalContextAcquisition ::= <NormalizedIntent> "->" <KeywordExtraction> "->" <DiscoveryPatternGeneration> "->" <ContextDiscovery> "->" <EvidenceInventory> KeywordExtraction ::= "technical_nouns" "," "action_verbs" "," "file_refs" "," "folders" DiscoveredArtifacts ::= "base_classes" "," "implementations" "," "registrations" "," "migrations" "," "signatures"
BeforeNew work redefines a Foo abstraction that already exists, unseen.
Afternormalized intent -> keywords -> dynamic discovery probes -> discovered artifacts{base classes, implementations, registrations} + evidence, before any architecture assumption
Dynamic Discovery Pattern Generation
- Stage: orient
- Axis: ontology
- Math type: computation
- Yields: procedure
Details
FlowKeywords → Globs + Greps + Targets → ProbeExecution
ProductionsDynamicDiscoveryPatternGeneration ::= <KeywordSet> "->" <GlobPatternSet> "," <GrepPatternSet> "," <TargetFileSet> DiscoveryProbe ::= <ProbeTool> "," <Pattern> "," <Purpose> ProbeTool ::= "Glob" | "Grep" | "Read"
BeforeDiscovery runs a fixed checklist of globs, blind to the task's own nouns.
Afterkeywords{nouns, verbs, folders, file-refs} -> generated globs + greps + target-files from the task's own language, not a fixed enumeration
Teleological Intent Gate
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowContextBundle → AdmissibleBranchEnumeration → UtilityCostScoring → ArgmaxSelection|Blocked
ProductionsTeleologicalIntentGate ::= <ContextBundle> "->" <AdmissibleBranchSet> "->" <UtilityCostScoring> "->" <SelectedBranch> | <BlockedNoAdmissibleBranch> BranchSelection ::= "argmax_utility_minus_cost_over_admissible" | "blocked_no_admissible_branch"
BeforeDecomposition begins on the first approach that comes to mind — no worth comparison, so effort is spent before the objective is even ranked.
Aftercontext_bundle -> enumerate admissible decomposition branches -> score utility - cost -> select the argmax -> WORTH_BEFORE_WORK gate before any planning
Planning Stage
Details
FlowContextBundle → ActivePrinciples → SelectedProtocols → PhaseGraph → LinearizedPhases|CycleRepair
ProductionsPlanningStage ::= <ContextBundle> "->" <PrincipleActivation> "->" <ProtocolSemanticSelection> "->" <PhaseDecomposition> "->" <FourDPhaseGraph> "->" <DependencyLinearization> PlanningHandoff ::= "z_graph_acyclic" "," "every_phase_has_inputs_outputs_four_axes" "," "order_topological_severity_metadata_only" "," "every_mandatory_principle_binds_a_validator" "->" "pass_to_compilation" | "repair_owner_planning"
BeforePhases grouped under SPRINT: CRITICAL headers; a protocol picked from a trigger word.
Aftercontext_bundle -> activate principles (each binds a decision-test + validator) -> select protocols by semantic fit -> decompose -> 4D graph -> linearize by dependency (severity is metadata)
Principle Activation
Details
FlowContextBundle → DecisionSurfaces → PrincipleFit → ActivePrincipleSet
ProductionsPrincipleActivation ::= <DecisionSurfaceSet> "->" <PrincipleCatalogTest> "->" <ApplicabilityDisposition> "," <ValidatorBinding> "," <Severity> ApplicabilityDisposition ::= "applies" | "uncertain" | "not_applicable" Severity ::= "mandatory" | "recommended" | "contextual" | "discouraged"
Before'SRP applies' asserted as a label, with no decision-test and nothing that enforces it.
Afterdecision surfaces -> test each principle{applies|uncertain|not-applicable + reason} -> bind validator + severity -> a label alone is never proof reasoning occurred
Protocol Semantic Selection
Details
FlowContextBundle + ActivePrinciples → SemanticMatch → SelectedProtocols → VerificationInjected
ProductionsProtocolSemanticSelection ::= <RequestedTransition> "," <ArchitectureSurfaceSet> "," <ActivePrincipleSet> "->" <SemanticFitMatch> "->" <SelectedProtocolSet> "->" <MandatoryVerificationInjection> Protocol ::= "module-separation" | "extension-no-modify" | "dependency-inversion" | "intention-emission" | "invariant-inheritance" | "registry-resolution" | "security-hardening" | "performance-eng" | "infra-provisioning" | "resilience-recovery" | "replacement-elim" | "enforcement-authoring" | "verification-gate"
BeforeThe word 'secure' in the task auto-selects the security protocol.
Afterrequested transition + surfaces -> semantic-fit match against the protocol library -> selected set -> the mandatory verification protocol always injected
Phase Decomposition
Details
FlowSelectedProtocols → VerbChains → PhaseSet → AnnotatedPhases
ProductionsPhaseDecomposition ::= <SelectedProtocolSet> "->" <VerbChainSet> "->" <PhaseSet> "->" <PhaseAnnotationSet> PhaseAnnotation ::= "id" "," "verb" "," "objective" "," "inputs" "," "outputs" "," "affected_artifacts" "," "principles" "," "severity" "," "loop_class" "," "graph_4d"
BeforeA protocol's steps emitted as a flat task list with no inputs, outputs, or dependency metadata.
Afterselected protocols -> verb chains -> phases annotated{id, verb, objective, inputs, outputs, principles, severity, loop_class, 4D graph}
Four-Dimensional Phase Graph
Details
FlowPhase → Z + X + Y + W Graph
ProductionsFourDPhaseGraph ::= <Phase> "->" <SequentialAxis> "," <LateralAxis> "," <DiagonalAxis> "," <PropagationAxis> SequentialAxis ::= "Z: prior_required_phases" LateralAxis ::= "X: independent_peer_phases" DiagonalAxis ::= "Y: shared_data_or_output_relationships" PropagationAxis ::= "W: superseded_state, propagated_contracts, breaks_if_omitted"
BeforeA phase records only its order — its downstream ripple is invisible.
Afterphase -> Z{prior required phases} + X{independent peers} + Y{shared-data} + W{superseded state, propagated contracts, breaks-if-omitted}; empty W carries no-consumer evidence
Dependency Linearization
Details
FlowPhaseGraph → CycleCheck → TopologicalOrder|BlockedCycle
ProductionsDependencyLinearization ::= <PhaseGraph> "->" <CycleDetection> "->" <TopologicalOrder> | <BlockedCycleSet> LinearizationResult ::= "pass_topological_order" | "blocked_cycle"
BeforePhases ordered by priority label; a hidden cycle ships undetected.
Afterphase graph -> detect Z-cycles (block on any) -> topological Z-order with a stable tie-breaker; severity never controls order
Severity Assignment
- Stage: project
- Axis: reasoning
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowPhase → LocalPrinciples → WorstSeverity
ProductionsSeverityAssignment ::= <Phase> "->" <LocalPrincipleSet> "->" <WorstSeverityResolution> "->" <Severity>
BeforeSeverity used as a section header that groups the phases.
Afterphase -> worst severity of its governing principles -> per-phase metadata that ROUTES the repair, never a grouping or ordering axis
Loop Class Labeling
Details
FlowVerb → LoopClass → LoopPattern
ProductionsLoopClassLabeling ::= <Verb> "->" <LoopClass> "->" <LoopPattern> LoopClass ::= "Construction" | "Perceptual" | "Cognitive" | "Executive" | "Linking"
BeforeA phase's cognitive role is implicit in its verb.
Afterverb -> loop class{Construction|Perceptual|Cognitive|Executive|Linking} -> the phase's cognitive role made explicit
Compilation Stage
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowPhaseRecords → TaskTemplates + PatternConstraints → AtomicTasks → RippleChains + Numbering
ProductionsCompilationStage ::= <PhaseRecordSet> "->" <VerbTemplateBinding> "," <CodebasePatternEnforcement> "->" <TaskAtomization> "->" <RippleChainAnalysis> "->" <HierarchicalNumbering> CompilationHandoff ::= "every_task_atomic_and_target_specific" "," "every_task_has_evidence_contract" "," "nine_ripple_dimensions_with_names" "->" "pass_to_validation" | "repair_owner_compilation"
BeforePhases emitted as vague tasks with count-only ripple ('touches 3 consumers').
Afterphase records -> bind verb templates + codebase-pattern constraints -> atomize -> attach 9-dimension NAMED ripple chain -> number N.N.N
Codebase Pattern Enforcement
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowTask → PatternViolationScan → RequiredRewrite → CompliantTask
ProductionsCodebasePatternEnforcement ::= <Task> "->" <ForbiddenPatternSet> "->" <ViolationSet> "->" <CompliantRewrite> PatternDomain ::= "factory_creation" | "dependency_injection" | "registry_discovery" | "event_emission" | "ports_adapters" | "contract_first" | "encapsulation" | "structured_observability" | "bounded_complexity" | "secrets_management" | "input_validation" | "least_privilege" | "config_externalization" | "fail_fast" | "legacy_elimination" | "enforcement_rule"
BeforeA task says 'construct Foo' with no required pattern — direct instantiation slips through.
Aftertask -> scan forbidden forms -> rewrite each to its required form{factory, DI, registry, events, ports, contract-first, fail-fast, secrets} before emit
Verb Template Binding
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowVerb → TaskPattern → Tools → ValidationCommand
ProductionsVerbTemplateBinding ::= <Verb> "->" <TaskPattern> "," <ToolSet> "," <ValidationCommand> Verb ::= "ANALYZE" | "FIND" | "EXTRACT" | "CREATE" | "VERIFY" | "FILTER" | "EXECUTE" | "WRITE" | "READ" | "LINK" | "ITERATE"
Before'CREATE Foo' becomes a task with no tools and no way to validate it.
Afterverb -> task pattern + tool set + BLOCKING validation command -> a verb becomes a task only through a validated template
Task Atomization
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowPhase → TaskGroups → AtomicActions + Gates → AtomicTasks
ProductionsTaskAtomization ::= <Phase> "->" <TaskGroupSet> "->" <AtomicActionSet> "->" <CodebasePatternEnforcement> "->" <AtomicTaskSet> AtomicTask ::= <Action> "," <Target> "," <ExpectedEvidence> "," <ValidationMethod> "," <DoneCondition>
BeforeOne coarse task 'refactor the Foo module' — too big to execute or validate.
Afterphase -> task groups -> atomic actions (gated by codebase patterns) -> each carries an evidence contract + validation method + done-condition
Ripple Chain Analysis
- Stage: act
- Axis: formalisation
- Math type: graph
- Yields: edge-list
Details
FlowTask → RippleDimensions → NamedImpacts → DownstreamChain
ProductionsRippleChainAnalysis ::= <Task> "->" <RippleDimensionSet> "->" <ImpactSet> "->" <DownstreamEffectSet> RippleDimensionSet ::= "registry" "," "contracts" "," "persistence" "," "security" "," "infrastructure" "," "performance" "," "observability" "," "enforcement" "," "consumers" ImpactSet ::= <NamedImpact> | "none_with_applicability_evidence"
BeforeImpact recorded as a count ('affects 4 things'), filtered to the first match.
Aftertask -> 9 dims{registry, contracts, persistence, security, infrastructure, performance, observability, enforcement, consumers} -> every named downstream impact + consequence-if-omitted; empty dim carries applicability evidence
Validator Coverage
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowPattern → DetectorDiscovery → AuthorOrUpdate → RegisterAndRegenerate → EnforcementActive
ProductionsValidatorCoverage ::= <ArchitecturalPattern> "->" <DetectorDiscovery> "->" <CoverageDecision> "->" <RegisterAndRegenerate> "->" <EnforcementActive> CoverageDecision ::= "update_existing_detector" | "author_new_detector"
BeforeA new Foo invariant protected by a convention nobody enforces.
Afterpattern -> discover a detector or author one -> register + regenerate the catalog -> the rule becomes an active gate, not a convention
Structured Observability Context
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowTask → ObservabilityTrigger → RequiredContext → SchemaValidation
ProductionsStructuredObservabilityContext ::= <Task> "->" <ObservabilityTriggerSet> "->" <RequiredContextSet> "->" <ObservabilitySchema> RequiredContext ::= "error" | "violation" | "event" | "lifecycle" | "contract"
BeforeAn error task emits a stringified blob instead of queryable context.
Aftertask -> observability trigger{error|violation|event|lifecycle|contract} -> required schema-complete, machine-queryable context matched to the concern
Cross-Cutting Surface Coverage
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowTask → SurfaceDetection → SurfaceGates → CoverageVerification
ProductionsCrossCuttingSurfaceCoverage ::= <Task> "->" <SurfaceSet> "->" <SurfaceGateSet> "->" <CoverageGate> SurfaceSet ::= "security" | "performance" | "infrastructure" | "resilience"
BeforeA change gated only on structure; its threat, budget, and failure consequences uncovered.
Aftertask -> surfaces{security, performance, infrastructure, resilience} -> a gate per surface -> coverage beyond structure verified
Legacy Elimination
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowChange → SupersededDetection → SamePassRemoval → SinglePathGate
ProductionsLegacyElimination ::= <Change> "->" <SupersededPathSet> "->" <SamePassDeletion> "->" <SinglePathGate> SupersededPathSet ::= "dual_path" | "fallback" | "deprecated" | "dead_code" | "orphaned_export"
BeforeA replaced Foo path left behind beside its successor as a dual path 'for now'.
Afterchange -> detect superseded{dual-path, fallback, deprecated, dead code, orphaned export} -> delete in the SAME change -> exactly one live path remains
Hierarchical Numbering
- Stage: act
- Axis: formalisation
- Math type: algebra
- Yields: ordered-structure
Details
FlowPhases → Tasks → Subtasks → N.N.N Coordinates
ProductionsHierarchicalNumbering ::= <PhaseIndex> "->" <TaskIndex> "->" <SubtaskIndex> "->" <HierarchicalId> HierarchicalId ::= "N" | "N.N" | "N.N.N"
BeforeTasks numbered before the phase order is stable, so ids churn.
Afterstable order -> Phase N -> Task N.N -> Subtask N.N.N -> addressable coordinates assigned only after order is fixed
Admissibility Constraint Gate
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowTaskRecords + PhaseRecords + SelectedBranch → RealisedCostSum → BudgetAndLimitCheck → Admissible|RouteBack
ProductionsAdmissibilityConstraintGate ::= <TaskRecordSet> "," <PhaseRecordSet> "," <SelectedBranch> "->" <RealisedCostSum> "->" <BudgetAndLimitCheck> "->" <AdmissibilityVerdict> AdmissibilityVerdict ::= "admissible_within_budget_and_limits" | "inadmissible_route_to_intent" | "limit_breach_route_to_act"
BeforeThe compiled plan goes straight to verification — its realised cost is never checked against the selected branch's budget, so an over-budget or off-branch plan is verified and shipped anyway.
Aftertask_records + phase_records -> sum realised cost -> compare to branch budget + hard limits -> every task traces to the selected branch -> ADMISSIBLE_BEFORE_VERIFY gate | route back to intent/act
Validation Stage
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowContextBundle + Phases + Tasks → ValidationSuites → ClaimVerification → SemanticPolicy → ValidationReport
ProductionsValidationStage ::= <ContextBundle> "," <PhaseRecordSet> "," <TaskRecordSet> "->" <ValidationSuiteBattery> "," <EvidenceBasedClaimVerification> "," <SemanticDebtPolicy> "->" <ValidationReport> ValidationReport ::= "pass" | "repair_required" | "blocked"
BeforeA claim marked supported because no contradiction was found; policy enforced by banning a word.
Aftercontext + phases + tasks -> GV-* suites -> verify every claim by evidence -> semantic-debt rubric (relation to a concept) -> validation report
Semantic Debt Policy
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowContent → ConceptMatch → RelationClassification → Allowed|Violation|Investigate
ProductionsSemanticDebtPolicy ::= <Content> "->" <ControlledConceptMatch> "->" <ConceptRelation> "->" <PolicyDecision> ConceptRelation ::= "introduce" | "retain" | "remove" | "analyze" | "mention" | "assert" PolicyDecision ::= "allowed" | "violation" | "investigate"
BeforeA substring ban blocks the word 'fallback' but the fallback design passes by renaming.
Aftercontent -> match a controlled concept -> classify the RELATION{introduce|retain -> violation; mention|analyze|remove -> allowed} -> a renamed prohibited design still fails
Evidence-Based Claim Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowRecords → MaterialClaims → EvidenceWeighing → ClaimVerdicts
ProductionsEvidenceBasedClaimVerification ::= <RecordSet> "->" <MaterialClaimSet> "->" <EvidenceWeighing> "->" <ClaimVerdictSet> ClaimVerdict ::= "supported" | "contradicted" | "not_applicable" | "unsupported"
Before'Foo has no other consumers' asserted with no search recorded.
Afterrecords -> material claims -> weigh supporting vs contradicting evidence -> verdict{supported|contradicted|not-applicable|unsupported}; a zero-result claim records its searched scope
Validation Suite Battery
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowGeneratedRecords → SuiteChecks → OwnedFindings → Pass|RepairRequired
ProductionsValidationSuiteBattery ::= <GeneratedRecordSet> "->" <SuiteCheckSet> "->" <OwnedFindingSet> "->" <SuiteVerdict> ValidationSuite ::= "GV-STATE" | "GV-AUTHORITY" | "GV-ACTIVATION" | "GV-PLAN" | "GV-TASKS" | "GV-RIPPLE" | "GV-SEMANTIC" | "GV-EVIDENCE" | "GV-OUTPUT" SuiteVerdict ::= "pass" | "repair_required"
BeforeA validation gate is a bare checkmark that names no evidence.
Afterrecords -> GV-STATE/AUTHORITY/ACTIVATION/PLAN/TASKS/RIPPLE/SEMANTIC/EVIDENCE/OUTPUT -> each finding names what it examined + an owner stage -> zero blocker/error is the only pass
Repair Stage
- Stage: verify
- Axis: verification
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowFindings → EarliestOwner → Invalidate + Rerun → Repaired|Blocked
ProductionsRepairStage ::= <FindingSet> "->" <EarliestOwnerStage> "->" <SeverityFailureRouting> "->" <DependentInvalidation> "->" <RerunFromOwner> RepairTermination ::= "status_pass_to_rendering" | "cycle_exceeds_max_blocked"
BeforeA finding patched at the last stage; upstream cause left intact, downstream records stale.
Afterfindings -> earliest responsible owner stage -> apply fix -> invalidate every dependent downstream -> re-run from that stage (bounded to 3 cycles)
Bounded Repair Loop
- Stage: verify
- Axis: verification
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowRepairRequired → CycleGuard → InvalidateAndRegenerate → Pass|Blocked
ProductionsBoundedRepairLoop ::= <RepairRequired> "->" <CycleGuard> "->" <InvalidateDependents> "," <RegenerateDownstream> "->" <BoundedTermination> BoundedTermination ::= "repaired_pass" | "repair_limit_exceeded_blocked"
BeforeRepair loops unbounded, re-deriving forever on an unfixable finding.
Afterrepair-required -> cycle guard -> invalidate + regenerate downstream -> exceeding max_cycles terminates as blocked with the remaining findings
Severity Failure Routing
- Stage: verify
- Axis: verification
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowFinding → Severity → RepairRoute
ProductionsSeverityFailureRouting ::= <Finding> "->" <Severity> "->" <RepairRoute> RepairRoute ::= "block_and_repair" | "repair" | "disposition_required" | "investigate"
BeforeEvery finding blocks the same way, regardless of severity.
Afterfinding -> severity -> route{blocker -> block+repair; error -> repair; warning -> disposition; lower -> investigate} -> severity routes failure, never phase order
Rendering Stage
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowValidatedRecords|BlockedReport → DeterministicRender → SuccessArtifact|BlockedArtifact
ProductionsRenderingStage ::= <ValidatedRecordSet> | <BlockedValidationReport> "->" <DeterministicRender> "->" <GenerationResult> GenerationResult ::= "success_output_file" | "blocked_output_file"
BeforeRendering invents a new architecture decision and pre-checks future execution boxes.
Aftervalidated records | blocked report -> deterministic render -> exactly one terminal{success artifact | blocked report}; future execution checkboxes left unchecked
Checklist Output Rendering
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowContext + Phases + Graphs + Ripples + Gates → ChecklistMarkdown
ProductionsChecklistOutputRendering ::= <GoverningContext> "->" <PrincipleDisposition> "->" <LinearOrderedPhaseSet> "->" <PerPhaseGraphAndRipple> "->" <TaskHierarchy> "->" <AppendixSet> "->" <FinalExecutionGate> AppendixSet ::= "file_organization" "," "evidence_inventory" "," "registry_contract_enforcement_changes"
BeforeThe checklist drops ripple impacts to counts and renders inactive principles as mandatory.
Aftercontext -> principle disposition -> phases in Z-order{loop class, severity, 4D graph, named ripple} -> N.N.N tasks with evidence contracts -> per-phase gate -> appendices -> final blocking gate (all unchecked)
Explicit Termination
- Stage: terminate
- Axis: termination
- Math type: set-theory
- Yields: set | boolean
Details
FlowValidationStatus → TerminalSelection → WrittenArtifact
ProductionsExplicitTermination ::= <ValidationStatus> "->" <TerminalSelection> "->" <RenderIntegrityCheck> "->" <WrittenArtifact> TerminalSelection ::= "write_success_artifact" | "write_blocked_report"
BeforeThe generator stops while the status is still repairable, or loops past its bound.
Aftervalidation status -> terminal selection{write success artifact | write blocked report} -> render-integrity check -> exactly one written artifact, no premature stop, no unbounded loop
Cross-Stage Invariants
- Meta record
Details
FlowEveryStage → AlwaysRules + NeverRules → BoundGenerator
ProductionsCrossStageInvariants ::= <AlwaysRuleSet> "," <NeverRuleSet> "->" <BoundGeneratorContract> InvariantClass ::= "authority_and_directionality_first" | "discover_before_assume" | "principle_bound_to_validator" | "dependency_order_severity_routes" | "single_output_contract_handoff" | "four_axis_graph_with_ripple" | "evidence_for_every_claim" | "generation_gate_not_execution_gate" | "repair_from_earliest_invalid_stage" | "deterministic_render_no_new_decision"
BeforeEach stage guards its own rules; a global always/never guarantee is nowhere enforced.
Afterevery stage bound by ALWAYS{authority-first, discover-before-assume, principle-bound-to-validator, dependency-order, single-output handoff, 4D + ripple, evidence-for-claims, repair-from-earliest} + NEVER{prior-knowledge-as-evidence, protocol-from-trigger-word, substring-ban, severity-grouping}
Checklist Creation Kernel
- Math type: computation
- Yields: procedure
Details
FlowOrientation → Planning → Compilation → Validation → Repair → Rendering
ProductionsChecklistCreationKernel ::= <OrientationStage> "->" <PlanningStage> "->" <CompilationStage> "->" <ValidationStage> "->" <RepairStage> "->" <RenderingStage>
Derivation map
BeforeA task compiled straight into a flat checklist, ungated and unordered.
Afterorientation -> planning -> compilation -> validation -> repair -> rendering, bound by cross-stage invariants -> a validated dependency-ordered checklist OR an evidence-bearing blocked report
<Checklist Governance Concern>
- Meta record
Details
FlowAuthority → Evidence → Principles → Phases → Graph → Ripples → Validation → Repair → Terminal
ProductionsChecklistGovernanceConcern ::= <OrientationContext> "->" <PlanningGraph> "->" <CompiledTaskSet> "->" <ValidationVerdict> "->" <BoundedRepair> "->" <RenderedTerminal> CompletionCondition ::= "authority_and_directionality_resolved" "," "phases_dependency_ordered_with_4d_graph" "," "tasks_atomic_with_named_ripple_chains" "," "claims_evidence_backed" "," "semantic_policy_satisfied" "," "bounded_repair_converged" "," "single_terminal_emitted"
codebase-verification
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_verification_loop["Verification Loop"]
n_context_initialization["Context Initialization"]
n_verification_execution["Verification Execution"]
n_early_success_exit["Early Success Exit"]
n_violation_classification["Violation Classification"]
n_severity_ordered_remediation["Severity-Ordered Remediation"]
n_iteration_bound["Iteration Bound"]
n_file_scoped_fix["File-Scoped Fix"]
n_file_limit_remediation["File Limit Remediation"]
n_import_boundary_remediation["Import Boundary Remediation"]
n_naming_convention_remediation["Naming Convention Remediation"]
n_base_class_compliance_remediation["Base-Class Compliance Remediation"]
n_css_token_remediation["CSS Token Remediation"]
n_dom_factory_remediation["DOM Factory Remediation"]
n_console_usage_remediation["Console Usage Remediation"]
n_lifecycle_symmetry_remediation["Lifecycle Symmetry Remediation"]
n_stylelint_post_fix["Stylelint Post-Fix"]
n_reverification_gate["Reverification Gate"]
n_partial_success_reporting["Partial Success Reporting"]
n_completion_report["Completion Report"]
n_codebase_verification_kernel["Codebase Verification Kernel"]
n_compliance_verification_concern["<Compliance Verification Concern>"]
n_verification_loop --> n_violation_classification
n_context_initialization --> n_iteration_bound
n_reverification_gate --> n_verification_execution
n_codebase_verification_kernel --> n_context_initialization
n_codebase_verification_kernel --> n_verification_execution
n_codebase_verification_kernel --> n_violation_classification
n_codebase_verification_kernel --> n_iteration_bound
n_codebase_verification_kernel --> n_file_scoped_fix
n_codebase_verification_kernel --> n_reverification_gate
n_codebase_verification_kernel --> n_completion_report
n_codebase_verification_kernel --> n_severity_ordered_remediationVerification Loop
- Stage: verify
- Axis: verification
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowInit → Verify → Classify → Fix → Reverify → Pass|Limit
ProductionsVerificationLoop ::= <Initialization> "->" <VerificationRun> "->" (<PassReport> | <ViolationClassification> "->" <RemediationCycle> "->" <VerificationLoop>) LoopExit ::= "passed" | "max_iterations_reached"
BeforeA one-shot fix attempt, unverified — some violations remain and no one knows.
Afterinit -> verify -> classify failures -> fix -> re-verify -> repeat until pass or iteration limit
Context Initialization
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowDiscoverRules → LoadGuidance → InitializeState → SetBounds
ProductionsContextInitialization ::= <RuleDiscovery> "->" <GuidanceLoad> "->" <VerificationState> "->" <IterationBound> VerificationState ::= "verification_results" "," "iteration_count" "," "max_iterations"
BeforeFailures interpreted with no known rule context, so fixes miss the point.
Afterdiscover architecture docs + design guidance -> init result containers + iteration counter + max attempts
Verification Execution
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowExecuteSuite → CaptureOutput → ParseErrors → ParseWarnings → PassBoolean
ProductionsVerificationExecution ::= <VerificationCommand> "->" <RawOutput> "->" <ParsedResult> ParsedResult ::= <ErrorSet> "," <WarningSet> "," <PassStatus> PassStatus ::= "errors.length == 0"
BeforeCompliance asserted from confidence, not from the verifier's output.
Afterrun verification suite -> capture raw output -> parse errors + warnings -> pass = errors.length == 0
Early Success Exit
- Stage: terminate
- Axis: termination
- Math type: set-theory
- Yields: set | boolean
Details
FlowVerificationResult → IsPass? → ReportSuccess|Continue
ProductionsEarlyExit ::= <ParsedResult> "->" <PassCheck> "->" <SuccessReport> PassCheck ::= "true" | "false" SuccessReport ::= "zero_violations"
BeforeA clean verification result still triggers unnecessary remediation.
Afterparsed result -> is pass? -> report zero-violations success and terminate, no mutation
Violation Classification
Details
FlowError → Category → Strategy
ProductionsViolationClassification ::= <ErrorSet> "->" <CategorizedViolationSet> Category ::= "file_limit" | "import_pattern" | "naming" | "base_class" | "css_token" | "dom_factory" | "console" | "lifecycle" | "unknown" CategorizedViolation ::= <Error> "," <Category> "," <RemediationStrategy>
BeforeErrors fixed by ad hoc text editing, not by their semantics.
Aftereach error -> category{file_limit | import | naming | base_class | css_token | dom_factory | console | lifecycle} -> matching strategy
Severity-Ordered Remediation
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowCategorizedViolations → SeveritySort → OrderedFixQueue
ProductionsSeverityOrdering ::= <ViolationCategorySet> "->" <SeverityRank> "->" <OrderedViolationQueue> SeverityRank ::= "critical" | "high" | "medium" | "low"
BeforeA cosmetic warning fixed before a structural blocker.
Afterclassified violations -> group by category -> order by severity -> fix highest architectural risk first
Iteration Bound
- Stage: terminate
- Axis: termination
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowIncrement → CompareLimit → Continue|PartialExit
ProductionsIterationBound ::= <IterationCount> "->" <Increment> "->" <LimitCheck> "->" <LoopDecision> LoopDecision ::= "continue_remediation" | "stop_manual_review_required"
BeforeAutomated remediation loops forever on an unfixable violation.
Afterincrement iteration -> compare to max -> {continue | stop, manual review required}
File-Scoped Fix
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowReadFile → AnalyzeViolation → Transform → WriteFile
ProductionsFileScopedFix ::= <Violation> "->" <FileRead> "->" <ViolationAnalysis> "->" <DesignGuidedTransformation> "->" <FileWrite> DesignGuidedTransformation ::= <CurrentContent> "," <ViolationType> "," <DesignGuide> "->" <UpdatedContent>
BeforeA fix edits broadly, breaking things the verifier didn't flag.
Afterviolation -> read file -> analyze -> transform per design guidance -> write updated content
File Limit Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowOversizedFile → ResponsibilitySplit → NewArtifacts → ReferenceUpdate → SizeCheck
ProductionsFileLimitFix ::= <OversizedArtifact> "->" <ResponsibilityPartition> "->" <ArtifactSplit> "->" <ReferenceRewrite> "->" <LineLimitValidation> LineLimitValidation ::= "line_count <= configured_limit"
BeforeAn oversized file trimmed by deleting code instead of splitting responsibility.
Afteroversized file -> split responsibilities into compliant artifacts -> preserve imports/exports -> rewire references -> size <= limit
Import Boundary Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowInvalidImport → BoundaryRule → ApprovedPath → RewriteImport → DependencyCheck
ProductionsImportBoundaryFix ::= <ImportViolation> "->" <BoundaryPolicy> "->" <AllowedReference> "->" <ImportRewrite> "->" <DependencyValidation> BoundaryPolicy ::= "same_module_only" | "shared_boundary_required" | "adapter_boundary_required"
BeforeA cross-boundary import error silenced without restoring the boundary.
Afterinvalid import -> boundary rule{same-module | shared | adapter} -> approved path -> rewrite -> verify dependency direction
Naming Convention Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowInvalidName → NamingRule → NewName → Rename → ReferenceUpdate
ProductionsNamingFix ::= <NamingViolation> "->" <NamingConvention> "->" <CompliantIdentifier> "->" <RenameOperation> "->" <ReferenceConsistencyCheck>
BeforeA file renamed but its references left dangling.
Afterinvalid name -> naming rule -> compliant identifier -> rename -> update all references (identity migration)
Base-Class Compliance Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowNonCompliantClass → ExpectedBase → RefactorExtension → HookMigration → Verify
ProductionsBaseClassFix ::= <ClassRole> "->" <ExpectedBaseAbstraction> "->" <InheritanceOrCompositionUpdate> "->" <LifecycleHookMigration> "->" <ComplianceCheck> ComplianceCheck ::= "class_extends_expected_base" | "uses_required_composition_boundary"
BeforeA class missing its required base 'fixed' by silencing the rule.
Afterclass role -> expected base -> refactor inheritance/composition -> migrate duplicated lifecycle into hooks -> verify behavior represented
CSS Token Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowHardcodedStyle → TokenLookup → Replacement → StyleValidation
ProductionsCssTokenFix ::= <HardcodedStyleValue> "->" <DesignTokenResolution> "->" <TokenReplacement> "->" <StyleValidation> DesignTokenResolution ::= "existing_token" | "new_token_required" | "manual_review_required"
BeforeA hardcoded color left in place, the rule disabled instead.
Afterhardcoded style value -> resolve design token{existing | new | manual review} -> replace -> style validation
DOM Factory Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowDirectDOM → FactoryBoundary → Rewrite → BehaviorCheck
ProductionsDomFactoryFix ::= <DirectDomUsage> "->" <ApprovedCreationBoundary> "->" <FactoryRewrite> "->" <LifecycleCompatibilityCheck> DirectDomUsage ::= "document.querySelector" | "document.createElement" | "innerHTML" | "direct_event_binding"
BeforeDirect document.createElement kept, the rule ignored.
Afterdirect DOM{querySelector, createElement, innerHTML, direct event} -> approved creation boundary -> factory rewrite -> lifecycle check
Console Usage Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowConsoleCall → LoggerMapping → Replacement → SearchNoConsole
ProductionsConsoleFix ::= <ConsoleUsage> "->" <LoggerSeverityMapping> "->" <LoggerReplacement> "->" <ConsoleAbsenceCheck> LoggerSeverityMapping ::= "console.log->info" | "console.warn->warn" | "console.error->error"
BeforeA console.log left in and the rule bypassed.
Afterconsole call -> logger severity mapping{log->info, warn->warn, error->error} -> replace -> verify no direct console remains
Lifecycle Symmetry Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowAcquireResource → MissingRelease? → AddCleanup → SymmetryCheck
ProductionsLifecycleFix ::= <LifecycleViolation> "->" <AcquiredResourceSet> "->" <CleanupRequirementSet> "->" <DestroyPathUpdate> "->" <SymmetryValidation> SymmetryValidation ::= "created_resources == destroyed_resources"
BeforeA resource acquired with no release path, leaking.
Afterlifecycle violation -> acquired resources -> add destroy/teardown -> verify created == destroyed
Stylelint Post-Fix
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowRemediation → Stylelint → StyleErrors? → FixStyle → Continue
ProductionsStylePostValidation ::= <RemediatedArtifacts> "->" <StyleValidationRun> "->" (<StylePass> | <StyleFixCycle>) StyleFixCycle ::= <StyleErrorSet> "->" <StyleCorrectionSet> "->" <StyleValidationRun>
BeforeThe next architectural cycle runs on style-broken code.
Afterremediation -> run style validation -> fix style errors -> block re-verification until style passes
Reverification Gate
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowFixesApplied → LocalValidation → FullVerification
ProductionsReverificationGate ::= <RemediationResult> "->" <PostFixValidation> "->" <VerificationExecution>
BeforeLocal corrections trusted as global compliance.
Afterfixes applied -> local validation -> rerun the FULL authoritative verification suite
Partial Success Reporting
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowMaxIterations → RemainingViolations → ManualReviewReport
ProductionsPartialSuccessReport ::= <IterationLimitReached> "->" <RemainingViolationSet> "->" <ManualReviewRequired> ManualReviewRequired ::= "remaining_errors" "," "remaining_warnings" "," "blocked_categories"
BeforeIteration bound hit and the run silently reports success.
Aftermax iterations -> remaining violations categorized -> mark result manual-review-required (visible, actionable residue)
Completion Report
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowFinalState → Iterations → FixedCount → WarningCount → Report
ProductionsCompletionReport ::= <FinalVerificationState> "," <IterationCount> "," <FixedCount> "," <RemainingWarningCount> FinalVerificationState ::= "passed" | "partial_success" | "failed"
BeforeA report that mixes fixed violations with tolerated warnings.
Afterfinal state -> {total iterations, fixed count, remaining warnings, final status{passed | partial | failed}}
Codebase Verification Kernel
- Math type: computation
- Yields: procedure
Details
FlowContext → Verify → Parse → Pass? → Classify → Fix → StyleValidate → Reverify → Report
ProductionsCodebaseVerificationKernel ::= <ContextInitialization> "->" <VerificationExecution> "->" (<EarlyExit> | <ViolationClassification> "->" <IterationBound> "->" <SeverityOrdering> "->" <FileScopedFix> "->" <StylePostValidation> "->" <ReverificationGate>) "->" <CompletionReport> SuccessCondition ::= "verification_errors == 0" FailureBound ::= "iteration_count > max_iterations"
Derivation map
BeforeCompliance claimed after one edit, never re-verified.
Aftercontext -> verify -> parse -> pass? -> classify -> severity-order fix -> style validate -> reverify -> repeat until zero errors or bound
<Compliance Verification Concern>
- Meta record
Details
FlowRules → Verify → Errors → Categories → Fixes → LocalValidation → Reverify → Report
ProductionsComplianceConcern ::= <RuleContext> "->" <AuthoritativeVerification> "->" <ViolationRegistry> "->" <RemediationQueue> "->" <BoundedMutationCycle> "->" <Reverification> "->" <FinalStatus> FinalStatus ::= "passed" | "partial_success_manual_review" | "failed"
context-verification
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_phase_separated_execution["Phase-Separated Execution"]
n_evidence_gated_claim_verification["Evidence-Gated Claim Verification"]
n_validation_gate["Validation Gate"]
n_file_modification_recovery["File Modification Recovery"]
n_trust_anchor_declaration["Trust Anchor Declaration"]
n_environment_capability_verification["Environment Capability Verification"]
n_tool_calibration["Tool Calibration"]
n_behavioral_self_test["Behavioral Self-Test"]
n_adversarial_input_testing["Adversarial Input Testing"]
n_defensive_string_normalization["Defensive String Normalization"]
n_safe_arithmetic_contract["Safe Arithmetic Contract"]
n_recursion_control["Recursion Control"]
n_recursive_self_verification["Recursive Self-Verification"]
n_advanced_tool_escalation["Advanced Tool Escalation"]
n_investigation_report["Investigation Report"]
n_action_log["Action Log"]
n_contract_based_verification_kernel["Contract-Based Verification Kernel"]
n_context_verification_concern["<Context Verification Concern>"]
n_contract_based_verification_kernel --> n_tool_calibration
n_contract_based_verification_kernel --> n_behavioral_self_test
n_contract_based_verification_kernel --> n_validation_gate
n_contract_based_verification_kernel --> n_trust_anchor_declaration
n_contract_based_verification_kernel --> n_advanced_tool_escalation
n_contract_based_verification_kernel --> n_phase_separated_execution
n_contract_based_verification_kernel --> n_evidence_gated_claim_verification
n_contract_based_verification_kernel --> n_investigation_report
n_context_verification_concern --> n_validation_gatePhase-Separated Execution
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowDetectPhase → BindCapabilities → EnforceMode → ExecuteAllowedOnly → EmitPhaseArtifact
ProductionsPhaseExecution ::= <PhaseDetect> "->" <CapabilityBinding> "->" <ModeEnforcement> "->" <AllowedExecution> "->" <PhaseOutput> PhaseDetect ::= "INVESTIGATE" | "ACTION" AllowedExecution ::= <InvestigationOnly> | <ActionOnly> InvestigationOnly ::= "Discover" "Test" "Document" "NoModify" ActionOnly ::= "FixKnownGap" "Modify" "Version" "NoDiscovery"
BeforeAn investigation quietly starts fixing gaps; a fix quietly expands its scope.
Afterdetect phase{INVESTIGATE | ACTION} -> bind allowed ops -> INVESTIGATE{discover, test, document, no-modify} | ACTION{fix known gap, version, no-discovery}
Evidence-Gated Claim Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowClaim → EvidenceRequirement → Observation → Classification → Report
ProductionsClaimVerification ::= <ClaimSet> "->" <EvidenceMap> "->" <ObservationSet> "->" <VerdictSet> "->" <Report> ClaimSet ::= <Claim> | <Claim> "," <ClaimSet> VerdictSet ::= "verified" | "contradicted" | "unverified"
Before'The core has no infra imports' trusted because it sounds right.
Afterclaims -> map each to an observable evidence requirement -> collect implementation evidence -> verdict{verified | contradicted | unverified}
Validation Gate
- Stage: terminate
- Axis: termination
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowStage → Criteria → Evaluate → Pass|Warn|Block → Continue|Abort
ProductionsValidationGate ::= <Stage> "->" <CriteriaSet> "->" <GateResult> GateResult ::= "PASS" | "WARN" | "BLOCK" CriteriaSet ::= <Criterion> | <Criterion> "," <CriteriaSet> Criterion ::= <Condition> ":" <PriorityRank> PriorityRank ::= "critical" | "high" | "medium" | "low"
BeforeA stage's uncertainty stays hidden and flows silently downstream.
Afterstage -> criteria{critical | noncritical} -> {PASS | WARN | BLOCK} -> block downstream on a critical failure
File Modification Recovery
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowEditFail → ReRead → MergeDelta → WriteFullState → Verify
ProductionsFileRecovery ::= "ModificationError" "->" <ReadCurrent> "->" <Merge> "->" <WriteComplete> "->" <VerifyWrite> Merge ::= <CurrentContent> "+" <RequiredChange> "->" <NewContent> VerifyWrite ::= "Exists" "&" "ContentMatches"
BeforeA stale-write failure re-patches the old content, corrupting state.
Afteredit fail -> re-read current -> merge the delta into full state -> write complete version -> verify{exists & content matches}
Trust Anchor Declaration
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowMinimalAssumptions → Boundary → VerificationScope → Disclosure
ProductionsTrustAnchor ::= <AssumptionSet> "->" <TrustBoundary> "->" <Scope> AssumptionSet ::= <Assumption> | <Assumption> "," <AssumptionSet> Assumption ::= "RuntimeWorks" | "FilesystemWorks" | "CommandExecutionWorks" | "ToolIOWorks" TrustBoundary ::= "CannotVerifyVerifierWithoutExternalReference"
BeforeThe verifier's own axioms are hidden, so its boundary is unknowable.
Afterdeclare minimal assumptions{runtime, filesystem, execution, tool IO} -> boundary{cannot verify the verifier} -> disclosed, not verified
Environment Capability Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowRequirement → Probe → Status → Severity → CapabilityMode
ProductionsEnvironmentVerification ::= <RequirementSet> "->" <ProbeSet> "->" <StatusSet> "->" <CapabilityVerdict> CapabilityVerdict ::= "full" | "degraded" | "blocked" Status ::= "passed" | "failed" Requirement ::= "runtime" | "packageManager" | "writePermission" | "filesystem"
BeforeAdvanced analysis relied on before checking the runtime can run it.
Afterrequirements{runtime, package manager, write, filesystem} -> probe each -> classify by severity -> mode{full | degraded | blocked}
Tool Calibration
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowKnownGood + KnownBad → RunTool → CompareExpected → CalibrateReliability
ProductionsToolCalibration ::= <FixtureSet> "->" <ToolRun> "->" <ExpectedComparison> "->" <ReliabilityVerdict> FixtureSet ::= <KnownGood> "," <KnownBad> ReliabilityVerdict ::= "reliable" | "false_positive_risk" | "false_negative_risk" | "unreliable"
BeforeA detector's match trusted with no control test.
Afterknown-good + known-bad fixtures -> run tool -> detect false-positive AND false-negative -> reliable only if both controls pass
Behavioral Self-Test
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowClaimedBehavior → PositiveCase + NegativeCase → Execute → Compare → Verdict
ProductionsBehavioralSelfTest ::= <BehaviorClaim> "->" <TestCasePair> "->" <ExecutionResult> "->" <BehaviorVerdict> TestCasePair ::= <PositiveCase> "," <NegativeCase> BehaviorVerdict ::= "matches_contract" | "false_positive" | "false_negative" | "failed"
BeforeA claimed capability trusted without ever running it on a case.
Afterclaimed behavior -> positive + negative case -> execute -> compare -> {matches contract | false-positive | false-negative | failed}
Adversarial Input Testing
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowAttackInput → ExecuteDetector → ExpectedReject|ExpectedIgnore → VulnerabilityVerdict
ProductionsAdversarialTesting ::= <AttackSet> "->" <DetectorExecution> "->" <SecurityVerdict> AttackSet ::= <Attack> | <Attack> "," <AttackSet> Attack ::= "pathTraversal" | "nullByte" | "unicodeHomoglyph" | "commentFalsePositive" | "patternSpoof" SecurityVerdict ::= "blocked" | "ignored" | "vulnerable"
BeforeA detector accepted after ordinary examples pass, never tested hostilely.
Afterattacks{pathTraversal, nullByte, unicodeHomoglyph, commentFalsePositive, patternSpoof} -> run detector -> {blocked | ignored | vulnerable}
Defensive String Normalization
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowRawString → NullGuard → StripDanger → Normalize → SafeString
ProductionsStringNormalization ::= <RawString> "->" <NullGuard> "->" <DangerRemoval> "->" <UnicodeNormalize> "->" <SafeString> NullGuard ::= "reject(null|undefined)" DangerRemoval ::= "remove('../')" | "remove('..\\')" | "remove(NULL_BYTE)" UnicodeNormalize ::= "NFC"
BeforeA raw external string passed straight to a filesystem or command boundary.
Afterraw string -> null-guard -> strip{'../', null byte} -> Unicode NFC -> only the sanitized string crosses a boundary
Safe Arithmetic Contract
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowOperands → PreconditionCheck → Compute → FiniteCheck → BoundsCheck → Result|Failure
ProductionsSafeArithmetic ::= <Operands> "->" <Preconditions> "->" <Computation> "->" <Postconditions> "->" <NumericOutput> Preconditions ::= "denominator != 0" | "operands finite" Postconditions ::= "isFinite(result)" | "withinBounds(result)" NumericOutput ::= <Number> | "null" | <TypedFailure>
BeforeA division runs unchecked and returns NaN or Infinity into a decision.
Afteroperands -> preconditions{denominator != 0, finite} -> compute -> postconditions{isFinite, within bounds} -> number | null | typed failure
Recursion Control
- Stage: act
- Axis: formalisation
- Math type: dynamical-systems
- Yields: boolean | counter
Details
FlowEnter → IncrementDepth → CheckLimit → Continue|Reject → Exit
ProductionsRecursionControl ::= <EnterRecursiveCall> "->" <DepthIncrement> "->" <LimitCheck> "->" <Decision> "->" <Exit> Decision ::= "continue" | "reject_max_depth_exceeded" LimitCheck ::= "currentDepth <= maxDepth"
BeforeA recursive self-reference runs away with no depth bound.
Afterenter -> increment depth -> depth <= max? -> {continue | reject max-depth} -> unwind on exit
Recursive Self-Verification
- Stage: verify
- Axis: verification
- Math type: probability
- Yields: number[0,1]
Details
FlowSelfDefinition → ExtractClaims → VerifyClaims → DetectDiscrepancies → ConfidenceAdjustment
ProductionsSelfVerification ::= <SelfDefinition> "->" <SelfClaimSet> "->" <EvidenceSearch> "->" <DiscrepancySet> "->" <ConfidenceState> ConfidenceState ::= "confirmed" | "partially_confirmed" | "overclaimed" | "invalid"
BeforeThe verifier exempts itself from its own rules and overclaims.
Afterself definition -> extract self-claims -> search implementation evidence -> discrepancies -> confidence{confirmed | overclaimed | invalid}
Advanced Tool Escalation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowNeed → CapabilityGap → GenerateTool → ExecuteTool → ParseEvidence → Integrate
ProductionsToolEscalation ::= <AnalysisNeed> "->" <CapabilityCheck> "->" <ToolConstruction> "->" <ToolExecution> "->" <EvidenceIntegration> CapabilityCheck ::= "direct_capability_available" | "requires_generated_tool" ToolConstruction ::= "write_script" "->" "execute_script" "->" "parse_results"
BeforeA capability gap filled by inference instead of evidence.
Afteranalysis need -> capability gap -> write script -> execute -> parse -> integrate the result as evidence
Investigation Report
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowEvidenceSet → FindingSet → RiskSet → Confidence → Report
ProductionsInvestigationReport ::= <EvidenceSet> "->" <Findings> "->" <Risks> "->" <Confidence> "->" <Report> Findings ::= <VerifiedFinding> | <Discrepancy> | <UnverifiedClaim> Report ::= "investigation_report"
BeforeAn investigation that also 'quickly fixes' what it found.
Afterevidence -> findings + risks + adversarial results + confidence -> one investigation report, no remediation
Action Log
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowDocumentedGap → BoundedFix → Version → Verify → ActionLog
ProductionsActionLog ::= <DocumentedGapSet> "->" <FixSet> "->" <VersionedArtifact> "->" <Verification> "->" <Log> DocumentedGapSet ::= <Gap> | <Gap> "," <DocumentedGapSet> FixSet ::= <Fix> | <Fix> "," <FixSet> Log ::= "action_log"
BeforeA fix run against a gap that was never documented, discovering new scope mid-flight.
Afterdocumented gaps only -> bounded fix -> version -> verify write -> action log; discovers nothing new
Contract-Based Verification Kernel
- Math type: computation
- Yields: procedure
Details
FlowAssumptions → Phase → Environment → Calibration → Execution → AdversarialTest → SelfVerify → TypedOutput
ProductionsVerificationKernel ::= <TrustAnchor> "->" <PhaseExecution> "->" <EnvironmentVerification> "->" <ToolCalibration> "->" <BehavioralSelfTest> "->" <AdversarialTesting> "->" <ValidationGate> "->" <SelfVerification> "->" <TypedOutput> TypedOutput ::= "investigation_report" | "action_log" | "blocked_execution_report"
Derivation map
BeforeBehavior trusted because it looks right, with no phase, calibration, or self-check.
Afterdeclare assumptions -> detect phase -> verify environment -> calibrate tools -> phase-legal execution -> adversarial test -> validation gate -> self-verify -> typed artifact
<Context Verification Concern>
- Meta record
Details
FlowContract → Capability → Operation → Gate → Artifact
ProductionsConcernAlgorithm ::= <PhaseContract> "->" <CapabilityBinding> "->" <Operation> "->" <ValidationGate> "->" <TypedArtifact> PhaseContract ::= <Precondition> "," <AllowedActionSet> "," <ForbiddenActionSet> "," <Postcondition> TypedArtifact ::= <Report> | <Log> | <Failure>
css-cascade
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_cascade_layer_partition["Cascade Layer Partition"]
n_token_source_of_truth["Token Source-of-Truth"]
n_type_keyed_appearance["Type-Keyed Appearance"]
n_custom_type_registration["Custom Type Registration"]
n_governed_construction_boundary["Governed Construction Boundary"]
n_placement_isolation["Placement Isolation"]
n_assembly_composition["Assembly Composition"]
n_layer_fitness_enforcement["Layer Fitness Enforcement"]
n_type_migration_centralization["Type-Migration Centralization"]
n_css_type_cascade_concern["CSS Type-Cascade Kernel"]
n_css_type_cascade_concern --> n_cascade_layer_partition
n_css_type_cascade_concern --> n_token_source_of_truth
n_css_type_cascade_concern --> n_type_keyed_appearance
n_css_type_cascade_concern --> n_custom_type_registration
n_css_type_cascade_concern --> n_placement_isolation
n_css_type_cascade_concern --> n_assembly_composition
n_css_type_cascade_concern --> n_layer_fitness_enforcementCascade Layer Partition
- Math type: algebra
- Yields: ordered-structure
Details
FlowRoot → LayerOrderDeclaration → PerFileLayerBinding → LayerPrecedence → DeterministicCascade
ProductionsCascadeLayerPartition ::= <LayerOrderDeclaration> "->" <LayeredBindingSet> "->" <PrecedencePolicy> LayerOrderDeclaration ::= "@layer" "tokens" "," "globals" "," "shell" "," "components" "," "app" LayeredBinding ::= <StyleFile> "assigned_to" <ExactlyOneLayer> PrecedencePolicy ::= "app_over_components_over_shell_over_globals_over_tokens" "," "layer_beats_specificity" "," "no_unlayered_rule"
Before.foo { color: red; } #page .foo { color: blue; }
After@layer tokens, globals, components, app; @layer globals { [data-el="foo"] { color: var(--fg); } } @layer app { .foo-view { gap: var(--space-4); } }
Token Source-of-Truth
- Math type: set-theory
- Yields: set | boolean
Details
FlowPrimitive → TokenDeclaration → DownstreamReference → NoLiteralWhereTokenExists
ProductionsTokenSourceOfTruth ::= <PrimitiveSet> "->" <TokenDeclarationSet> "->" <ReferenceOnlyDownstream> TokenCategory ::= "color" | "space" | "radius" | "type_scale" | "size" | "duration" | "z_index" LiteralPolicy ::= "reference_token" | "zero_value_exempt"
Before.foo { color: #33bb55; } .bar { color: #33bb55; }
After@layer tokens { :root { --foo: #33bb55; } } @layer globals { [data-el="foo"], [data-el="bar"] { color: var(--foo); } }
Type-Keyed Appearance
- Math type: logic
- Yields: boolean
Details
FlowType → GlobalAppearanceRule → DefinedOncePerType → TokenizedValues
ProductionsTypeKeyedAppearance ::= <TypeSelector> "->" <AppearanceRule> "->" <DefinedOncePerType> TypeSelector ::= <ElementTag> | "[data-el=" <CustomType> "]" | <TypeSelector> "[data-" ("variant"|"size"|"gap"|"tone"|"measure"|"layout") "=" <Value> "]" AppearanceProperty ::= "look" | "size" | "spacing" | "intrinsic_rendering_behavior" ForbiddenKey ::= "purpose_class"
Before.foo-label { font-size: 12px; color: gray; }
After@layer globals { [data-el="foo"] { font-size: var(--text-sm); color: var(--fg-muted); } }
Custom Type Registration
- Math type: set-theory
- Yields: set | boolean
Details
FlowSemanticConcept → DefineElement(type, baseTag, dataEl) → TypeRegistry → DataElStamp → GlobalAppearanceContract
ProductionsCustomTypeRegistration ::= <SemanticConcept> "->" <ElementDefinition> "->" <TypeRegistryEntry> "->" <RenderedTypeStamp> "->" <AppearanceBinding> ElementDefinition ::= "type" "," "baseTag" "," "dataElToken" RenderedTypeStamp ::= <BaseTag> "carrying" "data-el=" <DataElToken> AppearanceBinding ::= "[data-el=" <DataElToken> "]" "owns_exactly_one_global_appearance_rule"
Before<span class="foo">…</span> .foo { color: gray; }
AfterdefineElement({ type: "foo", baseTag: "output", dataEl: "foo" }); @layer globals { [data-el="foo"] { color: var(--fg-muted); } }
Governed Construction Boundary
- Math type: computation
- Yields: procedure
Details
FlowNodeSpec → RegistryResolution → ScalarMapping → UnknownReject|InlineStyleReject → GovernedNode
ProductionsGovernedConstruction ::= <NodeSpec> "->" <RegistryLookup> "->" <ScalarApplication> "->" <GuardSet> "->" <RenderedNode> NodeSpec ::= "el" "," "variant?" "," "size?" "," "gap?" "," "tone?" "," "measure?" "," "layout?" "," "class?" "," "on?" "," "children?" ScalarApplication ::= "each_axis_key->data-attr" "," "class=gated_iconfont_or_u_or_c" GuardSet ::= "throw_on_unknown_element" "," "throw_on_unknown_handler" "," "throw_on_unknown_component" "," "reject_style_attribute"
Beforeconst n = document.createElement("div"); n.className = "foo"; n.style.color = "red";
Afterconst n = dom({ el: "foo", tone: "bar", children: [text] });
Placement Isolation
- Math type: topology
- Yields: boolean
Details
FlowComponentType → PlacementRule → PositionStackingOverlayOnly → NoAppearanceLeak
ProductionsPlacementIsolation ::= <ComponentType> "->" <PlacementRule> "->" <ForbiddenAppearanceSet> PlacementProperty ::= "position" | "inset" | "top" | "right" | "bottom" | "left" | "z_index" | "float" | "clear" ForbiddenInComponents ::= "color" | "font" | "size" | "spacing" | "border" | "radius"
Before@layer components { [data-el="foo"] { position: fixed; inset-block-end: 1rem; color: white; } }
After@layer components { [data-el="foo"] { position: fixed; inset-block-end: var(--space-4); z-index: var(--z-overlay); } }
Assembly Composition
- Math type: algebra
- Yields: ordered-structure
Details
FlowView → ContainerSet → ChildArrangement → GutterConvention → NoAppearanceOverride
ProductionsAssemblyComposition ::= <View> "->" <StructuralContainerSet> "->" <ChildArrangement> "->" <GutterConvention> ChildArrangement ::= "flex" | "grid" | "token_valued_gap" GutterConvention ::= "container_pads_once" "," "child_width_100" "," "no_horizontal_margin" "," "narrower_via_explicit_width" "," "zero_margin_exempt" AppearanceAuthority ::= "none"
Before@layer app { .foo-view .bar { margin: 0 12px; box-shadow: 0 1px 2px; } }
After@layer app { .foo-view { display: grid; gap: var(--space-4); padding-inline: var(--space-4); } }
Layer Fitness Enforcement
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowLayerInvariant → FitnessFunction → StaticCheck → HardErrorNoWarn → PushGate
ProductionsLayerFitnessEnforcement ::= <InvariantSet> "->" <FitnessFunctionSet> "->" <VerdictGate> CssFitnessRule ::= "layer_order" | "no_appearance_in_components_or_app" | "no_class_in_globals" | "layered_class_format_c_or_u" | "no_bespoke_class" | "tokens_only" | "axis_value_validation" | "no_horizontal_margin" DomFitnessRule ::= "factory_only_creation" | "no_inline_style" GatePolicy ::= "hard_error_no_warn_tier" "," "no_inline_disable" "," "block_push_on_fail"
BeforereviewChecklist.push("no appearance in the app layer");
Afterexport const rules = { "no-appearance-in-app": "error", "factory-only-creation": "error" };
Type-Migration Centralization
- Math type: computation
- Yields: procedure
Details
FlowPurposeClassRule → DeriveType → RegisterTypeIfNeeded → MoveAppearanceToGlobals → DemoteResidue → ZeroAppearanceClassOutsideGlobals
ProductionsTypeMigration ::= <LegacyAppearanceRuleSet> "->" <TypeDerivation> "->" <GlobalCentralization> "->" <ResidueDemotion> "->" <ZeroDuplicationVerdict> TypeDerivation ::= "existing_tag" | "existing_variant" | "register_new_data_el_type" ResidueDemotion ::= "placement->components" "," "layout->app" ZeroDuplicationVerdict ::= "no_appearance_keyed_by_purpose_class_outside_globals" | "incomplete"
Before.foo { color: white; background: blue; position: sticky; top: 0; }
After@layer globals { [data-el="foo"] { color: var(--fg-on-accent); background: var(--bg-accent); } } @layer components { [data-el="foo"] { position: sticky; top: 0; } }
CSS Type-Cascade Kernel
- Meta record
Details
FlowLayerOrder → Tokens → TypeKeyedGlobals → Placement → Assembly → GovernedFactory → Fitness
ProductionsCssTypeCascadeKernel ::= <CascadeLayerPartition> "->" <TokenSourceOfTruth> "->" <TypeKeyedAppearance> "->" <CustomTypeRegistration> "->" <GovernedConstruction> "->" <PlacementIsolation> "->" <AssemblyComposition> "->" <LayerFitnessEnforcement> StylingBoundary ::= "values_in_tokens" "," "appearance_by_type_in_globals" "," "app_frame_in_shell" "," "structure_in_components" "," "assembly_in_app" OpenTypeVocabulary ::= "native_tag" | "registered_data_el_custom_type" CascadeContract ::= "layer_decides_precedence" "," "one_definition_per_property_per_type" "," "factory_and_linters_enforce"
governed-plan-loop
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_living_plan_state["Living Plan State"]
n_boundary_reconciliation["Boundary Reconciliation"]
n_phase_close_gate["Phase Close Gate"]
n_plan_phase_verification["Plan Phase Verification"]
n_governed_autonomous_plan_loop["Governed Autonomous Plan Loop"]
n_governed_plan_concern["<Governed Plan Concern>"]
n_phase_close_gate --> n_boundary_reconciliation
n_plan_phase_verification --> n_boundary_reconciliation
n_governed_autonomous_plan_loop --> n_living_plan_state
n_governed_autonomous_plan_loop --> n_boundary_reconciliation
n_governed_autonomous_plan_loop --> n_phase_close_gate
n_governed_autonomous_plan_loop --> n_plan_phase_verification
n_governed_plan_concern --> n_living_plan_state
n_governed_plan_concern --> n_phase_close_gateLiving Plan State
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowEmitDelta → GuardTransition → AppendOnly → Persist → RenderFromState
ProductionsLivingPlanState ::= <PlanDelta> "->" <TransitionGuard> "->" <DurableMerge> "->" <StateRender> TaskStatus ::= "pending" | "active" | "done" ConsiderationStatus ::= "open" | "confirmed" | "dismissed" DoneTransition ::= "requires" <GroundingCitation>
BeforePlan progress inferred from the conversation, so a discovery mid-pass falls out of scope on restart.
Afterplan delta -> transition guard{done requires grounding} -> append/update-only durable state{tasks, considerations, dismissed keys} -> render from state, restart-survivable
Boundary Reconciliation
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowCapture → DeferToBoundary → DedupBeforeTriage → Triage → DryPassOrBound
ProductionsBoundaryReconciliation ::= <Backlog> "->" <Dedup> "->" <Triage> "->" <Termination> Triage ::= "confirm" "->" <Task> | "dismiss" "->" <ResolvedFalse> Dedup ::= "newOpens" "against" "(confirmed | resolvedFalse)" Termination ::= "dryPass" | "maxReconcileRounds"
BeforeConsiderations acted on mid-phase, and a dismissed one resurfaces — the loop oscillates.
Aftercapture during phase -> act only at the boundary -> dedup new opens vs (confirmed | dismissed) -> triage{confirm -> task | dismiss -> resolved-false} -> dry pass or bound
Phase Close Gate
- Stage: terminate
- Axis: termination
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowAllTasksDone → DryPass → VerifyClean → CoverageConfirmed → CloseOrExecute
ProductionsPhaseCloseGate ::= <TaskCompletion> "&" <DryPass> "&" <VerifyResult> "&" <CoverageResult> "->" <Decision> Decision ::= "close" | "return_to_execute" VerifyResult ::= "scope:full" | "scope:work"
BeforeThe phase is self-declared done.
Afterall tasks done & dry reconciliation holds & verify clean (scope) & coverage graph confirms ripple -> close | return to execute; never self-declared
Plan Phase Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowAutoLoopback → ThreePassVerify → ReconcileFindings → LoopOwnedIncrement → PresentGate
ProductionsPlanPhaseVerification ::= <AutoLoopback> "->" <VerifyPasses> "->" <Reconcile> "->" <CounterIncrement> "->" <PresentGate> VerifyPasses ::= "evidence" "," "completeness" "," "adversarial" PresentGate ::= "verificationPasses >= 1" Counter ::= "loop_owned" "not_model_emitted"
BeforeA plan presented to the user un-reviewed, its verified flag set by model tokens.
Afterauto loopback -> 3 passes{evidence, completeness, adversarial} -> reconcile findings -> loop-owned counter (not model-emitted) -> render blocked until verified
Governed Autonomous Plan Loop
- Math type: computation
- Yields: procedure
Details
FlowSeedPhase → Investigate → Execute → GatedSelfAuditAndInform → CaptureConsiderations → BoundaryReconcile → CloseGate → ReSeedNextPhase
ProductionsGovernedPlanLoop ::= <PhaseSeed> "->" <ActivityCycle> "->" <BoundaryReconciliation> "->" <PhaseCloseGate> "->" <ReSeed> ActivityCycle ::= "investigate" "->" "execute" "->" "verify" SelfDrive ::= <CanonSelfInform> "&" <SkepticalSweep> "&" <PlanMaintenance> Completion ::= "gated_state" "not_judgment_call"
Derivation map
BeforeA long task driven from conversation memory, self-declared done, losing mid-pass discoveries on restart.
Afterseed phase -> investigate -> execute -> gated self-audit + canon self-inform -> capture + reconcile at boundary -> close only on a mechanically-resolved gated state -> re-seed next phase
<Governed Plan Concern>
- Meta record
Details
FlowSeedPhase → GatedActivity → BoundaryReconcile → CloseGate → ReSeed
ProductionsGovernedPlanConcern ::= <PhaseSeed> "->" <GatedActivityCycle> "->" <BoundaryReconciliation> "->" <PhaseCloseGate> "->" <ReSeed> GatedActivityCycle ::= "investigate" "->" "execute" "->" "gated_self_audit"
living-profile
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_profile_compose["Profile Compose"]
n_delta_capture["Delta Capture"]
n_idempotent_merge["Idempotent Merge"]
n_version_provenance["Version Provenance"]
n_deterministic_merge_core["Deterministic Merge Core"]
n_persistence_fork["Persistence Fork"]
n_seed_composition["Seed Composition"]
n_living_profile_kernel["Living Profile Kernel"]
n_living_accumulation_concern["<Living Accumulation Concern>"]
n_living_profile_kernel --> n_seed_composition
n_living_profile_kernel --> n_delta_capture
n_living_profile_kernel --> n_idempotent_merge
n_living_profile_kernel --> n_version_provenance
n_living_profile_kernel --> n_persistence_fork
n_living_profile_kernel --> n_profile_compose
n_living_accumulation_concern --> n_version_provenance
n_living_accumulation_concern --> n_persistence_forkProfile Compose
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowStore → ReadDoc|Empty → StripVolatileMetadata → CompactView → ContextInjection
ProductionsProfileCompose ::= <ProfileStore> "->" (<StoredDocument> | <EmptyDocument>) "->" <MetadataStrip> "->" <CompactKnowledgeView> "->" <ContextEvidence> CompactKnowledgeView ::= <AxisSet> "without" <VolatileMetadata> ContextEvidence ::= "disclosed_as_memory" "," "not_ground_truth" "," "reverifiable_against_source"
BeforeAccumulated profile knowledge treated as ground truth, never re-verified.
Afterprofile store -> read doc (or empty) -> strip volatile metadata -> compact view -> injected as disclosed memory, reverifiable against source
Delta Capture
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowStructuredTurn → KnowledgeDelta|Null → VerifiedThisTurnFilter → AdmissibleDelta
ProductionsDeltaCapture ::= <StructuredTurn> "->" (<KnowledgeDelta> | <NullDelta>) "->" <EvidenceFilter> "->" <AdmissibleDelta> EvidenceFilter ::= "verified_this_turn" "->" "supported" | "unverified" "->" "unsupported_reject" AdmissibleDelta ::= <AxisDeltaSet>
BeforeA speculative claim written into durable memory without same-turn evidence.
Afterstructured turn -> knowledge delta -> keep only facts verified this turn -> admissible delta; unverified rejected
Idempotent Merge
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowDoc + Delta → StableFactIdentity → PerFieldKindMerge → DedupeAndCap → MergedDoc
ProductionsIdempotentMerge ::= <Document> "," <AdmissibleDelta> "->" <FactIdentitySet> "->" <PerFieldKindApplication> "->" <DedupeAndCap> "->" <MergedDocument> FieldKind ::= "scalar_overwrite" | "set_union" | "list_append_dedupe_cap" DedupeAndCap ::= "dedupe_by_stable_identity" "," "cap_list_axis_to_limit"
BeforeRe-applying the same delta grows an axis and changes the document.
Afterdoc + delta -> stable fact identity -> per-field-kind merge{overwrite | union | append-dedupe-cap} -> double-apply is a no-op
Version Provenance
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowMergedDoc → ChangeDetect → (NoOp | VersionBump + Timestamp + ModificationRecord) → VersionedDoc
ProductionsVersionProvenance ::= <MergedDocument> "->" <ChangeDetection> "->" (<NoOpOutcome> | <VersionedOutcome>) ChangeDetection ::= "merged_equals_prior" "->" "no_op" | "merged_differs" "->" "versioned" VersionedOutcome ::= <VersionBump> "," <Timestamp> "," <ModificationRecord> ModificationRecord ::= "at" "," "changed_axes" "," "prior_version"
BeforeA version bumped and mutated in place even on a no-op merge.
Aftermerged doc -> change detect -> {no-op: untouched | real change: bump + timestamp + modification record}
Deterministic Merge Core
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
Flow(Doc, Delta, Clock) → PureMerge → (Doc', Modification|Null)
ProductionsProfileMergeCore ::= <Document> "," <AdmissibleDelta> "," <InjectedClock> "->" <PureMerge> "->" (<NextDocument> "," <ModificationOrNull>) PurityConstraint ::= "no_hidden_state" "," "no_hidden_time" "," "no_hidden_randomness" "," "referential_transparency" InjectedClock ::= "now_supplied_by_adapter"
BeforeMerge reads the wall clock internally, so identical inputs differ.
After(doc, delta, injected clock) -> pure merge -> (doc', modification|null); no hidden time/state/randomness
Persistence Fork
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowConnectionMode → AuthoritativeStore|LimitedMirror → ScopedKey → Persist|MirrorReadOnly
ProductionsPersistenceFork ::= <ConnectionMode> "->" (<AuthoritativeStore> | <LimitedMirror>) "->" <ScopedOwnerKey> "->" <PersistenceOutcome> ConnectionMode ::= "trusted_arm_connected" | "disconnected_limited" PersistenceOutcome ::= "persist_write_back" | "mirror_read_only" ScopedOwnerKey ::= "stable_owner_identity" "," "sanitized"
BeforeAccumulation written to a fallback mirror, creating a divergent source of truth.
Afterconnection mode -> {trusted arm connected: authoritative per-owner store, write back | disconnected: read-only mirror}
Seed Composition
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowFrozenBaseline + ComposedKnowledge → AdditiveOverlay → TurnSeed
ProductionsSeedComposition ::= <FrozenBaseline> "," <ComposedKnowledgeView> "->" <AdditiveOverlay> "->" <TurnSeed> AdditiveOverlay ::= "baseline_immutable" "," "knowledge_appended_not_merged_into_baseline" TurnSeed ::= <BaselineScope> "," <AccumulatedKnowledge>
BeforeAccumulated knowledge merged into the baseline, rewriting frozen scope.
Afterfrozen baseline + composed knowledge -> additive overlay (baseline immutable) -> turn seed
Living Profile Kernel
- Math type: computation
- Yields: procedure
Details
FlowBaseline → Compose → Seed → Turn → Delta → Merge(Clock) → Version → Persist → (next turn)
ProductionsLivingProfileKernel ::= <SeedComposition> "->" <ReasoningTurn> "->" <DeltaCapture> "->" <IdempotentMerge> "->" <ProfileMergeCore> "->" <VersionProvenance> "->" <PersistenceFork> "->" <ProfileCompose> KernelInvariant ::= "grows_only_from_verified_evidence" "," "never_overrides_frozen_scope" "," "never_overrides_live_source" "," "bounded_and_idempotent" "," "auditable_and_reversible"
Derivation map
BeforePer-turn evidence written to memory ungated, unbounded, unversioned.
Aftercompose -> seed -> turn -> capture verified delta -> idempotent merge (injected clock) -> version only real change -> persist against the fork -> loop
<Living Accumulation Concern>
- Meta record
Details
FlowEvidence → Admissibility → IdempotentMerge → Provenance → Persistence → AdditiveOverlay
ProductionsLivingAccumulationConcern ::= <DisclosedMemory> "->" <AdmissibleDelta> "->" <IdempotentBoundedMerge> "->" <VersionProvenance> "->" <PersistenceFork> "->" <AdditiveBaselineOverlay> IdempotentBoundedMerge ::= "stable_identity" "," "dedupe" "," "cap" "," "double_apply_is_no_op"
mode-driven-response-schema
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_composed_turn_contract["Composed Turn Contract"]
n_loop_owned_mode_selection["Loop-Owned Mode Selection"]
n_versioned_turn_provenance["Versioned Turn Provenance"]
n_mode_contract_validation["Mode Contract Validation"]
n_mode_driven_response_schema["<Mode-Driven Response Schema>"]
n_loop_owned_mode_selection --> n_composed_turn_contract
n_loop_owned_mode_selection --> n_mode_contract_validation
n_loop_owned_mode_selection --> n_versioned_turn_provenance
n_mode_driven_response_schema --> n_composed_turn_contract
n_mode_driven_response_schema --> n_loop_owned_mode_selection
n_mode_driven_response_schema --> n_versioned_turn_provenanceComposed Turn Contract
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowRegisterField → SelectByMode → ProjectSchema → ProjectInstruction → StampVersion
ProductionsComposedTurnContract ::= <FieldRegistry> "->" <ModeProjection> "->" <SchemaAndInstruction> ModeKey ::= "(" "phase" "," "activity" ")" SchemaVersion ::= "content_hash" "(" <FieldSet> ")" Determinism ::= "same_mode" "->" "byte_identical" "(" <Schema> "," <Instruction> ")"
BeforeThe validation schema and the model's instruction hand-maintained twice, so they drift.
Afterfield registry -> project per (phase, activity) mode -> schema + instruction from ONE source -> same mode = byte-identical, changing a field changes both
Loop-Owned Mode Selection
- Math type: computation
- Yields: procedure
Details
FlowLoopAssignMode → ComposeContract → ValidateAgainstContract
ProductionsLoopOwnedModeSelection ::= <LoopAssignedMode> "->" <ComposeContract> "->" <ValidateResponse> ModeAuthority ::= "loop_owned" "not_model_selected"
Derivation map
BeforeThe model's output carries the field that selects which contract it's graded against.
Afterloop assigns (phase, activity) mode -> compose contract -> validate; the model can never grade itself against a contract it chose
Versioned Turn Provenance
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowStampVersion → AssignCausalOrder → AppendOnly → BumpOnChange → Query
ProductionsVersionedTurnProvenance ::= <SchemaVersion> "->" <CausalOrder> "->" <AppendOnlyRecord> CausalOrder ::= "single_writer_counter" "not" "disk_read_max" Provenance ::= "bump_on_real_change" "no_op_appends_nothing"
BeforeA turn graded against a schema version its stored state never saw.
Afteraccepted turn -> stamp version by content -> single-writer causal order -> append-only, mode-tagged record; a no-op appends nothing
Mode Contract Validation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowResponse → ValidateAgainstContract → Valid|SelfHealRetry → Accepted|Rejected
ProductionsModeContractValidation ::= <Response> "," <ModeContract> "->" <Validation> "->" (<Accepted> | <SelfHealRetry> "->" <ModeContractValidation>) SelfHealRetry ::= "error_specific_remediation" "(" <ValidationIssues> ")" "bounded"
BeforeA response accepted because it looked right, not because it satisfied the mode's schema.
Afterresponse + mode contract -> validate -> {valid | error-specific self-heal retry, bounded} -> accepted | rejected
<Mode-Driven Response Schema>
- Meta record
Details
FlowComposeContract → ValidateByMode → SelfRemediate → GovernFields → PersistVersioned
ProductionsModeDrivenResponseSchema ::= <ComposedTurnContract> "->" <LoopOwnedModeSelection> "->" <SelfRemediation> "->" <GroundingAdvisory> "->" <VersionedTurnProvenance> SingleSource ::= "instruction" "=" "validation" "=" "projection" "(" <FieldRegistry> ")" SelfRemediation ::= "error_specific_retry" "(" <ValidationIssues> "," <ModeContract> ")" GroundingAdvisory ::= "typed_field" "->" "validator" "(" "advisory_not_blocking" ")"
pag
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_pag_document_declaration["PAG Document Declaration"]
n_pag_keyword_ontology["PAG Keyword Ontology"]
n_pag_phase_decomposition["PAG Phase Decomposition"]
n_pag_validation_gate["PAG Validation Gate"]
n_pag_control_flow_determinism["PAG Control-Flow Determinism"]
n_pag_constraint_boundary["PAG Constraint Boundary"]
n_pag_tool_invocation["PAG Tool Invocation"]
n_pag_coordination_construct["PAG Coordination Construct"]
n_pag_ambiguity_reduction["PAG Ambiguity Reduction"]
n_pag_authoring_kernel["PAG Authoring Kernel"]
n_pag_well_formedness_validation["PAG Well-Formedness Validation"]
n_pag_instruction_concern["<PAG Instruction Concern>"]
n_pag_authoring_kernel --> n_pag_document_declaration
n_pag_authoring_kernel --> n_pag_keyword_ontology
n_pag_authoring_kernel --> n_pag_phase_decomposition
n_pag_authoring_kernel --> n_pag_validation_gate
n_pag_authoring_kernel --> n_pag_control_flow_determinism
n_pag_authoring_kernel --> n_pag_tool_invocation
n_pag_authoring_kernel --> n_pag_coordination_construct
n_pag_authoring_kernel --> n_pag_constraint_boundary
n_pag_authoring_kernel --> n_pag_well_formedness_validation
n_pag_well_formedness_validation --> n_pag_validation_gate
n_pag_well_formedness_validation --> n_pag_control_flow_determinismPAG Document Declaration
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowFrontmatter → TypeDeclaration → DefaultVerb → MetaBlock → DeclaredContract
ProductionsPagDocumentDeclaration ::= <Frontmatter> "->" <TypeDeclaration> "->" <MetaBlock> "->" <DeclaredContract> PagDocumentType ::= "AGENT" | "WORKFLOW" | "PROTOCOL" | "POLICY" | "CHECKLIST" | "TEMPLATE" | "TASK" | "INSTRUCTION" | "PROMPT" | "COMMAND" | "TEST" | "DEBUG" | "VERIFICATION" | "DISTILLATION" | "AUDIT" | "TRANSLATION" | "COMPOSITION" PagDocumentVerb ::= "IS" | "ENFORCES" | "EXECUTES" | "PERFORMS" | "PROVIDES" | "IMPLEMENTS" | "DEFINES" | "MANAGES" | "COORDINATES" | "HAS" | "GENERATES" | "RESOLVES" | "FINDS" | "FIXES" | "VERIFIES" | "CLASSIFIES" | "DISTILLS" | "ABSTRACTS" | "ELIMINATES" | "AUDITS" | "MEASURES" | "SCORES" | "CORRECTS" | "RENDERS" | "COMPOSES" | "FOLDS"
BeforeA document instructs with no declared type — its semantic contract is implicit.
Afterfrontmatter -> THIS {AGENT|WORKFLOW|CHECKLIST} {IS|EXECUTES|ENFORCES} description -> META block -> declared contract
PAG Keyword Ontology
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowProseIntent → KeywordCategory → UppercaseToken → PrepositionBinding → StructuredDirective
ProductionsPagKeywordOntology ::= <KeywordCategory> "->" <KeywordToken> "->" <PrepositionBinding> "->" <StructuredDirective> PagKeywordCategory ::= "action" | "control_flow" | "declaration" | "modifier" | "coordination" | "state_machine" | "dag" | "priority_queue" | "flowchart" | "document_type" PagPreposition ::= "FROM" | "TO" | "INTO" | "WITH" | "USING" | "AGAINST" | "IN" | "AS"
Before'Get the data and check it' — prose the model must interpret.
Afterprose intent -> uppercase token{READ|ANALYZE|VALIDATE} + preposition{FROM|INTO|AGAINST} -> structured directive, low interpretive variance
PAG Phase Decomposition
Details
FlowDirectiveSet → PhaseBoundary → DeclaredVariables → DataFlow → PhaseOutput
ProductionsPagPhaseDecomposition ::= <DirectiveSet> "->" <PhaseBoundarySet> "->" <DataFlowGraph> PagPhaseHeader ::= "#" "PHASE" <PhaseNumber> ":" <PhaseTitle> PagScopeRule ::= "declare_before_use" "," "document_wide_scope" "," "no_forward_reference"
BeforeDirectives poured in one flat block, forward-referencing later work.
Afterdirectives -> single-objective phases{declared inputs/outputs, declare-before-use, no forward reference} -> explicit data flow
PAG Validation Gate
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowPhaseOutput → CheckConditionSet → EvidenceOrAssertion → FailureAction → GateVerdict
ProductionsPagValidationGate ::= <PhaseOutput> "->" <CheckItemSet> "->" <OptionalFailureAction> "->" <GateVerdict> PagCheckMarker ::= "check" | "ASSERT" | "REQUIRE" | "ANALYZE" PagGateConstraint ::= "conditions_verifiable" "," "three_to_five_conditions" "," "no_vague_assertion" PagGateVerdict ::= "pass" | "fail_with_action"
BeforeA phase ends with 'looks good' — a vague, uncheckable assertion.
Afterphase output -> 3-5 verifiable checks{ASSERT | REQUIRE} + optional failure action -> gate verdict
PAG Control-Flow Determinism
- Stage: act
- Axis: formalisation
- Math type: logic
- Yields: boolean
Details
FlowCondition → BranchSet → IterationForm → FailureForm → DeterministicPath
ProductionsPagControlFlow ::= <Conditional> | <Iteration> | <FailureHandling> PagIteration ::= "FOR" "EACH" <Iterator> "IN" <Collection> ":" <DirectiveSet> PagControlConstraint ::= "colon_terminated" "," "for_each_not_for" "," "complete_branch_directives"
BeforeBranching and iteration inferred from prose order; a bare FOR, a missing colon.
AfterIF/ELSE IF/ELSE + FOR EACH x IN collection + TRY/CATCH -> every conditional colon-terminated, complete branch directives
PAG Constraint Boundary
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowBehaviorPolicy → AlwaysSet → NeverSet → WhenScopedSet → BoundaryContract
ProductionsPagConstraintBoundary ::= <AlwaysBlock> "," <NeverBlock> "," <WhenBlockSet> PagConstraintForm ::= "ALWAYS" | "NEVER" | "WHEN" PagConstraintQuality ::= "specific" "," "verifiable" "," "scoped"
BeforeBehavioral rules as general exhortation ('be careful with data').
AfterALWAYS + NEVER blocks + WHEN-scoped rules -> each constraint specific and verifiable, not vague guidance
PAG Tool Invocation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowToolVerb → ToolTarget → ParameterClause → ResultBinding → RuntimeAction
ProductionsPagToolInvocation ::= <ToolVerb> <ToolTarget> <OptionalParamClause> <OptionalResultClause> PagResultBinding ::= "INTO" <Identifier> | "->" <Identifier> | "AS" <Identifier>
BeforeAn external effect described in prose, not runtime-addressable.
Aftertool verb{READ|WRITE|GLOB|GREP|BASH} + WITH/USING params + INTO/-> result -> named effect with an explicit binding
PAG Coordination Construct
Details
FlowOrchestrationNeed → CoordinationConstruct → DependencyEdges → ExecutionSchedule
ProductionsPagCoordination ::= <StateMachine> | <Dag> | <PriorityQueue> | <ParallelBlock> PagCoordinationForm ::= "STATE_MACHINE" | "DAG" | "PRIORITY_QUEUE" | "PARALLEL" | "AWAIT"
BeforeConcurrency and ordering implied by the order sentences appear in.
Afterorchestration -> STATE_MACHINE | DAG{DEPENDS_ON, PARALLEL_GROUP} | PRIORITY_QUEUE | PARALLEL/AWAIT -> declared structure
PAG Ambiguity Reduction
Details
FlowProseAmbiguity → TokenStructure → PatternRecognition → ReducedVariance
ProductionsPagAmbiguityReduction ::= <ProseIntent> "->" <StructuredPattern> "->" <ReducedInterpretationLoad> PagApplicabilityBound ::= "input_shaping_only" "," "probabilistic_output" "," "not_always_applicable"
BeforeProse intent claimed to guarantee deterministic model output.
Afterprose -> structured tokens -> reduced interpretation load; input-shaping only, output stays probabilistic (tends-toward-deterministic, not guaranteed)
PAG Authoring Kernel
- Math type: computation
- Yields: procedure
Details
FlowDeclaration → MetaBlock → Variables → Phases → Gates → Directives → Constraints → PagDocument
ProductionsPagAuthoringKernel ::= <PagDocumentDeclaration> "->" <PagKeywordOntology> "->" <PagPhaseDecomposition> "->" <PagValidationGate> "->" <PagControlFlow> "->" <PagToolInvocation> "->" <PagCoordination> "->" <PagConstraintBoundary>
Derivation map
BeforeAn instruction written as prose, ungated and untyped.
Afterfrontmatter + typed declaration -> meta block -> variables -> phases each closed by a gate -> directives{keywords, control flow, tools, coordination} -> ALWAYS/NEVER
PAG Well-Formedness Validation
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowPagDocument → DefectScan → DefectSet → WellFormednessVerdict
ProductionsPagWellFormedness ::= <PagDocument> "->" <DefectScanSet> "->" <WellFormednessVerdict> PagDefect ::= "for_without_each" | "lowercase_keyword" | "missing_colon" | "phase_without_gate" | "vague_condition" | "prose_directive" PagWellFormednessVerdict ::= "well_formed" | "ill_formed"
BeforeA PAG document trusted because it reads fluently.
Afterdocument -> defect scan{for-without-each, lowercase keyword, missing colon, phase-without-gate, vague condition, prose directive} -> well-formed | ill-formed
<PAG Instruction Concern>
- Meta record
Details
FlowDocumentType → Keywords → Phases → Gates → ToolsAndCoordination → Constraints → WellFormedness
ProductionsPagInstructionConcern ::= <PagDocumentDeclaration> "->" <PagKeywordOntology> "->" <PagPhaseDecomposition> "->" <PagValidationGate> "->" <PagToolInvocation> "->" <PagCoordination> "->" <PagConstraintBoundary> "->" <PagWellFormedness>
pattern-distillation
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_analysis_workspace["Analysis Workspace"]
n_registry_baseline["Registry Baseline"]
n_compliance_gap["Compliance Gap"]
n_semantic_domain_partitioning["Semantic Domain Partitioning"]
n_behavioral_signature_extraction["Behavioral Signature Extraction"]
n_cross_class_pattern_detection["Cross-Class Pattern Detection"]
n_behavioral_inconsistency["Behavioral Inconsistency"]
n_sequential_chain_duplication["Sequential Chain Duplication"]
n_temporal_coupling_detection["Temporal Coupling Detection"]
n_relational_graph_duplication["Relational Graph Duplication"]
n_causal_wiring_duplication["Causal Wiring Duplication"]
n_anomaly_outlier_detection["Anomaly Outlier Detection"]
n_conceptual_duplication_detection["Conceptual Duplication Detection"]
n_fractal_scale_duplication["Fractal Scale Duplication"]
n_anti_pattern_classification["Anti-Pattern Classification"]
n_anti_pattern_priority_matrix["Anti-Pattern Priority Matrix"]
n_abstraction_boundary_principle["Abstraction Boundary Principle"]
n_base_class_candidate_selection["Base-Class Candidate Selection"]
n_concrete_vs_abstract_responsibility_split["Concrete-vs-Abstract Responsibility Split"]
n_template_method_lifecycle["Template Method Lifecycle"]
n_base_schematic_composition["Base Schematic Composition"]
n_migration_ordering["Migration Ordering"]
n_backup_verified_migration["Backup-Verified Migration"]
n_anti_pattern_elimination_verification["Anti-Pattern Elimination Verification"]
n_registry_regeneration["Registry Regeneration"]
n_anti_reintroduction_gate["Anti-Reintroduction Gate"]
n_distillation_metrics["Distillation Metrics"]
n_pattern_distillation_history["Pattern Distillation History"]
n_pattern_distillation_completion_truthfulness["Completion Truthfulness"]
n_pattern_distiller_kernel["Pattern Distiller Kernel"]
n_pattern_distillation_concern["<Pattern Distillation Concern>"]
n_pattern_distiller_kernel --> n_analysis_workspace
n_pattern_distiller_kernel --> n_registry_baseline
n_pattern_distiller_kernel --> n_compliance_gap
n_pattern_distiller_kernel --> n_semantic_domain_partitioning
n_pattern_distiller_kernel --> n_cross_class_pattern_detection
n_pattern_distiller_kernel --> n_anti_pattern_classification
n_pattern_distiller_kernel --> n_base_class_candidate_selection
n_pattern_distiller_kernel --> n_base_schematic_composition
n_pattern_distiller_kernel --> n_registry_regeneration
n_pattern_distiller_kernel --> n_distillation_metrics
n_pattern_distiller_kernel --> n_behavioral_signature_extraction
n_pattern_distiller_kernel --> n_anti_pattern_priority_matrix
n_pattern_distiller_kernel --> n_migration_ordering
n_pattern_distiller_kernel --> n_backup_verified_migration
n_pattern_distiller_kernel --> n_anti_pattern_elimination_verification
n_pattern_distiller_kernel --> n_pattern_distillation_history
n_pattern_distiller_kernel --> n_pattern_distillation_completion_truthfulnessAnalysis Workspace
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowSession → Workspace → ContextLoad → Manifest → Gate
ProductionsAnalysisWorkspace ::= <SessionId> "->" <WorkspacePath> "->" <ContextResourceSet> "->" <Manifest> "->" <InitializationGate> InitializationGate ::= "workspace_exists" "," "manifest_written" "," "baseline_docs_loaded" "," "registry_loaded"
BeforeRefactoring begins ad hoc, with no auditable record of what it started from.
Aftersession -> workspace{phase/metric/migration locations} -> load baseline + registries -> manifest -> block if required context missing
Registry Baseline
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowRegistry → ExistingAbstractions → ImplementationCounts → HierarchyMetrics → Baseline
ProductionsRegistryBaseline ::= <RegistryData> "->" <BaseAbstractionSet> "->" <ImplementationMetricSet> "->" <HierarchyMetricSet> "->" <BaselineReport> ImplementationMetricSet ::= "total_base_classes" "," "total_implementations" "," "implementation_count_by_base"
BeforeA new base abstraction created without measuring what already exists.
Afterregistry -> existing bases + implementation counts + hierarchy depth -> current abstraction state, before proposing a change
Compliance Gap
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowRoleClasses → ExpectedBaseRule → ConformingSet + NonconformingSet → ComplianceRate
ProductionsComplianceGap ::= <RoleClassSet> "->" <BaseExpectation> "->" <ConformanceScan> "->" <GapReport> BaseExpectation ::= <RoleName> "extends" <ExpectedBaseClass> GapReport ::= "noncompliant_count" "," "compliant_count" "," "compliance_rate"
Before'The Foos don't extend a base' — but is the base missing, or just its adoption?
Afterrole classes -> expected base rule -> conforming vs nonconforming -> compliance rate distinguishing missing adoption from missing abstraction
Semantic Domain Partitioning
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowResourceSet → RoleClassifier → SemanticDomains → DomainMetrics
ProductionsSemanticDomainPartitioning ::= <ResourceSet> "->" <RoleClassification> "->" <SemanticDomainSet> SemanticDomain ::= <DomainName> "," <ResourcePathSet> "," <ClassCount> "," <BehavioralSignatureSet> RoleClassification ::= "manager" | "repository" | "handler" | "service" | "controller" | "adapter" | "worker" | "unknown"
BeforeAbstractions drawn from arbitrary files instead of families of like responsibility.
Afterresources -> classify by role{manager|repository|handler|service|adapter} -> per-family analysis
Behavioral Signature Extraction
Details
FlowClassResource → BehaviorScan → Signature → DomainSignatureSet
ProductionsBehavioralSignature ::= <InitializationBehavior> "," <LifecycleBehavior> "," <ErrorHandlingBehavior> "," <StateManagementBehavior> "," <DependencyManagementBehavior> "," <PublicMethodPatternSet> LifecycleBehavior ::= "initialize" "," "destroy" "," "onInitialize" "," "onDestroy"
BeforeA base-class candidate proposed on naming similarity alone.
Afterclass -> scan{constructor, lifecycle hooks, error handling, state, dependencies, public methods} -> behavioral signature (evidence, not names)
Cross-Class Pattern Detection
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowDomainSignatures → CrossClassSearch → DuplicatePatternSet
ProductionsCrossClassPatternDetection ::= <BehavioralSignatureSet> "->" <RepeatedStructureSearch> "->" <CrossClassPatternSet> CrossClassPattern ::= <PatternName> "," <OccurrenceCount> "," <AffectedResourceSet> "," <PatternRole> PatternRole ::= "initialization" | "lifecycle" | "error_handling" | "state_management" | "dependency_management"
BeforeOne duplicated block noticed; the family-wide repetition stays invisible.
Aftersignatures -> search repeated{imports, init, lifecycle, error, state, deps} across the role family -> cross-class pattern + occurrence count
Behavioral Inconsistency
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowBehaviorFamily → VariationCounts → ConsistencyRate → NormalizeCandidate
ProductionsBehavioralInconsistency ::= <BehaviorFamily> "->" <VariationSet> "->" <ConsistencyMetric> "->" <InconsistencyVerdict> ConsistencyMetric ::= "max_variation_count / total_variation_count" InconsistencyVerdict ::= "consistent" | "weakly_consistent" | "inconsistent"
BeforeThree competing implementations of one behavior, none textually duplicated, so nothing flags.
Afterbehavior family -> variation counts -> consistency = dominant/total -> {consistent | weakly | inconsistent} -> normalize the inconsistent
Sequential Chain Duplication
Details
FlowRoleFamily → OrderedCallSequence → SequenceAlignment → RepeatedChainSet
ProductionsSequentialChainDuplication ::= <CallSequenceSet> "->" <SequenceAlignment> "->" <RepeatedOrderedChainSet> RepeatedOrderedChain ::= <OrderedStepList> "," <OccurrenceCount> "," <AffectedResourceSet>
BeforeTwo classes call the same steps in the same order, but no single block is textually identical, so frequency scanning finds nothing.
Afterrole family -> extract ordered call-sequence per class -> align sequences -> repeated ordered chain + occurrence count
Temporal Coupling Detection
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowRoleFamily → OrderingConstraintSet → CrossFamilyIntersection → SharedCouplingContract
ProductionsTemporalCouplingDetection ::= <OrderingConstraintSet> "->" <ConstraintIntersection> "->" <SharedTemporalContractSet> OrderingConstraint ::= <Operation> "must_precede" <Operation> | <Operation> "must_follow" <Operation>
BeforeEvery class re-encodes 'call setup before use, teardown after' as scattered ad-hoc ordering, and the shared lifecycle contract stays invisible.
Afterrole family -> must-precede/must-follow constraints per class -> intersect across family -> shared temporal-coupling contract
Relational Graph Duplication
Details
FlowRoleFamily → DependencySubgraph → SubgraphIsomorphism → RepeatedWiringSet
ProductionsRelationalGraphDuplication ::= <DependencySubgraphSet> "->" <IsomorphismScan> "->" <RepeatedWiringSubgraphSet> RepeatedWiringSubgraph ::= <NodeSet> "," <EdgeSet> "," <OccurrenceCount> "," <AffectedResourceSet>
BeforeThe same object graph — acquire A, wire B onto A, hand both to C — is reassembled by hand in every class.
Afterrole family -> dependency-acquisition subgraph per class -> subgraph isomorphism across family -> repeated wiring subgraph
Causal Wiring Duplication
Details
FlowRoleFamily → CausalEdgeSet → TriggerReactionMatch → RepeatedCausalWiringSet
ProductionsCausalWiringDuplication ::= <CausalEdgeSet> "->" <TriggerReactionMatch> "->" <RepeatedCausalWiringSet> CausalEdge ::= <Trigger> "causes" <Reaction> "," <OccurrenceCount>
BeforeThe same trigger-to-reaction wiring — this event runs that handler, that failure invokes this recovery — is duplicated across the family.
Afterrole family -> cause->effect edges per class -> match trigger/reaction pairs across family -> repeated causal-wiring set
Anomaly Outlier Detection
- Stage: see
- Axis: analysis
- Math type: probability
- Yields: number[0,1]
Details
FlowBehaviorFamily → DominantSignature → DeviationScore → OutlierSet
ProductionsAnomalyOutlierDetection ::= <BehaviorFamily> "->" <DominantSignature> "->" <DeviationScoreSet> "->" <OutlierSet> Outlier ::= <Resource> "," <DeviationScore> "," <DeviationReason>
BeforeA family shares one behavior — except the one class that does it differently, and a consistency ratio only reports 'weakly consistent' without naming the deviant.
Afterbehavior family -> per-class deviation score against the dominant signature -> outlier set + why each deviates -> normalize or justify
Conceptual Duplication Detection
- Stage: see
- Axis: analysis
- Math type: information-theory
- Yields: novelty-score
Details
FlowRoleFamily → SemanticSignature → MeaningCluster → ConceptualDuplicateSet
ProductionsConceptualDuplicationDetection ::= <SemanticSignatureSet> "->" <MeaningClustering> "->" <ConceptualDuplicateSet> SemanticSignature ::= <Intent> "," <InputOutputShape> "," <EffectSet>
BeforeTwo implementations mean the same thing under different names, so no textual, structural, or frequency scan flags them.
Afterrole family -> semantic signature per behavior (intent, inputs->outputs, effects) -> cluster by meaning not name -> same-meaning/different-name set + novelty score
Fractal Scale Duplication
Details
FlowCandidateShape → MultiScaleRecurrence → ScaleInvariance → AbstractionScale
ProductionsFractalScaleDuplication ::= <CandidateShape> "->" <MultiScaleRecurrenceScan> "->" <ScaleInvarianceVerdict> ScaleInvarianceVerdict ::= "method_scale" | "class_scale" | "module_scale" | "scale_invariant"
BeforeThe distiller scans one scale — the class family — and misses that the same shape repeats at the method level and again at the module level.
Aftercandidate shape -> test recurrence at method / class / module scale -> scale-invariant duplication + the scale the abstraction belongs at
Anti-Pattern Classification
Details
FlowFinding → AntiPatternRecord → PriorityInput
ProductionsAntiPatternClassification ::= <FindingSet> "->" <AntiPatternSet> AntiPattern ::= <AntiPatternType> "," <Pattern> "," <OccurrenceCount> "," <Impact> "," <Effort> "," <PriorityRank> "," <AffectedResourceSet> AntiPatternType ::= "copy_paste_duplication" | "behavioral_inconsistency" | "architectural_violation" | "conceptual_duplication" | "structural_duplication" | "sequential_duplication" | "temporal_coupling" | "relational_duplication" | "causal_duplication" | "scale_duplication" PriorityRank ::= "critical" | "high" | "medium" | "low"
BeforeFindings kept as loose notes, not comparable across the backlog.
Afterfindings -> anti-pattern records{type, occurrence, impact, effort, severity, affected resources}
Anti-Pattern Priority Matrix
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowAntiPattern → ImpactScore + EffortScore → Priority → SortedBacklog
ProductionsPriorityMatrix ::= <AntiPatternSet> "->" <ScoredAntiPatternSet> "->" <PriorityBandSet> ScoredAntiPattern ::= <AntiPattern> "," <ImpactScore> "," <EffortScore> "," <PriorityValue> PriorityValue ::= <ImpactScore> "*" <EffortScore> PriorityBand ::= "priority_1" | "priority_2" | "priority_3"
BeforeRefactoring picks a target by gut feel, not value.
Afteranti-patterns -> impact * effort -> priority -> sorted into remediation bands
Abstraction Boundary Principle
Details
FlowAntiPattern → BoundaryPrinciples → PrinciplesMet → AbstractionEligible
ProductionsBoundaryPrincipleEvaluation ::= <AntiPattern> "->" <BoundaryPrincipleSet> "->" <EligibilityVerdict> BoundaryPrincipleSet ::= "universal" "," "invariant" "," "foundational" "," "enforcing" "," "reducing_load" EligibilityVerdict ::= "base_candidate" | "utility_candidate" | "composition_candidate" | "local_refactor_only"
BeforeDuplication abstracted into a base whether or not the behavior belongs below the subclass boundary.
Afteranti-pattern -> boundary principles{universal, invariant, foundational, enforcing, load-reducing} -> {base | utility | composition | local-refactor}
Base-Class Candidate Selection
Details
FlowAntiPattern + DomainCoverage + BoundaryScore → Candidate|Reject
ProductionsBaseClassCandidateSelection ::= <AntiPattern> "," <DomainCoverage> "," <BoundaryScore> "->" <CandidateVerdict> CandidateVerdict ::= "create_base_class" | "prefer_composition" | "prefer_utility" | "reject_abstraction" DomainCoverage ::= "occurrence_count / total_domain_classes"
BeforeIncidental reuse promoted to inheritance.
Afteranti-pattern + domain coverage + boundary score -> verdict{create_base | prefer_composition | prefer_utility | reject}
Concrete-vs-Abstract Responsibility Split
Details
FlowFamilyBehaviorSet → InvariantPartition + VariantPartition → ConcreteBase + AbstractSeam
ProductionsResponsibilitySplit ::= <FamilyBehaviorSet> "->" <InvariantSet> "," <VariantSet> "->" <ConcreteBase> "," <AbstractSeamSet> InvariantSet ::= "behavior identical across every family member" VariantSet ::= "behavior that differs per family member" AbstractSeam ::= <VariantBehaviorName> "," <SeamKind> SeamKind ::= "hook" | "abstract_method" | "injected_strategy" | "parameter"
BeforeThe split is drawn from a fixed OOP lifecycle vocabulary (constructor/initialize/destroy/onInitialize/executeCore), which pre-decides the shape whether or not the family's behavior matches it.
Afterfamily behavior -> partition INVARIANT (identical across every member) from VARIANT (differs per member) -> invariant set = concrete base, variant set = the abstract seam; the hook names are read from the variant behavior, not assumed
Template Method Lifecycle
Details
FlowPublicMethod → Guard → SharedBehavior → Hook → ErrorPolicy → Result
ProductionsTemplateLifecycle ::= <LifecycleMethod> "->" <GuardCheck> "->" <SharedOperation> "->" <SubclassHook> "->" <ErrorHandlingPolicy> LifecycleMethod ::= "initialize" | "destroy" | "execute" | "process" SubclassHook ::= "onInitialize" | "onDestroy" | "onExecute" | "onProcess"
BeforeEach subclass re-implements the same guard-setup-cleanup lifecycle.
Afterpublic lifecycle method -> guard -> shared setup/cleanup -> subclass hook -> centralized error handling -> one predictable contract
Base Schematic Composition
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCandidate → GenerateBase → SizeCheck → SplitIfNeeded → BaseArtifact
ProductionsBaseSchematicComposition ::= <BaseClassCandidate> "->" <GeneratedBaseArtifact> "->" <ConstraintCheck> "->" <PersistableBaseArtifact> ConstraintCheck ::= "line_count <= max_allowed_lines" "," "name_matches_convention" "," "location_matches_architecture"
BeforeA base generated so large it becomes the new god object.
Aftercandidate -> generate base -> size <= max (split if oversized) + name + location conventions -> persistable base
Migration Ordering
Details
FlowTargetClasses → ComplexityMetric → SortedMigrationOrder
ProductionsMigrationOrdering ::= <TargetClassSet> "->" <ComplexityScoreSet> "->" <MigrationQueue> ComplexityScore ::= "line_count" | "method_count" | "dependency_count" | "state_property_count" MigrationQueue ::= "ascending_complexity"
BeforeThe most complex implementation migrated first, and the base is wrong before it's proven.
Aftertarget classes -> complexity score -> migrate ascending complexity -> prove the base on simple cases first
Backup-Verified Migration
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowBackup → Refactor → Verify → Commit|Restore
ProductionsMigrationExecution ::= <TargetClass> "->" <Checkpoint> "->" <RefactorToBase> "->" <Verification> "->" <MigrationOutcome> MigrationOutcome ::= "committed" | "restored_from_checkpoint" | "failed_with_log"
BeforeA refactor breaks a target and there is no way back.
Afterper target -> checkpoint -> refactor to the base -> verify the anti-pattern is gone -> commit | restore from checkpoint
Anti-Pattern Elimination Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowKnownAntiPattern → ScopeSearch → RemainingOccurrences → Pass|Fail
ProductionsAntiPatternElimination ::= <AntiPatternPatternSet> "->" <WholeScopeSearch> "->" <RemainingOccurrenceSet> "->" <EliminationVerdict> EliminationVerdict ::= "eliminated" | "remaining_unapproved_occurrences" | "base_only_occurrence"
BeforeDistillation declared done while the old pattern still lives at three sites.
Afterknown anti-pattern -> search the whole scope -> allow only approved base-location occurrences -> fail completion on unapproved duplicates
Registry Regeneration
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowRefactorResult → RegistryRegeneration → RegistryReadback → RepresentationCheck
ProductionsRegistryRegeneration ::= <MigrationResult> "->" <RegistryUpdate> "->" <UpdatedRegistry> "->" <RegistryVerification> RegistryVerification ::= "new_base_present" "," "implementation_count_updated" "," "old_pattern_absent_or_marked"
BeforeThe registry still reflects the pre-refactor architecture.
Aftermigration result -> regenerate registry -> reread -> confirm new base + migrated implementations represented
Anti-Reintroduction Gate
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowDistilledBoundary → LintRuleAuthored → PluginBuilt → CatalogRegenerated → EnforcedBoundary
ProductionsAntiReintroductionGate ::= <DistilledBoundary> "->" <CustomLintRule> "->" <PluginBuild> "->" <CatalogRegeneration> "->" <EnforcementVerdict> EnforcementVerdict ::= "gate_active" | "gate_absent"
BeforeThe distilled base eliminates the duplication today, but nothing stops the next author re-introducing the same anti-pattern — the gate held only for this run, by discipline.
Afterdistilled boundary -> author/strengthen a custom lint rule forbidding the anti-pattern + the base-bypass -> build the plugin -> regenerate the rule catalog -> the boundary is enforced structurally
Distillation Metrics
- Stage: verify
- Axis: verification
- Math type: probability
- Yields: number[0,1]
Details
FlowBeforeMetrics + AfterMetrics → ReductionMetrics → ROISummary
ProductionsDistillationMetrics ::= <BaselineMetricSet> "," <PostMigrationMetricSet> "->" <FinalMetricSet> FinalMetricSet ::= "duplication_reduction" "," "code_reduction" "," "base_class_adoption" "," "lines_saved" "," "maintenance_burden_reduction" "," "cognitive_load_reduction"
BeforeROI asserted ('much cleaner now') with no numbers.
Afterbefore + after -> {duplication reduction, code reduction, adoption rate, lines saved, maintenance + cognitive-load reduction}
Pattern Distillation History
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowSummary → HistoryAppend → MetricSnapshot → LessonsLearned
ProductionsDistillationHistory ::= <SummaryReport> "->" <HistoryLog> "->" <MetricStore> "->" <ReusableLearningSet> ReusableLearning ::= <Lesson> "," <Evidence> "," <ApplicabilityContext>
BeforeEach distillation forgets the last — the same lessons re-learned.
Aftersummary -> durable history log + metric snapshots + lessons -> reusable evidence for future abstraction decisions
Completion Truthfulness
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowPhaseGates → VerificationResults → Metrics → Complete|Incomplete
ProductionsDistillationCompletion ::= <InitializationGate> "," <RegistryGate> "," <SemanticAnalysisGate> "," <AntiPatternGate> "," <AbstractionGate> "," <MigrationGate> "," <EnforcementGate> "," <MetricsGate> "->" <CompletionVerdict> CompletionVerdict ::= "pattern_distillation_complete" | "pattern_distillation_incomplete"
Before'Done' asserted while verification, registry-update, and the anti-reintroduction gate never ran.
Aftergates{workspace, baseline, semantic, anti-pattern, abstraction, migration, verification, registry, enforcement, metrics} all pass -> complete; else incomplete
Pattern Distiller Kernel
- Math type: computation
- Yields: procedure
Details
FlowWorkspace → Registry → Semantics → AntiPatterns → Abstraction → Migration → Verification → Metrics → History
ProductionsPatternDistillerKernel ::= <AnalysisWorkspace> "->" <RegistryBaseline> "->" <ComplianceGap> "->" <SemanticDomainPartitioning> "->" <BehavioralSignature> "->" <CrossClassPatternDetection> "->" <AntiPatternClassification> "->" <PriorityMatrix> "->" <BoundaryPrincipleEvaluation> "->" <BaseClassCandidateSelection> "->" <ResponsibilitySplit> "->" <BaseSchematicComposition> "->" <MigrationExecution> "->" <AntiPatternElimination> "->" <RegistryRegeneration> "->" <DistillationMetrics> "->" <DistillationHistory>
Derivation map
BeforeRepeated behavior abstracted by intuition, migrated irreversibly, never verified.
Afterworkspace -> baseline -> semantics -> anti-patterns -> abstraction boundary -> base schematic -> reversible migration -> elimination proof -> registry regenerate -> ROI -> history
<Pattern Distillation Concern>
- Meta record
Details
FlowEvidence → Semantics → AntiPattern → Boundary → Abstraction → Migration → Verification → Metrics
ProductionsPatternDistillationConcern ::= <EvidenceWorkspace> "->" <ArchitecturalBaseline> "->" <SemanticDomainSet> "->" <BehavioralSignatureSet> "->" <AntiPatternSet> "->" <AbstractionBoundary> "->" <ReusableSchematic> "->" <MigrationPlan> "->" <EliminationVerification> "->" <ROIMetrics> AbstractionBoundary ::= "universal" "," "invariant" "," "foundational" "," "enforcing" "," "reducing_load"
quality-engine
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_quality_governance_loop["Quality Governance Loop"]
n_canonical_config_resolution["Canonical Config Resolution"]
n_stage_ordering["Stage Ordering"]
n_comment_normalization_remediation["Comment Normalization Remediation"]
n_custom_rule_derivation["Custom-Rule Derivation"]
n_machine_verdict_derivation["Machine Verdict Derivation"]
n_bounded_cascade_termination["Bounded Cascade Termination"]
n_quality_engine_concern["Quality-Engine Kernel"]
n_quality_governance_loop --> n_canonical_config_resolution
n_quality_governance_loop --> n_stage_ordering
n_quality_governance_loop --> n_comment_normalization_remediation
n_quality_governance_loop --> n_machine_verdict_derivation
n_quality_governance_loop --> n_bounded_cascade_termination
n_quality_engine_concern --> n_canonical_config_resolution
n_quality_engine_concern --> n_stage_ordering
n_quality_engine_concern --> n_quality_governance_loopQuality Governance Loop
- Math type: computation
- Yields: procedure
Details
FlowUpdate → Normalize → Resolve → Verify → Clean? → Fix → Reverify → Clean|Escalate
ProductionsQualityGovernanceLoop ::= <Update> "->" <NormalizationPrefix> "->" <CheckPlanResolution> "->" <Verification> "->" (<CleanVerdict> | <DownstreamFixCycle> "->" <QualityGovernanceLoop>) DownstreamFixCycle ::= <InScopeFindings> "->" <ModelFixBurst> "->" <Reapply> "->" <BoundedReverify> BoundedReverify ::= "passCount <= MAX_CASCADE_PASSES" "AND" "in_scope_findings_strictly_decrease" | "escalate"
Derivation map
BeforeA code edit judged clean by the model's read, not the machine verdict.
Afterapply -> normalize -> resolve CheckPlan -> verify -> {clean | fix in-scope + reverify, bounded, findings strictly decrease} -> clean | escalate
Canonical Config Resolution
Details
FlowCanonicalConfig → Expand → OwnershipResolution → ConflictDetection → HumanAuthorityRouting → ResolvedPlan|ConflictReport
ProductionsCanonicalConfigResolution ::= <CanonicalConfig> "->" <PerToolExpansion> "->" <SingleOwnerPerSurface> "->" <ConflictDetection> "->" (<ResolvedPlan> | <ConflictReport>) ConflictKind ::= "ownership_overlap" | "unsatisfiable_on_fixed" | "value_out_of_range" | "known_bad_pair" Resolution ::= "single_owner_enabled" | "route_to_human_authority_gate"
BeforeOne config expanded to many tools with contradictory, unowned rules.
Aftercanonical config -> per-tool expansion -> one owner per contested surface -> detect conflicts{ownership overlap, unsatisfiable, out-of-range, known-bad-pair} fail-closed -> resolved plan | conflict report
Stage Ordering
Details
FlowStages → RunnabilityDAG → InvalidatesTopoSort → BandPartition → OrderedStages
ProductionsStageOrdering ::= <StageSet> "->" <DependsOnDAG> "->" <InvalidatesOrder> "->" <BandPartition> "->" <OrderedStages> BandPartition ::= "normalization_prefix" "," "structural_band" "," "semantic_suffix" BackEdgePolicy ::= "allowed_only_in_semantic_suffix_resolved_at_runtime"
BeforeChecks run in arbitrary order, so a fix re-dirties an already-passed stage forever.
Afterstages -> runnability DAG (dependsOn) -> topo-order by invalidates (fixes point forward) -> bands{normalization prefix, structural, semantic suffix}; back-edges only in the suffix
Comment Normalization Remediation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowCanonicalRule + GrammarDescriptor → Compile → TokenScan|ASTBacking → DirectivePreservingStrip → CalibratedFix
ProductionsCommentNormalization ::= <CanonicalCommentRule> "->" <PerLanguageDescriptor> "->" <CompiledBacking> "->" <DirectivePreservingStrip> "->" <SafetyBoundary> CompiledBacking ::= "ast_lite_token_scan_in_memory" | "real_ast_via_tier_p_sandbox" SafetyBoundary ::= "tool_calibration" "," "adversarial_input_testing"
BeforeA comment-strip auto-fix hardcoded per language, so adding a language means new code.
Aftercanonical rule + comment-grammar descriptor -> compile per language -> token-scan (in-memory) | real-AST (sandbox) -> preserve directive comments -> trust only after calibration + adversarial test
Custom-Rule Derivation
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowEvidence → AntiPattern → BoundaryPrinciple → Candidate → Migrate → Verify → Admit|HumanGate
ProductionsCustomRuleDerivation ::= <RepeatedEvidence> "->" <AntiPatternClassification> "->" <BoundaryPrincipleEvaluation> "->" <CandidateSelection> "->" <BackupVerifiedMigration> "->" <SelfCertGate> SelfCertGate ::= "tightening_admitted" | "self_certifying_or_loosening_routes_to_human_authority"
BeforeThe AI authors and loosens a rule that governs its own output.
Afterrepeated evidence -> anti-pattern classify -> boundary principle -> candidate -> migrate with rollback -> verify elimination -> {tightening admitted | self-certify/loosen routes to the human gate}
Machine Verdict Derivation
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowCheckResults → ExitCodesAndFindings → MachineVerdict
ProductionsMachineVerdictDerivation ::= <CheckResults> "->" <ExitCodeAndFindingParse> "->" <MachineVerdict> MachineVerdict ::= "clean" | "violations"
BeforeA pass declared from the model's reading of the diff, not the tool's exit.
Aftercheck results -> exit codes + parsed findings -> machine verdict{clean | violations}; the model's read is never the signal
Bounded Cascade Termination
- Stage: terminate
- Axis: termination
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowPassResult → CompletionGate → Stop|Continue|Escalate
ProductionsBoundedCascadeTermination ::= <PassResult> "->" <CompletionGate> "->" (<Clean> | <BoundedContinue> | <Escalate>) CompletionGate ::= "clean" | "findings_strictly_decrease" "AND" "passCount <= MAX_CASCADE_PASSES" | "escalate"
BeforeA remediation cascade that loops until it happens to pass, or forever.
Aftereach pass -> {clean: stop | findings strictly decrease AND passCount <= MAX: continue | else: escalate}
Quality-Engine Kernel
- Meta record
Details
FlowPolicy → Resolve → Order → Normalize → Execute(G+P) → Verdict → Cascade → Clean|Escalate
ProductionsQualityEngineKernel ::= <QualityPolicy> "->" <CanonicalConfigResolution> "->" <StageOrdering> "->" <CommentNormalization> "->" <CheckPlanExecution> "->" <VerdictDerivation> "->" <QualityGovernanceLoop> CheckPlanExecution ::= "generation_checks_server_side" "," "project_commands_via_relay" VerdictDerivation ::= "exit_code" | "parse_findings" EngineBoundary ::= "pure_core_no_runtime_execution_behind_port_adapter"
taxonomy
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_taxonomy_jurisdiction["Taxonomy Jurisdiction"]
n_reshape_risk_priority["Reshape Risk Priority"]
n_path_role_walk["Path Role Walk"]
n_concern_classification["Concern Classification"]
n_name_projection["Name Projection"]
n_container_reshape["Container Reshape"]
n_vocabulary_admission_gate["Vocabulary Admission Gate"]
n_discovery_verification["Discovery Verification"]
n_taxonomy_ledger["Taxonomy Ledger"]
n_taxonomy_completion["Taxonomy Completion"]
n_taxonomy_kernel["Taxonomy Kernel"]
n_taxonomy_concern["<Taxonomy Concern>"]
n_taxonomy_kernel --> n_taxonomy_jurisdiction
n_taxonomy_kernel --> n_reshape_risk_priority
n_taxonomy_kernel --> n_path_role_walk
n_taxonomy_kernel --> n_concern_classification
n_taxonomy_kernel --> n_name_projection
n_taxonomy_kernel --> n_container_reshape
n_taxonomy_kernel --> n_vocabulary_admission_gate
n_taxonomy_kernel --> n_discovery_verification
n_taxonomy_kernel --> n_taxonomy_ledger
n_taxonomy_kernel --> n_taxonomy_completionTaxonomy Jurisdiction
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowRegistry → GovernedRootSet → ContainerSet → GovernedFileSet → FlaggedFolderSet
ProductionsTaxonomyJurisdiction ::= <Registry> "->" <GovernedRootSet> "->" <JurisdictionPartition> JurisdictionPartition ::= <GovernedFileSet> "," <IgnoredSet> "," <FlaggedFolderSet> GovernedRootSet ::= <ContainerSet> "," <BucketSet> "," <IgnoreSet>
BeforeWhether a file is governed is decided per file as it comes up, so an undeclared tree is silently exempt and a stray root-level folder reads as legitimate.
Afterregistry -> governed roots -> containers + buckets + ignore entries -> the governed file set, and the flagged set of root folders declared as neither
Reshape Risk Priority
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowContainerSet → ReferenceSurfaceCount → RiskScore → OrderedContainerQueue
ProductionsReshapeRiskPriority ::= <ContainerSet> "->" <RiskScoreSet> "->" <OrderedContainerQueue> RiskScore ::= <ImporterCount> "*" <ShapeDiscoveredSurfaceCount>
BeforeConversion starts wherever the tree looks worst, so the first container is the one with the most importers and the most pattern-resolved aggregators.
Aftercontainers -> score(importer count x shape-discovered surface count) -> ascending rank -> pilot the lowest-risk container end to end first
Path Role Walk
Details
FlowGovernedPath → DepthSequence → RoleAssignment → RoleEdgeList → DepthViolationSet
ProductionsPathRoleWalk ::= <GovernedPath> "->" <RoleAssignment> "->" <RoleEdgeList> "," <DepthViolationSet> RoleAssignment ::= <Container> "<" <Subject> "<" <Concern> DepthViolation ::= "over_cap" | "role_repeated" | "role_revisited" | "file_outside_concern"
BeforeA path is judged by whether it looks tidy, so a concern folder nested under a concern folder and a subject folder below its concern both read as ordinary nesting.
Afterpath -> assign each depth a role in the order container < subject < concern -> depth<=cap and no role repeated or revisited -> the role-assignment edge list plus the violating depths
Concern Classification
Details
FlowGovernedFile → PrimaryResponsibility → CandidateConcernSet → AssignedConcern → SplitCandidateSet
ProductionsConcernClassification ::= <GovernedFile> "->" <CandidateConcernSet> "->" <AssignedConcern> "|" <SplitCandidate> CandidateConcernSet ::= <PrimaryResponsibility> "->" <DeclaredConcern> "+" AssignedConcern ::= <NarrowestAccurateConcern> "|" <DomainWardTieBreak>
BeforeA file is tagged from where it currently sits, so a saturated label absorbs several distinct roles and a two-role file is hidden under whichever word came first.
Afterread the file -> narrowest accurate declared concern -> one concern: classified; two concerns: split candidate; irreducible overlap: domain-ward layer wins
Name Projection
Details
FlowAssignedConcern → SubjectSelection → VariantTrigger → TargetName → TargetFolderChain
ProductionsNameProjection ::= <AssignedConcern> "," <Subject> "," <VariantTrigger> "->" <TargetName> "," <TargetFolderChain> TargetName ::= <Subject> "." <Variant>? "." <ConcernTag> "." <Extension> TargetFolderChain ::= <Container> "/" <SubjectFolder>? "/" <ConcernFolder> VariantTrigger ::= "collision" | "facet" | "none"
BeforeThe new name is written by hand, so the tag lands mid-name, a compound swallows the concern, and the folder chain is chosen separately from the filename.
After(subject, variant?, concern, ext) -> foo.<variant>.<concern>.<ext> with the tag terminating -> the folder chain container/[subject]/<concern-folder> that the tag itself determines
Container Reshape
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowOrderedContainerQueue → SplitExecution → MoveRename → ImporterUpdate → TestMirrorMove → SurfaceRepoint
ProductionsContainerReshape ::= <Container> "->" <SplitExecution> "->" <MoveRename> "->" <ReferenceUpdate> "->" <SurfaceRepoint> ReferenceUpdate ::= <ImporterUpdate> "," <TestMirrorMove>
BeforeA rename tool rewrites every literal path across the whole tree at once, and the surfaces that resolve by pattern are never re-pointed.
Afterone container -> split candidates first -> move and rename -> update every importer -> move the mirrored tests -> re-point every shape-discovered surface -> gate green before the next container
Vocabulary Admission Gate
- Stage: constrain
- Axis: teleology
- Math type: optimisation
- Yields: boolean
Details
FlowProposedWord → CoverageCheck → CoveringConcern → IsATest → AdmissionVerdict
ProductionsVocabularyAdmissionGate ::= <ProposedWord> "->" <CoverageCheck> "->" <IsATest> "->" <AdmissionVerdict> CoverageCheck ::= <ProposedWord> "->" <RejectionTableIndex> "->" <CoveringConcern> "|" "uncovered" RejectionTableIndex ::= <RefusedWord> "->" <DeclaredConcern> AdmissionVerdict ::= "admit_concern" | "admit_subject" | "refuse_rename_file" | "refuse_covered_by" <CoveringConcern>
BeforeAn unclassifiable file is answered by adding its word to the vocabulary, or by an ignore entry, and the check goes green either way; where a word is refused, the refusal names only what is wrong.
Afterproposed word -> rejection-table index resolves the covering concern: refuse naming it, and rename the file -> uncovered: is-a a role: concerns; has-a a thing: subjects -> otherwise refuse; admission is a maintainer-approved registry edit
Discovery Verification
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowShapeDiscoveredSurfaceSet → CollectedSetBefore → CollectedSetAfter → DiscoveryVerdict
ProductionsDiscoveryVerification ::= <ShapeDiscoveredSurfaceSet> "->" <CollectedSetDelta> "->" <DiscoveryVerdict> CollectedSetDelta ::= <CollectedSetBefore> "-" <CollectedSetAfter> DiscoveryVerdict ::= "preserved" | "intended_change" | "silently_emptied"
BeforeThe gate is green after the rename, so the reshape is called done; the aggregator that collected by suffix now collects nothing and there is nothing left to check.
Afterper aggregator -> collected member set before vs after -> equal or intentionally changed: pass; silently emptied or shrunk: fail, and a green gate is not evidence
Taxonomy Ledger
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowRegistryVersion → ContainerConversionState → AdmissionRecordSet → TaxonomyLedger
ProductionsTaxonomyLedger ::= <RegistryVersion> "," <ContainerConversionState> "," <AdmissionRecordSet> AdmissionRecord ::= <ProposedWord> "," <AdmissionVerdict> "," <Reasoning>
BeforeWhich containers are converted and which words were refused is remembered rather than recorded, so the same rejected word is proposed again and the vocabulary drifts from the document.
Afterregistry version + per-container conversion state + admitted and refused words -> a durable ledger the next reshape and the next proposal both read
Taxonomy Completion
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowTaxonomyLedger → ResidualFindingSet → CompletionVerdict
ProductionsTaxonomyCompletion ::= <TaxonomyLedger> "->" <ResidualFindingSet> "->" <CompletionVerdict> ResidualFindingSet ::= <PlacementViolationSet> "+" <NamingViolationSet> "+" <SplitCandidateSet> "+" <UnverifiedSurfaceSet> CompletionVerdict ::= "taxonomy_complete" | "taxonomy_incomplete"
BeforeConversion is declared done on the container count, while unclassified files sit under an ignore entry and one aggregator still collects nothing.
Afterevery governed file placed and named to the grammar AND every split candidate resolved AND every surface verified preserved -> complete; any residual -> incomplete
Taxonomy Kernel
- Math type: computation
- Yields: procedure
Details
FlowJurisdiction → RiskPriority → RoleWalk → Classification → NameProjection → Reshape → AdmissionGate → DiscoveryVerification → Ledger → Completion
ProductionsTaxonomyKernel ::= <TaxonomyJurisdiction> "->" <ReshapeRiskPriority> "->" <PathRoleWalk> "->" <ConcernClassification> "->" <NameProjection> "->" <ContainerReshape> "->" <VocabularyAdmissionGate> "->" <DiscoveryVerification> "->" <TaxonomyLedger> "->" <TaxonomyCompletion>
Derivation map
BeforeNaming and placement are conventions carried in reviewers' heads, so a path has more than one right answer, an undeclared word enters whenever a file resists classification, and no pattern resolves a concern tree-wide.
Afterjurisdiction -> risk priority -> role walk -> classification -> name projection -> container reshape -> admission gate -> discovery verification -> ledger -> completion
<Taxonomy Concern>
- Meta record
Details
FlowJurisdiction → RoleWalk → Classification → NameProjection → Reshape → AdmissionGate → Verification → Ledger
ProductionsTaxonomyConcern ::= <GovernedRootSet> "->" <RoleEdgeList> "->" <AssignedConcern> "->" <TargetName> "," <TargetFolderChain> "->" <DiscoveryVerdict> "->" <TaxonomyLedger>
test-coverage
Every algorithm contract in this domain: its position on the derivation loop, its intent and invariant, the flow it walks, its productions as a grammar, what it composes and is composed by, which forces and principles it answers to, what grounds it and what it grounds, and, where the record carries one, an exemplar. The diagram shows what composes what inside the domain.
Relations diagram
flowchart LR
n_coverage_workspace["Coverage Workspace"]
n_surface_grid_walk["Surface Grid Walk"]
n_uncovered_gap_derivation["Uncovered Gap Derivation"]
n_coverage_risk_prioritisation["Coverage Risk Prioritisation"]
n_technique_invariant_selection["Technique and Invariant Selection"]
n_test_authoring["Test Authoring"]
n_evidence_verdict["Evidence Verdict"]
n_coverage_ledger["Coverage Ledger"]
n_coverage_completion["Coverage Completion"]
n_test_coverage_kernel["Test Coverage Kernel"]
n_test_coverage_concern["<Test Coverage Concern>"]
n_test_coverage_kernel --> n_coverage_workspace
n_test_coverage_kernel --> n_surface_grid_walk
n_test_coverage_kernel --> n_uncovered_gap_derivation
n_test_coverage_kernel --> n_coverage_risk_prioritisation
n_test_coverage_kernel --> n_technique_invariant_selection
n_test_coverage_kernel --> n_test_authoring
n_test_coverage_kernel --> n_evidence_verdict
n_test_coverage_kernel --> n_coverage_ledger
n_test_coverage_kernel --> n_coverage_completionCoverage Workspace
- Stage: orient
- Axis: ontology
- Math type: set-theory
- Yields: set | boolean
Details
FlowUnitUnderTest → SurfaceCatalog → CandidateSurfaceSet → CoverageWorkspace
ProductionsCoverageWorkspace ::= <UnitUnderTest> "->" <SurfaceCatalog> "->" <CandidateSurfaceSet>
BeforeTesting starts from whatever surfaces come to mind, with no record of the full space a system can fail in.
Afterunit under test -> load the test-surface catalog{dimension x lens -> invariant, technique} -> a coverage workspace enumerating every surface the unit CAN carry
Surface Grid Walk
- Stage: see
- Axis: analysis
- Math type: set-theory
- Yields: set | boolean
Details
FlowSurfaceCatalog → GridWalk → PresentCellSet → CandidateGapSet
ProductionsSurfaceGridWalk ::= <CandidateSurfaceSet> "->" <DimensionLensGrid> "->" <PresentCellSet> "," <CandidateGapSet> DimensionLensGrid ::= <OntologyDimension> "x" <AnalysisLens>
BeforeCoverage is asserted from the surfaces already tested, so the empty cells of the dimension x lens grid stay invisible.
Aftercatalog -> walk (dimension x lens) grid -> present cells (a surface exists) vs empty cells (no surface) -> the candidate-gap set the anomaly lens surfaces
Uncovered Gap Derivation
Details
FlowCandidateGapSet → FailabilityFilter → RequiredUncoveredSet
ProductionsUncoveredGapDerivation ::= <CandidateGapSet> "->" <FailabilityFilter> "->" <RequiredUncoveredSet>
BeforeThe gap set is treated as final, so cells that cannot fail for this unit are chased and real gaps are diluted.
Aftercandidate gaps -> keep only cells this unit CAN fail in -> required-but-uncovered set = the surfaces still owed a test
Coverage Risk Prioritisation
- Stage: intent
- Axis: teleology
- Math type: optimisation
- Yields: boolean | ranking
Details
FlowRequiredUncoveredSet → RiskScore → PrioritisedSurfaceQueue
ProductionsCoverageRiskPrioritisation ::= <RequiredUncoveredSet> "->" <RiskScoreSet> "->" <PrioritisedSurfaceQueue> RiskScore ::= <FailureImpact> "*" <Reachability>
BeforeEvery uncovered surface is treated as equally urgent, so a rarely-hit cosmetic gap competes with an unguarded security boundary.
Afterrequired-uncovered surfaces -> failure-impact x reachability -> priority -> the highest-risk surfaces first
Technique and Invariant Selection
Details
FlowSurface → InvariantStatement → ModeMatchedTechnique → SurfacePlan
ProductionsTechniqueInvariantSelection ::= <Surface> "->" <Invariant> "," <ModeMatchedTechnique> "->" <SurfacePlan>
BeforeA test is written before deciding what must hold or how to obtain evidence, so it asserts an accidental condition with the wrong technique.
Aftersurface -> state its invariant (the assertion) -> pick the technique whose reasoning mode matches how the surface is observed -> a matched (invariant, technique) plan
Test Authoring
- Stage: act
- Axis: formalisation
- Math type: computation
- Yields: procedure
Details
FlowSurfacePlan → PredicateAssertion → EvidenceWiring → RunnableTest
ProductionsTestAuthoring ::= <SurfacePlan> "->" <PredicateAssertion> "," <EvidenceWiring> "->" <RunnableTest>
BeforeThe plan stays a note; the predicate is never realized as an executable check that gathers evidence.
Aftersurface plan -> realize the predicate as an executable assertion -> wire the evidence source the technique requires -> a runnable test for the surface
Evidence Verdict
- Stage: verify
- Axis: verification
- Math type: logic
- Yields: boolean
Details
FlowRunnableTest → EvidenceSet → Verdict
ProductionsEvidenceVerdict ::= <RunnableTest> "->" <EvidenceSet> "->" <Verdict> Verdict ::= "pass" | "fail" | "unknown"
BeforeA surface with no run is silently treated as passing, so absence of evidence reads as evidence of correctness.
Afterrun the test -> gather evidence -> non-empty evidence set: pass or fail; empty evidence set: unknown (the coverage-gap state), never pass
Coverage Ledger
- Stage: commit
- Axis: representation
- Math type: information-theory
- Yields: hash | novelty-score
Details
FlowVerdictSet → CoverageLedger → ResidualGapSet
ProductionsCoverageLedger ::= <VerdictSet> "->" <SurfaceLedger> "->" <ResidualGapSet>
BeforeEach run forgets the last, so which surfaces are covered, uncovered, or unknown must be re-derived every time.
Afterverdicts -> a durable coverage ledger{surface -> verdict} + the residual uncovered/unknown set -> reusable coverage state
Coverage Completion
- Stage: terminate
- Axis: termination
- Math type: logic
- Yields: boolean
Details
FlowCoverageLedger → RequiredSurfaceCheck → CompletionVerdict
ProductionsCoverageCompletion ::= <CoverageLedger> "->" <RequiredSurfaceCheck> "->" <CompletionVerdict> CompletionVerdict ::= "coverage_complete" | "coverage_incomplete"
BeforeCoverage is declared done while required surfaces remain unknown, so the untested cells hide behind an aggregate percentage.
Afterledger -> every required surface carries a surface + technique + invariant AND a non-unknown verdict -> complete; any required-unknown remains -> incomplete
Test Coverage Kernel
- Math type: computation
- Yields: procedure
Details
FlowWorkspace → GridWalk → GapDerivation → RiskPriority → TechniqueInvariant → TestAuthoring → EvidenceVerdict → Ledger → Completion
ProductionsTestCoverageKernel ::= <CoverageWorkspace> "->" <SurfaceGridWalk> "->" <UncoveredGapDerivation> "->" <CoverageRiskPrioritisation> "->" <TechniqueInvariantSelection> "->" <TestAuthoring> "->" <EvidenceVerdict> "->" <CoverageLedger> "->" <CoverageCompletion>
Derivation map
BeforeCoverage is pursued by intuition and reported as a percentage, so the space a system can fail in is never walked and unknown surfaces pass silently.
Afterworkspace -> grid walk -> gap derivation -> risk priority -> technique+invariant -> authored test -> evidence verdict -> ledger -> completion
<Test Coverage Concern>
- Meta record
Details
FlowSurfaceSpace → GridWalk → RequiredGaps → Priority → TechniqueInvariant → AuthoredTest → Verdict → Ledger
ProductionsTestCoverageConcern ::= <SurfaceCatalog> "->" <DimensionLensGrid> "->" <RequiredUncoveredSet> "->" <PrioritisedSurfaceQueue> "->" <SurfacePlanSet> "->" <RunnableTestSet> "->" <VerdictSet> "->" <CoverageLedger>