Skip to content

VladimirGutuev/cross-agent-memory / skills/cross-agent-handoff

cross-agent-handoff

Verified

Transfer unfinished feature work between Claude Code, Codex, Kimi Code, Antigravity, or another coding-agent harness with a verified worktree snapshot. Use only when the user asks to hand off, continue, resume, pause, close, or supersede work in progress, or when the shared-memory index contains an active handoff that clearly matches the current task. Do not invoke for a new unrelated task or ordinary shared-memory recall.

scripts/new-handoff.ps1

View on GitHub
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidatePattern('^[a-z0-9]+(?:-[a-z0-9]+)*$')]
    [string]$Slug,

    [Parameter(Mandatory = $true)]
    [string]$Goal,

    [Parameter(Mandatory = $true)]
    [string]$SourceAgent,

    [Parameter(Mandatory = $true)]
    [string]$TargetAgent,

    [string[]]$OwnedPath = @(),
    [string]$BaseRef,
    [string]$RepositoryRoot,
    [string]$MemoryRoot
)

$ErrorActionPreference = 'Stop'

function ConvertTo-YamlScalar([string]$value) {
    return "'" + $value.Replace("'", "''") + "'"
}

function ConvertTo-IndexText([string]$value) {
    $singleLine = ($value -replace '\r?\n', ' ') -replace '\s+', ' '
    return $singleLine.Trim().Replace('[', '(').Replace(']', ')').Replace('`', "'")
}

function Join-PathSegments([string]$basePath, [string[]]$segments) {
    $result = $basePath
    foreach ($segment in $segments) {
        $result = Join-Path $result $segment
    }
    return $result
}

function Invoke-GitText([string[]]$arguments, [switch]$AllowFailure) {
    $previousErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = 'Continue'
    try {
        $output = (& git -C $script:resolvedRepositoryRoot @arguments 2>$null | Out-String).Trim()
        $exitCode = $LASTEXITCODE
    }
    finally {
        $ErrorActionPreference = $previousErrorActionPreference
    }
    if ($exitCode -ne 0 -and -not $AllowFailure) {
        throw "git $($arguments -join ' ') failed with exit code $exitCode."
    }
    return [pscustomobject]@{
        Text = $output
        ExitCode = $exitCode
    }
}

if ($RepositoryRoot) {
    $script:resolvedRepositoryRoot = (Resolve-Path -LiteralPath $RepositoryRoot).Path
}
else {
    $gitRoot = (& git rev-parse --show-toplevel 2>$null | Out-String).Trim()
    if ($LASTEXITCODE -ne 0 -or -not $gitRoot) {
        throw 'Run this script inside a Git repository or pass -RepositoryRoot.'
    }
    $script:resolvedRepositoryRoot = (Resolve-Path -LiteralPath $gitRoot).Path
}

$insideWorkTree = Invoke-GitText -arguments @('rev-parse', '--is-inside-work-tree')
if ($insideWorkTree.Text -ne 'true') {
    throw "$script:resolvedRepositoryRoot is not a Git worktree."
}

if ($MemoryRoot) {
    if ([System.IO.Path]::IsPathRooted($MemoryRoot)) {
        $resolvedMemoryRoot = [System.IO.Path]::GetFullPath($MemoryRoot)
    }
    else {
        $resolvedMemoryRoot = [System.IO.Path]::GetFullPath((Join-Path $script:resolvedRepositoryRoot $MemoryRoot))
    }
}
else {
    $resolvedMemoryRoot = Join-PathSegments $script:resolvedRepositoryRoot @('docs', 'agent-memory')
}

$indexPath = Join-Path $resolvedMemoryRoot 'MEMORY.md'
if (-not (Test-Path -LiteralPath $indexPath -PathType Leaf)) {
    throw "Shared-memory index is missing: $indexPath"
}

$startMarker = '<!-- cross-agent-handoffs:start -->'
$endMarker = '<!-- cross-agent-handoffs:end -->'
$markerPattern = '(?ms)<!-- cross-agent-handoffs:start -->\s*(?<body>.*?)\s*<!-- cross-agent-handoffs:end -->'
$indexContent = Get-Content -LiteralPath $indexPath -Raw -Encoding UTF8
$markerMatches = [regex]::Matches($indexContent, $markerPattern)
if ($markerMatches.Count -ne 1) {
    throw "Shared-memory index must contain exactly one active-handoff marker block."
}

$templatePath = Join-PathSegments (Split-Path -Parent $PSScriptRoot) @('assets', 'handoff-template.md')
if (-not (Test-Path -LiteralPath $templatePath -PathType Leaf)) {
    throw "Handoff template is missing: $templatePath"
}

$head = (Invoke-GitText -arguments @('rev-parse', 'HEAD')).Text
$branchResult = Invoke-GitText -arguments @('symbolic-ref', '--quiet', '--short', 'HEAD') -AllowFailure
$branch = if ($branchResult.ExitCode -eq 0 -and $branchResult.Text) { $branchResult.Text } else { '(detached)' }

if ($BaseRef) {
    $base = (Invoke-GitText -arguments @('merge-base', 'HEAD', $BaseRef)).Text
}
else {
    $upstreamResult = Invoke-GitText -arguments @(
        'rev-parse',
        '--abbrev-ref',
        '--symbolic-full-name',
        '@{upstream}'
    ) -AllowFailure

    $baseCandidate = $null
    if ($upstreamResult.ExitCode -eq 0 -and $upstreamResult.Text) {
        $baseCandidate = $upstreamResult.Text
    }
    else {
        $originMainResult = Invoke-GitText -arguments @('rev-parse', '--verify', 'origin/main') -AllowFailure
        if ($originMainResult.ExitCode -eq 0) {
            $baseCandidate = 'origin/main'
        }
    }

    if ($baseCandidate) {
        $base = (Invoke-GitText -arguments @('merge-base', 'HEAD', $baseCandidate)).Text
    }
    else {
        $base = $head
    }
}

$statusLines = @(& git -C $script:resolvedRepositoryRoot status --porcelain=v1 --untracked-files=all)
if ($LASTEXITCODE -ne 0) {
    throw "git status failed with exit code $LASTEXITCODE."
}
$dirty = $statusLines.Count -gt 0

if ($OwnedPath.Count -gt 0) {
    $ownedStatusLines = @(& git -C $script:resolvedRepositoryRoot status --short -- $OwnedPath)
    if ($LASTEXITCODE -ne 0) {
        throw "git status for -OwnedPath failed with exit code $LASTEXITCODE."
    }

    $scope = ($OwnedPath | ForEach-Object { '- `{0}`' -f $_ }) -join "`n"
    if ($ownedStatusLines.Count -gt 0) {
        $changedFiles = ($ownedStatusLines | ForEach-Object { '- `{0}`' -f $_.TrimEnd() }) -join "`n"
    }
    else {
        $changedFiles = '- No changes reported for the declared paths at creation time.'
    }
}
else {
    $scope = '- FILL BEFORE TRANSFER: declare exact owned paths and exclusions.'
    $changedFiles = '- FILL BEFORE TRANSFER: list only files owned by this feature.'
}

$utcNow = [DateTimeOffset]::UtcNow
$timestamp = $utcNow.ToString('yyyyMMdd-HHmmss')
$isoTimestamp = $utcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
$id = "$timestamp-$Slug"
$activeRoot = Join-PathSegments $resolvedMemoryRoot @('handoffs', 'active')
[void](New-Item -ItemType Directory -Path $activeRoot -Force)
$outputPath = Join-Path $activeRoot "$id.md"
if (Test-Path -LiteralPath $outputPath) {
    throw "Handoff already exists: $outputPath"
}

$repositoryName = Split-Path -Leaf $script:resolvedRepositoryRoot
$worktreeSummary = if ($dirty) {
    "dirty; Git reports $($statusLines.Count) changed or untracked path(s). Only declared feature paths are owned."
}
else {
    'clean'
}

$content = Get-Content -LiteralPath $templatePath -Raw -Encoding UTF8
$replacements = [ordered]@{
    '{{ID}}' = $id
    '{{SOURCE_AGENT}}' = ConvertTo-YamlScalar $SourceAgent
    '{{TARGET_AGENT}}' = ConvertTo-YamlScalar $TargetAgent
    '{{CREATED_AT}}' = $isoTimestamp
    '{{UPDATED_AT}}' = $isoTimestamp
    '{{REPOSITORY}}' = ConvertTo-YamlScalar $repositoryName
    '{{WORKTREE}}' = ConvertTo-YamlScalar $script:resolvedRepositoryRoot
    '{{BRANCH}}' = ConvertTo-YamlScalar $branch
    '{{BASE_SHA}}' = $base
    '{{HEAD_SHA}}' = $head
    '{{DIRTY}}' = $dirty.ToString().ToLowerInvariant()
    '{{SLUG}}' = $Slug
    '{{GOAL}}' = $Goal
    '{{SCOPE}}' = $scope
    '{{CHANGED_FILES}}' = $changedFiles
    '{{WORKTREE_SUMMARY}}' = $worktreeSummary
}
foreach ($replacement in $replacements.GetEnumerator()) {
    $content = $content.Replace($replacement.Key, $replacement.Value)
}

[System.IO.File]::WriteAllText(
    $outputPath,
    $content,
    [System.Text.UTF8Encoding]::new($false)
)

$indexContent = Get-Content -LiteralPath $indexPath -Raw -Encoding UTF8
$markerMatches = [regex]::Matches($indexContent, $markerPattern)
if ($markerMatches.Count -ne 1) {
    throw "Shared-memory index changed and no longer has exactly one active-handoff marker block."
}

$existingBodyLines = @(
    $markerMatches[0].Groups['body'].Value -split '\r?\n' |
        ForEach-Object { $_.Trim() } |
        Where-Object { $_ -and $_ -ne '- None.' }
)
if ($existingBodyLines -match [regex]::Escape("handoffs/active/$id.md")) {
    throw "Shared-memory index already contains a pointer for '$id'."
}

$goalForIndex = ConvertTo-IndexText $Goal
$targetForIndex = ConvertTo-IndexText $TargetAgent
$branchForIndex = ConvertTo-IndexText $branch
$pointer = '- [{0}](handoffs/active/{0}.md) - {1}; target: `{2}`; branch: `{3}`.' -f @(
    $id,
    $goalForIndex,
    $targetForIndex,
    $branchForIndex
)
$pointerLines = @($existingBodyLines) + @($pointer)
$lineEnding = if ($indexContent.Contains("`r`n")) { "`r`n" } else { "`n" }
$newMarkerBlock = $startMarker + $lineEnding +
    ($pointerLines -join $lineEnding) + $lineEnding +
    $endMarker
$markerRegex = [regex]::new(
    $markerPattern,
    [System.Text.RegularExpressions.RegexOptions]::Multiline -bor
        [System.Text.RegularExpressions.RegexOptions]::Singleline
)
$updatedIndexContent = $markerRegex.Replace(
    $indexContent,
    [System.Text.RegularExpressions.MatchEvaluator]{
        param($match)
        return $newMarkerBlock
    },
    1
)
[System.IO.File]::WriteAllText(
    $indexPath,
    $updatedIndexContent,
    [System.Text.UTF8Encoding]::new($false)
)

Write-Host "Created handoff draft: $outputPath" -ForegroundColor Green
Write-Host "Added active pointer to: $indexPath"
Write-Host 'Replace every FILL BEFORE TRANSFER marker, then run validate-handoffs.ps1.'
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall