# file-change-tracker.ps1 -- PostToolUse hook
# Records all file modifications with SHA-256 hashes for rollback and blame.
# Never blocks (always exits 0).
#
# Part of @connexum/ai-governance

$rawInput = [Console]::In.ReadToEnd()

if ([string]::IsNullOrWhiteSpace($rawInput)) { exit 0 }

try { $input_obj = $rawInput | ConvertFrom-Json } catch { exit 0 }

$toolName = if ($input_obj.tool_name) { $input_obj.tool_name } else { '' }
$toolInput = $input_obj.tool_input

# Only track file modification tools
if ($toolName -notin 'Edit', 'Write', 'NotebookEdit') { exit 0 }

$filePath = if ($toolInput.file_path) { $toolInput.file_path }
             elseif ($toolInput.path) { $toolInput.path }
             else { '' }

if (-not $filePath -or -not (Test-Path $filePath)) { exit 0 }

$agentName = if ($input_obj.agent_name) { $input_obj.agent_name } else { 'unknown' }
$timestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')
$sessionId = if ($env:CXNI_SESSION_ID) { $env:CXNI_SESSION_ID } else { [DateTimeOffset]::UtcNow.ToUnixTimeSeconds().ToString() }

# Compute current file hash (after modification)
try {
    $afterHash = (Get-FileHash -Path $filePath -Algorithm SHA256).Hash.ToLower()
    $fileSize = (Get-Item $filePath).Length
} catch {
    $afterHash = 'error'
    $fileSize = 0
}

# Change tracking directory
$trackDir = $null
foreach ($candidate in @(
    '.claude/governance/file-changes',
    '.claude/audit/file-changes',
    'GOVERNANCE/file-changes'
)) {
    if (Test-Path $candidate) {
        $trackDir = $candidate
        break
    }
    try {
        New-Item -ItemType Directory -Path $candidate -Force | Out-Null
        $trackDir = $candidate
        break
    } catch { continue }
}

if (-not $trackDir) { exit 0 }

$trackFile = Join-Path $trackDir "changes-$([DateTime]::UtcNow.ToString('yyyy-MM-dd')).jsonl"

$entry = @{
    timestamp = $timestamp
    session = $sessionId
    agent = $agentName
    tool = $toolName
    file = $filePath
    sha256 = $afterHash
    bytes = $fileSize
} | ConvertTo-Json -Compress

try {
    Add-Content -Path $trackFile -Value $entry -ErrorAction SilentlyContinue
} catch { }

exit 0
