# wal-flush.ps1 - WAL persist-only Stop hook (H22 S111). KHONG sinh noi dung, KHONG push, KHONG block.
# Fail-open MOI nhanh: exit 0 ke ca loi (Stop-hook exit!=0 co hanh vi rieng - CAM).
# Per-path add + CAND commit (X3: add/commit da-pathspec = all-or-nothing khi 1 path vang).
try {
  $root = if ($env:CLAUDE_PROJECT_DIR) { $env:CLAUDE_PROJECT_DIR } else { "." }
  Set-Location $root
  # INTERLOCK rebase-state (S120 W0.3). Dang rebase/mid-surgery => HEAD co the DETACHED.
  # Commit len detached HEAD = mo-coi commit khi `rebase --abort` => MAT VIEC (R3 fault-inject chung minh).
  # Guard nay THU HEP hook, KHONG them hanh-vi: no chan hook TU-HUY chinh floor N.2 ma no phuc-vu
  # (anh ky S119 fix#8b = TRONG KHUNG, khong can adap-request).
  # !! Dat SAU Set-Location: dat truoc thi Test-Path soi nham CWD (hook chay tu thu-muc bat-ky).
  if ((Test-Path ".git/rebase-merge") -or (Test-Path ".git/rebase-apply")) { exit 0 }
  $paths = @(".claude/WAL.md", ".claude/agent-memory/", ".claude/workflows/runs/", ".claude/sessions/")
  # 4 path (S146): +.claude/sessions/ = thu-muc phien-LOGIC (session-model, hub-form session-<N>).
  # Floor canonical = engine PHAN N (N.2) - B1 con-tro, KHONG dien-giai lai luat o day.
  # !! GIU $paths O DUNG DONG 13: nhieu doc trich-dan "wal-flush.ps1:13" (tiep.md :23, spec, memory).
  #    Chen dong TREN day = lao-hoa het cac trich-dan do (class acceptance-literal-tu-lao-hoa S121).
  $cand = @()
  foreach ($p in $paths) {
    git add -- $p 2>$null
    git diff --cached --quiet -- $p 2>$null
    if ($LASTEXITCODE -ne 0) { $cand += $p }
  }
  if ($cand.Count -gt 0) {
    $ts = Get-Date -Format "yyyyMMddTHHmm"
    git commit -q -m "wal: flush $ts" -- $cand 2>$null | Out-Null
  }
} catch { }
exit 0
