# distill-shard-probe.ps1 — C11 (adap dot-11, S144 2026-07-22)
# Trigger nen-kết-tinh theo ĐẾM VẬT THẬT (so shard chua-gist), thay trigger ngay-lich.
# Owner: co-che = O-6 (anh chot) · so = min_pending_shards (anh chot 7 @S144).
#
# 🔴 SINGLE-SOURCE: nguong DOC TU memory-budget.json, KHONG hardcode o day (B1).
# 🔴 -RepoRoot = duong fault-inject (chay tren cay tam de chung script CO RANG, khong chi happy-path).
#
# SHARD = archive/<period>.md CHUA co <period>.gist.md cap doi.
# LOAI TRU tuong minh: _INDEX.md (muc-luc) + *.gist.md.
#   Vi sao phai ghi ro: bo dem dau tien cua lead ra 20, trong do 5 la _INDEX.md => 25% duong-gia.

param(
    [string]$RepoRoot = "$PSScriptRoot\..",
    [switch]$Quiet
)

$ErrorActionPreference = 'Stop'
$root      = (Resolve-Path $RepoRoot).Path
$budgetPath = Join-Path $root '.claude\agent-memory\memory-budget.json'
$memRoot    = Join-Path $root '.claude\agent-memory'

# --- doc nguong LIVE tu single-source (UTF8 tuong minh — tranh bay encoding E-010) ---
if (-not (Test-Path $budgetPath)) { Write-Output "SHARD-PROBE: khong thay memory-budget.json -> probe-loi (khong chan)"; exit 0 }
$raw = [IO.File]::ReadAllText($budgetPath, [Text.Encoding]::UTF8) -replace "^﻿", ""
$cfg = $raw | ConvertFrom-Json
$dt  = $cfg.distill_trigger
if ($null -eq $dt) { Write-Output "SHARD-PROBE: thieu key distill_trigger -> FAIL-LOUD (khong gia dinh default)"; exit 0 }

$minShards  = $dt.min_pending_shards
$bulkShards = $dt.bulk_note_shards

# --- dem shard chua-gist ---
$pending = @()
if (Test-Path $memRoot) {
    Get-ChildItem -Path $memRoot -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $arc = Join-Path $_.FullName 'archive'
        if (Test-Path $arc) {
            Get-ChildItem -Path $arc -Filter '*.md' -File -ErrorAction SilentlyContinue | ForEach-Object {
                $n = $_.Name
                if ($n -like '_INDEX*.md')   { return }   # muc-luc (ke ca ban rotate _INDEX-<period>.md @S167), KHONG phai shard
                if ($n -like '*.gist.md')    { return }   # ban nen, KHONG phai shard
                $gist = Join-Path $arc ($n -replace '\.md$', '.gist.md')
                if (-not (Test-Path $gist)) { $pending += $_.FullName }
            }
        }
    }
}
$n = $pending.Count

# --- phan dinh ---
if ($null -eq $minShards) {
    Write-Output "SHARD-PROBE: pending=$n | nguong=CHUA-DAT (null) => INERT, owner chua cho so"
    exit 0
}
# 🔴 RANH `-gt` KHONG PHAI `-ge` — doi @S144 sau owner-decision lan 2.
# Vi sao: owner chot "lay 15, TANG DAN neu them vao" = nguong NEO VAO trang-thai hien tai
# (15 shard da-phu) => 15 phai IM, chi 16+ moi KEU. Voi `-ge` thi 15 keu ngay = vo nghia.
# 🔸 Toan-tu la thu CUA LEAD (lead viet sang nay), so 15 la thu CUA OWNER. Lead sua toan-tu
# cho khop y-dinh owner, KHONG dung con so. Owner veto duoc bat ky luc nao.
$fire = ($n -gt $minShards)
$state = if ($fire) { 'KEU' } else { 'IM' }
$bulk = ''
if ($null -ne $bulkShards -and $n -gt $bulkShards) { $bulk = " | BAO-TO: backlog $n > $bulkShards (van nen het, chi canh bao)" }

Write-Output "SHARD-PROBE: pending=$n | nguong=$minShards => $state$bulk"
if ($fire -and -not $Quiet) {
    Write-Output "  -> de xuat chay /sleep-recovery-memory-l2 (nen additive, KHONG de ban goc)"
    $pending | Select-Object -First 8 | ForEach-Object { Write-Output "     $($_.Substring($root.Length+1))" }
    if ($n -gt 8) { Write-Output "     ... +$($n-8) shard nua" }
}
exit 0
