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/close-handoff.ps1

View on GitHub
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidatePattern('^[0-9]{8}-[0-9]{6}-[a-z0-9]+(?:-[a-z0-9]+)*$')]
    [string]$Id,

    [Parameter(Mandatory = $true)]
    [ValidateSet('closed', 'superseded')]
    [string]$Status,

    [ValidatePattern('^[0-9]{8}-[0-9]{6}-[a-z0-9]+(?:-[a-z0-9]+)*$')]
    [string]$Replacement,

    [string]$RepositoryRoot,
    [string]$MemoryRoot
)

$ErrorActionPreference = 'Stop'

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

function Get-FrontMatter([string]$content) {
    $match = [regex]::Match(
        $content,
        '\A---\r?\n(?<frontmatter>.*?)\r?\n---(?:\r?\n|$)',
        [System.Text.RegularExpressions.RegexOptions]::Singleline
    )
    if (-not $match.Success) {
        throw 'Handoff is missing YAML frontmatter.'
    }

    $metadata = @{}
    foreach ($line in ($match.Groups['frontmatter'].Value -split '\r?\n')) {
        if ($line -match '^\s*([A-Za-z][A-Za-z0-9_-]*):\s*(.*?)\s*$') {
            $key = $Matches[1]
            $value = $Matches[2].Trim()
            if (
                $value.Length -ge 2 -and
                (($value.StartsWith("'") -and $value.EndsWith("'")) -or
                ($value.StartsWith('"') -and $value.EndsWith('"')))
            ) {
                $value = $value.Substring(1, $value.Length - 2)
            }
            $metadata[$key] = $value
        }
    }
    return $metadata
}

function Set-FrontMatterField(
    [string]$content,
    [string]$field,
    [string]$value
) {
    $headerMatch = [regex]::Match(
        $content,
        '\A---(?<newline>\r?\n)(?<frontmatter>.*?)(?<closing>\r?\n)---(?<after>\r?\n|$)',
        [System.Text.RegularExpressions.RegexOptions]::Singleline
    )
    if (-not $headerMatch.Success) {
        throw 'Handoff is missing YAML frontmatter.'
    }

    $lineEnding = $headerMatch.Groups['newline'].Value
    $frontmatter = $headerMatch.Groups['frontmatter'].Value
    $fieldPattern = "(?m)^$([regex]::Escape($field)):\s*.*$"
    if ([regex]::IsMatch($frontmatter, $fieldPattern)) {
        $replacementLine = "$field`: $value"
        $frontmatter = [regex]::Replace(
            $frontmatter,
            $fieldPattern,
            [System.Text.RegularExpressions.MatchEvaluator]{
                param($match)
                return $replacementLine
            },
            1
        )
    }
    else {
        $frontmatter = $frontmatter.TrimEnd("`r", "`n") +
            $lineEnding + "$field`: $value"
    }

    $body = $content.Substring($headerMatch.Length)
    return '---' + $lineEnding + $frontmatter +
        $lineEnding + '---' + $headerMatch.Groups['after'].Value + $body
}

if ($Status -eq 'superseded' -and [string]::IsNullOrWhiteSpace($Replacement)) {
    throw '-Replacement is required when -Status superseded.'
}
if ($Status -eq 'closed' -and -not [string]::IsNullOrWhiteSpace($Replacement)) {
    throw '-Replacement is valid only when -Status superseded.'
}
if ($Replacement -eq $Id) {
    throw 'A handoff cannot supersede itself.'
}

if ($RepositoryRoot) {
    $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.'
    }
    $resolvedRepositoryRoot = (Resolve-Path -LiteralPath $gitRoot).Path
}

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

$indexPath = Join-Path $resolvedMemoryRoot 'MEMORY.md'
$activePath = Join-PathSegments $resolvedMemoryRoot @('handoffs', 'active', "$Id.md")
$archiveRoot = Join-PathSegments $resolvedMemoryRoot @('handoffs', 'archive')
$archivePath = Join-Path $archiveRoot "$Id.md"

if (-not (Test-Path -LiteralPath $indexPath -PathType Leaf)) {
    throw "Shared-memory index is missing: $indexPath"
}
if (-not (Test-Path -LiteralPath $activePath -PathType Leaf)) {
    throw "Active handoff is missing: $activePath"
}
if (Test-Path -LiteralPath $archivePath) {
    throw "Archive target already exists: $archivePath"
}

$content = Get-Content -LiteralPath $activePath -Raw -Encoding UTF8
if ($content -match 'FILL BEFORE TRANSFER|\bTODO\b') {
    throw 'Resolve every transfer placeholder before closing the handoff.'
}
$metadata = Get-FrontMatter $content
if (-not $metadata.ContainsKey('id') -or $metadata['id'] -ne $Id) {
    throw "Handoff frontmatter id must equal '$Id'."
}
if (
    -not $metadata.ContainsKey('status') -or
    $metadata['status'] -notin @('active', 'paused', 'blocked')
) {
    throw 'Only an active, paused, or blocked handoff can be closed.'
}

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

$pointerPattern = [regex]::Escape("handoffs/active/$Id.md")
$bodyLines = @(
    $markerMatches[0].Groups['body'].Value -split '\r?\n' |
        ForEach-Object { $_.Trim() } |
        Where-Object { $_ }
)
$matchingLines = @($bodyLines | Where-Object { $_ -match $pointerPattern })
if ($matchingLines.Count -ne 1) {
    throw "Shared-memory index must contain exactly one active pointer for '$Id'."
}
$remainingLines = @(
    $bodyLines |
        Where-Object { $_ -notmatch $pointerPattern -and $_ -ne '- None.' }
)
if ($remainingLines.Count -eq 0) {
    $remainingLines = @('- None.')
}

$lineEnding = if ($indexContent.Contains("`r`n")) { "`r`n" } else { "`n" }
$newMarkerBlock = '<!-- cross-agent-handoffs:start -->' + $lineEnding +
    ($remainingLines -join $lineEnding) + $lineEnding +
    '<!-- cross-agent-handoffs:end -->'
$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
)

$updatedAt = [DateTimeOffset]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
$updatedContent = Set-FrontMatterField $content 'status' $Status
$updatedContent = Set-FrontMatterField $updatedContent 'updated_at' $updatedAt
if ($Status -eq 'superseded') {
    $updatedContent = Set-FrontMatterField $updatedContent 'superseded_by' $Replacement
}

[void](New-Item -ItemType Directory -Path $archiveRoot -Force)
[System.IO.File]::WriteAllText(
    $activePath,
    $updatedContent,
    [System.Text.UTF8Encoding]::new($false)
)
Move-Item -LiteralPath $activePath -Destination $archivePath
[System.IO.File]::WriteAllText(
    $indexPath,
    $updatedIndexContent,
    [System.Text.UTF8Encoding]::new($false)
)

Write-Host "Archived handoff: $archivePath" -ForegroundColor Green
Write-Host "Removed active pointer from: $indexPath"
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