feat(usage): reproduce TokenTracker session_hash for task attribution

This commit is contained in:
mika kuns
2026-08-24 13:31:29 +02:00
parent 0e74650d70
commit 1cb574bd96
2 changed files with 58 additions and 0 deletions
@@ -0,0 +1,25 @@
using System.Security.Cryptography;
using System.Text;
namespace ClaudeDo.Worker.Usage.TokenTracker;
/// <summary>
/// Reproduces TokenTracker's session identity so its export rows can be joined onto our
/// <c>task_runs.session_id</c>. The formula is <c>sha256(source + "\0" + id)</c>, hex, first
/// 24 chars (TokenTracker's <c>lib/session-analytics.js</c>, <c>sessionHash()</c>). The export
/// never carries the raw session id, so this is the only way to attribute a row to a task.
/// Verified against a real export on 2026-08-24 — the test vectors are the proof, don't touch them.
/// </summary>
public static class SessionHash
{
private const int HashLength = 24;
public static string? ForClaudeSession(string? sessionId)
{
if (string.IsNullOrWhiteSpace(sessionId)) return null;
var bytes = Encoding.UTF8.GetBytes($"claude\0{sessionId}");
var hash = SHA256.HashData(bytes);
return Convert.ToHexString(hash).ToLowerInvariant()[..HashLength];
}
}