Skip to content

foryourhealth111-pixel/Vibe-Skills

Vibe Code Orchestrator (VCO) is a governed runtime entry that freezes requirements, bounds execution, and enforces verification and phase cleanup.

FileKindSize
SKILL.mdskill md17.2 KB
agents/templates/debugger.mdmarkdown323 B
agents/templates/planner.mdmarkdown313 B
agents/templates/reviewer.mdmarkdown331 B
agents/templates/security-reviewer.mdmarkdown341 B
references/change-proof-matrix.mdmarkdown2.6 KB
references/contributor-zone-decision-table.mdmarkdown2.2 KB
references/developer-entry-contract.mdmarkdown2.7 KB
references/fixtures/external-corpus/external-corpus-gate.jsonconfig8.6 KB
references/fixtures/external-corpus/prompt-signals.jsonconfig412.4 KB
references/fixtures/external-corpus/skill-keyword-index.backup.jsonconfig30.6 KB
references/fixtures/external-corpus/skill-keyword-index.candidate.jsonconfig26.5 KB
references/fixtures/external-corpus/vco-suggestions.jsonconfig16.6 KB
references/fixtures/migration-map.jsonconfig7.8 KB
references/fixtures/retro-compare/safety-gate/baseline-cer.jsonconfig294 B
references/fixtures/retro-compare/safety-gate/current-cer.jsonconfig1.1 KB
references/fixtures/retro-compare/safety-gate/delta.jsonconfig1.0 KB
references/fixtures/retro-compare/sample-run/baseline-cer.jsonconfig324 B
references/fixtures/retro-compare/sample-run/current-cer.jsonconfig1.2 KB
references/fixtures/retro-compare/sample-run/delta.jsonconfig1.0 KB
references/fixtures/retro-compare/smoke/baseline-smoke.jsonconfig266 B
references/fixtures/retro-compare/smoke/current-smoke.jsonconfig1.0 KB
references/fixtures/retro-compare/smoke/delta-smoke.jsonconfig1.0 KB
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/cleanup-receipt.jsonconfig1.3 KB
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/governance-capsule.jsonconfig408 B
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/intent-contract.jsonconfig2.2 KB
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/phase-plan-execute.jsonconfig2.4 KB
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/skeleton-receipt.jsonconfig722 B
references/fixtures/runtime/vibe-sessions/20260413T131910Z-pr153-rabbit-review-fix/stage-lineage.jsonconfig1.3 KB
references/fixtures/skills-audit/bio-science-problem/bio-science-problem-map.csvother9.2 KB
references/fixtures/skills-audit/bio-science-problem/bio-science-problem-map.jsonconfig18.1 KB
references/fixtures/verify/routing-stability/vibe-routing-stability-gate.jsonconfig24.4 KB
references/index.mdmarkdown1.3 KB
references/proof-bundles/claude-code-managed-closure-candidate/linux-managed-run-01-local-host/installed-runtime-outputs/runtime-freshness-receipt.jsonconfig262 B
references/proof-bundles/claude-code-managed-closure-candidate/manifest.jsonconfig2.6 KB
references/proof-bundles/linux-full-authoritative-candidate/linux-pwsh-run-01-wsl/installed-runtime-outputs/runtime-freshness-receipt.jsonconfig298 B
references/proof-bundles/linux-full-authoritative-candidate/linux-pwsh-run-02-docker/installed-runtime-outputs/runtime-freshness-receipt.jsonconfig298 B
references/proof-bundles/linux-full-authoritative-candidate/manifest.jsonconfig3.3 KB
references/proof-bundles/openclaw-runtime-core-preview-candidate/manifest.jsonconfig1.9 KB
references/release-ledger.jsonlother5.1 KB
scripts/README.mdmarkdown1.7 KB
scripts/bootstrap/one-shot-setup.ps1script797 B
scripts/bootstrap/one-shot-setup.shscript482 B
scripts/bootstrap/scaffold-claude-preview.ps1script875 B
scripts/bootstrap/scaffold-claude-preview.shexecutablescript866 B
scripts/bootstrap/sync-local-compat.ps1script2.6 KB
scripts/common/AntiProxyGoalDrift.ps1script15.1 KB
scripts/common/NodeLaunchWrapper.ps1script13.1 KB
scripts/common/ProcessLedger.ps1script27.1 KB
scripts/common/ProtectedDocumentCleanup.ps1script6.9 KB
scripts/common/README.mdmarkdown1.9 KB
scripts/common/Resolve-VgoAdapter.ps1script4.3 KB
scripts/common/adapter_registry_query.pyexecutablescript3.8 KB
scripts/common/python_helpers.shscript2.8 KB
scripts/common/resolve_vgo_adapter.pyexecutablescript2.4 KB
scripts/common/runtime_contracts.pyscript3.7 KB
scripts/common/vibe-governance-helpers.ps1script75.6 KB
scripts/common/vibe-wave-gate-runner.ps1script28.3 KB
scripts/governance/Invoke-NodeProcessAudit.ps1script3.6 KB
scripts/governance/Invoke-NodeZombieCleanup.ps1script3.7 KB
scripts/governance/README.mdmarkdown5.1 KB
scripts/governance/audit-upstream.ps1script22.7 KB
scripts/governance/export-repo-cleanliness-inventory.ps1script8.6 KB
scripts/governance/install-local-worktree-excludes.ps1script2.0 KB
scripts/governance/invoke-mem0-policy.ps1script1.0 KB
scripts/governance/invoke-openspec-governance.ps1script8.6 KB
scripts/governance/new-origin-record.ps1script3.3 KB
scripts/governance/phase-end-cleanup.ps1script10.7 KB
scripts/governance/publish-absorption-soft-rollout.ps1script3.2 KB
scripts/governance/publish-openspec-soft-rollout.ps1script9.3 KB
scripts/governance/release-cut.ps1script25.1 KB
scripts/governance/set-gsd-overlay-rollout.ps1script3.9 KB
scripts/governance/set-openspec-rollout.ps1script3.1 KB
scripts/governance/sync-bundled-vibe.ps1script20.3 KB
scripts/install/Install-VgoAdapter.ps1script2.0 KB
scripts/install/install_vgo_adapter.pyexecutablescript524 B
scripts/overlay/README.mdmarkdown885 B
scripts/overlay/suggest-browserops-provider.ps1script9.3 KB
scripts/overlay/suggest-overlays.ps1script17.3 KB
scripts/release/build_release_bundle.pyscript6.5 KB
scripts/research/README.mdmarkdown1.1 KB
scripts/research/build-eval-slicing-catalog.ps1script2.6 KB
scripts/research/build-watch-portfolio-review.ps1script3.5 KB
scripts/research/build-xl-operator-checklist.ps1script2.3 KB
scripts/research/extract-prompt-signals.ps1script6.7 KB
scripts/research/generate-vco-suggestions.ps1script9.7 KB
scripts/research/sync-mcp-catalog.ps1script3.5 KB
scripts/research/vibe-adaptive-train.ps1script10.1 KB
scripts/router/README.mdmarkdown1.8 KB
scripts/router/invoke-pack-route.pyscript428 B
scripts/router/modules/00-core-utils.ps1script14.6 KB
scripts/router/modules/01-openai-responses.ps1script17.9 KB
scripts/router/modules/10-observability.ps1script11.7 KB
scripts/router/modules/11-route-probe.ps1script20.7 KB
scripts/router/modules/12-heartbeat.ps1script19.9 KB
scripts/router/modules/19-custom-admission.ps1script16.3 KB
scripts/router/modules/20-routing-rules.ps1script1.7 KB
scripts/router/modules/21-capability-interview.ps1script11.8 KB
scripts/router/modules/22-intent-contract.ps1script18.2 KB
scripts/router/modules/30-openspec.ps1script8.3 KB
scripts/router/modules/31-gsd-overlay.ps1script5.5 KB
scripts/router/modules/32-prompt-overlay.ps1script8.0 KB
scripts/router/modules/33-memory-governance.ps1script5.5 KB
scripts/router/modules/34-data-scale-overlay.ps1script25.8 KB
scripts/router/modules/35-quality-debt-overlay.ps1script13.4 KB
scripts/router/modules/36-framework-interop-overlay.ps1script16.9 KB
scripts/router/modules/37-ml-lifecycle-overlay.ps1script22.4 KB
scripts/router/modules/38-python-clean-code-overlay.ps1script16.2 KB
scripts/router/modules/39-system-design-overlay.ps1script15.5 KB
scripts/router/modules/40-cuda-kernel-overlay.ps1script17.7 KB
scripts/router/modules/42-ai-rerank-overlay.ps1script14.0 KB
scripts/router/modules/43-retrieval-overlay.ps1script22.4 KB
scripts/router/modules/44-dialectic-team-gate.ps1script7.5 KB
scripts/router/modules/44-exploration-overlay.ps1script17.7 KB
scripts/router/modules/45-daily-dialectic-guard.ps1script6.6 KB
scripts/router/modules/47-closure-overlay.ps1script9.2 KB
scripts/router/modules/48-llm-acceleration-overlay.ps1script104.6 KB
scripts/router/modules/49-prompt-asset-boost.ps1script28.3 KB
scripts/router/resolve-pack-route.ps1script4.1 KB
scripts/router/runtime_neutral/custom_admission.pyscript349 B
scripts/router/runtime_neutral/router_contract.pyscript356 B
scripts/ruc-nlpir/preflight.ps1script5.3 KB
scripts/runtime/Freeze-RuntimeInputPacket.ps1script33.0 KB
scripts/runtime/Invoke-AntiProxyGoalDriftCompaction.ps1script551 B
scripts/runtime/Invoke-DeepInterview.ps1script1.1 KB
scripts/runtime/Invoke-PhaseCleanup.ps1script11.1 KB
scripts/runtime/Invoke-PlanExecute.ps1script13.7 KB
scripts/runtime/Invoke-SkeletonCheck.ps1script3.1 KB
scripts/runtime/Invoke-VibeCanonicalEntry.ps1script12.9 KB
scripts/runtime/VibeMemoryActivation.Common.ps1script41.3 KB
scripts/runtime/VibeMemoryBackends.Common.ps1script12.4 KB
scripts/runtime/VibeRuntime.Common.ps1script298.6 KB
scripts/runtime/VibeSkillRouting.Common.ps1script19.0 KB
scripts/runtime/VibeWorkspaceMemory.Common.ps1script6.9 KB
scripts/runtime/Write-RequirementDoc.ps1script23.7 KB
scripts/runtime/Write-XlPlan.ps1script32.3 KB
scripts/runtime/invoke-vibe-runtime.ps1script69.7 KB
scripts/runtime/memory_backend_driver.pyscript14.2 KB
scripts/runtime/skill_authority_driver.pyscript375 B
scripts/runtime/workspace_memory_driver.pyscript24.8 KB
scripts/setup/check-kvm-host-readiness.shscript3.4 KB
scripts/setup/check-windows-eval-iso-readiness.shexecutablescript2.2 KB
scripts/setup/check-windows-proof-vm-state.shexecutablescript2.0 KB
scripts/setup/export-codex-settings-sanitized.ps1script2.6 KB
scripts/setup/fetch-windows11-eval-iso.shexecutablescript4.1 KB
scripts/setup/install-local-vm-host.shexecutablescript1.6 KB
scripts/setup/persist-codex-openai-env.ps1script2.4 KB
scripts/setup/run-windows-proof-vm.shexecutablescript11.4 KB
scripts/setup/send-qmp-boot-keys.pyexecutablescript3.0 KB
scripts/setup/send-qmp-text.pyexecutablescript3.0 KB
scripts/setup/show-windows-proof-media-options.shexecutablescript1.6 KB
scripts/setup/stop-windows-proof-vm.shexecutablescript1.6 KB
scripts/setup/sync-codex-settings-to-user-env.ps1script2.6 KB
scripts/uninstall/Uninstall-VgoAdapter.ps1script1.4 KB
scripts/uninstall/uninstall_vgo_adapter.pyscript526 B
scripts/verify/README.mdmarkdown3.8 KB
scripts/verify/cer-compare.ps1script8.5 KB
scripts/verify/fixtures/README.mdmarkdown1.1 KB
scripts/verify/fixtures/document-cleanup-safety/README.mdmarkdown527 B
scripts/verify/fixtures/document-cleanup-safety/ambiguous-cn-set/metadata.jsonconfig101 B
scripts/verify/fixtures/document-cleanup-safety/ambiguous-cn-set/source/.tmp/docs/重庆市永川区技术预见与制度创新项目申报书1-修订版.docxbinary56 B
scripts/verify/fixtures/document-cleanup-safety/ambiguous-cn-set/source/.tmp/docs/重庆市永川区技术预见与制度创新项目申报书1-补充材料.pdfbinary56 B
scripts/verify/fixtures/document-cleanup-safety/ambiguous-cn-set/source/docs/重庆市永川区技术预见与制度创新项目申报书1-正式版.docxbinary36 B
scripts/verify/fixtures/document-cleanup-safety/mixed-office-assets/metadata.jsonconfig101 B
scripts/verify/fixtures/document-cleanup-safety/mixed-office-assets/source/.tmp/staging/budget-review.xlsxbinary59 B
scripts/verify/fixtures/document-cleanup-safety/mixed-office-assets/source/.tmp/staging/quarterly-review-deck.pptxbinary60 B
scripts/verify/fixtures/document-cleanup-safety/mixed-office-assets/source/docs/reference-manual.pdfbinary21 B
scripts/verify/fixtures/document-cleanup-safety/non-protected-control/metadata.jsonconfig101 B
scripts/verify/fixtures/document-cleanup-safety/non-protected-control/source/.tmp/control.txtmarkdown54 B
scripts/verify/fixtures/llm-acceleration.mock.jsonconfig1.0 KB
scripts/verify/fixtures/pilot-browserops.jsonconfig541 B
scripts/verify/fixtures/pilot-deep-extraction.jsonconfig731 B
scripts/verify/fixtures/pilot-desktopops.jsonconfig587 B
scripts/verify/fixtures/pilot-memory.jsonconfig575 B
scripts/verify/fixtures/pilot-prompt.jsonconfig525 B
scripts/verify/fixtures/process-health/external-node-protected-fixture.jsonconfig345 B
scripts/verify/fixtures/process-health/healthy-managed-fixture.jsonconfig1.1 KB
scripts/verify/fixtures/process-health/managed-completed-alive-fixture.jsonconfig1.2 KB
scripts/verify/fixtures/process-health/managed-stale-fixture.jsonconfig1.1 KB
scripts/verify/fixtures/process-health/no-node-processes-fixture.jsonconfig131 B
scripts/verify/fixtures/prompt-asset-boost.mock.jsonconfig1.2 KB
scripts/verify/gate-family-index.mdmarkdown2.5 KB
scripts/verify/lib/VibeOfflineSkillsAudit.Suites.ps1script11.8 KB
scripts/verify/lib/VibeOfflineSkillsAudit.ps1script12.2 KB
scripts/verify/lib/VibeRouteAudit.Suites.ps1script7.9 KB
scripts/verify/lib/VibeRouteAudit.ps1script5.2 KB
scripts/verify/live-document-gate.pyscript7.6 KB
scripts/verify/probe-scientific-packs.ps1script55.1 KB
scripts/verify/publish-proof.pyscript409 B
scripts/verify/runtime_neutral/README.mdmarkdown2.5 KB
scripts/verify/runtime_neutral/_bootstrap.pyscript321 B
scripts/verify/runtime_neutral/bio_science_pack_consolidation_audit.pyscript421 B
scripts/verify/runtime_neutral/bootstrap_doctor.pyscript494 B
scripts/verify/runtime_neutral/code_quality_pack_consolidation_audit.pyscript717 B
scripts/verify/runtime_neutral/coherence_gate.pyscript529 B
scripts/verify/runtime_neutral/freshness_gate.pyscript494 B
scripts/verify/runtime_neutral/global_pack_consolidation_audit.pyscript635 B
scripts/verify/runtime_neutral/ml_skills_pruning_audit.pyscript574 B
scripts/verify/runtime_neutral/opencode_preview_smoke.pyscript674 B
scripts/verify/runtime_neutral/release_notes_quality.pyscript701 B

scripts/runtime/invoke-vibe-runtime.ps1

View on GitHub
param(
    [Parameter(Mandatory)] [string]$Task,
    [ValidateSet('interactive_governed')] [string]$Mode = 'interactive_governed',
    [string]$RunId = '',
    [AllowEmptyString()] [string]$WorkspaceRoot = '',
    [string]$ArtifactRoot = '',
    [AllowEmptyString()] [string]$EntryIntentId = '',
    [AllowEmptyString()] [string]$RequestedStageStop = '',
    [AllowEmptyString()] [string]$RequestedGradeFloor = '',
    [AllowEmptyString()] [string]$HostDecisionJson = '',
    [AllowEmptyString()] [string]$ModuleExecutionJsonFile = '',
    [AllowEmptyString()] [string]$GovernanceScope = '',
    [AllowEmptyString()] [string]$RootRunId = '',
    [AllowEmptyString()] [string]$ParentRunId = '',
    [AllowEmptyString()] [string]$ParentUnitId = '',
    [AllowEmptyString()] [string]$InheritedRequirementDocPath = '',
    [AllowEmptyString()] [string]$InheritedExecutionPlanPath = '',
    [AllowEmptyString()] [string]$DelegationEnvelopePath = '',
    [string[]]$ApprovedSpecialistSkillIds = @(),
    [switch]$ExecuteGovernanceCleanup,
    [switch]$ApplyManagedNodeCleanup
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Ensure consistent UTF-8 encoding for Unicode path compatibility (e.g., Chinese username paths)
if ($PSVersionTable.PSEdition -eq 'Desktop' -or $PSVersionTable.Platform -eq 'Win32NT') {
    # Windows PowerShell 5.x: set console encoding to UTF-8
    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    $OutputEncoding = [System.Text.Encoding]::UTF8
} else {
    # PowerShell Core 7+: already defaults to UTF-8, but ensure consistency
    $OutputEncoding = [System.Text.Encoding]::UTF8
}

. (Join-Path $PSScriptRoot 'VibeRuntime.Common.ps1')
. (Join-Path $PSScriptRoot 'VibeMemoryBackends.Common.ps1')
. (Join-Path $PSScriptRoot 'VibeMemoryActivation.Common.ps1')

function Wait-VibeArtifactSet {
    param(
        [Parameter(Mandatory)] [string[]]$Paths,
        [int]$TimeoutSeconds = 5,
        [int]$PollMilliseconds = 100
    )

    $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
    do {
        $missing = @($Paths | Where-Object { -not (Test-Path -LiteralPath $_) })
        if ($missing.Count -eq 0) {
            return [pscustomobject]@{
                ready = $true
                missing = @()
            }
        }

        Start-Sleep -Milliseconds $PollMilliseconds
    } while ((Get-Date) -lt $deadline)

    return [pscustomobject]@{
        ready = $false
        missing = @($Paths | Where-Object { -not (Test-Path -LiteralPath $_) })
    }
}

function Invoke-VibePythonRuntimeSummaryFinalizer {
    param(
        [Parameter(Mandatory)] [string]$RepoRoot,
        [Parameter(Mandatory)] [object]$Payload,
        [Parameter(Mandatory)] [string]$SummaryPath
    )

    $pythonInvocation = Get-VgoPythonCommand
    $scriptPath = Join-Path $RepoRoot 'packages\runtime-core\src\vgo_runtime\canonical_entry.py'
    $runtimeCoreSrc = Join-Path $RepoRoot 'packages\runtime-core\src'
    $contractsSrc = Join-Path $RepoRoot 'packages\contracts\src'
    $inputPath = Join-Path ([System.IO.Path]::GetTempPath()) ("vgo-runtime-summary-finalize-" + [System.Guid]::NewGuid().ToString("N") + ".json")
    $previousPythonPath = $env:PYTHONPATH

    try {
        Write-VibeJsonArtifact -Path $inputPath -Value $Payload
        $pythonPathEntries = @($runtimeCoreSrc, $contractsSrc)
        if (-not [string]::IsNullOrWhiteSpace($previousPythonPath)) {
            $pythonPathEntries += $previousPythonPath
        }
        $env:PYTHONPATH = ($pythonPathEntries -join [System.IO.Path]::PathSeparator)
        $pythonArgs = @($pythonInvocation.prefix_arguments)
        $pythonArgs += @(
            $scriptPath,
            '--finalize-runtime-summary-input-json', $inputPath,
            '--output-json-path', $SummaryPath
        )
        $commandOutput = & $pythonInvocation.host_path @pythonArgs 2>&1
        $commandExitCode = if ($null -eq $LASTEXITCODE) { 0 } else { [int]$LASTEXITCODE }
        if ($commandExitCode -ne 0) {
            throw ("Python runtime summary finalizer exited with code {0}: {1}" -f $commandExitCode, ((@($commandOutput) | ForEach-Object { [string]$_ }) -join [Environment]::NewLine))
        }
        if (-not (Test-Path -LiteralPath $SummaryPath -PathType Leaf)) {
            throw ("Python runtime summary finalizer did not write runtime-summary.json: {0}" -f $SummaryPath)
        }
        return (Get-Content -LiteralPath $SummaryPath -Raw -Encoding UTF8 | ConvertFrom-Json)
    } finally {
        if ([string]::IsNullOrWhiteSpace($previousPythonPath)) {
            Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
        } else {
            $env:PYTHONPATH = $previousPythonPath
        }
        if (Test-Path -LiteralPath $inputPath) {
            Remove-Item -LiteralPath $inputPath -Force -ErrorAction SilentlyContinue
        }
    }
}

function Complete-VibeGovernedRuntimeStop {
    param(
        [Parameter(Mandatory)] [string]$RunId,
        [Parameter(Mandatory)] [string]$Mode,
        [Parameter(Mandatory)] [string]$Task,
        [Parameter(Mandatory)] [string]$ArtifactBaseRoot,
        [Parameter(Mandatory)] [string]$SessionRoot,
        [Parameter(Mandatory)] [object]$HierarchyState,
        [Parameter(Mandatory)] [object]$StorageProjection,
        [Parameter(Mandatory)] [object]$Skeleton,
        [Parameter(Mandatory)] [object]$RuntimeInput,
        [Parameter(Mandatory)] [object]$GovernanceCapsule,
        [Parameter(Mandatory)] [object]$StageLineage,
        [AllowNull()] [object]$Interview = $null,
        [AllowNull()] [object]$Requirement = $null,
        [AllowNull()] [object]$Plan = $null,
        [AllowNull()] [object]$Execute = $null,
        [AllowNull()] [object]$Cleanup = $null,
        [AllowNull()] [object]$HostStageDisclosure = $null,
        [AllowEmptyString()] [string]$HostStageDisclosurePath = '',
        [AllowNull()] [object]$HostUserBriefing = $null,
        [AllowEmptyString()] [string]$HostUserBriefingPath = '',
        [AllowNull()] [object]$BoundedReturnControl = $null,
        [AllowNull()] [object]$MemoryActivationReport = $null,
        [AllowEmptyString()] [string]$MemoryActivationReportPath = '',
        [AllowEmptyString()] [string]$MemoryActivationMarkdownPath = '',
        [AllowNull()] [object]$DeliveryAcceptanceReport = $null,
        [AllowEmptyString()] [string]$DeliveryAcceptanceReportPath = '',
        [AllowEmptyString()] [string]$DeliveryAcceptanceMarkdownPath = '',
        [AllowNull()] [object]$ExecutionManifestDocument = $null,
        [AllowNull()] [object]$DelegationValidation = $null
    )

    $interviewReceiptPath = if (
        $Interview -and
        $Interview.PSObject.Properties.Name -contains 'receipt_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Interview.receipt_path)
    ) {
        [string]$Interview.receipt_path
    } else {
        ''
    }
    $requirementDocPath = if (
        $Requirement -and
        $Requirement.PSObject.Properties.Name -contains 'governance_scope' -and
        [string]$Requirement.governance_scope -eq 'child' -and
        $Requirement.PSObject.Properties.Name -contains 'requirement_doc_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Requirement.requirement_doc_path)
    ) {
        [string]$Requirement.requirement_doc_path
    } elseif (
        $Requirement -and
        $Requirement.PSObject.Properties.Name -contains 'primary_requirement_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Requirement.primary_requirement_path)
    ) {
        [string]$Requirement.primary_requirement_path
    } elseif (
        $Requirement -and
        $Requirement.PSObject.Properties.Name -contains 'requirement_doc_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Requirement.requirement_doc_path)
    ) {
        [string]$Requirement.requirement_doc_path
    } else {
        ''
    }
    $legacyRequirementDocPath = if (
        $Requirement -and
        $Requirement.PSObject.Properties.Name -contains 'legacy_requirement_doc_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Requirement.legacy_requirement_doc_path)
    ) { [string]$Requirement.legacy_requirement_doc_path } else { '' }
    $requirementReceiptPath = if (
        $Requirement -and
        $Requirement.PSObject.Properties.Name -contains 'receipt_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Requirement.receipt_path)
    ) {
        [string]$Requirement.receipt_path
    } else {
        ''
    }
    $moduleExecutionPath = if (
        $Execute -and
        $Execute.PSObject.Properties.Name -contains 'module_execution_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Execute.module_execution_path) -and
        (Test-Path -LiteralPath ([string]$Execute.module_execution_path) -PathType Leaf)
    ) {
        [string]$Execute.module_execution_path
    } else {
        ''
    }
    $executionPlanPath = if (
        $Plan -and
        $Plan.PSObject.Properties.Name -contains 'governance_scope' -and
        [string]$Plan.governance_scope -eq 'child' -and
        $Plan.PSObject.Properties.Name -contains 'execution_plan_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Plan.execution_plan_path)
    ) {
        [string]$Plan.execution_plan_path
    } elseif (
        $Plan -and
        $Plan.PSObject.Properties.Name -contains 'primary_plan_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Plan.primary_plan_path)
    ) {
        [string]$Plan.primary_plan_path
    } elseif ($Plan) {
        [string]$Plan.execution_plan_path
    } else {
        ''
    }
    $legacyExecutionPlanPath = if (
        $Plan -and
        $Plan.PSObject.Properties.Name -contains 'legacy_execution_plan_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$Plan.legacy_execution_plan_path)
    ) { [string]$Plan.legacy_execution_plan_path } else { '' }

    $criticalArtifactPaths = @(
        [string]$Skeleton.receipt_path,
        [string]$RuntimeInput.packet_path,
        [string]$GovernanceCapsule.path,
        [string]$StageLineage.path,
        $interviewReceiptPath,
        $requirementDocPath,
        $requirementReceiptPath,
        $executionPlanPath,
        $(if ($Plan) { [string]$Plan.module_work_plan_path } else { '' }),
        $(if ($Plan) { [string]$Plan.receipt_path } else { '' }),
        $(if ($Execute) { [string]$Execute.receipt_path } else { '' }),
        $(if ($Execute) { [string]$Execute.execution_manifest_path } else { '' }),
        $moduleExecutionPath,
        $(if ($Cleanup) { [string]$Cleanup.receipt_path } else { '' }),
        [string]$DeliveryAcceptanceReportPath,
        [string]$MemoryActivationReportPath,
        [string]$MemoryActivationMarkdownPath
    ) | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }

    if ($HostStageDisclosure) {
        $criticalArtifactPaths += [string]$HostStageDisclosurePath
    }
    if (-not [string]::IsNullOrWhiteSpace([string]$HostUserBriefingPath)) {
        $criticalArtifactPaths += [string]$HostUserBriefingPath
    }
    if ($DelegationValidation) {
        $criticalArtifactPaths += [string]$DelegationValidation.receipt_path
    }

    $artifactReadiness = Wait-VibeArtifactSet -Paths $criticalArtifactPaths
    if (-not $artifactReadiness.ready) {
        throw ("Governed runtime returned before critical artifacts were durable. Missing: {0}" -f (@($artifactReadiness.missing) -join ', '))
    }

    if (-not (Test-Path -LiteralPath ([string]$RuntimeInput.packet_path) -PathType Leaf)) {
        throw 'Missing Python-built runtime-input-packet.json.'
    }

    $contractWorkspaceRoot = if (
        $StorageProjection -and
        $StorageProjection.PSObject.Properties.Name -contains 'workspace_root' -and
        -not [string]::IsNullOrWhiteSpace([string]$StorageProjection.workspace_root)
    ) {
        [string]$StorageProjection.workspace_root
    } else {
        Resolve-VibeContractWorkspaceRoot -RepoRoot ([string]$runtime.repo_root) -ArtifactRoot $ArtifactBaseRoot
    }
    $legacyDocumentationWrites = @(
        $legacyRequirementDocPath,
        $legacyExecutionPlanPath
    ) | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }
    $artifactBundle = Write-VibeRunArtifactBundle `
        -RepoRoot ([string]$runtime.repo_root) `
        -RunId $RunId `
        -WorkspaceRoot $contractWorkspaceRoot `
        -ArtifactRoot $ArtifactBaseRoot `
        -Requirement ([pscustomobject]@{
            task = $Task
            requirement_doc_path = $requirementDocPath
            legacy_requirement_doc_path = $legacyRequirementDocPath
            receipt_path = $requirementReceiptPath
            stage = 'requirement_doc'
        }) `
        -Plan $(if ($Plan) {
            [pscustomobject]@{
                task = $Task
                execution_plan_path = $executionPlanPath
                legacy_execution_plan_path = $legacyExecutionPlanPath
                module_work_plan_path = [string]$Plan.module_work_plan_path
                receipt_path = [string]$Plan.receipt_path
                stage = 'xl_plan'
            }
        } else { $null }) `
        -Status ([pscustomobject]@{
            requested_stage_stop = if ($RuntimeInput.packet.PSObject.Properties.Name -contains 'requested_stage_stop') { [string]$RuntimeInput.packet.requested_stage_stop } else { $null }
            terminal_stage = [string](Get-VibeNestedPropertySafe -InputObject $StageLineage -PropertyPath @('lineage', 'last_stage_name') -DefaultValue '')
            proof_ready = [bool]($null -ne $DeliveryAcceptanceReport -and $null -ne $Cleanup)
            status = if ($Cleanup) { 'completed' } elseif ($Plan) { 'ready_for_execution' } else { 'awaiting_agent_skill_organization' }
        }) `
        -Proof ([pscustomobject]@{
            task = $Task
            run_id = $RunId
            stage_lineage_path = [string]$StageLineage.path
            delivery_acceptance_report_path = [string]$DeliveryAcceptanceReportPath
            cleanup_receipt_path = if ($Cleanup) { [string]$Cleanup.receipt_path } else { $null }
        }) `
        -LegacyWrites @($legacyDocumentationWrites) `
        -HostId ([string]$env:VCO_HOST_ID)
    Sync-VibeSessionArtifactsToRunRoot `
        -SessionRoot $SessionRoot `
        -RunArtifactRoot ([string]$artifactBundle.descriptor.artifact_root) `
        -ArtifactDescriptor $artifactBundle.descriptor

    $delegationValidationReceiptPath = if ($DelegationValidation) { [string]$DelegationValidation.receipt_path } else { '' }
    $summaryArtifacts = New-VibeRuntimeSummaryArtifactProjection `
        -SkeletonReceiptPath ([string]$Skeleton.receipt_path) `
        -RuntimeInputPacketPath ([string]$RuntimeInput.packet_path) `
        -GovernanceCapsulePath ([string]$GovernanceCapsule.path) `
        -StageLineagePath ([string]$StageLineage.path) `
        -IntentContractPath $interviewReceiptPath `
        -RequirementDocPath $requirementDocPath `
        -RequirementReceiptPath $requirementReceiptPath `
        -ExecutionPlanPath $executionPlanPath `
        -ExecutionPlanReceiptPath $(if ($Plan) { [string]$Plan.receipt_path } else { '' }) `
        -ModuleWorkPlanPath $(if ($Plan) { [string]$Plan.module_work_plan_path } else { '' }) `
        -ModuleExecutionPath $moduleExecutionPath `
        -AgentExecutionHandoffPath $(if ($Execute -and $Execute.PSObject.Properties.Name -contains 'agent_execution_handoff_path') { [string]$Execute.agent_execution_handoff_path } else { '' }) `
        -ExecuteReceiptPath $(if ($Execute) { [string]$Execute.receipt_path } else { '' }) `
        -ExecutionManifestPath $(if ($Execute) { [string]$Execute.execution_manifest_path } else { '' }) `
        -HostStageDisclosurePath $(if ($HostStageDisclosure) { [string]$HostStageDisclosurePath } else { '' }) `
        -HostUserBriefingPath ([string]$HostUserBriefingPath) `
        -CleanupReceiptPath $(if ($Cleanup) { [string]$Cleanup.receipt_path } else { '' }) `
        -DeliveryAcceptanceReportPath ([string]$DeliveryAcceptanceReportPath) `
        -DeliveryAcceptanceMarkdownPath ([string]$DeliveryAcceptanceMarkdownPath) `
        -MemoryActivationReportPath ([string]$MemoryActivationReportPath) `
        -MemoryActivationMarkdownPath ([string]$MemoryActivationMarkdownPath) `
        -DelegationEnvelopePath ([string]$HierarchyState.delegation_envelope_path) `
        -DelegationValidationReceiptPath $delegationValidationReceiptPath
    $summaryArtifacts | Add-Member -NotePropertyName 'requirement' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.requirement) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'plan' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.plan) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'status' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.status) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'proof' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.proof) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'artifact_manifest' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.manifest) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_compatibility' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.legacy_compatibility) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_requirement_doc' -NotePropertyValue $legacyRequirementDocPath -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_execution_plan' -NotePropertyValue $legacyExecutionPlanPath -Force
    $summaryPath = Join-Path $SessionRoot 'runtime-summary.json'
    $summary = Invoke-VibePythonRuntimeSummaryFinalizer `
        -RepoRoot $runtime.repo_root `
        -Payload ([pscustomobject]@{
            run_id = $RunId
            mode = $Mode
            task = $Task
            artifact_root = $ArtifactBaseRoot
            session_root = $SessionRoot
            hierarchy_state = $HierarchyState
            artifacts = $summaryArtifacts
            module_assignments = $RuntimeInput.packet.module_assignments
            stage_lineage = $StageLineage
            storage_projection = $StorageProjection
            memory_activation_report = $MemoryActivationReport
            delivery_acceptance_report = $DeliveryAcceptanceReport
            host_stage_disclosure = $HostStageDisclosure
            host_user_briefing = $HostUserBriefing
            bounded_return_control = $BoundedReturnControl
            agent_execution_handoff = $(if ($Execute -and $Execute.PSObject.Properties.Name -contains 'agent_execution_handoff') { $Execute.agent_execution_handoff } else { $null })
            artifact_contract = $artifactBundle.manifest
        }) `
        -SummaryPath $summaryPath
    Sync-VibeSessionArtifactsToRunRoot `
        -SessionRoot $SessionRoot `
        -RunArtifactRoot ([string]$artifactBundle.descriptor.artifact_root) `
        -ArtifactDescriptor $artifactBundle.descriptor

    return [pscustomobject]@{
        run_id = $RunId
        mode = $Mode
        session_root = $SessionRoot
        summary_path = $summaryPath
        host_stage_disclosure_path = if ($HostStageDisclosure) { [string]$HostStageDisclosurePath } else { $null }
        host_stage_disclosure = $HostStageDisclosure
        host_user_briefing_path = $HostUserBriefingPath
        host_user_briefing = $HostUserBriefing
        artifact_contract = $artifactBundle
        summary = $summary
    }
}

$runtime = Get-VibeRuntimeContext -ScriptPath $PSCommandPath
$workspaceRootWasProvided = -not [string]::IsNullOrWhiteSpace($WorkspaceRoot)
$artifactRootWasProvided = -not [string]::IsNullOrWhiteSpace($ArtifactRoot)
$resolvedWorkspaceRoot = if (-not $workspaceRootWasProvided -and $artifactRootWasProvided) {
    Get-VibeWorkspaceRoot -RepoRoot $runtime.repo_root -WorkspaceRoot $ArtifactRoot
} else {
    Get-VibeWorkspaceRoot -RepoRoot $runtime.repo_root -WorkspaceRoot $WorkspaceRoot
}
$runtime | Add-Member -NotePropertyName workspace_root -NotePropertyValue $resolvedWorkspaceRoot -Force
$artifactBaseRoot = if (-not $workspaceRootWasProvided -and $artifactRootWasProvided) {
    $resolvedWorkspaceRoot
} else {
    Get-VibeArtifactRoot `
        -RepoRoot $runtime.repo_root `
        -Runtime $runtime `
        -WorkspaceRoot $resolvedWorkspaceRoot `
        -ArtifactRoot $ArtifactRoot
}
$ArtifactRoot = $artifactBaseRoot
$Mode = Resolve-VibeRuntimeMode -Mode $Mode -DefaultMode ([string]$runtime.runtime_modes.default_mode)
if ([string]::IsNullOrWhiteSpace($RunId)) {
    $RunId = New-VibeRunId
}
if (-not [string]::IsNullOrWhiteSpace($ModuleExecutionJsonFile)) {
    $sourceSessionRoot = Get-VibeSessionRoot -RepoRoot $runtime.repo_root -RunId $RunId -Runtime $runtime -ArtifactRoot $artifactBaseRoot
    $requestedWorkspace = if ($workspaceRootWasProvided) { $resolvedWorkspaceRoot } else { '' }
    $resolvedWorkspaceRoot = Resolve-VibeResultWorkspaceRoot `
        -RepoRoot $runtime.repo_root -SessionRoot $sourceSessionRoot -RunId $RunId `
        -FallbackWorkspaceRoot $resolvedWorkspaceRoot -RequestedWorkspaceRoot $requestedWorkspace
    $runtime | Add-Member -NotePropertyName workspace_root -NotePropertyValue $resolvedWorkspaceRoot -Force
}
if ($workspaceRootWasProvided -or $artifactRootWasProvided) {
    Initialize-VibeWorkspaceProjectDescriptor `
        -RepoRoot $runtime.repo_root `
        -WorkspaceRoot $resolvedWorkspaceRoot `
        -Runtime $runtime | Out-Null
}
if (-not [string]::IsNullOrWhiteSpace($ModuleExecutionJsonFile)) {
    if ($RequestedStageStop -ne 'phase_cleanup') {
        throw 'Agent module execution re-entry must target phase_cleanup.'
    }

    $sessionRoot = Get-VibeSessionRoot -RepoRoot $runtime.repo_root -RunId $RunId -Runtime $runtime -ArtifactRoot $artifactBaseRoot
    $submittedModuleExecutionPath = [System.IO.Path]::GetFullPath($ModuleExecutionJsonFile)
    $moduleExecutionPath = Get-VibeModuleExecutionPath -SessionRoot $sessionRoot

    $runtimeInputPath = Join-Path $sessionRoot 'runtime-input-packet.json'
    $governanceCapsulePath = Join-Path $sessionRoot 'governance-capsule.json'
    $stageLineagePath = Join-Path $sessionRoot 'stage-lineage.json'
    $executeReceiptPath = Join-Path $sessionRoot 'phase-execute.json'
    $executionManifestPath = Join-Path $sessionRoot 'execution-manifest.json'
    foreach ($requiredPath in @(
        $runtimeInputPath,
        $governanceCapsulePath,
        $stageLineagePath,
        $executeReceiptPath,
        $executionManifestPath,
        (Join-Path $sessionRoot 'module-work-plan.json'),
        (Join-Path $sessionRoot 'agent-execution-handoff.json')
    )) {
        if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) {
            throw ("Agent module execution re-entry is missing source artifact: {0}" -f $requiredPath)
        }
    }

    $stageLineageDocument = Get-Content -LiteralPath $stageLineagePath -Raw -Encoding UTF8 | ConvertFrom-Json
    if ([string]$stageLineageDocument.last_stage_name -ne 'plan_execute') {
        throw 'Agent module execution re-entry requires a source run stopped at plan_execute.'
    }
    $runtimeInputPacket = Get-Content -LiteralPath $runtimeInputPath -Raw -Encoding UTF8 | ConvertFrom-Json
    $frozenTask = [string]$runtimeInputPacket.task
    if ([string]::IsNullOrWhiteSpace($frozenTask)) {
        throw 'Agent module execution re-entry requires the frozen task from runtime-input-packet.json.'
    }
    $executionManifestDocument = Get-Content -LiteralPath $executionManifestPath -Raw -Encoding UTF8 | ConvertFrom-Json
    $submittedModuleExecutionJson = Get-Content -LiteralPath $submittedModuleExecutionPath -Raw -Encoding UTF8
    # Check the JSON root token before PowerShell can unwrap a singleton array.
    if (-not $submittedModuleExecutionJson.TrimStart().StartsWith('{')) {
        throw 'Agent module execution must be a JSON object.'
    }
    $moduleExecution = $submittedModuleExecutionJson | ConvertFrom-Json
    if (-not (Test-VibeStructuredObject -InputObject $moduleExecution)) {
        throw 'Agent module execution must be a JSON object.'
    }
    $moduleWorkPlanPath = Join-Path $sessionRoot 'module-work-plan.json'
    $pendingResultPath = Join-Path $sessionRoot ('.module-execution.{0}.tmp' -f [guid]::NewGuid().ToString('N'))
    $previousPythonPath = $env:PYTHONPATH
    try {
        [System.IO.File]::WriteAllText($pendingResultPath, $submittedModuleExecutionJson, [System.Text.UTF8Encoding]::new($false))
        $contractsSrc = Join-Path ([string]$runtime.repo_root) 'packages/contracts/src'
        $env:PYTHONPATH = (@($contractsSrc, $previousPythonPath) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join [System.IO.Path]::PathSeparator
        $pythonInvocation = Get-VgoPythonCommand
        $validationArgs = @($pythonInvocation.prefix_arguments) + @(
            '-m', 'vgo_contracts.module_execution_contract',
            '--session-root', $sessionRoot,
            '--source-run-id', $RunId,
            '--submitted-file', $pendingResultPath,
            '--emit-required-modules'
        )
        $validationOutput = & $pythonInvocation.host_path @validationArgs 2>&1
        if ($LASTEXITCODE -ne 0) {
            throw ("Agent module execution validation failed: {0}" -f ((@($validationOutput) | ForEach-Object { [string]$_ }) -join [Environment]::NewLine))
        }
        $validationResult = ((@($validationOutput) | ForEach-Object { [string]$_ }) -join [Environment]::NewLine) | ConvertFrom-Json
        $requiredModuleIds = @($validationResult.required_module_ids)
        if ([System.IO.File]::Exists($moduleExecutionPath)) {
            # Preserve a null backup path through PowerShell's .NET string binding.
            [System.IO.File]::Replace($pendingResultPath, $moduleExecutionPath, [NullString]::Value)
        } else {
            [System.IO.File]::Move($pendingResultPath, $moduleExecutionPath)
        }
    } finally {
        if ([string]::IsNullOrWhiteSpace($previousPythonPath)) {
            Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
        } else {
            $env:PYTHONPATH = $previousPythonPath
        }
        if ([System.IO.File]::Exists($pendingResultPath)) {
            [System.IO.File]::Delete($pendingResultPath)
        }
    }
    $completedUnitCount = @($moduleExecution.units | Where-Object { [string]$_.module_id -in $requiredModuleIds -and [string]$_.state -eq 'completed' }).Count
    $failedUnitCount = @($moduleExecution.units | Where-Object { [string]$_.module_id -in $requiredModuleIds -and [string]$_.state -eq 'failed' }).Count
    $blockedUnitCount = @($moduleExecution.units | Where-Object { [string]$_.module_id -in $requiredModuleIds -and [string]$_.state -eq 'blocked' }).Count
    $failedModuleCount = @($moduleExecution.modules | Where-Object { [string]$_.module_id -in $requiredModuleIds -and [string]$_.state -eq 'failed' }).Count
    $blockedModuleCount = @($moduleExecution.modules | Where-Object { [string]$_.module_id -in $requiredModuleIds -and [string]$_.state -eq 'blocked' }).Count
    $executionManifestDocument.status = if (($failedUnitCount + $blockedUnitCount + $failedModuleCount + $blockedModuleCount) -eq 0) { 'completed' } else { 'completed_with_failures' }
    $executionManifestDocument.module_handoff.status = 'agent_results_received'
    $executionManifestDocument.module_handoff.control_owner = 'vibe'
    $executionManifestDocument | Add-Member -NotePropertyName 'module_execution_path' -NotePropertyValue $moduleExecutionPath -Force
    $executionManifestDocument | Add-Member -NotePropertyName 'completed_unit_count' -NotePropertyValue ([int]$completedUnitCount) -Force
    $executionManifestDocument | Add-Member -NotePropertyName 'failed_unit_count' -NotePropertyValue ([int]$failedUnitCount) -Force
    $executionManifestDocument | Add-Member -NotePropertyName 'blocked_unit_count' -NotePropertyValue ([int]$blockedUnitCount) -Force
    Write-VibeJsonArtifact -Path $executionManifestPath -Value $executionManifestDocument

    $requirementReceiptPath = Join-Path $sessionRoot 'requirement-doc-receipt.json'
    $executionPlanReceiptPath = Join-Path $sessionRoot 'execution-plan-receipt.json'
    $requirementReceipt = Get-Content -LiteralPath $requirementReceiptPath -Raw -Encoding UTF8 | ConvertFrom-Json
    $executionPlanReceipt = Get-Content -LiteralPath $executionPlanReceiptPath -Raw -Encoding UTF8 | ConvertFrom-Json
    $reentryRequirementDocPath = if (
        $requirementReceipt.PSObject.Properties.Name -contains 'primary_requirement_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$requirementReceipt.primary_requirement_path)
    ) {
        [string]$requirementReceipt.primary_requirement_path
    } elseif (
        $requirementReceipt.PSObject.Properties.Name -contains 'requirement_doc_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$requirementReceipt.requirement_doc_path)
    ) {
        [string]$requirementReceipt.requirement_doc_path
    } else {
        [string]$executionPlanReceipt.requirement_doc_path
    }
    $reentryExecutionPlanPath = if (
        $executionPlanReceipt.PSObject.Properties.Name -contains 'primary_plan_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$executionPlanReceipt.primary_plan_path)
    ) {
        [string]$executionPlanReceipt.primary_plan_path
    } else {
        [string]$executionPlanReceipt.execution_plan_path
    }
    $reentryLegacyRequirementDocPath = if (
        $requirementReceipt.PSObject.Properties.Name -contains 'legacy_requirement_doc_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$requirementReceipt.legacy_requirement_doc_path)
    ) { [string]$requirementReceipt.legacy_requirement_doc_path } else { '' }
    $reentryLegacyExecutionPlanPath = if (
        $executionPlanReceipt.PSObject.Properties.Name -contains 'legacy_execution_plan_path' -and
        -not [string]::IsNullOrWhiteSpace([string]$executionPlanReceipt.legacy_execution_plan_path)
    ) { [string]$executionPlanReceipt.legacy_execution_plan_path } else { '' }
    $requirementContextArtifact = Get-Content -LiteralPath ([string]$requirementReceipt.memory_context_path) -Raw -Encoding UTF8 | ConvertFrom-Json
    $requirementMemoryContext = [pscustomobject]@{
        context_path = [string]$requirementReceipt.memory_context_path
        disclosure_level = [string]$requirementContextArtifact.disclosure_level
        capsule_count = [int]$requirementContextArtifact.capsule_count
        selected_capsules = @($requirementContextArtifact.selected_capsules)
        injected_item_count = @($requirementContextArtifact.items).Count
        estimated_tokens = [int]$requirementContextArtifact.estimated_tokens
        budget = $requirementContextArtifact.budget
    }
    $planContextArtifact = Get-Content -LiteralPath ([string]$executionPlanReceipt.plan_memory_context_path) -Raw -Encoding UTF8 | ConvertFrom-Json
    $planMemoryContext = [pscustomobject]@{
        context_path = [string]$executionPlanReceipt.plan_memory_context_path
        disclosure_level = [string]$planContextArtifact.disclosure_level
        capsule_count = [int]$planContextArtifact.capsule_count
        selected_capsules = @($planContextArtifact.selected_capsules)
        injected_item_count = @($planContextArtifact.items).Count
        estimated_tokens = [int]$planContextArtifact.estimated_tokens
        budget = $planContextArtifact.budget
    }
    $executionMemoryContextPath = Join-Path $sessionRoot 'memory-activation\execution-context-pack.json'
    $executionContextArtifact = Get-Content -LiteralPath $executionMemoryContextPath -Raw -Encoding UTF8 | ConvertFrom-Json
    $executionMemoryContext = [pscustomobject]@{
        context_path = $executionMemoryContextPath
        disclosure_level = [string]$executionContextArtifact.disclosure_level
        capsule_count = [int]$executionContextArtifact.capsule_count
        selected_capsules = @($executionContextArtifact.selected_capsules)
        injected_item_count = @($executionContextArtifact.items).Count
        estimated_tokens = [int]$executionContextArtifact.estimated_tokens
        budget = $executionContextArtifact.budget
    }
    $memoryBackendRoot = Join-Path $sessionRoot 'memory-backend'
    $restoredMemoryReadActions = @(
        Get-ChildItem -LiteralPath $memoryBackendRoot -Filter '*-read-response.json' -File -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object {
            $backendResult = Get-Content -LiteralPath $_.FullName -Raw -Encoding UTF8 | ConvertFrom-Json
            $owner = switch -Regex ($_.BaseName) {
                '^serena-' { 'Serena'; break }
                '^cognee-' { 'Cognee'; break }
                '^ruflo-' { 'ruflo'; break }
                default { 'state_store' }
            }
            [pscustomobject]@{
                owner = $owner
                status = [string]$backendResult.status
                item_count = [int]$backendResult.item_count
                items = @($backendResult.items)
                capsule_count = if ($backendResult.PSObject.Properties.Name -contains 'capsule_count') { [int]$backendResult.capsule_count } else { 0 }
                capsules = if ($backendResult.PSObject.Properties.Name -contains 'capsules') { @($backendResult.capsules) } else { @() }
                artifact_path = if ($backendResult.PSObject.Properties.Name -contains 'artifact_path') { $backendResult.artifact_path } else { $null }
                project_key = if ($backendResult.PSObject.Properties.Name -contains 'project_key') { $backendResult.project_key } else { $null }
                project_key_source = if ($backendResult.PSObject.Properties.Name -contains 'project_key_source') { $backendResult.project_key_source } else { $null }
                workspace_memory_plane = if ($backendResult.PSObject.Properties.Name -contains 'workspace_memory_plane') { $backendResult.workspace_memory_plane } else { $null }
            }
        }
    )
    $restoredSkeletonReadActions = @($restoredMemoryReadActions | Where-Object {
            [string]$_.owner -in @('state_store', 'Cognee')
        })
    if (@($restoredSkeletonReadActions | Where-Object { [string]$_.owner -eq 'state_store' }).Count -eq 0) {
        $restoredSkeletonReadActions = @(
            New-VibeSkeletonMemoryDigest -Runtime $runtime -Skeleton ([pscustomobject]@{
                    receipt = Get-Content -LiteralPath (Join-Path $sessionRoot 'skeleton-receipt.json') -Raw -Encoding UTF8 | ConvertFrom-Json
                    receipt_path = Join-Path $sessionRoot 'skeleton-receipt.json'
                }) -Task $frozenTask -SessionRoot $sessionRoot
        ) + @($restoredSkeletonReadActions)
    }
    $restoredDeepInterviewReadActions = @($restoredMemoryReadActions | Where-Object { [string]$_.owner -eq 'Serena' })
    if (@($restoredDeepInterviewReadActions).Count -eq 0 -and @($restoredMemoryReadActions).Count -gt 0) {
        $restoredDeepInterviewReadActions = @($restoredMemoryReadActions[0])
    }
    $restoredXlPlanReadActions = @($restoredMemoryReadActions | Where-Object {
            [string]$_.owner -in @('Serena', 'Cognee')
        })

    $cleanup = & (Join-Path $PSScriptRoot 'Invoke-PhaseCleanup.ps1') `
        -Task $frozenTask `
        -Mode $Mode `
        -RunId $RunId `
        -ArtifactRoot $artifactBaseRoot `
        -WorkspaceRoot $resolvedWorkspaceRoot `
        -ExecuteGovernanceCleanup:$ExecuteGovernanceCleanup `
        -ApplyManagedNodeCleanup:$ApplyManagedNodeCleanup
    $stageLineage = Add-VibeStageLineageEntry `
        -SessionRoot $sessionRoot `
        -RunId $RunId `
        -RootRunId $RunId `
        -StageName 'phase_cleanup' `
        -PreviousStageName 'plan_execute' `
        -PreviousStageReceiptPath $executeReceiptPath `
        -CurrentReceiptPath ([string]$cleanup.receipt_path) `
        -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract

    $deliveryAcceptanceReportPath = Join-Path $sessionRoot 'delivery-acceptance-report.json'
    $deliveryAcceptanceMarkdownPath = Join-Path $sessionRoot 'delivery-acceptance-report.md'
    $deliveryAcceptanceReport = if (Test-Path -LiteralPath $deliveryAcceptanceReportPath) {
        Get-Content -LiteralPath $deliveryAcceptanceReportPath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $hostUserBriefing = New-VibeHostUserBriefingProjection `
        -DeliveryAcceptanceReport $deliveryAcceptanceReport
    $hostUserBriefingPath = ''
    if ($hostUserBriefing) {
        $hostUserBriefingPath = Get-VibeHostUserBriefingPath -SessionRoot $sessionRoot
        Write-VgoUtf8NoBomText `
            -Path $hostUserBriefingPath `
            -Content (([string]$hostUserBriefing.rendered_text) + [Environment]::NewLine)
    }
    $memoryExecuteWrite = New-VibeExecutionMemoryWriteAction `
        -ExecutionManifestPath $executionManifestPath `
        -SessionRoot $sessionRoot `
        -Runtime $runtime `
        -RunId $RunId `
        -Task $frozenTask `
        -Grade ([string]$executionManifestDocument.internal_grade)
    $memoryExecuteRufloWrite = New-VibeRufloExecutionWriteAction `
        -Runtime $runtime `
        -ExecutionManifestPath $executionManifestPath `
        -SessionRoot $sessionRoot `
        -RunId $RunId `
        -Task $frozenTask `
        -Grade ([string]$executionManifestDocument.internal_grade)
    $memoryCleanupDecision = Get-VibeCleanupDecisionWriteAction `
        -RequirementDocPath $reentryRequirementDocPath `
        -ExecutionPlanPath $reentryExecutionPlanPath `
        -Runtime $runtime `
        -SessionRoot $sessionRoot `
        -Task $frozenTask
    $memoryCleanupCognee = Get-VibeCogneeCleanupWriteAction `
        -Runtime $runtime `
        -Task $frozenTask `
        -RequirementDocPath $reentryRequirementDocPath `
        -ExecutionPlanPath $reentryExecutionPlanPath `
        -ExecutionManifestPath $executionManifestPath `
        -SessionRoot $sessionRoot
    $memoryCleanupFold = New-VibeCleanupMemoryFold `
        -RequirementDocPath $reentryRequirementDocPath `
        -ExecutionPlanPath $reentryExecutionPlanPath `
        -ExecutionManifestPath $executionManifestPath `
        -CleanupReceiptPath ([string]$cleanup.receipt_path) `
        -SessionRoot $sessionRoot
    $memoryActivation = New-VibeMemoryActivationReport `
        -Runtime $runtime `
        -RunId $RunId `
        -SessionRoot $sessionRoot `
        -SkeletonReadActions @($restoredSkeletonReadActions) `
        -DeepInterviewReadActions @($restoredDeepInterviewReadActions) `
        -RequirementContextPack $requirementMemoryContext `
        -XlPlanReadActions @($restoredXlPlanReadActions) `
        -PlanContextPack $planMemoryContext `
        -PlanExecuteReadActions @($restoredMemoryReadActions) `
        -PlanExecuteContextPack $executionMemoryContext `
        -PlanExecuteWriteActions @($memoryExecuteWrite, $memoryExecuteRufloWrite) `
        -CleanupWriteActions @($memoryCleanupDecision, $memoryCleanupCognee) `
        -CleanupFoldAction $memoryCleanupFold
    $hierarchyState = Get-VibeHierarchyState `
        -GovernanceScope '' `
        -RunId $RunId `
        -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
    $storageProjection = New-VibeWorkspaceArtifactProjection `
        -RepoRoot $runtime.repo_root `
        -WorkspaceRoot $resolvedWorkspaceRoot `
        -Runtime $runtime `
        -ArtifactRoot $artifactBaseRoot `
        -RouterTargetRoot (Resolve-VgoTargetRoot -HostId (Resolve-VgoHostId -HostId $env:VCO_HOST_ID))
    $priorSummaryPath = Join-Path $sessionRoot 'runtime-summary.json'
    $priorSummary = if (Test-Path -LiteralPath $priorSummaryPath) {
        Get-Content -LiteralPath $priorSummaryPath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $priorArtifacts = if ($priorSummary -and $priorSummary.PSObject.Properties.Name -contains 'artifacts') {
        $priorSummary.artifacts
    } else {
        $null
    }
    $reentryLegacyWrites = @(
        $reentryLegacyRequirementDocPath,
        $reentryLegacyExecutionPlanPath
    ) | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }
    $artifactBundle = Write-VibeRunArtifactBundle `
        -RepoRoot ([string]$runtime.repo_root) `
        -RunId $RunId `
        -WorkspaceRoot $resolvedWorkspaceRoot `
        -ArtifactRoot $artifactBaseRoot `
        -Requirement ([pscustomobject]@{
            task = $frozenTask
            requirement_doc_path = $reentryRequirementDocPath
            legacy_requirement_doc_path = $reentryLegacyRequirementDocPath
            receipt_path = $requirementReceiptPath
            stage = 'requirement_doc'
        }) `
        -Plan ([pscustomobject]@{
            task = $frozenTask
            execution_plan_path = $reentryExecutionPlanPath
            legacy_execution_plan_path = $reentryLegacyExecutionPlanPath
            module_work_plan_path = $moduleWorkPlanPath
            receipt_path = $executionPlanReceiptPath
            stage = 'xl_plan'
        }) `
        -Status ([pscustomobject]@{
            requested_stage_stop = 'phase_cleanup'
            terminal_stage = [string]$stageLineage.lineage.last_stage_name
            proof_ready = [bool]($null -ne $deliveryAcceptanceReport -and $null -ne $cleanup)
            status = 'completed'
        }) `
        -Proof ([pscustomobject]@{
            task = $frozenTask
            run_id = $RunId
            stage_lineage_path = [string]$stageLineage.path
            delivery_acceptance_report_path = if (Test-Path -LiteralPath $deliveryAcceptanceReportPath) { $deliveryAcceptanceReportPath } else { $null }
            cleanup_receipt_path = [string]$cleanup.receipt_path
            module_execution_path = $moduleExecutionPath
        }) `
        -LegacyWrites @($reentryLegacyWrites) `
        -HostId ([string]$env:VCO_HOST_ID)
    Sync-VibeSessionArtifactsToRunRoot `
        -SessionRoot $sessionRoot `
        -RunArtifactRoot ([string]$artifactBundle.descriptor.artifact_root) `
        -ArtifactDescriptor $artifactBundle.descriptor
    $summaryArtifacts = New-VibeRuntimeSummaryArtifactProjection `
        -SkeletonReceiptPath (Join-Path $sessionRoot 'skeleton-receipt.json') `
        -RuntimeInputPacketPath $runtimeInputPath `
        -GovernanceCapsulePath $governanceCapsulePath `
        -StageLineagePath $stageLineagePath `
        -IntentContractPath ([string]$priorArtifacts.intent_contract) `
        -RequirementDocPath $reentryRequirementDocPath `
        -RequirementReceiptPath ([string]$priorArtifacts.requirement_receipt) `
        -ExecutionPlanPath $reentryExecutionPlanPath `
        -ExecutionPlanReceiptPath ([string]$priorArtifacts.execution_plan_receipt) `
        -ModuleWorkPlanPath (Join-Path $sessionRoot 'module-work-plan.json') `
        -ModuleExecutionPath $moduleExecutionPath `
        -AgentExecutionHandoffPath (Join-Path $sessionRoot 'agent-execution-handoff.json') `
        -ExecuteReceiptPath $executeReceiptPath `
        -ExecutionManifestPath $executionManifestPath `
        -HostStageDisclosurePath ([string]$priorArtifacts.host_stage_disclosure) `
        -HostUserBriefingPath $hostUserBriefingPath `
        -CleanupReceiptPath ([string]$cleanup.receipt_path) `
        -DeliveryAcceptanceReportPath $(if (Test-Path -LiteralPath $deliveryAcceptanceReportPath) { $deliveryAcceptanceReportPath } else { '' }) `
        -DeliveryAcceptanceMarkdownPath $(if (Test-Path -LiteralPath $deliveryAcceptanceMarkdownPath) { $deliveryAcceptanceMarkdownPath } else { '' }) `
        -MemoryActivationReportPath ([string]$memoryActivation.report_path) `
        -MemoryActivationMarkdownPath ([string]$memoryActivation.markdown_path)
    $summaryArtifacts | Add-Member -NotePropertyName 'requirement' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.requirement) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'plan' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.plan) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'status' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.status) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'proof' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.proof) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'artifact_manifest' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.manifest) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_compatibility' -NotePropertyValue ([string]$artifactBundle.descriptor.paths.legacy_compatibility) -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_requirement_doc' -NotePropertyValue $reentryLegacyRequirementDocPath -Force
    $summaryArtifacts | Add-Member -NotePropertyName 'legacy_execution_plan' -NotePropertyValue $reentryLegacyExecutionPlanPath -Force
    $summary = Invoke-VibePythonRuntimeSummaryFinalizer `
        -RepoRoot $runtime.repo_root `
        -Payload ([pscustomobject]@{
            run_id = $RunId
            mode = $Mode
            task = $frozenTask
            artifact_root = $artifactBaseRoot
            session_root = $sessionRoot
            hierarchy_state = $hierarchyState
            artifacts = $summaryArtifacts
            module_assignments = $runtimeInputPacket.module_assignments
            stage_lineage = $stageLineage
            storage_projection = $storageProjection
            memory_activation_report = $memoryActivation.report
            delivery_acceptance_report = $deliveryAcceptanceReport
            host_stage_disclosure = $(if ($priorSummary) { $priorSummary.host_stage_disclosure } else { $null })
            host_user_briefing = $hostUserBriefing
            bounded_return_control = $null
            agent_execution_handoff = $null
            module_execution = $moduleExecution
            artifact_contract = $artifactBundle.manifest
        }) `
        -SummaryPath $priorSummaryPath
    Sync-VibeSessionArtifactsToRunRoot `
        -SessionRoot $sessionRoot `
        -RunArtifactRoot ([string]$artifactBundle.descriptor.artifact_root) `
        -ArtifactDescriptor $artifactBundle.descriptor

    return [pscustomobject]@{
        run_id = $RunId
        mode = $Mode
        session_root = $sessionRoot
        summary_path = $priorSummaryPath
        artifact_contract = $artifactBundle
        summary = $summary
    }
}
$hostDecision = ConvertFrom-VibeHostDecisionJson -HostDecisionJson $HostDecisionJson
$hostContinuationContext = Get-VibeHostContinuationContext -HostDecision $hostDecision
$structuredBoundedReentry = Test-VibeStructuredBoundedReentryContext -ContinuationContext $hostContinuationContext
$storageProjection = New-VibeWorkspaceArtifactProjection `
    -RepoRoot $runtime.repo_root `
    -WorkspaceRoot $resolvedWorkspaceRoot `
    -Runtime $runtime `
    -ArtifactRoot $artifactBaseRoot `
    -RouterTargetRoot (Resolve-VgoTargetRoot -HostId (Resolve-VgoHostId -HostId $env:VCO_HOST_ID))
$hierarchyState = Get-VibeHierarchyState `
    -GovernanceScope $GovernanceScope `
    -RunId $RunId `
    -RootRunId $RootRunId `
    -ParentRunId $ParentRunId `
    -ParentUnitId $ParentUnitId `
    -InheritedRequirementDocPath $InheritedRequirementDocPath `
    -InheritedExecutionPlanPath $InheritedExecutionPlanPath `
    -DelegationEnvelopePath $DelegationEnvelopePath `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract

$hierarchyArgs = @{
    GovernanceScope = [string]$hierarchyState.governance_scope
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.root_run_id)) {
    $hierarchyArgs.RootRunId = [string]$hierarchyState.root_run_id
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.parent_run_id)) {
    $hierarchyArgs.ParentRunId = [string]$hierarchyState.parent_run_id
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.parent_unit_id)) {
    $hierarchyArgs.ParentUnitId = [string]$hierarchyState.parent_unit_id
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.inherited_requirement_doc_path)) {
    $hierarchyArgs.InheritedRequirementDocPath = [string]$hierarchyState.inherited_requirement_doc_path
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.inherited_execution_plan_path)) {
    $hierarchyArgs.InheritedExecutionPlanPath = [string]$hierarchyState.inherited_execution_plan_path
}
if (-not [string]::IsNullOrWhiteSpace([string]$hierarchyState.delegation_envelope_path)) {
    $hierarchyArgs.DelegationEnvelopePath = [string]$hierarchyState.delegation_envelope_path
}

$skeleton = & (Join-Path $PSScriptRoot 'Invoke-SkeletonCheck.ps1') `
    -Task $Task `
    -Mode $Mode `
    -RunId $RunId `
    -ArtifactRoot $artifactBaseRoot `
    -WorkspaceRoot $resolvedWorkspaceRoot
$governanceCapsule = Write-VibeGovernanceCapsule `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -GovernanceScope ([string]$hierarchyState.governance_scope) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'skeleton_check' `
    -CurrentReceiptPath ([string]$skeleton.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
$delegationValidation = $null
if ([string]$hierarchyState.governance_scope -eq 'child') {
    $delegationValidation = Assert-VibeDelegationEnvelope `
        -SessionRoot ([string]$skeleton.session_root) `
        -EnvelopePath ([string]$hierarchyState.delegation_envelope_path) `
        -HierarchyState $hierarchyState `
        -ExpectedChildRunId $RunId `
        -ExpectedParentRunId ([string]$hierarchyState.parent_run_id) `
        -ExpectedParentUnitId ([string]$hierarchyState.parent_unit_id) `
        -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
}
$memorySkeletonDigest = New-VibeSkeletonMemoryDigest -Runtime $runtime -Skeleton $skeleton -Task $Task -SessionRoot ([string]$skeleton.session_root)
$memorySkeletonCognee = $null
$skeletonMemoryReads = @($memorySkeletonDigest)
if (-not $structuredBoundedReentry) {
    $memorySkeletonCognee = Get-VibeCogneeReadAction -Runtime $runtime -Stage 'skeleton_check' -Task $Task -SessionRoot ([string]$skeleton.session_root)
    $skeletonMemoryReads = @($memorySkeletonDigest, $memorySkeletonCognee)
}
$freezeArgs = @{
    Task = $Task
    Mode = $Mode
    RunId = $RunId
    WorkspaceRoot = $resolvedWorkspaceRoot
    ArtifactRoot = $artifactBaseRoot
    EntryIntentId = $EntryIntentId
    RequestedStageStop = $RequestedStageStop
    RequestedGradeFloor = $RequestedGradeFloor
    HostDecisionJson = $HostDecisionJson
    ApprovedSpecialistSkillIds = $ApprovedSpecialistSkillIds
}
foreach ($key in @($hierarchyArgs.Keys)) {
    $freezeArgs[$key] = $hierarchyArgs[$key]
}
$runtimeInput = & (Join-Path $PSScriptRoot 'Freeze-RuntimeInputPacket.ps1') @freezeArgs
$runtimeInputPacket = if ($runtimeInput -and $runtimeInput.PSObject.Properties.Name -contains 'packet' -and $null -ne $runtimeInput.packet) {
    $runtimeInput.packet
} else {
    $null
}
$requestedStop = Resolve-VibeRequestedStageStop -RequestedStageStop $(if ($runtimeInputPacket) { [string]$runtimeInputPacket.requested_stage_stop } else { '' })
$interview = & (Join-Path $PSScriptRoot 'Invoke-DeepInterview.ps1') -Task $Task -Mode $Mode -RunId $RunId -ArtifactRoot $artifactBaseRoot -WorkspaceRoot $resolvedWorkspaceRoot -HostDecisionJson $HostDecisionJson
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'deep_interview' `
    -PreviousStageName 'skeleton_check' `
    -PreviousStageReceiptPath ([string]$skeleton.receipt_path) `
    -CurrentReceiptPath ([string]$interview.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
$memoryDeepInterviewRead = $null
$deepInterviewMemoryReads = @()
$requirementContextReads = @($memorySkeletonDigest)
if (-not $structuredBoundedReentry) {
    $memoryDeepInterviewRead = Get-VibeDeepInterviewMemoryReadAction -Runtime $runtime -Task $Task -SessionRoot ([string]$skeleton.session_root)
    $deepInterviewMemoryReads = @($memoryDeepInterviewRead)
    $requirementContextReads = @($memoryDeepInterviewRead, $memorySkeletonCognee, $memorySkeletonDigest)
}
$requirementMemoryContext = New-VibeRequirementContextPack -Runtime $runtime -ReadActions $requirementContextReads -SessionRoot ([string]$skeleton.session_root)
$requirementArgs = @{
    Task = $Task
    Mode = $Mode
    RunId = $RunId
    IntentContractPath = $interview.receipt_path
    RuntimeInputPacketPath = $runtimeInput.packet_path
    MemoryContextPath = $requirementMemoryContext.context_path
    ArtifactRoot = $artifactBaseRoot
    WorkspaceRoot = $resolvedWorkspaceRoot
}
foreach ($key in @($hierarchyArgs.Keys)) {
    $requirementArgs[$key] = $hierarchyArgs[$key]
}
$requirement = & (Join-Path $PSScriptRoot 'Write-RequirementDoc.ps1') @requirementArgs
$primaryRequirementDocPath = if (
    $requirement.PSObject.Properties.Name -contains 'primary_requirement_path' -and
    -not [string]::IsNullOrWhiteSpace([string]$requirement.primary_requirement_path)
) { [string]$requirement.primary_requirement_path } else { [string]$requirement.requirement_doc_path }
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'requirement_doc' `
    -PreviousStageName 'deep_interview' `
    -PreviousStageReceiptPath ([string]$interview.receipt_path) `
    -CurrentReceiptPath ([string]$requirement.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
if ($requestedStop -eq 'requirement_doc') {
    $hostStageDisclosurePath = Get-VibeHostStageDisclosurePath -SessionRoot ([string]$skeleton.session_root)
    $hostStageDisclosure = if (Test-Path -LiteralPath $hostStageDisclosurePath) {
        Get-Content -LiteralPath $hostStageDisclosurePath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $boundedSkillSearchGuide = if (
        $runtimeInputPacket.PSObject.Properties.Name -contains 'skill_search_guide' -and
        $null -ne $runtimeInputPacket.skill_search_guide
    ) {
        $runtimeInputPacket.skill_search_guide
    } else {
        $null
    }
    $boundedReturnControl = New-VibeBoundedReturnControlProjection `
        -RepoRoot ([string]$runtime.repo_root) `
        -RunId $RunId `
        -EntryIntentId $EntryIntentId `
        -StageLineage $stageLineage `
        -WorkflowLevelConfirmation $interview.intent_contract.workflow_level_confirmation `
        -SkillSearchGuide $boundedSkillSearchGuide
    $hostUserBriefing = New-VibeHostUserBriefingProjection -BoundedReturnControl $boundedReturnControl
    $hostUserBriefingPath = ''
    if ($hostUserBriefing) {
        $hostUserBriefingPath = Get-VibeHostUserBriefingPath -SessionRoot ([string]$skeleton.session_root)
        Write-VgoUtf8NoBomText -Path $hostUserBriefingPath -Content (([string]$hostUserBriefing.rendered_text) + [Environment]::NewLine)
    }

    return Complete-VibeGovernedRuntimeStop `
        -RunId $RunId `
        -Mode $Mode `
        -Task $Task `
        -ArtifactBaseRoot $artifactBaseRoot `
        -SessionRoot ([string]$skeleton.session_root) `
        -HierarchyState $hierarchyState `
        -StorageProjection $storageProjection `
        -Skeleton $skeleton `
        -RuntimeInput $runtimeInput `
        -GovernanceCapsule $governanceCapsule `
        -StageLineage $stageLineage `
        -Interview $interview `
        -Requirement $requirement `
        -HostStageDisclosure $hostStageDisclosure `
        -HostStageDisclosurePath $hostStageDisclosurePath `
        -HostUserBriefing $hostUserBriefing `
        -HostUserBriefingPath $hostUserBriefingPath `
        -BoundedReturnControl $boundedReturnControl `
        -DelegationValidation $delegationValidation
}
$planArgs = @{
    Task = $Task
    Mode = $Mode
    RunId = $RunId
    RequirementDocPath = $primaryRequirementDocPath
    RuntimeInputPacketPath = $runtimeInput.packet_path
    ArtifactRoot = $artifactBaseRoot
    WorkspaceRoot = $resolvedWorkspaceRoot
}
foreach ($key in @($hierarchyArgs.Keys)) {
    $planArgs[$key] = $hierarchyArgs[$key]
}
$planArgs.InheritedRequirementDocPath = $primaryRequirementDocPath
$memoryPlanSerena = $null
$memoryPlanCognee = $null
$xlPlanReadActions = @()
if (-not $structuredBoundedReentry) {
    $memoryPlanSerena = Get-VibeSerenaReadAction -Runtime $runtime -Stage 'xl_plan' -Task $Task -SessionRoot ([string]$skeleton.session_root)
    $memoryPlanCognee = Get-VibeCogneeReadAction -Runtime $runtime -Stage 'xl_plan' -Task $Task -SessionRoot ([string]$skeleton.session_root)
    $xlPlanReadActions = @($memoryPlanSerena, $memoryPlanCognee)
}
$planMemoryContext = New-VibePlanMemoryContextPack -Runtime $runtime -ReadActions $xlPlanReadActions -SessionRoot ([string]$skeleton.session_root) -Stage 'xl_plan' -ArtifactName 'plan-context-pack.json'
$planArgs.PlanMemoryContextPath = $planMemoryContext.context_path
$plan = & (Join-Path $PSScriptRoot 'Write-XlPlan.ps1') @planArgs
$primaryExecutionPlanPath = if (
    $plan.PSObject.Properties.Name -contains 'primary_plan_path' -and
    -not [string]::IsNullOrWhiteSpace([string]$plan.primary_plan_path)
) { [string]$plan.primary_plan_path } else { [string]$plan.execution_plan_path }
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'xl_plan' `
    -PreviousStageName 'requirement_doc' `
    -PreviousStageReceiptPath ([string]$requirement.receipt_path) `
    -CurrentReceiptPath ([string]$plan.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
if ($requestedStop -eq 'xl_plan') {
    $hostStageDisclosurePath = Get-VibeHostStageDisclosurePath -SessionRoot ([string]$skeleton.session_root)
    $hostStageDisclosure = if (Test-Path -LiteralPath $hostStageDisclosurePath) {
        Get-Content -LiteralPath $hostStageDisclosurePath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $boundedReturnControl = New-VibeBoundedReturnControlProjection `
        -RepoRoot ([string]$runtime.repo_root) `
        -RunId $RunId `
        -EntryIntentId $EntryIntentId `
        -StageLineage $stageLineage `
        -SkillSearchGuide $(if ($runtimeInputPacket.PSObject.Properties.Name -contains 'skill_search_guide') { $runtimeInputPacket.skill_search_guide } else { $null })
    $hostUserBriefing = New-VibeHostUserBriefingProjection -BoundedReturnControl $boundedReturnControl
    $hostUserBriefingPath = ''
    if ($hostUserBriefing) {
        $hostUserBriefingPath = Get-VibeHostUserBriefingPath -SessionRoot ([string]$skeleton.session_root)
        Write-VgoUtf8NoBomText -Path $hostUserBriefingPath -Content (([string]$hostUserBriefing.rendered_text) + [Environment]::NewLine)
    }

    return Complete-VibeGovernedRuntimeStop `
        -RunId $RunId `
        -Mode $Mode `
        -Task $Task `
        -ArtifactBaseRoot $artifactBaseRoot `
        -SessionRoot ([string]$skeleton.session_root) `
        -HierarchyState $hierarchyState `
        -StorageProjection $storageProjection `
        -Skeleton $skeleton `
        -RuntimeInput $runtimeInput `
        -GovernanceCapsule $governanceCapsule `
        -StageLineage $stageLineage `
        -Interview $interview `
        -Requirement $requirement `
        -Plan $plan `
        -HostStageDisclosure $hostStageDisclosure `
        -HostStageDisclosurePath $hostStageDisclosurePath `
        -HostUserBriefing $hostUserBriefing `
        -HostUserBriefingPath $hostUserBriefingPath `
        -BoundedReturnControl $boundedReturnControl `
        -DelegationValidation $delegationValidation
}
$grade = if ($plan.receipt -and $plan.receipt.internal_grade) { [string]$plan.receipt.internal_grade } else { Get-VibeInternalGrade -Task $Task }
$memoryPlanExecuteRead = Get-VibeRufloReadAction -Runtime $runtime -Task $Task -SessionRoot ([string]$skeleton.session_root) -Grade $grade
$executionMemoryContext = New-VibePlanMemoryContextPack -Runtime $runtime -ReadActions @($memoryPlanExecuteRead) -SessionRoot ([string]$skeleton.session_root) -Stage 'plan_execute' -ArtifactName 'execution-context-pack.json'
$executeArgs = @{
    Task = $Task
    Mode = $Mode
    RunId = $RunId
    RequirementDocPath = $primaryRequirementDocPath
    ExecutionPlanPath = $primaryExecutionPlanPath
    ModuleWorkPlanPath = $plan.module_work_plan_path
    RuntimeInputPacketPath = $runtimeInput.packet_path
    ArtifactRoot = $artifactBaseRoot
}
foreach ($key in @('GovernanceScope', 'RootRunId', 'ParentRunId', 'ParentUnitId')) {
    if ($hierarchyArgs.ContainsKey($key)) {
        $executeArgs[$key] = $hierarchyArgs[$key]
    }
}
$executeArgs.ExecutionMemoryContextPath = $executionMemoryContext.context_path
$executeArgs.WorkspaceRoot = $resolvedWorkspaceRoot
$execute = & (Join-Path $PSScriptRoot 'Invoke-PlanExecute.ps1') @executeArgs
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'plan_execute' `
    -PreviousStageName 'xl_plan' `
    -PreviousStageReceiptPath ([string]$plan.receipt_path) `
    -CurrentReceiptPath ([string]$execute.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
if ($execute.PSObject.Properties.Name -contains 'agent_execution_handoff' -and $null -ne $execute.agent_execution_handoff) {
    $hostStageDisclosurePath = Get-VibeHostStageDisclosurePath -SessionRoot ([string]$skeleton.session_root)
    $hostStageDisclosure = if (Test-Path -LiteralPath $hostStageDisclosurePath) {
        Get-Content -LiteralPath $hostStageDisclosurePath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $hostUserBriefing = New-VibeAgentExecutionHandoffBriefing -Handoff $execute.agent_execution_handoff
    $hostUserBriefingPath = Get-VibeHostUserBriefingPath -SessionRoot ([string]$skeleton.session_root)
    Write-VgoUtf8NoBomText -Path $hostUserBriefingPath -Content (([string]$hostUserBriefing.rendered_text) + [Environment]::NewLine)
    $executionManifestDocument = if (Test-Path -LiteralPath ([string]$execute.execution_manifest_path)) {
        Get-Content -LiteralPath ([string]$execute.execution_manifest_path) -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }

    return Complete-VibeGovernedRuntimeStop `
        -RunId $RunId `
        -Mode $Mode `
        -Task $Task `
        -ArtifactBaseRoot $artifactBaseRoot `
        -SessionRoot ([string]$skeleton.session_root) `
        -HierarchyState $hierarchyState `
        -StorageProjection $storageProjection `
        -Skeleton $skeleton `
        -RuntimeInput $runtimeInput `
        -GovernanceCapsule $governanceCapsule `
        -StageLineage $stageLineage `
        -Interview $interview `
        -Requirement $requirement `
        -Plan $plan `
        -Execute $execute `
        -HostStageDisclosure $hostStageDisclosure `
        -HostStageDisclosurePath $hostStageDisclosurePath `
        -HostUserBriefing $hostUserBriefing `
        -HostUserBriefingPath $hostUserBriefingPath `
        -ExecutionManifestDocument $executionManifestDocument `
        -DelegationValidation $delegationValidation
}
if ($requestedStop -eq 'plan_execute') {
    $hostStageDisclosurePath = Get-VibeHostStageDisclosurePath -SessionRoot ([string]$skeleton.session_root)
    $hostStageDisclosure = if (Test-Path -LiteralPath $hostStageDisclosurePath) {
        Get-Content -LiteralPath $hostStageDisclosurePath -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }
    $executionManifestDocument = if (Test-Path -LiteralPath ([string]$execute.execution_manifest_path)) {
        Get-Content -LiteralPath ([string]$execute.execution_manifest_path) -Raw -Encoding UTF8 | ConvertFrom-Json
    } else {
        $null
    }

    # plan_execute stops before cleanup/user-facing execution handoff is finalized, so this early return
    # intentionally does not synthesize bounded-return credentials or a host-user briefing.
    return Complete-VibeGovernedRuntimeStop `
        -RunId $RunId `
        -Mode $Mode `
        -Task $Task `
        -ArtifactBaseRoot $artifactBaseRoot `
        -SessionRoot ([string]$skeleton.session_root) `
        -HierarchyState $hierarchyState `
        -StorageProjection $storageProjection `
        -Skeleton $skeleton `
        -RuntimeInput $runtimeInput `
        -GovernanceCapsule $governanceCapsule `
        -StageLineage $stageLineage `
        -Interview $interview `
        -Requirement $requirement `
        -Plan $plan `
        -Execute $execute `
        -HostStageDisclosure $hostStageDisclosure `
        -HostStageDisclosurePath $hostStageDisclosurePath `
        -ExecutionManifestDocument $executionManifestDocument `
        -DelegationValidation $delegationValidation
}
$cleanup = & (Join-Path $PSScriptRoot 'Invoke-PhaseCleanup.ps1') -Task $Task -Mode $Mode -RunId $RunId -ArtifactRoot $artifactBaseRoot -WorkspaceRoot $resolvedWorkspaceRoot -ExecuteGovernanceCleanup:$ExecuteGovernanceCleanup -ApplyManagedNodeCleanup:$ApplyManagedNodeCleanup
$stageLineage = Add-VibeStageLineageEntry `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -RootRunId ([string]$hierarchyState.root_run_id) `
    -StageName 'phase_cleanup' `
    -PreviousStageName 'plan_execute' `
    -PreviousStageReceiptPath ([string]$execute.receipt_path) `
    -CurrentReceiptPath ([string]$cleanup.receipt_path) `
    -HierarchyContract $runtime.runtime_input_packet_policy.hierarchy_contract
$memoryExecuteWrite = New-VibeExecutionMemoryWriteAction `
    -ExecutionManifestPath ([string]$execute.execution_manifest_path) `
    -SessionRoot ([string]$skeleton.session_root) `
    -Runtime $runtime `
    -RunId $RunId `
    -Task $Task `
    -Grade $grade
$memoryExecuteRufloWrite = New-VibeRufloExecutionWriteAction `
    -Runtime $runtime `
    -ExecutionManifestPath ([string]$execute.execution_manifest_path) `
    -SessionRoot ([string]$skeleton.session_root) `
    -RunId $RunId `
    -Task $Task `
    -Grade $grade
$memoryCleanupDecision = Get-VibeCleanupDecisionWriteAction `
    -RequirementDocPath $primaryRequirementDocPath `
    -ExecutionPlanPath $primaryExecutionPlanPath `
    -Runtime $runtime `
    -SessionRoot ([string]$skeleton.session_root) `
    -Task $Task
$memoryCleanupCognee = Get-VibeCogneeCleanupWriteAction `
    -Runtime $runtime `
    -Task $Task `
    -RequirementDocPath $primaryRequirementDocPath `
    -ExecutionPlanPath $primaryExecutionPlanPath `
    -ExecutionManifestPath ([string]$execute.execution_manifest_path) `
    -SessionRoot ([string]$skeleton.session_root)
$memoryCleanupFold = New-VibeCleanupMemoryFold `
    -RequirementDocPath $primaryRequirementDocPath `
    -ExecutionPlanPath $primaryExecutionPlanPath `
    -ExecutionManifestPath ([string]$execute.execution_manifest_path) `
    -CleanupReceiptPath ([string]$cleanup.receipt_path) `
    -SessionRoot ([string]$skeleton.session_root)
$memoryActivation = New-VibeMemoryActivationReport `
    -Runtime $runtime `
    -RunId $RunId `
    -SessionRoot ([string]$skeleton.session_root) `
    -SkeletonReadActions $skeletonMemoryReads `
    -DeepInterviewReadActions $deepInterviewMemoryReads `
    -RequirementContextPack $requirementMemoryContext `
    -XlPlanReadActions $xlPlanReadActions `
    -PlanContextPack $planMemoryContext `
    -PlanExecuteReadActions @($memoryPlanExecuteRead) `
    -PlanExecuteContextPack $executionMemoryContext `
    -PlanExecuteWriteActions @($memoryExecuteWrite, $memoryExecuteRufloWrite) `
    -CleanupWriteActions @($memoryCleanupDecision, $memoryCleanupCognee) `
    -CleanupFoldAction $memoryCleanupFold
$deliveryAcceptanceReportPath = Join-Path $skeleton.session_root 'delivery-acceptance-report.json'
$deliveryAcceptanceMarkdownPath = Join-Path $skeleton.session_root 'delivery-acceptance-report.md'
$executionManifestDocument = if (Test-Path -LiteralPath ([string]$execute.execution_manifest_path)) {
    Get-Content -LiteralPath ([string]$execute.execution_manifest_path) -Raw -Encoding UTF8 | ConvertFrom-Json
} else {
    $null
}
$deliveryAcceptanceReport = if (Test-Path -LiteralPath $deliveryAcceptanceReportPath) {
    Get-Content -LiteralPath $deliveryAcceptanceReportPath -Raw -Encoding UTF8 | ConvertFrom-Json
} else {
    $null
}
$deliveryAcceptanceReportArtifactPath = if (Test-Path -LiteralPath $deliveryAcceptanceReportPath) {
    [string]$deliveryAcceptanceReportPath
} else {
    ''
}
$deliveryAcceptanceMarkdownArtifactPath = if (Test-Path -LiteralPath $deliveryAcceptanceMarkdownPath) {
    [string]$deliveryAcceptanceMarkdownPath
} else {
    ''
}
$hostUserBriefing = New-VibeHostUserBriefingProjection `
    -DeliveryAcceptanceReport $deliveryAcceptanceReport
$hostStageDisclosurePath = Get-VibeHostStageDisclosurePath -SessionRoot ([string]$skeleton.session_root)
$hostStageDisclosure = if (Test-Path -LiteralPath $hostStageDisclosurePath) {
    Get-Content -LiteralPath $hostStageDisclosurePath -Raw -Encoding UTF8 | ConvertFrom-Json
} else {
    $null
}
$hostUserBriefingPath = $null
if ($hostUserBriefing) {
    $hostUserBriefingPath = Get-VibeHostUserBriefingPath -SessionRoot ([string]$skeleton.session_root)
    Write-VgoUtf8NoBomText -Path $hostUserBriefingPath -Content (([string]$hostUserBriefing.rendered_text) + [Environment]::NewLine)
}

return Complete-VibeGovernedRuntimeStop `
    -RunId $RunId `
    -Mode $Mode `
    -Task $Task `
    -ArtifactBaseRoot $artifactBaseRoot `
    -SessionRoot ([string]$skeleton.session_root) `
    -HierarchyState $hierarchyState `
    -StorageProjection $storageProjection `
    -Skeleton $skeleton `
    -RuntimeInput $runtimeInput `
    -GovernanceCapsule $governanceCapsule `
    -StageLineage $stageLineage `
    -Interview $interview `
    -Requirement $requirement `
    -Plan $plan `
    -Execute $execute `
    -Cleanup $cleanup `
    -HostStageDisclosure $hostStageDisclosure `
    -HostStageDisclosurePath $hostStageDisclosurePath `
    -HostUserBriefing $hostUserBriefing `
    -HostUserBriefingPath ([string]$hostUserBriefingPath) `
    -MemoryActivationReport $memoryActivation.report `
    -MemoryActivationReportPath ([string]$memoryActivation.report_path) `
    -MemoryActivationMarkdownPath ([string]$memoryActivation.markdown_path) `
    -DeliveryAcceptanceReport $deliveryAcceptanceReport `
    -DeliveryAcceptanceReportPath $deliveryAcceptanceReportArtifactPath `
    -DeliveryAcceptanceMarkdownPath $deliveryAcceptanceMarkdownArtifactPath `
    -ExecutionManifestDocument $executionManifestDocument `
    -DelegationValidation $delegationValidation
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall