[content] src/gitProvider.ts (typescript)
let gitStashWatcher: vscode.FileSystemWatcher | undefined
let gitRefsWatcher: vscode.FileSystemWatcher | undefined

// Track recent git operation for annotating filesystem changes
let recentGitOperation: RecentGitOperation | null = null
const GIT_OPERATION_WINDOW_MS = 5000 // 5 seconds to attribute file changes to git

// ============================================================================
// Git State Detection
// ============================================================================

const execAsync = util.promisify(child_process.exec)

async function getWorkspacePath(): Promise<string | null> {
	const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
	return workspaceFolder?.uri.fsPath || null
}

async function getCurrentBranch(): Promise<string | null> {
	try {
		const cwd = await getWorkspacePath()
		if (!cwd) return null
		
		const { stdout } = await execAsync('git branch --show-current', { cwd })
		return stdout.trim() || null
	} catch {
		return null
	}
}

async function getCurrentCommit(): Promise<string | null> {
	try {
		const cwd = await getWorkspacePath()
		if (!cwd) return null
		
		const { stdout } = await execAsync('git rev-parse HEAD', { cwd })
		return stdout.trim() || null
	} catch {
		return null
	}
}

// ============================================================================
// Git Change Handling
// ============================================================================

function detectOperationType(fileType: 'head' | 'stash' | 'refs', branchChanged: boolean): GitOperationType {
	if (fileType === 'stash') {
		return 'stash'
	}
	if (fileType === 'head' && branchChanged) {
		return 'checkout'
	}
	// refs changes without branch change typically indicate pull/fetch/merge
	// We default to 'pull' as the most common case
	return 'pull'
}

async function handleGitFileChange(fileType: 'head' | 'stash' | 'refs'): Promise<void> {
	logToOutput(`Git ${fileType} file changed`, 'info')

	// Detect what changed
	const newBranch = await getCurrentBranch()
	const newCommit = await getCurrentCommit()
	const workspacePath = await getWorkspacePath()
	const repository = workspacePath || 'unknown'

	const branchChanged = currentGitState !== null && newBranch !== currentGitState.branch
	const commitChanged = currentGitState !== null && newCommit !== currentGitState.lastCommit

	if (fileType === 'head') {
		if (branchChanged) {
			logToOutput(`Branch changed from '${currentGitState?.branch}' to '${newBranch}'`, 'info')
		} else if (commitChanged) {
			logToOutput(`HEAD moved to ${newCommit?.substring(0, 7)}`, 'info')
		}
	} else if (fileType === 'stash' || fileType === 'refs') {
		logToOutput(`Git ${fileType} operation detected`, 'info')
	}

	// Record the git operation for filesystem change attribution
	const operationType = detectOperationType(fileType, branchChanged)
	recentGitOperation = {
		type: operationType,
		timestamp: Date.now(),
	}
	logToOutput(`Git operation recorded: ${operationType}`, 'info')

	// Update state
	if (newBranch) {
		currentGitState = {
			branch: newBranch,
			repository,
			lastCommit: newCommit,
		}
	}
}

// ============================================================================
// Public API
// ============================================================================

/**
 * Check if there was a recent git operation that could explain filesystem changes
 * Returns the operation type if within the time window, null otherwise
 */
export function getRecentGitOperation(): GitOperationType | null {
	if (!recentGitOperation) return null
	
	const elapsed = Date.now() - recentGitOperation.timestamp
	if (elapsed < GIT_OPERATION_WINDOW_MS) {
		return recentGitOperation.type
	}
	return null
}

// ============================================================================
// Initialization
// ============================================================================

async function tryInitializeGitProvider(): Promise<void> {
	try {
		const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
		if (!workspaceFolder) {
			logToOutput('No workspace folder found', 'info')
			return
		}

		// Check if this is a git repository
		const gitDir = vscode.Uri.joinPath(workspaceFolder.uri, '.git')
		try {
			await vscode.workspace.fs.stat(gitDir)
			logToOutput('Git repository found', 'info')

			// Get initial state
			const branch = await getCurrentBranch()
			const commit = await getCurrentCommit()
			
			currentGitState = {
				branch: branch || 'unknown',
				repository: workspaceFolder.uri.fsPath,
				lastCommit: commit,
			}
			
			logToOutput(`Initial git state: branch=${branch}, commit=${commit?.substring(0, 7)}`, 'info')

			// Watch .git/HEAD for branch changes
			gitHeadWatcher = vscode.workspace.createFileSystemWatcher(
				new vscode.RelativePattern(workspaceFolder, '.git/HEAD')
			)
			gitHeadWatcher.onDidChange(() => handleGitFileChange('head'))

			// Watch .git/refs for reference changes (pull, push, etc.)
			gitRefsWatcher = vscode.workspace.createFileSystemWatcher(
				new vscode.RelativePattern(workspaceFolder, '.git/refs/**/*')
			)
			gitRefsWatcher.onDidChange(() => handleGitFileChange('refs'))
			gitRefsWatcher.onDidCreate(() => handleGitFileChange('refs'))
			gitRefsWatcher.onDidDelete(() => handleGitFileChange('refs'))

			// Watch .git/refs/stash for stash operations
			gitStashWatcher = vscode.workspace.createFileSystemWatcher(
				new vscode.RelativePattern(workspaceFolder, '.git/refs/stash')
			)
			gitStashWatcher.onDidChange(() => handleGitFileChange('stash'))
			gitStashWatcher.onDidCreate(() => handleGitFileChange('stash'))
			gitStashWatcher.onDidDelete(() => handleGitFileChange('stash'))

			// Periodic state check as fallback
			gitStateCheckInterval = setInterval(async () => {
				const newBranch = await getCurrentBranch()
				const newCommit = await getCurrentCommit()
				
				if (currentGitState) {
					if (newBranch && newBranch !== currentGitState.branch) {
						logToOutput(`Periodic check detected branch change: ${currentGitState.branch} -> ${newBranch}`, 'info')
						await handleGitFileChange('head')
					} else if (newCommit && newCommit !== currentGitState.lastCommit) {
						logToOutput(`Periodic check detected commit change: ${currentGitState.lastCommit?.substring(0, 7)} -> ${newCommit.substring(0, 7)}`, 'info')
						await handleGitFileChange('head')
					}
				}
			}, 5000)

			gitWatcherInitialized = true
			logToOutput('Git provider initialized successfully', 'info')
		} catch {
			logToOutput('Not a git repository', 'info')
		}
	} catch (error) {
		logToOutput(`Error initializing git provider: ${error}`, 'error')
	}
}