# measure-agent-memory.ps1 - Harness-9 seed-by-measure (2026-06-17)
# Measures REAL bytes of each agent-memory tier so memory-budget.json caps are
# set from measurement, NOT an imagined "headroom" number (Harness-9 step a).
# Output: JSON to stdout. ASCII-only (gotcha #30). PS 5.1 compatible.
param([string]$Root = "$PSScriptRoot\..\.claude\agent-memory")

if (-not (Test-Path $Root)) { Write-Error "agent-memory root not found: $Root"; exit 1 }

$rows = @()
Get-ChildItem -Path $Root -Directory | Sort-Object Name | ForEach-Object {
    $dir = $_.FullName
    $name = $_.Name
    $mem = Join-Path $dir 'MEMORY.md'
    $l1 = if (Test-Path $mem) { (Get-Item $mem).Length } else { 0 }

    $archDir = Join-Path $dir 'archive'
    $verbatim = 0; $index = 0; $gist = 0
    if (Test-Path $archDir) {
        Get-ChildItem -Path $archDir -Filter *.md | ForEach-Object {
            if ($_.Name -like '_INDEX*.md') { $index += $_.Length }   # S167 split: rotated _INDEX-<period>.md stays in the l2_index axis (not verbatim)
            elseif ($_.Name -like '*.gist.md') { $gist += $_.Length }
            else { $verbatim += $_.Length }
        }
    }

    $rows += [ordered]@{
        agent             = $name
        l1_hot_bytes      = $l1
        l2_verbatim_bytes = $verbatim
        l2_index_bytes    = $index
        l2_gist_bytes     = $gist
        l1_over_30kb      = ($l1 -gt 30720)
    }
}

[ordered]@{
    measured_at_note = "run date stamped by caller (Date.now unavailable in workflow scripts)"
    soft_cap_l1_bytes = 30720
    autoinject_cap_bytes = 25600
    agents = $rows
} | ConvertTo-Json -Depth 5
