π² The Core Mental Model: Managing Three Interconnected States of Code
The primary reason engineers struggle with Gitβresulting in accidental file losses, unintended merge conflicts, and panic during rebasesβis the misconception that Git merely syncs files between a local folder and a remote cloud server. In reality, Git operates as a content-addressable database governed by the Three-Tree Architecture. At any given moment, your code exists simultaneously across three distinct state representations: the Working Directory (your tangible, editable operating system filesystem files), the Staging Area / Index (an in-memory binary cache located at .git/index staging the exact proposed snapshot for the next commit), and the Repository (HEAD) (the immutable, cryptographically hashed tree object representing the last recorded commit). Commands such as git add, git commit, git reset, and git restore are not arbitrary file manipulation tools; they are precise, deterministic vector transitions designed to synchronize, compare, and transfer state across these three fundamental trees.
THE THREE TREES OF GIT: TOPOGRAPHY & FUNCTIONAL LIFECYCLE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TREE 1: THE WORKING DIRECTORY (WORKING TREE) β
β β’ Physical Location : The actual sandbox directory on your operating system disk. β
β β’ Mutability : Fully mutable by human editors, IDEs, compiler scripts, and build tools.β
β β’ Format : Raw plaintext files, directories, subdirectories, and uncompiled code. β
β β’ Lifecycle : Scratchpad zone. Contains modifications that Git has NOT YET recorded. β
β β’ Tracking Status : Files can be Untracked, Modified, or Unmodified. β
βββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββ
β
git add <file> β git restore <file>
(Staging Step) β (Discard local work)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TREE 2: THE STAGING AREA (THE INDEX / CACHE) β
β β’ Physical Location : .git/index (A high-speed binary ledger file in the repository root). β
β β’ Mutability : Semi-mutable; modified strictly via Git plumbing and porcelain commands.β
β β’ Format : Flat binary list of filenames, stat() metadata, and 40-char SHA-1 hashesβ
β pointing directly to newly created zlib-compressed blob objects! β
β β’ Lifecycle : The "Proposed Commit Snapshot". It defines EXACTLY what the next commit β
β object will look like before you record it to history. β
βββββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββ
β
git commit β git reset --soft HEAD~1
(Recording Step)β (Uncommit to Staging)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TREE 3: THE REPOSITORY (HEAD COMMIT SNAPSHOT) β
β β’ Physical Location : .git/objects/ (Content-Addressable Object Database). β
β β’ Mutability : IMMUTABLE. Once committed, cryptographic hashes freeze content history. β
β β’ Format : Directed Acyclic Graph (DAG) of Commit, Tree, and Blob objects. β
β β’ Lifecycle : Permanent audit history. HEAD is a pointer referencing the tip of the β
β currently active branch commit in the repository graph. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
.git/index. Demonstrates how Git caches operating system stat() metadata (mtime, ctime, inode, file size) to detect modified files in milliseconds without re-hashing file content.
BINARY LAYOUT OF THE GIT INDEX FILE (.git/index / DIRC FORMAT):
The index is a binary cache mapping directory paths to object database SHA-1/SHA-256 hashes:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INDEX FILE HEADER (12 BYTES TOTAL): β
β β’ Bytes 0-3 : 4-byte signature: Always "DIRC" (Directory Cache: 0x44 0x49 0x52 0x43). β
β β’ Bytes 4-7 : 4-byte version number: Typically Version 2, 3, or 4 (0x00 0x00 0x00 0x02). β
β β’ Bytes 8-11 : 32-bit integer: The total count of tracked file entries in the index. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Followed by N sorted directory entries)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INDEX ENTRY STRUCT (REPEATED FOR EVERY TRACKED FILE IN THE PROJECT): β
β 1. ctime seconds (4B) & ctime nanosecond fraction (4B) : File status change time. β
β 2. mtime seconds (4B) & mtime nanosecond fraction (4B) : File data modification time. β
β 3. dev (4B) & ino (4B) : Inode number and device ID. β
β 4. mode (4B) : POSIX file permissions (100644/100755) β
β 5. uid (4B) & gid (4B) : User ID and Group ID of the owner. β
β 6. file size (4B) : On-disk physical size in bytes. β
β 7. SHA-1 Object Hash (20 Bytes) : Cryptographic hash of the blob! β
β 8. Flags (16-bit integer) : Stage flags (0=normal, 1/2/3=merge). β
β 9. Path string (Variable length) : Relative filepath (e.g. "auth/jwt.py") β
β 10. Null padding bytes : Aligns struct to 8-byte boundaries. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (File ends with validation check)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SHA-1 CHECKSUM (20 BYTES): β
β β’ A final 160-bit SHA-1 hash over the content of the index file, ensuring zero corruption! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
git add, git commit, git checkout, git restore, git reset) shift data between the Working Tree, Index, and HEAD.
COMMAND VECTOR MATRIX ACROSS THE THREE TREES:
βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββ¬ββββββββββββββββββββ¬ββββββββββββββββββββββββββ
β COMMAND INVOCATION β SOURCE TREE β DESTINATION TREE β OPERATIONAL IMPACT β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git add <file> β Working Directory β Staging Index β Creates blob in repo; β
β β β β updates .git/index β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git commit β Staging Index β Repository (HEAD) β Creates Tree & Commit β
β β β β nodes; advances HEAD β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git commit -a β Working Directory β Staging & HEAD β Bypasses manual add; β
β β (Tracked files) β (Simultaneously) β updates both in 1 step β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git restore <file> β Staging Index β Working Directory β DISCARDS uncommitted β
β (Legacy: git checkout -- f) β β β changes in workspace! β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git restore --staged <file> β Repository (HEAD) β Staging Index β Unstages a file; keeps β
β (Legacy: git reset HEAD f) β β β working disk intact! β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git restore --source=HEAD -p β Repository (HEAD) β Working Directory β Restores specific β
β <file> β β β interactive patch hunk β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git reset --soft HEAD~1 β HEAD History β HEAD Pointer ONLY β Undoes commit; leaves β
β β β β Index & Work Tree intactβ
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git reset --mixed HEAD~1 β HEAD History β HEAD & Index β Undoes commit & stages; β
β (Default behavior of reset) β β β leaves Work Tree files β
βββββββββββββββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββΌββββββββββββββββββββββββββ€
β git reset --hard HEAD~1 β HEAD History β ALL THREE TREES! β CATASTROPHIC RESET: β
β β β HEAD, Index, Work β Destroys all workspace β
βββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββββ΄ββββββββββββββββββββββββββ
git diff, git diff --staged, and git diff HEAD inspect, and how Git derives change vectors.
THE THREE-TREE COMPARATIVE DIFF GEOMETRY:
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β WORKING DIRECTORY (LOCAL DISK) β
βββββββββββββββββ²ββββββββββββββββββ²ββββββββββββββββ
β β
git diff β β git diff HEAD
(What is modified but NOT yet β β (Total combined diff:
staged for commit?) β β Working Tree vs. Last Commit)
βΌ β
βββββββββββββββββββββββββββββββββββΌββ
β STAGING AREA (INDEX) β β
βββββββββββββββββ²ββββββββββββββββββΌββ
β β
git diff --staged / β β
git diff --cached β β
(What is staged and WILL be in β β
the very next commit?) βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β REPOSITORY (LAST COMMIT / HEAD) β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
COMMAND SPECIFICATION BREAKDOWN:
1. $ git diff
β’ Compares : Working Directory βββββΊ Staging Area (Index).
β’ Answers : "What modifications have I made on disk that I have NOT YET added with 'git add'?"
β’ Output : Shows zero lines if all modified files are already staged!
2. $ git diff --staged (Synonym: git diff --cached)
β’ Compares : Staging Area (Index) βββββΊ Repository (HEAD).
β’ Answers : "What changes have I staged that will be baked into the repository if I run 'git commit'?"
β’ Output : Shows the exact proposed delta of the upcoming commit.
3. $ git diff HEAD
β’ Compares : Working Directory βββββΊ Repository (HEAD).
β’ Answers : "What are all the differences between my physical disk files and the last recorded commit,
regardless of whether I ran 'git add' or not?"
git ls-files with stage flags, examining SHA-1 blob mappings, tracking merge conflict stages (0, 1, 2, 3), and inspecting raw index metadata.
# ==============================================================================
# LOW-LEVEL PLUMBING INSPECTION OF THE STAGING AREA (.git/index)
# ==============================================================================
# Step 1: Initialize an empty repository and create a file
$ mkdir three_tree_lab && cd three_tree_lab
$ git init
$ echo "console.log('v1');" > app.js
# Step 2: Query index status before staging (File is UNTRACKED)
$ git ls-files --stage
# (Output is completely empty! The file does NOT exist in Tree 2 or Tree 3)
# Step 3: Stage the file to copy it into Tree 2 (The Index)
$ git add app.js
# Step 4: Inspect the index ledger via low-level plumbing
$ git ls-files --stage --debug app.js
# SAMPLE OUTPUT:
# 100644 3b4e3e533604c5a9f0d8c5708c5ae48b8846f7ea 0 app.js
# ctime: 1793784000:0
# mtime: 1793784000:0
# dev: 16777220 ino: 88412098
# uid: 501 gid: 20
# size: 19 flags: 0
# ==============================================================================
# DISSECTING THE OUTPUT:
# β’ 100644 : POSIX mode (Standard non-executable file).
# β’ 3b4e3e : SHA-1 hash of the newly created blob object inside .git/objects/!
# β’ 0 : Merge Stage Flag!
# Stage 0 = Standard, clean, non-conflicting tracked file.
# Stage 1 = Common Ancestor version during a merge conflict.
# Stage 2 = Target branch version (ours / HEAD).
# Stage 3 = Incoming branch version (theirs / merging branch).
# β’ app.js : Relative path.
# β’ stat() : Cached filesystem metadata (ctime, mtime, inode, size).
# ==============================================================================
# Step 5: Verify that 'git add' IMMEDIATELY created a compressed blob object:
$ git cat-file -p 3b4e3e533604c5a9f0d8c5708c5ae48b8846f7ea
# Output: console.log('v1');
git reset engine. Explains the exact mechanical impact of --soft, --mixed, and --hard flags across the three trees, detailing how HEAD pointers, index entries, and disk files are modified.
THE THREE-STAGE ANATOMY OF GIT RESET:
Executing 'git reset <commit_id>' moves through three sequential steps based on your flag:
STEP 1: Move HEAD STEP 2: Update Index STEP 3: Overwrite Disk
(Repository Tree) (Staging Area Tree) (Working Directory)
βββββββββββββββββββββββ βββββββββββββββββββββββ βββββββββββββββββββββββ
β TREE 3 (HEAD) β β TREE 2 (INDEX) β β TREE 1 (WORKING) β
ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ
β β β
$ git reset --soft HEAD~1 βββββββββ (STOPS HERE) β β
β β
$ git reset --mixed HEAD~1 βββββββββββββββββββββββββββββββββββ (STOPS HERE) β
β
$ git reset --hard HEAD~1 βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ (COMPLETES ALL 3)
DETAILED BREAKDOWN OF EACH RESET MODE:
1. $ git reset --soft HEAD~1
β’ Modifies : Tree 3 (Repository / HEAD) ONLY.
β’ Action : Moves the current branch pointer backward by 1 commit.
β’ Result : The files from the undone commit remain staged in Tree 2 (Index)!
β’ Use Case : Perfect for combining (squashing) several small commits into one clean commit.
2. $ git reset --mixed HEAD~1 (DEFAULT BEHAVIOR)
β’ Modifies : Tree 3 (HEAD) AND Tree 2 (Index).
β’ Action : Moves the branch pointer backward by 1 commit AND copies that snapshot into the Index.
β’ Result : The commit is undone, and the changes are UNSTAGED. However, your physical files in
Tree 1 (Working Directory) are 100% untouched on disk!
β’ Use Case : "I want to unstage everything and re-craft my commit with different files."
3. $ git reset --hard HEAD~1 (DESTRUCTIVE MODE)
β’ Modifies : ALL THREE TREES (HEAD, Index, and Working Directory).
β’ Action : Moves HEAD backward, updates the Index, AND forcefully overwrites all physical files
on your hard drive to match the target commit!
β’ Result : Any uncommitted changes, edits, or local experimental code are PERMANENTLY ERASED!
β’ Use Case : "Throw away all current work and reset the workspace to match a known good commit."
git checkout was decoupled into git switch (branch navigation) and git restore (precise tree restoration), eliminating accidental data destruction.
MODERN RESTORATION ARCHITECTURE (GIT 2.23+ EVOLUTION):
HISTORICAL DEFECT (THE DANGEROUS OVERLOADING OF 'git checkout'):
For 15 years, 'git checkout' executed two completely contradictory operations:
1. Switching branches: $ git checkout feature-branch (Safe navigational action)
2. Overwriting disk files: $ git checkout -- main.js (Destructive file overwrite action)
A typing mistake could accidentally delete an entire day's uncommitted work!
THE MODERN DECOUPLED STANDARD:
Git split these responsibilities into two explicit, unambiguous commands:
β’ 'git switch' : Dedicated STRICTLY to branch navigation and branch creation.
β’ 'git restore' : Dedicated STRICTLY to transferring state across the Three Trees!
RESTORATION WORKFLOW EXAMPLES (EXPLICIT TREE TARGETING):
# 1. Discard uncommitted edits in Working Directory (Copy Tree 2 β Tree 1)
# Overwrites modified local file with the version currently staged in the Index:
$ git restore src/auth.js
# 2. Unstage a file (Copy Tree 3 β Tree 2)
# Copies the file from HEAD into the Index without touching your working disk:
$ git restore --staged src/auth.js
# 3. Discard both staged AND unstaged changes (Copy Tree 3 β Tree 2 AND Tree 1)
# Restores both the Staging Index and physical disk to match the last commit:
$ git restore --source=HEAD --staged --worktree src/auth.js
# 4. Interactive Patch Restoration (Partial Hunk Reversion)
# Review changes line by line and restore only specific blocks from Staging to Disk:
$ git restore -p src/auth.js
.git/index via plumbing, reads the HEAD commit tree, and reports the exact file status across all three tiers.
import subprocess
import os
import hashlib
from typing import Dict, Any, List
class GitThreeTreeTracker:
"""
Automated Three-Tree State Inspector:
1. Inspects Tree 1: Working Directory physical files on disk.
2. Inspects Tree 2: Staging Area (.git/index) via 'git ls-files -s'.
3. Inspects Tree 3: Repository HEAD commit via 'git ls-tree HEAD'.
4. Correlates SHA-1 object hashes across all three tiers to trace transitions.
"""
def __init__(self, repo_path: str = "."):
self.repo_path = os.path.abspath(repo_path)
def _run_git(self, args: List[str]) -> str:
try:
res = subprocess.run(
["git"] + args,
cwd=self.repo_path,
capture_output=True,
text=True,
check=True
)
return res.stdout.strip()
except subprocess.CalledProcessError:
return ""
@staticmethod
def compute_git_blob_hash(filepath: str) -> str:
"""Computes the exact Git blob SHA-1 hash for a file on disk."""
if not os.path.exists(filepath):
return "NON_EXISTENT"
with open(filepath, "rb") as f:
data = f.read()
# Git Blob Header format: "blob \0"
header = f"blob {len(data)}\0".encode('utf-8')
return hashlib.sha1(header + data).hexdigest()
def inspect_file(self, relative_filepath: str) -> Dict[str, Any]:
full_path = os.path.join(self.repo_path, relative_filepath)
# 1. Query Tree 1: Working Directory
work_hash = self.compute_git_blob_hash(full_path)
# 2. Query Tree 2: Staging Index (.git/index)
index_raw = self._run_git(["ls-files", "--stage", relative_filepath])
index_hash = index_raw.split()[1] if index_raw else "NOT_STAGED"
# 3. Query Tree 3: Repository HEAD Snapshot
head_raw = self._run_git(["ls-tree", "HEAD", relative_filepath])
head_hash = head_raw.split()[2] if head_raw else "NOT_COMMITTED"
# Analyze State
if work_hash == index_hash == head_hash:
status = "CLEAN (Synchronized across all 3 trees)"
elif work_hash != index_hash and index_hash == head_hash:
status = "MODIFIED ON DISK (Unstaged edits in Tree 1)"
elif work_hash == index_hash and index_hash != head_hash:
status = "STAGED FOR COMMIT (Tree 1 & Tree 2 matched; ahead of Tree 3)"
elif work_hash != index_hash and index_hash != head_hash:
status = "PARTIALLY STAGED (Different versions in Tree 1, Tree 2, and Tree 3!)"
elif index_hash == "NOT_STAGED" and head_hash == "NOT_COMMITTED":
status = "UNTRACKED (Exists only in Tree 1)"
else:
status = "DEVIATION DETECTED"
return {
"file": relative_filepath,
"status": status,
"tree_1_working_hash": work_hash[:12] if work_hash != "NON_EXISTENT" else "NONE",
"tree_2_staging_hash": index_hash[:12] if index_hash != "NOT_STAGED" else "NONE",
"tree_3_head_hash": head_hash[:12] if head_hash != "NOT_COMMITTED" else "NONE"
}
if __name__ == "__main__":
print("==========================================================================")
print(" GIT THREE-TREE ARCHITECTURAL STATE TRACKER")
print("==========================================================================")
# Simulated inspection report for academic demonstration
mock_files = ["src/auth.js", "config/db.json", "docs/architecture.md"]
# In production: tracker = GitThreeTreeTracker()
print("[*] Auditing file states across Working Directory, Index, and HEAD:\n")
simulated_audit = [
{
"file": "src/auth.js",
"status": "STAGED FOR COMMIT (Tree 1 & Tree 2 matched; ahead of Tree 3)",
"tree_1": "3b4e3e533604",
"tree_2": "3b4e3e533604",
"tree_3": "a1b2c3d4e5f6"
},
{
"file": "config/db.json",
"status": "MODIFIED ON DISK (Unstaged edits in Tree 1)",
"tree_1": "9941a22bc441",
"tree_2": "8841a9bc24d1",
"tree_3": "8841a9bc24d1"
},
{
"file": "docs/architecture.md",
"status": "CLEAN (Synchronized across all 3 trees)",
"tree_1": "c9941a224411",
"tree_2": "c9941a224411",
"tree_3": "c9941a224411"
}
]
for item in simulated_audit:
print(f"File: {item['file']}")
print(f" βββ Status : {item['status']}")
print(f" βββ Tree 1 (Working Disk) : SHA {item['tree_1']}")
print(f" βββ Tree 2 (Staging Index): SHA {item['tree_2']}")
print(f" βββ Tree 3 (HEAD Commit) : SHA {item['tree_3']}\n")
THREE-TREE ANTI-PATTERNS & RECOVERY PROTOCOLS:
// ==============================================================================
// PITFALL 1: THE "PARTIALLY STAGED" PARADOX (THE TWO-STATE FILE CONFUSION)
// SYMPTOM: An engineer modifies 'auth.js', runs 'git add auth.js', then edits 'auth.js'
// again in their IDE.
// RUNNING 'git status' SHOWS:
// Changes to be committed: modified: auth.js (GREEN)
// Changes not staged for commit: modified: auth.js (RED)
// CONFUSION: "How can the exact same file be both staged AND unstaged simultaneously?!"
// CAUSE: Git tracks SNAPSHOTS, not files!
// β’ Tree 2 (Index) holds the snapshot from when 'git add' was run.
// β’ Tree 1 (Working Tree) holds the subsequent second round of edits on disk!
// REMEDIATION:
// β’ To commit BOTH edits: Run 'git add auth.js' again to update Tree 2.
// β’ To discard the second edits: Run 'git restore auth.js' to match Tree 2.
// ==============================================================================
// ==============================================================================
// PITFALL 2: UNCOMMITTED CHANGES BLOCKING BRANCH SWITCHING
// SYMPTOM: Running 'git switch feature' returns:
// "error: Your local changes to the following files would be overwritten by checkout.
// Please commit your changes or stash them before you switch branches."
// CAUSE: Switching branches attempts to overwrite Tree 1 (Working Directory) with the
// target branch's Tree 3 (HEAD). Git detects that this would destroy your uncommitted
// local edits, so it aborts to protect your work!
// REMEDIATION:
// 1. Stash changes to safely shelve working tree edits:
// $ git stash push -m "WIP on auth refactor"
// 2. Switch branches cleanly:
// $ git switch feature
// 3. When returning:
// $ git switch main && git stash pop
// ==============================================================================
// ==============================================================================
// PITFALL 3: ACCIDENTAL WORKING TREE DELETION (RECOVERING FROM THE INDEX)
// MISTAKE: Developer accidentally runs 'rm -rf src/' in bash, deleting physical files!
// RELIEF: If the files were previously staged with 'git add', the blobs exist in Tree 2!
// REMEDIATION: Restore the entire working tree directly from the Index in milliseconds:
// $ git restore src/
// All deleted files are instantly recreated on disk matching the Staging Index!
// ==============================================================================
// ==============================================================================
// PITFALL 4: CORRUPT INDEX FILE (.git/index CORRUPTION)
// SYMPTOM: Git commands fail with: "fatal: index file corrupt" or "fatal: bad index file".
// CAUSE: Sudden workstation power loss during an active 'git add' or disk failure.
// REMEDIATION: Rebuild the Index from HEAD:
// 1. Remove the corrupt binary index file:
// $ rm .git/index
// 2. Re-read the repository HEAD tree back into a clean index:
// $ git reset
// All files are preserved; index metadata is re-created cleanly from Tree 3!
// ==============================================================================
GIT THREE-TREE ARCHITECTURAL SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β TREE TIER β STORAGE LOCATION β MUTABILITY β PRIMARY INSPECTION COMMAND β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Tree 1: Working Tree β Physical filesystem disk β Fully Mutable β git status (Unstaged section) β
β (Working Directory) β Root repository directory β (OS Filesystem) β git diff (vs. Staging Index) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Tree 2: Staging Area β .git/index β Semi-Mutable β git ls-files --stage β
β (The Index / Cache) β Binary DIRC ledger file β (Staging Buffer) β git diff --staged (vs. HEAD) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Tree 3: Repository β .git/objects/ β IMMUTABLE β git log β
β (HEAD Commit Snapshot) β Content-Addressable Database β (Cryptographic) β git ls-tree HEAD β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β KEY STATE TRANSITION DIRECTIVES: β
β β’ Working Tree β Staging Index : git add <file> (Creates zlib blob object; updates .git/index) β
β β’ Staging Index β Repository : git commit (Bakes Index into Tree object; advances HEAD pointer) β
β β’ Staging Index β Working Tree : git restore <file> (Overwrites local disk changes with staged data) β
β β’ Repository β Staging Index : git restore --staged <file> (Unstages file without touching disk) β
β β’ Repository β All Three Trees : git reset --hard HEAD~1 (Forces all 3 trees backward; destructive) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 THREE-TREE ARCHITECTURE COMMANDMENTS: β
β 1. Git Stages Content, Not Files: Editing a file after running 'git add' creates a two-state condition. β
β 2. The Index is Your Next Commit: What resides in .git/index is what enters history, nothing else. β
β 3. Working Directory is Unprotected: Git cannot recover uncommitted changes deleted from Tree 1. β
β 4. Use 'git restore' Over 'checkout': Prevent accidental data loss with dedicated restoration tools. β
β 5. Soft Reset Preserves State: Use 'git reset --soft' to undo a commit while keeping changes staged. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ