Version Control

A version control system records explicitly saved file versions and their relationships, supporting diff inspection, history tracing, and collaborative merging. It does not automatically save every keystroke; which states can be restored depends on saved objects, references, and retention policies.

Second-Draft Verification Note (2026-10-15): This is the second draft of the HeLuoXu tutorial, revised against official specifications and documentation. Legacy experiment logs are labeled separately as "First-Draft Retained Output" and do not represent a re-run on Windows in this pass; see the current batch verification records for the environment and results of this pass. Examples such as "StarRiver Notes", accounts, orders, prices, and policies are fictional teaching data.

One-Sentence Definition

A version control system records explicitly saved file versions and their relationships, supporting diff inspection, history tracing, and collaborative merging. It does not automatically save every keystroke; which states can be restored depends on saved objects, references, and retention policies.

Why It Matters

  • Safe rollback: When prompts, configurations, or code break, you can return precisely to "the version that worked yesterday" instead of relying on files like prompt_final_v3_really_final.txt.
  • Traceability: Every change records an author, timestamp, and message. When an issue arises, you can inspect the commit metadata alongside code review records to diagnose the root cause.
  • Collaboration: When multiple people edit the same project concurrently, the tool attempts a text merge; even when no conflict is reported, you must still verify semantic compatibility.
  • Essential for AI projects: Shifts in model quality often come from subtle edits to prompts, dataset splits, or dependency versions. Without version control, regression testing (k4.eval.regression-test) has no reliable baseline for comparison.

How It Works / Diagram

This tutorial builds a foundational mental model around three operations: storing snapshots, computing diffs, and performing merges.

Concept Meaning Modern Implementation (Git)
Snapshot / Commit The state of the entire file set at a point in time + author, timestamp, commit message, and parent commit(s) Each commit records a full directory tree; unchanged files reuse existing objects
Content Addressing Using the cryptographic hash of the content as the object's "address" Git commonly uses SHA-1 and also supports SHA-256 depending on tooling
Diff Line-by-line comparison between two versions Computed on demand rather than stored as the primary format
Three-Way Merge Determining who changed what by referencing the common ancestor of two branches Uses the ort merge strategy by default
Centralized vs. Distributed History stored centrally (e.g., SVN, though working copies still carry local metadata) vs. a standard full clone carrying reachable history (Git, Mercurial) Distributed: commits and history queries run locally

Chapter 1 of Pro Git, "About Version Control", introduces local, centralized, and distributed VCS architectures: https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control; Git stores data as snapshots rather than deltas: https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F

Why a three-way merge requires a common ancestor:

Figure 1

The decision rule can be summarized per line: if ours == theirs, keep it directly; if ours == base, only the other side changed it, so take theirs; if theirs == base, take ours; otherwise flag a conflict.

Applicable Boundaries & Verification Points

The revision graph reflects commit relationships, whereas author fields and messages do not equate to cryptographically authenticated identity or verified intent. Git's snapshot model is logical; packed objects still use delta compression under the hood. A standard full clone includes reachable history, but shallow clones, partial clones, and single-branch clones are exceptions. A clean text merge only means the tool detected no textual overlap—semantic conflicts still require review and testing. The example below compares matching line indices assuming three equal-length, pre-aligned inputs; furthermore, a 12-character truncated hex hash is not suitable as a unique identifier in a production object store.

Primary references verified in this pass (2026-10-15):

Runnable Example

This script uses the Python standard library to demonstrate content addressing, snapshots, diffs, and three-way comparison across pre-aligned lines. It is an in-memory toy model and does not invoke Git.

# File: examples/01_version_control.py
"""Implement a toy version control system in 60 lines of Python: content-addressed storage + snapshots + diff + three-way merge."""
import hashlib, difflib, json

store = {}                                  # Object store: hash -> content (same core idea as Git's .git/objects)
def put(data: bytes) -> str:
    h = hashlib.sha256(data).hexdigest()[:12]
    store[h] = data
    return h

def commit(files: dict, parent, msg):
    tree = {name: put(text.encode()) for name, text in sorted(files.items())}   # Each file content -> object
    meta = json.dumps({"tree": tree, "parent": parent, "msg": msg}, sort_keys=True).encode()
    return put(meta)

def files_of(c):
    tree = json.loads(store[c])["tree"]
    return {n: store[h].decode() for n, h in tree.items()}

print("1. Two commits (snapshots rather than diffs)")
v1 = commit({"prompt.txt": "You are StarRiver Notes support.\nKeep answers concise.\n", "README": "demo\n"}, None, "Initial version")
v2 = commit({"prompt.txt": "You are StarRiver Notes support.\nKeep answers concise.\nSay you do not know if unsure.\n", "README": "demo\n"}, v1, "Add abstention rule")
log, c = [], v2
while c:
    m = json.loads(store[c]); log.append(f"  {c}  {m['msg']}  parent={m['parent']}"); c = m["parent"]
print("\n".join(log))
t1, t2 = json.loads(store[v1])["tree"], json.loads(store[v2])["tree"]
print("  README object hash is identical across both versions (unchanged files are not stored twice):", t1["README"] == t2["README"])
print("  Total objects in object store:", len(store))

print("\n2. Diff from v1 -> v2 (unified diff)")
a, b = files_of(v1)["prompt.txt"], files_of(v2)["prompt.txt"]
print("".join(difflib.unified_diff(a.splitlines(True), b.splitlines(True), "v1/prompt.txt", "v2/prompt.txt")))

print("3. Three-way merge: use common ancestor base to tell which side modified which line")
def merge3(base, ours, theirs):
    out, conflicts = [], 0
    for i, (b, o, t) in enumerate(zip(base, ours, theirs)):
        if o == t:            out.append(o)          # Both sides agree
        elif o == b:          out.append(t)          # Only theirs changed -> take theirs
        elif t == b:          out.append(o)          # Only ours changed -> take ours
        else:                                         # Both sides changed the same line -> conflict
            conflicts += 1
            out += ["<<<<<<< ours", o, "=======", t, ">>>>>>> theirs"]
    return out, conflicts
base   = ["Tone: polite", "Length: under 100 words", "Language: Chinese"]
ours   = ["Tone: polite", "Length: under 50 words",  "Language: Chinese"]      # A edits length
theirs = ["Tone: friendly", "Length: under 100 words", "Language: Chinese"]   # B edits tone
m, k = merge3(base, ours, theirs); print("  Edits on different lines -> conflicts:", k, "->", m)
theirs2 = ["Tone: polite", "Length: under 80 words", "Language: Chinese"]     # B also edits length
m, k = merge3(base, ours, theirs2); print("  Edits on the same line   -> conflicts:", k); print("\n".join("    " + x for x in m))

print("\n4. Why a two-way merge (without base) is insufficient: looking only at ours and theirs cannot tell who made the change")
print("  ours line 1 =", ours[0], " theirs line 1 =", theirs[0], " -> cannot tell which one to pick, must report conflict")

First-Draft Retained Output

The following log is retained from the first draft and reflects the original environment claimed there; it is not the re-run output of this pass. Second-draft code edits may produce different output; refer to the current batch verification records for the actual re-run status.

1. Two commits (snapshots rather than diffs)
  abef9633776a  Add abstention rule  parent=568d179b6d01
  568d179b6d01  Initial version  parent=None
  README object hash is identical across both versions (unchanged files are not stored twice): True
  Total objects in object store: 5

2. Diff from v1 -> v2 (unified diff)
--- v1/prompt.txt
+++ v2/prompt.txt
@@ -1,2 +1,3 @@
 You are StarRiver Notes support.
 Keep answers concise.
+Say you do not know if unsure.

3. Three-way merge: use common ancestor base to tell which side modified which line
  Edits on different lines -> conflicts: 0 -> ['Tone: friendly', 'Length: under 50 words', 'Language: Chinese']
  Edits on the same line   -> conflicts: 1
    Tone: polite
    <<<<<<< ours
    Length: under 50 words
    =======
    Length: under 80 words
    >>>>>>> theirs
    Language: Chinese

4. Why a two-way merge (without base) is insufficient: looking only at ours and theirs cannot tell who made the change
  ours line 1 = Tone: polite  theirs line 1 = Tone: friendly  -> cannot tell which one to pick, must report conflict
  • 1. The two commits produce 5 objects in total: 2 file-content blobs + 1 commit metadata object in v1, while v2 adds only the modified prompt.txt blob and 1 new commit metadata object. Because README did not change, both commits point to the exact same object hash (outputting True). That is how snapshot storage avoids wasting space.
  • 2. The diff is computed on the fly from two snapshots; +Say you do not know if unsure. indicates an added line.
  • 3. When A edits the length line and B edits the tone line, the three-way merge automatically resolves to ['Tone: friendly', 'Length: under 50 words', 'Language: Chinese'] because the edits touch different lines. When both edit the "Length" line, the conflict count is 1 and Git-style <<<<<<< / ======= / >>>>>>> conflict markers are emitted.
  • 4. Without a common ancestor, there is no way to tell whether "polite" or "friendly" is the newer value—that is why a three-way merge normally requires a common ancestor, while special cases such as unrelated histories must be handled separately.
  • Note: Real-world merge tools align lines using algorithms such as Longest Common Subsequence (LCS) to handle insertions and deletions; for simplicity, this toy script compares lines strictly by index.

Self-Test

Question: Two developers modify different files and Git merges them automatically without conflict. Can you conclude that the resulting program is compatible?

Reference Answer: No. One change might alter a function signature or behavior while the other relies on the old contract in a caller; a clean text merge does not validate runtime behavior. You should check interface contracts and run the relevant test suite.

Common Misconceptions

  • "Version control is just backup": Backups only store copies; version control also records causal lineage (parent commits), commit messages, and authors, while supporting branch merges.
  • "A VCS stores only the diffs between versions": Git stores logical snapshots and computes diffs on demand (see the Pro Git links above), though some earlier systems (such as RCS) did store deltas.
  • "Only source code needs version control": Prompts, evaluation datasets, configurations, and documentation should all be versioned; large binary artifacts (model weights, large datasets) are better suited to tools like Git LFS or DVC.
  • "A merge conflict means the merge tool is broken": A conflict means the tool refuses to guess on your behalf—when two people edit the same region, a human must decide.

Connection to AI Development

  • Store prompts and evaluation sets in the same repository and commit as your application code so every shift in model quality traces back to a concrete change.
  • Before asking an AI coding assistant to refactor code, commit a clean baseline first. Rolling back with version control if the edit goes wrong is far more reliable than asking the model to "undo it".
  • When resolving merge conflicts, the three-way context (base, ours, theirs) is the clearest input you can give an AI assistant to explain and reconcile the conflict.

Further Reading

Unverified Scope

  • The toy merge implementation does not align insertions, deletions, or file renames, nor does it detect semantic conflicts; it should not be used to evaluate the correctness of production VCS tools.

Current Example Execution Scope

2026-10-15: Passed. Toy snapshot / diff / line-index merge model; not a compatibility test of a production VCS.

View current execution log.

"First-Draft Retained Output" preserves the original text and is not newly generated by the second-draft code; its original conclusions must be read together with the second-draft revisions and boundary notes.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram