Skill v1.0.1
currentAutomated scan100/100~1 modified
name: core-internals description: Provides guidance and best practices on concurrent synchronization, IPC, filesystem atomicity, git subprocess wrapping, XML manifests, and CLI argument parsing for git-repo. metadata: version: "1.0.1"
Git Repo Core Internals Engineering Guide
Executive Summary
Welcome to the authoritative engineering guide for Git Repository Management within the git-repo codebase. This repository of folk knowledge exists to safeguard the intricate orchestration of our multi-repository synchronization toolchain. Historically, complex operations such as parallelized network fetches, layered manifest overrides, and interactive terminal rendering have been vulnerable to subtle concurrency races, deadlocks, and fragile system states. This guide captures these critical failure modes—ranging from IPC serialization bottlenecks and filesystem lock contentions to non-hermetic test pollution—and establishes rigid engineering constraints to prevent their regression.
To maintain system stability, this guide enforces strict architectural boundaries across the tooling ecosystem. It mandates stateless execution for multiprocessing pools, guaranteed atomicity for worktree layout modifications, and deterministic error translation for all standard Git subprocesses. Furthermore, it defines the standard operating procedures for canonical manifest object deduplication, the modernization of our hermetic testing frameworks, and the delivery of consistent, machine-readable CLI interfaces. By adhering to these paradigms, incoming engineers will ensure the reliability, performance, and extensibility of git-repo's core repository management infrastructure.
Summary
| Chapter Theme / Title | Scope & Objective | |
|---|---|---|
| Concurrent Synchronization & IPC | This domain governs the stable |
: : orchestration of parallel network : : : fetches, local checkouts, and : : : interleaved subprocess routines. It : : : strictly enforces safe : : : multiprocessing IPC, deterministic : : : Git locking via exponential backoff, : : : and state synchronization across : : : concurrent pool workers. :
: Layout** : creation, migration, and cleanup of : : : internal repository structures and : : : Git worktrees. It relies on ephemeral : : : temporary directories, atomic rename : : : operations, and robust error recovery : : : to prevent corrupted states during : : : unexpected interruptions. :
: Translation** : for wrapping, executing, and : : : translating standard Git subprocesses : : : within the Repo tooling ecosystem. It : : : mandates the use of centralized : : : command abstractions, strict version : : : gating, and deterministic stream : : : handling to guarantee reliable : : : repository state management and : : : actionable error reporting. :
: Deduplication** : validation, and canonicalization of : : : XML manifest components. It strictly : : : enforces semantic immutability via : : : NamedTuple implementations, defensive : : : copying for hierarchical override : : : scoping, and deterministic : : : JSON-backed file tracking across the : : : subsystem. :
: Modernization** : legacy unittest suites to modern : : : pytest functional paradigms and the : : : establishment of hermetic session : : : fixtures. It enforces strict : : : environment isolation to prevent : : : global state pollution (e.g., : : : developer .gitconfig bleeding) while : : : safely intercepting standard streams : : : and filesystem paths. :
: Consistency** : validation, and execution of : : : command-line arguments, enforcing : : : strict standardization for : : : machine-readable serialization, : : : unified logging, and deterministic, : : : thread-safe terminal interactions. :
: : execution, parameter validation, and : : : lifecycle management of user-defined : : : scripts within the repository : : : ecosystem. It ensures seamless : : : integration of extensions like : : : post-sync or pre-upload while : : : strictly isolating their execution : : : failures from core operational : : : workflows. :
Chapter: Concurrent Synchronization & IPC
Context: This domain governs the stable orchestration of parallel network fetches, local checkouts, and interleaved subprocess routines. It strictly enforces safe multiprocessing IPC, deterministic Git locking via exponential backoff, and state synchronization across concurrent pool workers.
Summary
| Rule ID | Principle / Constraint | Priority | Primary Symptom / Trap | |
|---|---|---|---|---|
| T1-01 | Stateless Class Methods | High | Passing bound instance |
: : for Parallel Pool Workers : : methods to a parallel : : : : : executor, dragging : : : : : unnecessary state into : : : : : the multiprocessing : : : : : serialization pipeline. :
: : Concurrent Standard : : calls directly from : : : Output : : within a parallelized : : : : : worker routine. :
: : Validation : : checkout jobs across all : : : : : project variants without : : : : : verifying layout types. :
: : Synchronization State : : at the very end of an : : : Persistence : : execution path without : : : : : exception guards. :
: : Backoff for Git : : init concurrently : : : Configuration Locks : : without retry logic for : : : : : config.lock` failures. :
: : Concurrent Git Config : : immediately without : : : Locks : : evaluating standard : : : : : streams for transient : : : : : lock errors. :
: : Interleaved Sync Stalls : : inside a while loop but : : : : : allowing the next loop : : : : : iteration to execute. :
: : Context Handlers for IPC : : connections or : : : : : multiprocessing managers : : : : : as raw variable : : : : : assignments without a : : : : : guaranteed teardown : : : : : phase. :
: : Handling in Parallel : : data lists to decide if a : : : Processing : : parallel orchestration : : : : : should abort. :
: : Count Safeguard : : min(target, len(items)) : : : : : to determine pool size, : : : : : which breaks if the item : : : : : list is unexpectedly : : : : : empty. :
: : Across Parallel Execution : : payloads to scalar : : : Boundaries : : indices during IPC : : : : : context setup without : : : : : updating the receiver : : : : : logic to rehydrate the : : : : : objects. :
: : Initialization for : : inherit updated class : : : Multiprocessing Pools : : variables inherently : : : : : without explicit : : : : : initialization. :
: : in Parallel Execution : : integer to the : : : : : chunksize parameter. :
: : Operations in Sync Local : : sync phase without : : : Half : : applying required file : : : : : operations. :
Rules
T1-01: Stateless Class Methods for Parallel Pool Workers
Rule: Always implement multiprocessing pool targets as stateless classmethods or standalone functions to bypass process serialization constraints.What: Worker execution targets within multiprocessing pools must beconstructed as fully decoupled class methods or standalone functions to bypassprocess serialization constraints.Applies To: Multiprocessing process pools, concurrent task scheduling, andExecuteInParallelimplementations.Why: Command execution objects were heavily bound to system state.Attempting to pass instance methods (self.method) to a multiprocessing poolfrequently causedPicklingErrorcrashes, as the underlying Pythonserialization mechanism cannot cleanly isolate bound object graphs. Failing toadhere to this typically results in IPC Serialization Error.
Trap 1: Passing bound instance methods to a parallel executor, dragging unnecessary state into the multiprocessing serialization pipeline.
Don't:
class InfoCommand:def _worker_logic(self, project):passdef run(self):self.ExecuteInParallel(jobs, self._worker_logic, projects)
Do:
class InfoCommand:@classmethoddef _worker_logic(cls, project_idx):project = cls.get_parallel_context()["projects"][project_idx]passdef run(self):self.ExecuteInParallel(jobs, self._worker_logic, range(len(projects)))
Exceptions: Threading-based execution models where memory is shared and pickling is not strictly enforced.
T1-02: Buffered Serialization of Concurrent Standard Output
Rule: Must capture standard output generated by concurrently executingtasks into isolated memory buffers for sequential display in the parentprocess.What: Data emitted by concurrently executing tasks must be captured intoisolated memory buffers and returned to the parent process for sequentialdisplay.Applies To: Parallel process execution layers generating human-readableCLI output.Why: When command execution was parallelized, worker processes wrotedirectly to standard output. This created severe race conditions resulting ingarbled, interleaved text output on the user's terminal. Failing to adhere tothis typically results in Interleaved Terminal Output.
Trap 1: Executing terminal print calls directly from within a parallelized worker routine.
Don't:
@classmethoddef _DiffHelper(cls, project):print(f"Project: {project.name}")print(f"Revision: {project.rev}")
Do:
@classmethoddef _DiffHelper(cls, project):buf = io.StringIO()buf.write(f"Project: {project.name}\n")buf.write(f"Revision: {project.rev}\n")return buf.getvalue()# In main process:for output in results:print(output, end="")
T1-03: Interleaved Sync Path Validation
Rule: Always validate the presence of a worktree when executinginterleaved sync processes to prevent layout evaluation crashes.What: When executing interleaved sync processes (parallelized networkfetches and checkouts), the operation must explicitly validate the presence ofa worktree, as not all Git repository types (e.g., mirrors) maintain localfile checkouts.Applies To: Concurrency logic withinsync.py.Why: Changing the default mode ofrepo syncto interleaved parallelizedcheckout tasks indiscriminately. This immediately broke AOSP mirror syncingbecause mirrors lack local checkout paths, resulting in aTypeErrorwhenevaluatingNoneTypepaths. Failing to adhere to this typically results inTypeError / Sync Failure.
Trap 1: Dispatching parallel checkout jobs across all project variants without verifying layout types.
Don't:
- Assuming
project.worktreealways contains anos.PathLikeobject during
interleaved syncing.
Do:
- Adding guard clauses to verify
project.worktree is not Noneand handling
--mirror modes explicitly before adding checkout tasks to the thread pool.
T1-04: Guaranteed Synchronization State Persistence
Rule: Must execute synchronization telemetry saving operations withintry...finallyblocks to guarantee data retention across executioninterrupts.What: Core sync operations must wrap network and filesystem operations intry...finallyblocks, ensuring that synchronization metadata (_fetch_timesand_local_sync_state) is persisted even if the sync operation fails or isinterrupted.Applies To:subcmds/sync.py, particularly the_Fetchlogic andmultiprocessing worker loops.Why: If a synchronization process encountered an error (like a fetchfailure), the operation exited early, dropping valuable telemetry andoptimization data (fetch times) for projects that successfully synced prior tothe crash. Failing to adhere to this typically results in **Telemetry Loss /Sync State Inconsistency**.
Trap 1: Placing save operations at the very end of an execution path without exception guards.
Don't:
result = self._Fetch(to_fetch, opt, err_event)if not result.success:raise SyncError("failed")# BAD: Never reached if an error is raisedself._fetch_times.Save()
Do:
try:result = self._Fetch(to_fetch, opt, err_event)if not result.success:raise SyncError("failed")finally:# GOOD: Always saves telemetry stateself._fetch_times.Save()
T1-05: Jittered Exponential Backoff for Git Configuration Locks
Rule: Always wrap concurrent Git mutations to shared configurations in anexponential backoff routine with jitter to mitigate transient filesystemlocks.What: When initializing submodules concurrently (e.g., `git submoduleinit`), the system must employ an exponential backoff mechanism withrandomized jitter to handle transient filesystem lock errors on.git/config.Applies To: Submodule initialization and any highly parallel Gitsubprocesses mutating shared configuration state.Why: Runningrepo sync -j<N>caused multiple child processes tosimultaneously attemptgit submodule init, which led to lock contention onthe parent project's config file and caused the entire sync operation to fail.Failing to adhere to this typically results in **File Lock Contention / SyncFailure**.
Trap 1: Firing `git submodule init` concurrently without retry logic for `config.lock` failures.
Don't:
# BAD: Fails immediately if .git/config.lock existssubprocess.run(["git", "submodule", "init", "--", path], check=True)
Do:
# GOOD: Catch lock errors and retry with jitterfor attempt in range(MAX_RETRIES):p = subprocess.run(["git", "submodule", "init", "--", path], stderr=subprocess.PIPE)if p.returncode == 0:breakif "could not lock config file" in p.stderr:time.sleep(base_delay * (2 ** attempt) + random.uniform(0, jitter))
Exceptions: Non-lock related Git errors should still fail immediately without retrying.
T1-06: Exponential Backoff for Concurrent Git Config Locks
Rule: Must analyze captured Git error streams to detect config lockcontention and orchestrate retries via structured logging instead of immediateprocess failure.What: Concurrent git operations modifying.git/config(such as submoduleinitialization) must utilize an exponential retry mechanism with jitter tohandle transient filesystem lock contention. Standard output and error streamsmust be captured and parsed to detect these locks.Applies To: project.py, specifically concurrentgit submodule initoperations or any parallel processes altering local repository configuration.Why: When synchronizing with high job values (-j), multiple parallelprocesses modifying.git/configtriggered race conditions, throwing 'couldnot lock config file' errors and aborting the sync. Failing to adhere to thistypically results in Transient Sync Failure / Lock Contention.
Trap 1: Failing a git command immediately without evaluating standard streams for transient lock errors.
Don't:
# BAD: Fails immediately on lock contentionif GitCommand(self, cmd).Wait() != 0:raise GitError(f"{self.name} submodule init failed")
Do:
# GOOD: Captures stdout/stderr and retries on 'lock' matchesgit_cmd = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True)if git_cmd.Wait() != 0:error = git_cmd.stderr or git_cmd.stdoutif "lock" in error:# apply exponential backoff + jitter logicelse:git_cmd.VerifyCommand() # Propagate real error
Trap 2: Using raw `print` statements to log retry attempts, which breaks structured output formats.
Don't:
# BAD: Unstructured print to stdoutprint(f"Attempt {attempt+1}: git {' '.join(cmd)} failed. Sleeping...")
Do:
# GOOD: Forwarded to centralized loggerlogger.warning("Attempt %d/%d: git %s failed. Error: %s. Sleeping %.2fs before retrying.", attempt+1, max_retries, cmd, error, delay)
Exceptions: Non-lock related Git errors should break the retry loop and be propagated immediately via git_cmd.VerifyCommand().
T1-07: Hard Termination on Interleaved Sync Stalls
Rule: Must trigger a definitive execution break and flag error signalswhenever an unresolvable stall is detected in an interleaved control loop.What: When an unresolvable stall is detected within an interleaved orparallel execution loop, the system must trigger a definitive state break(e.g., setting global events and breaking the loop) to prevent infinitedeadlocks.Applies To: subcmds/sync.py, specifically_SyncInterleavedor anylooping logic monitoring pending sets.Why: A bug existed where a stall was logged but the loop terminator(break) and error trigger (err_event.set()) were accidentally omitted.This allowed the sync routine to lock up infinitely when interdependentprojects failed to checkout. Failing to adhere to this typically results inInfinite Loop / Deadlock.
Trap 1: Logging an error state inside a `while` loop but allowing the next loop iteration to execute.
Don't:
# BAD: Omitted termination control flowif prev_pending == pending_relpaths:logger.error("Stall detected")prev_pending = pending_relpaths
Do:
# GOOD: Set event signals and immediately breakif prev_pending == pending_relpaths:logger.error("Stall detected")err_event.set()break
T1-08: Resource Management via Context Handlers for IPC
Rule: Always initialize multiprocessing components and background proxieswithinwithstatement context blocks to assure teardown semantics.What: Multiprocessing managers and SSH proxies initialized for parallelworkflows must be wrapped inwithblock context managers to guaranteecleanup of background processes and multiplexing sockets.Applies To: Concurrent network operations and parallelized repositorysynchronization (subcmds/sync.py).Why: When adding an interleaved fetch/checkout feature, paralleloperations required shared synchronization dictionaries and SSH connectionmultiplexing. Without context managers, exceptions or interrupts (e.g.,KeyboardInterrupt) would leave orphaned background processes and abandonedsockets. Failing to adhere to this typically results in **Resource Leaks /Orphaned Sockets**.
Trap 1: Initializing proxy connections or multiprocessing managers as raw variable assignments without a guaranteed teardown phase.
Don't:
# BAD: No guaranteed cleanup on exceptionmanager = multiprocessing.Manager()ssh_proxy = ssh.ProxyManager(manager)process_tasks(ssh_proxy)
Do:
# GOOD: Context managers assure RAII semanticswith multiprocessing.Manager() as manager:with ssh.ProxyManager(manager) as ssh_proxy:process_tasks(ssh_proxy)
T1-09: Dual-Channel Error Handling in Parallel Processing
Rule: Must decouple fast-fail signaling events from aggregated batch dataprocessing logic to ensure immediate worker termination across processes.What: In concurrent execution environments, inter-process signaling (forimmediate control flow) must be strictly separated from data aggregation (forend-of-batch error reporting).Applies To: Multi-process synchronization pools (_SyncInterleaved,_SyncPhased) and worker callback processors.Why: Reviewers questioned why a separate event flag was used when an arrayof errors was already being populated. Using only an aggregated list preventedworkers from rapidly terminating each other via fail-fast mechanisms. Failingto adhere to this typically results in Delayed Worker Termination.
Trap 1: Iterating over aggregated data lists to decide if a parallel orchestration should abort.
Don't:
# BAD: Waiting to process the whole batch before abortingerrors.append(result.error)if errors and opt.fail_fast:pool.close()
Do:
# GOOD: Using an IPC Event for immediate cross-process signalingerr_event.set()errors.append(result.error)if not ret and opt.fail_fast:pool.close()
T1-10: Minimum Process Pool Job Count Safeguard
Rule: Must bind dynamically computed multiprocessing job allocations to aminimum floor of 1 to prevent initialization crashes.What: When determining the number of worker processes for parallelexecution based on a variable target length (e.g., an array of projects), theresulting worker count must be explicitly bound to a minimum of 1.Applies To: Network fetch logic and multiprocessing pool initializations(e.g.,_Fetchinsync.py).Why: A regression occurred where passing an empty project list evaluatedthe worker count to 0. This crashed the multiprocessing pool initializationwith a ValueError. Returning early was rejected as a fix because secondaryside-effects (like state saves) within the function still needed to execute.Failing to adhere to this typically results in **ValueError / Process PoolCrash**.
Trap 1: Directly using `min(target, len(items))` to determine pool size, which breaks if the item list is unexpectedly empty.
Don't:
jobs = min(opt.jobs_network, len(projects_list))
Do:
jobs = max(1, min(opt.jobs_network, len(projects_list)))
T1-11: Safeguarding Object State Across Parallel Execution Boundaries
Rule: Always transmit deeply serialized objects directly across parallelboundaries, or strictly reconstruct object relationships within the downstreamworker.What: When offloading command execution to parallel processes, workersmust receive properly serialized complex object data, not dissociatedidentifiers, unless the downstream API explicitly reconstructs the objectstate.Applies To: Parallel execution contexts (ParallelContext,ExecuteInParallel) within multi-project commands likerepo forallandrepo upload.Why: A refactoring attempt to optimize IPC by passing integer projectindices instead of full project objects to parallel workers caused criticalbreakage. Worker processes subsequently attempted to access attributes (like.manifest) on integer types, leading to unhandled exceptions. Failing toadhere to this typically results in **AttributeError / Early ExitRegression**.
Trap 1: Truncating object payloads to scalar indices during IPC context setup without updating the receiver logic to rehydrate the objects.
Don't:
# Worker receives an integer index instead of a Projectmanifests = {project.manifest.topdir: project.manifest}
Do:
# Worker receives fully serialized Project objects (or properly reconstructs them)manifests = {project.manifest.topdir: project.manifest}
T1-12: Explicit Context Initialization for Multiprocessing Pools
Rule: Must dictate shared states through an explicitinitializerargument injected into the multiprocessing pool rather than implicitly relyingon execution fork behavior.What: Shared parallel context must be managed using an explicit contextmanager and passed viainitializerandinitargsinmultiprocessing.Pool,rather than relying on unvalidated class attributes or fork memory semantics.Applies To: Any command or module utilizingmultiprocessing.Pool(e.g.,ExecuteInParallel).Why: Relying onforkmemory semantics for sharing context works on someLinux systems but fails deterministically on environments (like macOS/Windows)where memory is not automatically shared or when the multiprocessing startmethod defaults tospawn. Failing to adhere to this typically results inState Leakage / Uninitialized Context.
Trap 1: Assuming child workers inherit updated class variables inherently without explicit initialization.
Don't:
# BAD: Implicit state sharingcls.parallel_context = datawith multiprocessing.Pool(jobs) as pool:pool.imap_unordered(func, inputs)
Do:
# GOOD: Explicit initializer passed to workerswith multiprocessing.Pool(jobs,initializer=cls._SetParallelContext,initargs=(cls._parallel_context,)) as pool:pool.imap_unordered(func, inputs)
Trap 2: A context manager directly yielding an internal dictionary, allowing unvalidated and lingering usage.
Don't:
# BAD: Direct yield of state without lifecycle validation@contextlib.contextmanagerdef ParallelContext(cls):yield cls._parallel_context
Do:
# GOOD: Lifecycle management and defensive assertions@contextlib.contextmanagerdef ParallelContext(cls):assert cls._parallel_context is Nonecls._parallel_context = {}try:yieldfinally:cls._parallel_context = None
T1-13: Dynamic Task Chunk Sizing in Parallel Execution
Rule: Always formulate thechunksizeof mapping workers dynamicallybased on the dataset to job ratio to avoid workload serialization blocks.What: When utilizingmultiprocessing.Pool.imap_unordered, thechunksizemust be dynamically calculated based on the ratio of inputs toworker jobs, rather than statically hardcoded.Applies To: Parallel task dispatch mechanisms (ExecuteInParallel,synchronization loops).Why: Using a statically hardcoded chunk size (e.g., `WORKER_BATCH_SIZE =32`) forced all tasks onto a single worker thread when the total number ofprojects in the manifest was fewer than 32, completely negating the benefit ofparallelism for smaller workloads. Failing to adhere to this typically resultsin Thread Serialization / Under-utilization.
Trap 1: Passing a hardcoded batch integer to the `chunksize` parameter.
Don't:
# BAD: Hardcoded chunksize leads to serialization for small input listssubmit(func, inputs, chunksize=WORKER_BATCH_SIZE)
Do:
# GOOD: Dynamic chunking balances load across workerscalc_chunk = min(max(1, len(inputs) // jobs), WORKER_BATCH_SIZE)submit(func, inputs, chunksize=calc_chunk)
Exceptions: When evaluating specifically within tests that forcefully isolate to a single job execution (jobs=1).
T1-14: Deferred Worktree Operations in Sync Local Half
Rule: Must enqueue manifest copy and link actions into the synchronizationbuffer explicitly prior to issuing early return signals for up-to-daterepositories.What: File link (linkfile) and copy (copyfile) directives must bescheduled using the synchronization buffer (syncbuf.later1) within theSync_LocalHalfexecution phase. They must not be bypassed if the repositoryexits its sync early due to being up-to-date.Applies To: Local synchronization logic of projects (project.py->Sync_LocalHalf).Why: A bug existed where if a project had published commits in Gerrit(meaning its local state was merged), the sync process would return early andentirely skip applying the manifest'slinkfileandcopyfileoperations,leading to missing or stale files in the developer's worktree. Failing toadhere to this typically results in Worktree Desync / Missing Files.
Trap 1: Returning early from the sync phase without applying required file operations.
Don't:
# BAD: Skipped file modifications when commits are publishedif pub == head:return
Do:
# GOOD: Schedule file operations via syncbuf before returningif pub == head:syncbuf.later1(self, _doff, not verbose)return
Cross-Domain Dependencies
- Upstream: T3 | Subprocess Git Integration & Error Translation -
Standardizes Git command stream capturing and exception typing, enabling reliable lock contention detection.
- Downstream: T2 | Filesystem Atomicity & Worktree Layout - *Relies on
parallel execution guard clauses to ensure worktrees exist before checkout operations are dispatched.*
- Downstream: T6 | CLI Argument Parsing & UX Consistency - *Requires
buffered standard outputs and structured logger directives from parallel tasks to maintain coherent terminal formatting.*
Chapter: Filesystem Atomicity & Worktree Layout
Context: This domain governs the deterministic creation, migration, and cleanup of internal repository structures and Git worktrees. It relies on ephemeral temporary directories, atomic rename operations, and robust error recovery to prevent corrupted states during unexpected interruptions.
Summary
: : : : Trap :
| :-------- | :---------------------------- | :------- | :-------------------- | |
|---|---|---|---|---|
| T2-01 | Unique Subproject Keys in | High | Using the git |
: : Worktree Environments : : directory or : : : : : repository name as a : : : : : unique hash key for : : : : : deduplicating project : : : : : objects. :
: : Directory Pruning : : recursive delete : : : : : calls to wipe an old : : : : : link destination : : : : : without verifying its : : : : : internal contents. :
: : Temporary Git Artifacts : : or state-modifying : : : : : operations without : : : : : wrapping the cleanup : : : : : routine in a : : : : : finally block. :
: : Initialization via Temporary : : complex directory : : : Worktrees : : structure directly at : : : : : its final target path : : : : : without atomicity : : : : : guarantees. :
: : : : nested string-based : : : : : os.path : : : : : constructions. :
: : Initialization via Temporary : : a system directory at : : : Renames : : its final, visible : : : : : destination. :
: : Configuration State : : configuration : : : : : variables back and : : : : : forth during setup. :
: : Ownership and Release : : variable reference to : : : : : a temporary directory : : : : : after it has been : : : : : renamed, allowing a : : : : : deferred cleanup : : : : : routine to operate on : : : : : an unowned path. :
: : Invalidation Post-Rename : : config object to set : : : : : flags after the : : : : : underlying directory : : : : : has been renamed. :
: : Destructive Worktree : : object directory : : : Operations : : immediately upon : : : : : deleting a single : : : : : project that uses it. :
: : Garbage Collection Fallbacks : : legacy fallback for : : : : : repository safety : : : : : configurations : : : : : without informing the : : : : : user of the potential : : : : : unreliability. :
: : Restructuring : : path migrations, : : : : : structural : : : : : re-designs, and : : : : : initialization logic : : : : : changes into a single : : : : : Pull : : : : : Request/Patchset. :
: : Replacement During Submodule : : string .replace() : : : Migration : : to update a portion : : : : : of a file path. :
: : Migrations from Network-Only : : directory migrations : : : Operations : : globally prior to : : : : : downloading network : : : : : changes. :
: : File Cleanup : : library file removal : : : : : and failing to handle : : : : : the scenario where : : : : : the file no longer : : : : : exists. :
: : Deserialization : : files in text mode : : : : : without validating : : : : : structure, allowing : : : : : exceptions to bubble : : : : : up and break the CLI. :
: : Repository Configurations : : python open() : : : : : context manager and : : : : : print() to mutate : : : : : core git directories. :
: : Minimization : : and building : : : : : directory paths : : : : : inside the file : : : : : reading scope. :
: : Worktrees : : rmtree on a live : : : : : repository path. :
: : Resolution for Git Worktrees : : rewriting the : : : : : gitdir file using : : : : : os.path.relpath : : : : : without checking if : : : : : the source path is : : : : : absolute first. :
: : Repository Shallow Cloning : : shallow clone for : : : : : configuration : : : : : repositories, causing : : : : : subsequent : : : : : initialization/branch : : : : : switching commands to : : : : : fail due to missing : : : : : objects. :
Rules
T2-01: Unique Subproject Keys in Worktree Environments
Rule: Always use repository-relative paths instead of git directory namesas unique deduplication keys to prevent collisions in worktree environments.What: Repository-relative paths must be used instead of git directorynames as unique deduplication keys to prevent collisions in environmentsutilizing git worktrees.Applies To: Subproject iteration and deduplication logic, primarily withincommand.pyor project discovery utilities.Why: When tracking derived subprojects, the system originally usedgitdiras a unique identifier. In git worktree setups, multiple distinctproject instances can share the same underlyinggitdir, leading to silentdata collisions and missed projects during sync operations. Failing to adhereto this typically results in Data Collision / Omission.
Trap 1: Using the git directory or repository name as a unique hash key for deduplicating project objects.
Don't:
derived_projects.update((p.gitdir, p) for p in project.GetDerivedSubprojects())
Do:
derived_projects.update((p.RelPath(local=False), p) for p in project.GetDerivedSubprojects())
T2-02: Non-Destructive Bottom-Up Directory Pruning
Rule: Always utilize non-destructive, bottom-up directory iteration thatexclusively targets empty directories and symlinks during legacy path cleanup.What: Legacy path cleanup must utilize non-destructive, bottom-updirectory iteration that specifically targets empty directories and symlinks,avoiding recursive tree destruction.Applies To: Workspace migration, obsolete symlink cleanup, andplatform_utilsfile deletion wrappers.Why: When a subproject's destination directory changed, thesynchronization tool utilized aggressive recursive deletion (rmtree) toremove the previous location. This routinely endangered untracked developercode or extraneous files housed inside the obsolete tree. Failing to adhere tothis typically results in Accidental Data Deletion.
Trap 1: Using aggressive recursive delete calls to wipe an old link destination without verifying its internal contents.
Don't:
if platform_utils.isdir(absDest):platform_utils.rmtree(absDest)
Do:
# Use a safe helper that only removes empty dirs/symlinks bottom-upplatform_utils.removedirs(absDest)
Trap 2: Attempting directory deletion without explicitly pruning stale manifest files first.
Don't:
platform_utils.removedirs(need_remove_path)# Misses files entirely as removedirs stops at regular files
Do:
if os.path.isfile(need_remove_path) or os.path.islink(need_remove_path):platform_utils.remove(need_remove_path)platform_utils.removedirs(os.path.dirname(need_remove_path))
Exceptions: Explicitly defined cases where a directory is formally tracked and deleted from the manifest metadata, explicitly commanding removal.
T2-03: Guaranteed Cleanup of Temporary Git Artifacts
Rule: Must wrap any operation mutating the local.gitrepository withtemporary states inside atry/finallyblock to guarantee restoration.What: Operations mutating the local.gitrepository with temporarystates (e.g., tracking alt refs during fetch) must wrap the operation in atry/finallyblock to guarantee state restoration.Applies To: Subprocess network operations and filesystem interactionsaffecting the.gitdatabase.Why: If a network operation threw an exception (like aGitAuthErrorprompting for credentials), the cleanup logic was bypassed. This left orphanedreferences in the object database and corrupted future repository syncs.Failing to adhere to this typically results in Stale Repository State.
Trap 1: Running destructive or state-modifying operations without wrapping the cleanup routine in a `finally` block.
Don't:
setup_temporary_refs()run_git_fetch() # Might throw GitAuthErrorcleanup_temporary_refs()
Do:
setup_temporary_refs()try:run_git_fetch()finally:cleanup_temporary_refs()
T2-04: Atomic Directory Initialization via Temporary Worktrees
Rule: Always perform directory initialization via temporary directoriesand an atomic rename to prevent fragmented repository states.What: Directory initialization processes must use temporary directoriesand atomic renames to prevent partial or corrupted states upon unexpectedinterruption.Applies To: Filesystem operations involving git repository setup,specifically superproject initialization and dot-git dir creation.Why: Historically, initializing git directories directly in their finalpath left behind broken, partially-initialized structures if the user orsystem interrupted the process. This caused subsequent workflow executions tofail permanently. Failing to adhere to this typically results in **CorruptState / Initialization Failure**.
Trap 1: Initializing a complex directory structure directly at its final target path without atomicity guarantees.
Don't:
os.makedirs(final_git_dir, exist_ok=True)subprocess.run(['git', 'init', final_git_dir])
Do:
temp_dir = tempfile.mkdtemp(dir=target_base)try:subprocess.run(['git', 'init', temp_dir])platform_utils.rename(temp_dir, final_git_dir)finally:platform_utils.rmtree(temp_dir, ignore_errors=True)
T2-05: Pathlib Adoption over os.path
Rule: Avoid legacyos.pathAPIs; prefer modernpathlib.Pathstructuresfor traversing, joining, and creating files.What: Use modern Pythonpathlib.Pathparadigms for traversing, joining,and creating files instead of the legacyos.pathAPIs.Applies To: Filesystem and worktree directory manipulation.Why: Chainingos.path.joinand callingos.mkdirrepeatedly bloated thecodebase, was less readable, and invited platform separator path bugs. Failingto adhere to this typically results in Pathing Errors / High Complexity.
Trap 1: Relying on heavily nested string-based os.path constructions.
Don't:
manifest_dir = os.path.join(self.repodir, 'manifests')os.mkdir(manifest_dir)with open(os.path.join(manifest_dir, 'config'), 'w') as fp:fp.write(data)
Do:
manifest_dir = self.repodir / 'manifests'manifest_dir.mkdir(parents=True, exist_ok=True)(manifest_dir / 'config').write_text(data)
Exceptions: Legacy modules pending modernization where intermingling os.path strings and Path objects would break typing contracts.
T2-06: Atomic Directory Initialization via Temporary Renames
Rule: Never construct complex internal.gitdirectories in-situ; executeinitialization inside an ephemeral directory and atomically rename it uponcompletion.What: Complex directory structures (like internal.gitdirectories) mustbe constructed inside an ephemeral temporary directory on the same filesystemvolume, and only moved to their final path via an atomic rename once fullyvalidated.Applies To: Filesystem creation (os.makedirs) and repositoryinitialization (_InitGitDir).Why: Interrupted or failed operations left partially initialized.gitdirectories in-situ. Follow-up operations encountered corrupt directory trees,which the legacy recovery logic could not reliably clean up. Failing to adhereto this typically results in Corrupt Repository State.
Trap 1: Creating and mutating a system directory at its final, visible destination.
Don't:
os.makedirs(self.gitdir)self._ReferenceGitDir(self.objdir, self.gitdir)
Do:
tmp_gitdir = create_tmp_dir(os.path.dirname(self.gitdir))os.makedirs(tmp_gitdir)self._ReferenceGitDir(self.objdir, tmp_gitdir)platform_utils.rename(tmp_gitdir, self.gitdir)
T2-07: Encapsulation of Transient Configuration State
Rule: Never reassign class-level instance attributes to intermediate pathsduring object setup; use local variables for temporary state tracking.What: Never temporarily reassign class-level instance attributes (e.g.,self.config) to point to intermediate or ephemeral paths. Use localvariables for temporary objects during setup, assigning the final result tothe class instance only upon success.Applies To: Object initialization workflows withinproject.py.Why: During atomic.gitdirectory initialization,self.configwastemporarily overwritten to point to a temporary working directory. If theoperation crashed, the object was left in an invalid state, pointing to adeleted transient path. Failing to adhere to this typically results inCorrupt Instance State.
Trap 1: Swapping out instance configuration variables back and forth during setup.
Don't:
self.config = GitConfig.ForRepository(gitdir=tmp_gitdir)# initialization stepsplatform_utils.rename(tmp_gitdir, self.gitdir)self.config = GitConfig.ForRepository(gitdir=self.gitdir)
Do:
tmp_config = GitConfig.ForRepository(gitdir=tmp_gitdir)# apply setup using tmp_configplatform_utils.rename(tmp_gitdir, self.gitdir)self.config = GitConfig.ForRepository(gitdir=self.gitdir)
T2-08: Explicit Temporary Resource Ownership and Release
Rule: Always nullify references to a temporary directory immediately aftersuccessfully renaming it to its permanent destination.What: When executing atomic directory initializations via temporary paths,the reference to the temporary directory must be explicitly nullifiedimmediately after successfully renaming it to its final destination.Applies To: Filesystem operations, specifically inproject.pyatomic Gitdirectory initializations (_InitGitDir).Why: If a temporary directory reference was maintained after beingatomic-renamed, the subsequent error-handling orfinallycleanup block couldmistakenly delete the directory. In parallel environments, another concurrentjob could validly create a new temporary directory at that exact freed path,causing the current process to inadvertently nuke an active resource belongingto another job. Failing to adhere to this typically results in **Data Loss /Race Condition**.
Trap 1: Keeping a stale variable reference to a temporary directory after it has been renamed, allowing a deferred cleanup routine to operate on an unowned path.
Don't:
try:tmp_gitdir = tempfile.mkdtemp()# ... initialize ...platform_utils.rename(tmp_gitdir, self.gitdir)# BAD: tmp_gitdir still holds the path stringfinally:if tmp_gitdir and os.path.exists(tmp_gitdir):platform_utils.rmtree(tmp_gitdir) # Risk of race condition
Do:
try:tmp_gitdir = tempfile.mkdtemp()# ... initialize ...platform_utils.rename(tmp_gitdir, self.gitdir)tmp_gitdir = None # GOOD: explicitly release ownership of the pathfinally:if tmp_gitdir and os.path.exists(tmp_gitdir):platform_utils.rmtree(tmp_gitdir)
T2-09: Configuration Object Invalidation Post-Rename
Rule: Must discard intermediate configuration instances bound to temporarypaths once the underlying directory is atomic-renamed.What: Configuration instances (e.g.,GitConfig) bound to a temporaryfilesystem path must be abandoned after the path is atomic-renamed. A newinstance tracking the permanent directory path must be used for subsequentsettings.Applies To: Git config lifecycle management across atomic filesystemboundary events.Why: Applying configuration changes likegc.pruneExpireusing an objectinstantiated against a temporary path resulted in IO errors or lost state ifthe operations occurred after the directory was moved to its final, permanentlocation. Failing to adhere to this typically results in **Lost Configuration/ IO Error**.
Trap 1: Using a temporary config object to set flags after the underlying directory has been renamed.
Don't:
curr_config = GitConfig.ForRepository(gitdir=tmp_gitdir)platform_utils.rename(tmp_gitdir, self.gitdir)curr_config.SetString("gc.pruneExpire", "never") # BAD: Path no longer valid
Do:
curr_config = GitConfig.ForRepository(gitdir=tmp_gitdir)platform_utils.rename(tmp_gitdir, self.gitdir)self.config.SetString("gc.pruneExpire", "never") # GOOD: Using permanent config tracking self.gitdir
T2-10: Granular Safety Checks for Destructive Worktree Operations
Rule: Must evaluate explicit dependency subsets and prompt overridesbefore wiping shared object directories.What: Destructive operations (like wiping directories) must separatelyevaluate and prompt overrides for distinct risk categories (uncommitted localchanges vs. shared object directories), and only delete a shared objectdirectory if all dependent projects are successfully wiped.Applies To: Commands modifying or deleting project directories and.repo/project-objects.Why: Deleting shared.repostate indiscriminately could leave otherreferencing projects broken if they relied on the same object directory,requiring strict subset checks beforermtreeexecution. Failing to adhere tothis typically results in Repository Corruption / Data Loss.
Trap 1: Deleting a shared object directory immediately upon deleting a single project that uses it.
Don't:
# BAD: Deletes shared objdir, breaking other projectsproject.DeleteWorktree(force=True)if os.path.exists(project.objdir):platform_utils.rmtree(project.objdir)
Do:
# GOOD: Verify all users of the objdir are deleted firstproject.DeleteWorktree(force=True)successful_wipes.add(project.relpath)# Later...if users.issubset(successful_wipes):platform_utils.rmtree(objdir)
T2-11: Explicit Warnings for Legacy Garbage Collection Fallbacks
Rule: Must emit a visible warning tosys.stderrwhen disabling Gitgarbage collection via legacy fallback configurations.What: When disabling Git garbage collection for shared networkrepositories using legacy mechanisms (gc.pruneExpire=never), the toolingmust emit a visiblesys.stderrwarning due to the unreliability of older Gitclients.Applies To: Git configuration manipulation and local filesystem management(_GCProjects).Why: Older Git clients (pre 2.7.0) do not natively support theextensions.preciousObjectsflag. To prevent garbage collection fromcorrupting shared objects,repoforcesgc.pruneExpiretonever. Becausethis is imperfect, it can lead to unreliable repository states, requiringexplicit user notification. Failing to adhere to this typically results inData Loss / Corruption.
Trap 1: Silently executing a legacy fallback for repository safety configurations without informing the user of the potential unreliability.
Don't:
# BAD: Silent fallback to legacy GC directiveif git_require((2, 7, 0)):project.config.SetString('extensions.preciousObjects', 'true')else:project.config.SetString('gc.pruneExpire', 'never')
Do:
# GOOD: Alerting the user to the legacy system riskif git_require((2, 7, 0)):project.config.SetString('extensions.preciousObjects', 'true')else:print('WARNING: shared projects are unreliable when using old versions of git...', file=sys.stderr)project.config.SetString('gc.pruneExpire', 'never')
T2-12: Atomic Commits for Filesystem Restructuring
Rule: Always strictly isolate structural filesystem modifications andmigrations into single atomic commits to maintain bisectability.What: Refactoring critical filesystem paths (like migrating internal.gitsubmodule structures) must be strictly isolated into atomic commits topreserve bisectability.Applies To: Worktree layout updates,.gitmetadata migrations, andsubmodule structure changes.Why: A monolithic commit attempted to restructure how submodules werestored (fromsubprojects/tomodules/), update initialization logic, andalter fetching. This density made code review difficult and created a highrisk of regressions that would be impossible to bisect cleanly. Failing toadhere to this typically results in Unbisectable Regressions.
Trap 1: Bundling filesystem path migrations, structural re-designs, and initialization logic changes into a single Pull Request/Patchset.
Don't:
- Submit 1 patchset: [Refactor] Move submodules to modules/, update git config
flags, and modify sync --init behaviors.
Do:
- Submit 3 sequential patchsets: 1) Isolate init flag changes. 2) Migrate
filesystem directories from subprojects to modules. 3) Enable Git recurse submodules integration.
T2-13: Precise Symlink Target Replacement During Submodule Migration
Rule: Always use explicit path prefixes instead of generic substringreplacements to update symlink targets during legacy layout migrations.What: Symlink updates during filesystem layout migrations must use exactpath prefixes rather than global substring replacements to update relativetargets safely.Applies To: Repository migration logic (project.py); specifically_MigrateSubprojectLinksor similar symlink target modifications.Why: During the migration of legacy submodule directories, using genericstring replacement (target.replace) on symlink paths unintentionallycorrupted paths if a user's directory structure legitimately contained thetarget string (e.g.,subproject-objects) in a higher-level parent directoryname. Failing to adhere to this typically results in **Broken Symlinks /Corruption**.
Trap 1: Using a generic string `.replace()` to update a portion of a file path.
Don't:
if "subproject-objects" in target:new_target = target.replace("subproject-objects", "module-objects")
Do:
if target.startswith("../../subproject-objects/"):new_target = target.replace("../../subproject-objects/", "../../module-objects/")
T2-14: Isolating Filesystem Migrations from Network-Only Operations
Rule: Never execute internal repository layout migrations as part ofnetwork fetch iterations.What: Internal repository layout migrations must only execute during localworktree initialization phases, never during network fetch iterations.Applies To: Repository sync operations (subcmds/sync.py) and worktreecheckout logic (project.py).Why: Binding irreversible filesystem layout migrations to thesynccommand's network-fetch loop risked partially migrating the repository if theprocess was interrupted, or if a user requested a network-only sync, leavingthe local workspace out of sync with internal references. Failing to adhere tothis typically results in Repository Corruption.
Trap 1: Executing internal directory migrations globally prior to downloading network changes.
Don't:
# In subcmds/sync.py during network fetchingfor p in all_projects:p._MigrateOldSubprojectDirs()# ... fetch logic
Do:
# Inside project.py during _InitWorkTree() or checkoutdef _InitWorkTree(self):self._MigrateOldSubmoduleDirs()# ... symlink creation and checkout logic
T2-15: Idempotent Cross-Platform File Cleanup
Rule: Must employplatform_utils.remove()for file cleanup to safelyabsorb OS access violations and gracefully swallowENOENT.What: File cleanup operations must use the internalplatform_utils.remove()instead of the standardos.remove()to handleWindows-specific OS limitations. Furthermore, cleanup must be idempotent byexplicitly catching and swallowingerrno.ENOENTerrors.Applies To: Local worktree operations, internal state file cleanup (e.g.,deleting obsolete copyfiles or linkfiles).Why: Sync operations would abruptly crash on Windows due to unhandledEACCESissues on read-only files/symlinks with nativeos.remove().Furthermore, if a tracking file was already deleted manually by the user or aprior interrupted run, unhandledENOENTexceptions would needlessly fail theoperation. Failing to adhere to this typically results in **Crash onMissing/Locked File**.
Trap 1: Relying on standard library file removal and failing to handle the scenario where the file no longer exists.
Don't:
if path:try:os.remove(path)except OSError as error:print(f'error: remove {path} failed.')return 1
Do:
try:platform_utils.remove(path)except OSError as e:if e.errno == errno.ENOENT:# File does not exist, safe to ignorepass
T2-16: Self-Healing Binary JSON Deserialization
Rule: Always read internal JSON state files in binary mode (rb) andimplement explicit error catching to seamlessly discard corrupted states.What: Internal JSON tracking files must be read in binary mode (rb) toallow the JSON parser to detect text encoding safely. Additionally, parsingmust be wrapped in atry/exceptblock to automatically delete the file andrecover if the JSON is corrupted.Applies To: Manifest metadata tracking files, internal cache parsing(e.g.,copy-link-files.json).Why: When the operating system's default text encoding did not match thefile's encoding, aUnicodeDecodeErrorcould occur. Additionally, if the JSONstate file was corrupted (e.g., due to an abrupt power loss or killedprocess),repo syncwould permanently fail until the user manuallydiscovered and deleted the corrupted state file. Failing to adhere to thistypically results in Corrupt State Deadlock.
Trap 1: Opening JSON state files in text mode without validating structure, allowing exceptions to bubble up and break the CLI.
Don't:
with open(copylinkfiles_path, 'r') as fd:old_copylinkfiles_path = json.load(fd)
Do:
with open(copylinkfiles_path, 'rb') as fp:try:old_copylinkfiles_path = json.load(fp)except:print('error: %s is not a json formatted file.' % copylinkfiles_path, file=sys.stderr)platform_utils.remove(copylinkfiles_path)return False
T2-17: Atomic File Writes for Repository Configurations
Rule: Must utilize atomic file writes rather than standard contexts whengenerating core.gitconfiguration files.What: System state modifications, specifically writing the.gitpointerfiles for submodules, must be performed using an atomic write pattern (e.g.,writing to a lockfile and renaming) rather than standard file descriptors.Applies To: All file I/O operations directly modifying.gitcontents,worktrees, or manifest definitions.Why: Using standardopen()and writing to.gitfiles directly leavesthe repository vulnerable to corruption if the process is interrupted (e.g.,via Ctrl+C or SIGTERM) during the write loop, resulting in a partially writtenpointer. Failing to adhere to this typically results in **Corrupted GitWorktree**.
Trap 1: Using the standard python `open()` context manager and `print()` to mutate core git directories.
Don't:
with open(dotgit, "w") as fp:print(f"gitdir: {rel_path}", file=fp)
Do:
_lwrite(dotgit, f"gitdir: {rel_path}\n")
T2-18: File Descriptor Lock Scope Minimization
Rule: Minimize file descriptor lock retention by executing string andstate logic outside of standard reading contexts.What: Data processing and variable manipulation must be extracted out offile descriptor lock contexts (with open(...)) to minimize resourceretention.Applies To: Any block parsing local text or configuration files.Why: Holding file descriptors open while executing CPU-bound stringmanipulations increases lock contention probability and expands the attacksurface for race conditions when multiple concurrent processes read/writerepository states. Failing to adhere to this typically results in **ResourceLock Contention**.
Trap 1: Processing strings and building directory paths inside the file reading scope.
Don't:
with open(dotgit) as fp:setting = fp.read()gitdir = setting.split(":")[1].strip()dotgit_path = os.path.normpath(os.path.join(self.worktree, gitdir))
Do:
with open(dotgit) as fp:setting = fp.read()# Lock released, safe to processgitdir = setting.split(":")[1].strip()dotgit_path = os.path.normpath(os.path.join(self.worktree, gitdir))
T2-19: Two-Phase Atomic Deletion for Worktrees
Rule: Must enact permanent.gitand worktree removal via a two-phasedestruction pattern utilizing a temporary trash path.What: When permanently removing a.gitdirectory or worktree, the systemmust first perform an atomic rename to a temporary trash path beforeinitiating the recursive deletion.Applies To: Garbage collection (gc.py), worktree cleanup, and submoduleremoval logic.Why: Recursive deletion is not instantaneous. If a user forcefullyinterrupted (Ctrl+C) thermtreeoperation, the directory was left in a'wedged' (partially deleted but still registered) state, permanently breakingfuture syncs for that repository. Failing to adhere to this typically resultsin Wedged / Orphaned Worktree.
Trap 1: Directly triggering `rmtree` on a live repository path.
Don't:
for path in to_delete:platform_utils.rmtree(path)
Do:
for path in to_delete:temp_path = rename_to_trash(path)platform_utils.rmtree(temp_path)
T2-20: Conditional Absolute Path Resolution for Git Worktrees
Rule: Always independently verify if a tracked worktree path is absolutebefore initiating internal path recreation procedures.What: Updates to.gitdirectory reference files (e.g.,gitdir:) mustverify whether the stored worktree path is absolute before attempting torecreate it as a relative path to avoid path corruption and permissionserrors.Applies To: Internal Git directory layout management, specificallycross-platform Git worktree initialization (project.py).Why: On certain platforms like Windows, modifying the internaldotgitfile in situ fails due to file permissions. Code was added to delete andrecreate the file using relative paths. However, depending on the Git version,the initial path could already be relative, making conversion unsafe withoutanisabs()check. Failing to adhere to this typically results inPermission Denied / Path Corruption.
Trap 1: Blindly deleting and rewriting the `gitdir` file using `os.path.relpath` without checking if the source path is absolute first.
Don't:
platform_utils.remove(dotgit)with open(dotgit, "w", newline="\n") as fp:print("gitdir:", os.path.relpath(git_worktree_path, self.worktree), file=fp)
Do:
if os.path.isabs(git_worktree_path):platform_utils.remove(dotgit)with open(dotgit, "w", newline="\n") as fp:print("gitdir:", os.path.relpath(git_worktree_path, self.worktree), file=fp)
T2-21: Independent Manifest Repository Shallow Cloning
Rule: Never propagate the primary manifest--depthflag to govern thecore manifest repository's clone boundaries.What: The depth configuration for cloning the central manifest repositorymust be explicitly decoupled from the depth configuration applied to the childprojects it governs, and its default must not regress existing multi-stageinit workflows.Applies To: Repo initialization commands (repo init,subcmds/init.py).Why: Using the global--depthflag inadvertently forced shallow cloneson all child projects. Introducing a dedicated--manifest-depthoption fixedthis, but defaulting it to 1 caused a regression during 'double repo init'workflows (where subsequent checkouts failed against truncated manifesthistories). Failing to adhere to this typically results in **WorkflowRegression / History Truncation**.
Trap 1: Defaulting to a shallow clone for configuration repositories, causing subsequent initialization/branch switching commands to fail due to missing objects.
Don't:
group.add_option('--manifest-depth', type='int', default=1, metavar='DEPTH',help='create a shallow clone of the manifest repo')
Do:
group.add_option('--manifest-depth', type='int', default=0, metavar='DEPTH',help='create a shallow clone of the manifest repo')
Cross-Domain Dependencies
- Upstream: T3 | Subprocess Git Integration & Error Translation - *Network
operations and git process invocations require safe staging paths and catchable exceptions to trigger filesystem cleanups.*
- Downstream: T1 | Concurrent Synchronization & IPC - *Parallel checkout
operations depend heavily on atomic path modifications and lock-free directory states to prevent race conditions.*
- Downstream: T4 | Manifest Object Model & Deduplication - *Filesystem
migrations and subproject tree building directly parse and reflect canonicalized XML manifest declarations.*
Chapter: Subprocess Git Integration & Error Translation
Context: This chapter defines the constraints for wrapping, executing, and translating standard Git subprocesses within the Repo tooling ecosystem. It mandates the use of centralized command abstractions, strict version gating, and deterministic stream handling to guarantee reliable repository state management and actionable error reporting.
Summary
| Rule ID | Principle / Constraint | Priority | Primary Symptom / Trap | |
|---|---|---|---|---|
| T3-01 | Unborn Branch Resolution | High | Catching a rev-parse |
: : via Symbolic-Ref : : GitError and immediately : : : : : falling back to manual : : : : : file system reads or : : : : : emitting warnings. :
: : Abstraction Usage : : manually inside a class : : : : : to invoke Git. :
: : Git Output Parsing : : with tabs and defending : : : : : against length : : : : : variations. :
: : Context and Native Path : : objects, using : : : Passing : : Git-specific directory : : : : : shifts, and suppressing : : : : : piped output. :
: : Constraints for Promisor : : flag without ensuring : : : Packs : : compatibility first. :
: : Availability Caching : : exceptions to terminate : : : : : the process instead of : : : : : returning control to the : : : : : caller. :
: : Validation : : subprocess execution : : : : : method on an already : : : : : completed process object. :
: : Compatibility : : modern CLI flags into : : : : : subprocess wrappers. :
: : Published Local Branches : : LocalSyncFail when an : : : : : upstream gain exists, : : : : : completely ignoring the : : : : : force_rebase argument. :
: : Failure Translation : : 128 errors equally : : : : : without sniffing stdout : : : : : for authentication prompt : : : : : aborts. :
: : Unborn Git HEAD : : exception immediately : : : : : upon a GitError when : : : : : checking for the HEAD : : : : : reference. :
: : Output Handling : : success and attempting to : : : : : return an output variable : : : : : that hasn't been : : : : : initialized. :
: : Fallback : : arbitrary SHA-1 will : : : : : unconditionally succeed : : : : : if --depth is used. :
: : Option Syntax : : with incorrect, : : : : : unverified key strings. :
: : Guard Under Git Worktrees : : submodules without : : : : : verifying if the : : : : : underlying Git worktree : : : : : feature is active. :
: : Configuration Resolution : : home directory as the : : : : : sole location for : : : : : .gitconfig. :
: : Error Contexting : : failure and re-raising it : : : : : as a generic git error : : : : : with a concatenated : : : : : string message. :
: : for Subprocess : : fixed number of : : : Diagnostics : : characters and ignoring : : : : : stderr entirely. :
Rules
T3-01: Unborn Branch Resolution via Symbolic-Ref
Rule: Always attemptgit symbolic-refbefore falling back to manual fileparsing to correctly resolve unborn branches.What: When querying local Git branch structures,git symbolic-refmustbe attempted as a fallback before file parsing to correctly identify unbornbranches whererev-parsefails.Applies To: Subprocess Git integrations resolvingHEADor local refs.Why: Freshly initialized repositories and orphan branches present 'unborn'states where standardrev-parsecommands returned errors, triggeringfalse-positive warnings or crashing the client. Failing to adhere to thistypically results in Incorrect Branch Detection.
Trap 1: Catching a `rev-parse` GitError and immediately falling back to manual file system reads or emitting warnings.
Don't:
try:return rev_parse(HEAD)except GitError:logger.warning("Unparseable HEAD")return parse_file(HEAD)
Do:
try:return rev_parse(HEAD)except GitError:try:return run_git_command("symbolic-ref", "-q", HEAD)except GitError:passreturn parse_file(HEAD)
T3-02: Centralized GitCommand Abstraction Usage
Rule: Strictly use the internalGitCommandabstraction for local Gitoperations instead of invoking rawsubprocess.run.What: Use the internalGitCommandabstraction for executing Gitoperations rather than rawsubprocess.runto guarantee consistent tracing,environment handling, and error translations.Applies To: Any module interacting with local git binaries, such asgit_refs.py.Why: Developers bypassing the centralized wrapper led to duplicatedsubprocess execution logic, loss of global tracing capabilities (e.g.,REPO_TRACE), and fragmented error handling across the codebase. Failing toadhere to this typically results in Missing Tracing / Environment Bugs.
Trap 1: Wrapping `subprocess.run` manually inside a class to invoke Git.
Don't:
def _Run(self, *cmd):return subprocess.run(['git', f'--git-dir={self._gitdir}', *cmd],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
Do:
import git_commanddef _Run(self, cmd):p = git_command.GitCommand(None,cmd,capture_stdout=True,capture_stderr=True,bare=True,gitdir=self._gitdir,)p.Wait()return p
Exceptions: Low-level testing utilities isolated from the core application state, where bypassing GitCommand is necessary to bootstrap a test repository.
T3-03: NUL-Byte Delimiters for Git Output Parsing
Rule: Always specify NUL-byte delimiters (%00) when parsing Git commandoutput to prevent splitting errors.What: When parsing Git formatted output, utilize the NUL byte (%00)instead of tabs or spaces, and leverage precise tuple unpacking without lengthvalidation.Applies To: Parsing output from Git commands likegit for-each-reforgit status.Why: Using whitespace or tabs to split field data exposed the parser tofailures if reference names or other entities inherently included thosecharacters. NUL delimiters guarantee absolute safety and allow removal ofdefensive parsing loops. Failing to adhere to this typically results in **DataParsing Failure**.
Trap 1: Formatting git fields with tabs and defending against length variations.
Don't:
# Using tab delimiter and checking lensubprocess.run(['git', 'for-each-ref', '--format=%(objectname)\t%(refname)'])for line in output.splitlines():fields = line.split('\t')if len(fields) < 2:continueref_id, name = fields[:2]
Do:
# Using NUL delimiter and direct unpackingGitCommand(..., ['for-each-ref', '--format=%(objectname)%00%(refname)%00%(symref)'])for line in output.splitlines():ref_id, name, symref = line.split('\0')
T3-04: Subprocess Execution Context and Native Path Passing
Rule: Pass nativepathlib.Pathobjects via thecwdargument ratherthan stringifying them or utilizing Git's-Cflag.What: Execute subprocesses with correct internal API paradigms: omit Git's-Cin favor of thecwd=parameter, passpathlib.Pathobjects inherently,and drop-qwhen actively capturing output.Applies To: Subprocess command building and execution in test scaffoldingand Git interactions.Why: Passing-Ccombined with forced string casting of paths createdredundant logic. Additionally, suppressing underlying git output via-qcompletely masked the root cause of errors captured within the internal streambuffers. Failing to adhere to this typically results in **ObscuredDiagnostics**.
Trap 1: Stringifying Path objects, using Git-specific directory shifts, and suppressing piped output.
Don't:
subprocess.check_call(['git', '-C', str(git_dir), 'init', '-q'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Do:
subprocess.check_call(['git', 'init'],cwd=git_dir,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
T3-05: Runtime Git Version Constraints for Promisor Packs
Rule: Explicitly verify local Git version compatibility before injectingmodern CLI flags into subprocess calls.What: Operations utilizing modern Git arguments like--missing=allow-promisormust be explicitly gated by a minimal supportedversion check against the local executable.Applies To: Subprocess handlers forgit rev-listand repackingmechanisms on partial clones.Why: Git 2.17.0 introduced advanced promisor arguments. Hardcoding thesearguments in the execution engine crashed older repository clients on machineswhere Git had been downgraded or not updated. Failing to adhere to thistypically results in Subprocess Crash.
Trap 1: Invoking a modern git CLI flag without ensuring compatibility first.
Don't:
if opt.repack:return self.repack_projects(projects, opt)
Do:
if opt.repack:git_require((2, 17, 0), fail=True, msg="--repack")return self.repack_projects(projects, opt)
T3-06: Centralized Dependency Availability Caching
Rule: Centralize and cache external dependency checks to fail gracefullywithout abruptly terminating the calling process.What: External dependency checks (e.g., verifying SSH installation) mustbe centralized, cached internally, and fail gracefully without forciblyexiting the calling process.Applies To: System API wrappers and subprocess managers (e.g.,ProxyManager,ssh.py).Why: Deep utility functions checking for external binaries previouslycalledsys.exit(1)uponFileNotFoundError. This abruptly terminated theexecution for users in environments missing the dependency, even if theirspecific workflow did not actually require it. Failing to adhere to thistypically results in Unexpected Process Termination.
Trap 1: Catching missing binary exceptions to terminate the process instead of returning control to the caller.
Don't:
def version():try:return _parse_ssh_version()except FileNotFoundError:print("fatal: ssh not installed", file=sys.stderr)sys.exit(1)
Do:
def version():try:return _parse_ssh_version()except FileNotFoundError as e:print("warn: ssh not installed", file=sys.stderr)raise e
Trap 2: Duplicating inline `try-except` blocks for missing binaries across multiple execution methods rather than centralizing state.
Don't:
def run_command1(self):try:subprocess.Popen(['ssh'])except FileNotFoundError:return Falsedef run_command2(self):try:subprocess.Popen(['ssh'])except FileNotFoundError:return False
Do:
def __enter__(self):try:version()self._ssh_installed = Trueexcept FileNotFoundError:self._ssh_installed = Falsereturn selfdef run_command(self):if not self._ssh_installed:return Falsesubprocess.Popen(['ssh'])
T3-07: Subprocess Return Code Validation
Rule: Validate subprocess success strictly usingcheck_returncode()onthe completed process object.What: When utilizing the standard Pythonsubprocesslibrary, the correctmethod to validate execution success on aCompletedProcessobject ischeck_returncode(). Do not callcheck_call()on the returned object.Applies To: Any Python code wrapping git commands and handlingsubprocess.CompletedProcessresults.Why: Legacy code inadvertently calledcheck_call()on the result ofrun_command, which triggered a runtimeAttributeErrorinstead of raisingthe expectedsubprocess.CalledProcessErroron failure. Failing to adhere tothis typically results in AttributeError.
Trap 1: Calling a non-existent subprocess execution method on an already completed process object.
Don't:
ret = subprocess.run(cmd, capture_output=True)ret.check_call() # Raises AttributeError
Do:
ret = subprocess.run(cmd, capture_output=True)# This will raise subprocess.CalledProcessError for usret.check_returncode()
T3-08: Strict Git Version Compatibility
Rule: Never pass Git flags that are unsupported by the minimum requiredGit version listed in the project's manifest.What: Do not pass modern CLI flags to subprocess Git operations if thoseflags are not supported by the minimum required Git version listed in theproject's dependency manifest.Applies To: Git subprocess string assembly inproject.py.Why: The--no-auto-gcflag was appended to clone commands to preventdeadlocks, but this flag did not exist in Git 1.7.9, immediately breakingcheckout operations for environments restricted to the minimum supportedbaseline. Failing to adhere to this typically results in **Unknown OptionError**.
Trap 1: Injecting convenient, modern CLI flags into subprocess wrappers.
Don't:
cmd.append("--no-auto-gc")
Do:
- Disabling auto-gc via configuration setters (`self.config.SetInt("gc.auto",
0)`) that are safely interpreted across legacy Git versions.
T3-09: Rebase Override for Published Local Branches
Rule: Allow rewriting of published local commits by respecting theforce_rebaseargument during sync operations.What: When a local branch is published but not yet merged upstream, `reposync --rebasemust respect theforce_rebase` argument to allow rewritingpublished commits, rather than unconditionally throwing a sync failure.Applies To:project.py, specifically_Rebaseand_FastForwardpathexecution during sync.Why: The tool previously threw an error instructing the user to run with--rebase, but didn't actually execute the rebase when the flag was provided,forcing developers to manually fix the state. Failing to adhere to thistypically results in Broken UX / Unhandled Rebase State.
Trap 1: Throwing a `LocalSyncFail` when an upstream gain exists, completely ignoring the `force_rebase` argument.
Don't:
if upstream_gain and not force_rebase:# Fails even if force_rebase is TRUE due to logic gapfail(LocalSyncFail("branch is published... rerun with the --rebase option"))
Do:
if upstream_gain:if force_rebase:syncbuf.later1(self, _dorebase, not verbose)else:fail(LocalSyncFail("branch is published... rerun with the --rebase option"))
T3-10: SSO Authentication Failure Translation
Rule: Intercept Git exit code 128 and translate it to a typedGitAuthErrorwhen stdout indicates an SSO session abort.What: Git commands that fail with exit code 128 due to an SSO sessionabort must be explicitly intercepted and translated into a typedGitAuthError, preventing them from being masked as a missing reference.Applies To: project.py, Git Subprocess Wrappers evaluatinggitcmd.stdoutand return codes (specifically fetch/sync operations interacting with SSOremote helpers).Why: In non-interactive environments, an expired SSO token caused Git tofail with a generic exit code 128. The tool misinterpreted this as a missingupstream reference, leading to confusing error logs that obscured theunderlying authentication requirement. Failing to adhere to this typicallyresults in Ambiguous Auth Failure.
Trap 1: Treating all exit code 128 errors equally without sniffing stdout for authentication prompt aborts.
Don't:
# BAD: Ambiguous handling of 128elif current_branch_only and is_sha1 and ret == 128:# Assuming missing upstream referenceraise GitError("Couldn't find the ref you asked for")
Do:
# GOOD: Explicit trap for SSO helperselif ret == 128 and gitcmd.stdout and "remote helper 'sso' aborted session" in gitcmd.stdout:raise GitAuthError(gitcmd.stdout)
Exceptions: Repositories containing multiple remotes where an auth failure on a secondary remote might be non-fatal. (Currently flagged for future review but translation stands).
T3-11: Direct Read Fallback for Unborn Git HEAD
Rule: Implement a direct file system read of.git/HEADas a fallbackwhen standard sub-commands fail to resolve the reference.What: When standard Git commands fail to resolve the current HEAD (e.g.,throwing aGitError), the system must fall back to directly reading theinternal.git/HEADfile from the filesystem before propagating a fatalerror.Applies To: project.py,GetHead()implementations traversing repositorystate.Why: Empty repositories or states featuring unborn branches caused `gitrev-parse HEAD` to fail outright. Without a fallback, this cascaded into aNoManifestExceptionand aborted the entire synchronization process. Fallingback to the raw.git/HEADtext bypassed the strict ref checks. Failing toadhere to this typically results in Hard Crash / NoManifestException.
Trap 1: Raising a fatal internal exception immediately upon a `GitError` when checking for the HEAD reference.
Don't:
# BAD: Strict reliance on git sub-commandstry:return self.rev_parse(HEAD)except GitError as e:path = self.GetDotgitPath(subpath=HEAD)raise NoManifestException(path, str(e))
Do:
# GOOD: Fallback text parsing mechanismtry:return self.rev_parse(HEAD)except GitError as e:path = self.GetDotgitPath(subpath=HEAD)try:with open(path) as fd:# Read branch manuallyexcept OSError:raise NoManifestException(path, str(e))
Exceptions: If the physical .git/HEAD file raises an OSError (meaning it truly does not exist on disk), a NoManifestException is necessary and valid.
T3-12: Safe Git Subprocess Output Handling
Rule: Always validate the return code of a Git subprocess before accessingits standard output properties.What: Git subprocess output wrappers must explicitly handle non-zero exitcodes to prevent accessing uninitialized variables, and stream properties mustbe spell-checked against the underlying class definitions.Applies To: Git subprocess wrappers (git_superproject.py,GitCommand)and any execution context capturing stdout/stderr.Why: When a Git command (likegit rev-parse) failed, the code attemptedto return a variable (data) that was only initialized on success, causing anUnboundLocalError. Furthermore, error logging attempts crashed due to a typoaccessingp.stdwerrinstead ofp.stderr. Failing to adhere to thistypically results in Runtime Crash / UnboundLocalError.
Trap 1: Assuming subprocess success and attempting to return an output variable that hasn't been initialized.
Don't:
# BAD: data is unbound if retval != 0retval = p.Wait()if retval == 0:data = p.stdoutelse:log_error("Failed")return data
Do:
# GOOD: Explicit error handling with early returnretval = p.Wait()if retval != 0:log_error(f"Failed: {p.stderr}")return Nonereturn p.stdout
Trap 2: Typo in the attribute name for capturing standard error from the `GitCommand` class.
Don't:
# BAD: Invalid attribute triggers AttributeErrorself._LogWarning("Error: {}", p.stdwerr)
Do:
# GOOD: Correct attribute referenceself._LogWarning("Error: {}", p.stderr)
T3-13: Shallow Clone SHA-1 Fetch Fallback
Rule: Provide a full-sync fallback when shallow fetch requests forspecific SHA-1s are rejected by server policies.What: Git fetch requests targeting specific SHA-1s with--depthenabledmust handle graceful fallbacks, as server-side policies often restrictunadvertised object fetching.Applies To: Git fetch routines inproject.py, specifically duringincremental or optimized shallow clones.Why: When optimizing syncs by directly fetching specific SHA-1s with adepth limitation, operations failed silently or returned generic errorsbecause some Git servers do not advertise all objects, explicitly rejectingsuch requests. Failing to adhere to this typically results in **SyncFailure**.
Trap 1: Assuming a fetch of an arbitrary SHA-1 will unconditionally succeed if `--depth` is used.
Don't:
# BAD: Missing fallback for unadvertised objectsret = fetch_sha1(depth=1)if ret < 0:break
Do:
# GOOD: Explicit fallback to a full sync (depth-less) if the specific SHA-1 is rejectedret = fetch_sha1(depth=1)if depth and is_sha1 and ret == 1:# Server may not allow fetching unadvertised refs, fallback to full syncbreak
Exceptions: Servers specifically configured to allow uploadpack.allowReachableSHA1InWant or similar parameters, though the client cannot assume this.
T3-14: Validating Gerrit Push Option Syntax
Rule: Pass custom Gerrit push options strictly using the documentedcustom-keyed-valueparameter syntax.What: When passing custom metadata to Gerrit via Git push options,strictly adhere to thecustom-keyed-valuesyntax as defined by the remoteserver documentation.Applies To:upload.pyoperations mapping superproject state to `git push-o`.Why: The client attempted to attach superproject metadata to pushoperations usingcustom-key-value, which was ignored by the Gerrit serverbecause the documented parameter wascustom-keyed-value. Failing to adhereto this typically results in Metadata Loss / Server Rejection.
Trap 1: Constructing push options with incorrect, unverified key strings.
Don't:
# BAD: Incorrect key formatpush_options.append(f"custom-key-value=rootRepo:{host}/{sp_name}")
Do:
# GOOD: Matches external documentationpush_options.append(f"custom-keyed-value=rootRepo:{host}/{sp_name}")
T3-15: Submodule Initialization Guard Under Git Worktrees
Rule: Skip Git submodule initialization sequences if the repository isactively utilizing Git worktrees.What: Submodule initialization operations (git submodule init) must beexplicitly skipped if the repository is configured to use Git worktrees.Applies To: Git command wrappers, worktree initialization sequences, andsubmodule lifecycle operations inproject.py.Why: Upstream Git has known bugs and incomplete feature support regardingthe use of submodules within worktrees. Attempting to initialize submodulesunder these conditions leads to undefined behavior and broken repositorystates. Failing to adhere to this typically results in **Upstream Git Bug /Inconsistency**.
Trap 1: Blindly initializing submodules without verifying if the underlying Git worktree feature is active.
Don't:
self._InitWorkTree(force_sync=force_sync, submodules=submodules)if self.has_subprojects:self._InitSubmodules()
Do:
self._InitWorkTree(force_sync=force_sync, submodules=submodules)# Avoid doing a submodule init when using worktrees as the support for# submodules is incomplete.if self.has_subprojects and not self.use_git_worktrees:self._InitSubmodules()
T3-16: XDG Compliant Git Configuration Resolution
Rule: Resolve user Git configuration files natively honoring theXDG_CONFIG_HOMEenvironment variable before defaulting to legacy paths.What: Git configuration lookups must natively respect theXDG_CONFIG_HOMEenvironment variable, falling back to~/.config/git/configbefore finally querying the legacy~/.gitconfiglocation.Applies To: Git configuration parsing, environment setup, and hermetictests.Why: Users who migrated their dotfiles to the XDG Base DirectorySpecification experienced issues because internal tooling rigidly expected~/.gitconfigto exist, bypassing user intentions and leading tounauthenticated or unconfigured repository actions. Failing to adhere to thistypically results in Orphaned Configuration State.
Trap 1: Hardcoding the user's home directory as the sole location for `.gitconfig`.
Don't:
def _getUserConfig():return os.path.expanduser("~/.gitconfig")
Do:
def _getUserConfig():"""This matches git: https://git-scm.com/docs/git-config#FILES"""xdg_config_home = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))xdg_config_file = os.path.join(xdg_config_home, "git", "config")if os.path.exists(xdg_config_file):return xdg_config_filereturn os.path.expanduser("~/.gitconfig")
T3-17: Strongly-Typed Subprocess Error Contexting
Rule: Raise strongly-typedGitCommandErrorexceptions with granularstate context instead of generic Git errors.What: Git commands that yield non-zero exit codes must raise a specializedGitCommandErrorcontaining granular execution context, rather than a genericGitError.Applies To: Subprocess execution wrappers withingit_command.pyanddownstream consumers handling Git process states.Why: When commands failed silently or raised generic errors, downstreamhandlers could not differentiate between configuration errors and actualsubprocess failures, leading to loss of arguments and return codes. Failing toadhere to this typically results in Lost Diagnostic Context.
Trap 1: Catching a subprocess failure and re-raising it as a generic git error with a concatenated string message.
Don't:
if self.rc != 0:raise GitError("%s: %s" % (command[1], e))
Do:
if self.rc != 0:raise GitCommandError(message="git command failure",project=project.name,command_args=self.cmdv,git_rc=self.rc,git_stdout=stdout,)
T3-18: Line-Based Log Extraction for Subprocess Diagnostics
Rule: Extract and log the first meaningful line of both standard outputand error streams rather than enforcing arbitrary truncation limits.What: When capturing subprocess logs for error reporting, extract thefirst meaningful line ofstdoutandstderrinstead of relying on arbitrarycharacter limits.Applies To: Error truncation logic for Git subprocesses inWait()blocks.Why: Truncating output by an arbitrary number of characters (e.g., 80chars) occasionally cut off the actual error string. Furthermore, ignoringstderrhid the root cause of the subprocess failure. Failing to adhere tothis typically results in Obfuscated Error Logs.
Trap 1: Truncating stdout to a fixed number of characters and ignoring stderr entirely.
Don't:
stdout = self.stdout[:80] if self.stdout else None
Do:
# Prefer extracting the first full line and including stderrstdout_line = self.stdout.splitlines()[0] if self.stdout else Nonestderr_line = self.stderr.splitlines()[0] if self.stderr else None
Cross-Domain Dependencies
- Upstream: T2 | Filesystem Atomicity & Worktree Layout - *Subprocess
executions must coordinate with filesystem atomicity rules, particularly regarding submodule paths and worktree usage to prevent upstream Git bugs.*
- Downstream: T5 | Hermetic Testing & Test Modernization - *Testing
frameworks depend on hermetic GitCommand wrappers and mocked stream capture to validate subprocess behaviors safely.*
Chapter: Manifest Object Model & Deduplication
Context: This chapter governs the parsing, validation, and canonicalization of XML manifest components. It strictly enforces semantic immutability via NamedTuple implementations, defensive copying for hierarchical override scoping, and deterministic JSON-backed file tracking across the subsystem.
Summary
| Rule ID | Principle / Constraint | Priority | Primary Symptom / Trap | |
|---|---|---|---|---|
| T4-01 | Strict Traversal Prefix | High | Using broad substring |
: : Matching for Relative : : matching to detect : : : URLs : : relative traversal : : : : : sequences. :
: : Inheritance Scoping : : inheritance constraints : : : : : for dynamically : : : : : overridden node elements. :
: : Membership Checks : : list objects inside loop : : : : : conditions. :
: : Shared Collections Prior : : collection reference and : : : to In-Place Mutation : : immediately using an : : : : : in-place operator, : : : : : unknowingly mutating the : : : : : original source. :
: : Hashable Object : : __eq__ on a standard : : : Deduplication : : mutable Python class to : : : : : allow set insertion. :
: : Initialization Over : : bracket literal when a : : : Dictionary Literals : : null set is encountered : : : : : prior to a union : : : : : operation. :
: : Elements for Reliable : : __eq__ and __hash__ : : : Deduplication : : on mutable classes and : : : : : using list.append() : : : : : which allows duplicates : : : : : to accrue. :
: : Node Parsing : : conditions checking : : : : : nodeName sequentially : : : : : in a loop. :
: : File Path State Tracking : : sequentially into a flat : : : : : text file using newlines : : : : : as the only delimiter. :
: : Deltas : : and list appends to : : : : : calculate the difference : : : : : between two collections. :
: : Validation in Layered : : revision without : : : Manifests : : asserting the previous : : : : : expected state. :
Rules
T4-01: Strict Traversal Prefix Matching for Relative URLs
Rule: Always explicitly evaluate exact path-traversal prefixes (./or../) when resolving relative URLs. Never rely on generic substring matching.What: Relative URL path detection must explicitly evaluate exactpath-traversal prefixes to avoid inadvertently capturing hidden files orcustom naming structures.Applies To: URL string manipulation and Git submodule path resolution.Why: The path parser attempted to identify relative submodule paths bychecking if the URL started with a dot (.). This excessively broadevaluation failed on identically named hidden repositories or customsub-namespaces (e.g.,.foo), improperly joining them to the base URL.Failing to adhere to this typically results in Invalid Path Resolution.
Trap 1: Using broad substring matching to detect relative traversal sequences.
Don't:
if url.startswith("."):url = urllib.parse.urljoin("%s/" % self.remote.url, url)
Do:
if url.startswith("./") or url.startswith("../"):url = urllib.parse.urljoin("%s/" % self.remote.url, url)
T4-02: Extend-Project Inheritance Scoping
Rule: Must explicitly restrictextend-projectXML nodes fromautomatically inheriting contextually local execution scopes (local:groups)from root parents.What: When managing XML manifestation directives,extend-projectnodesmust be actively restricted from inheriting contextually local executionscopes (local:groups).Applies To: XML manifest engine mappings and override properties.Why: Without explicit protection, extended project entitiesunintentionally inherited top-level project local groups, confusing theinclusion and exclusion scoping directives that drive synchronizationboundaries. Failing to adhere to this typically results in **ScopeContamination**.
Trap 1: Omitting group inheritance constraints for dynamically overridden node elements.
Don't:
- Allow XML logic to process
extend-projectthe exact same way it processes
raw project roots without negative test coverage.
Do:
- Implement testing and parsing guards proving that elements processed under
extend-project actively strip local: group attributes.
T4-03: Tuple Immutability in Membership Checks
Rule: Always use immutable tuples instead of list literals for membershiptests against constant sequences within hot loops.What: Utilize immutable tuples()instead of list literals[]whenperforming membership tests (theinoperator) against constant sequences tominimize reallocation overhead and adhere to idiomatic Python.Applies To: XML manifest parsing logic (manifest_xml.py) and hot loopsacross the codebase.Why: During recursive node parsing, list literals were instantiated onevery iteration solely to check if a node name matched fixed schema elements.Failing to adhere to this typically results in Performance Degradation.
Trap 1: Instantiating transient list objects inside loop conditions.
Don't:
if node.nodeName in ["include", "project"]:
Do:
if node.nodeName in ("include", "project"):
T4-04: Defensive Copying of Shared Collections Prior to In-Place Mutation
Rule: Must defensively copy shared parent collections before applyingin-place update operators (|=), strictly handling null-safety during theprocess.What: When propagating inherited collections (e.g., manifest group sets)to child nodes, shared parent sets must be defensively copied prior toapplying in-place union or update operators (|=). Null-safety must behandled during the copy.Applies To: XML Manifest Parsing (manifest_xml.py); hierarchical statepropagation where child elements inherit and augment parent states.Why: Assigning a parent's group set directly to a child and then using thein-place union operator (|=) modified the original parent set in memory.This caused the child's specific groups to 'leak' into unrelated sibling nodesprocessed subsequently. Failing to adhere to this typically results in **StateCorruption / Group Leakage**.
Trap 1: Assigning a shared collection reference and immediately using an in-place operator, unknowingly mutating the original source.
Don't:
# BAD: In-place modification mutates the shared parent_groups objectnodeGroups = parent_groupsif node.hasAttribute("groups"):nodeGroups |= self._ParseSet(node.getAttribute("groups"))
Do:
# GOOD: Create a localized copy before mutationnodeGroups = parent_groups.copy() if parent_groups else set()if node.hasAttribute("groups"):nodeGroups |= self._ParseSet(node.getAttribute("groups"))
Trap 2: Falling back to an empty set instantiation after a copy call without guarding against a null reference.
Don't:
# BAD: Raises AttributeError if parent_groups is Noneinclude_groups = parent_groups.copy() or set()
Do:
# GOOD: Null-safe default evaluation prior to the copy invocationinclude_groups = (parent_groups or set()).copy()
T4-05: Immutable NamedTuples for Hashable Object Deduplication
Rule: Always subclassNamedTupleto define custom objects stored inhash-based collections. Never implement manual__hash__and__eq__functions on mutable classes.What: Custom objects stored in hash-based collections (likesetor usedasdictkeys) for deduplication must guarantee immutability. Avoid manuallyimplementing__eq__and__hash__on mutable classes; instead, subclassNamedTuple.Applies To: Manifest deduplication logic (project.py); specificallyelements like_CopyFileand_LinkFilestored in sets.Why: Manually implementing__hash__on a standard class based on itsmutable__dict__attributes created a landmine. If the object's propertieschanged after insertion into a set, the hash mismatched, rendering the objectunreachable and breaking deduplication. Failing to adhere to this typicallyresults in Memory Leak / Deduplication Failure.
Trap 1: Overriding `__hash__` and `__eq__` on a standard mutable Python class to allow set insertion.
Don't:
# BAD: Properties can mutate, altering the hash post-insertionclass _CopyFile:def __init__(self, src, dest):self.src = srcself.dest = destdef __hash__(self):return hash(repr(sorted(self.__dict__.items())))def __eq__(self, other):return self.__dict__ == other.__dict__
Do:
# GOOD: Use typing.NamedTuple to guarantee immutabilityfrom typing import NamedTupleclass _CopyFile(NamedTuple):src: strdest: str
T4-06: Strict Empty Set Initialization Over Dictionary Literals
Rule: Must explicitly invokeset()when initializing empty collectionsmeant for set operations. Never fall back to the empty bracket literal{}.What: When initializing or providing a fallback empty collection meant forset operations (such as union|or|=), explicitly instantiate aset()rather than using the empty literal{}.Applies To: Python collection management globally; prominently surfacedduring list-to-set manifest group migrations.Why: During a migration from lists to sets for group parsing, an emptydefault was incorrectly represented as{}. Since{}evaluates to adictin Python, attempting a set union between a valid set and the empty dict threwan immediate, fatalTypeError. Failing to adhere to this typically resultsin Runtime Crash / TypeError.
Trap 1: Falling back to the empty bracket literal when a null set is encountered prior to a union operation.
Don't:
# BAD: '{}' creates an empty dictionary, throwing a TypeError upon unionexpanded_project_groups = {"all"} | (self.groups or {})
Do:
# GOOD: Explicitly initialize an empty setexpanded_project_groups = {"all"} | (self.groups or set())
T4-07: Immutable Manifest Elements for Reliable Deduplication
Rule: Always represent manifest file operations as inherently immutablestructures to guarantee safe, order-preserving deduplication.What: Manifest elements representing file operations must be implementedas immutable structures (e.g.,NamedTuple) to ensure safe deduplication anddeterministic order preservation, avoiding manual string-based hashing.Applies To: Manifest parsing models, specifically<copyfile>and<linkfile>abstractions.Why: Previously, manifest objects were stored in mutable lists, relying onmanual string representations (repr) and sorted dictionary items forhashing. This risked state corruption and failed to cleanly deduplicaterepeated entries while maintaining the relative declaration sequence. Failingto adhere to this typically results in **Silent Data Corruption / RedundantFile Operations**.
Trap 1: Implementing custom `__eq__` and `__hash__` on mutable classes and using `list.append()` which allows duplicates to accrue.
Don't:
class _CopyFile:def __hash__(self):# BAD: Manual serialization of mutable dictionaryreturn hash(repr(sorted(self.__dict__.items())))self.copyfiles.append(_CopyFile(src, dest))
Do:
class _CopyFile(NamedTuple):# GOOD: Inherently immutable and hashablesrc: strdest: str# GOOD: Using a dict to deduplicate while preserving insertion orderself.copyfiles[_CopyFile(src, dest)] = True
T4-08: Mutually Exclusive XML Node Parsing
Rule: Always chain mutually exclusive XML node type checks using anif-elifstructure rather than independent sequential statements.What: When parsing mutually exclusive XML node types, use anif-elifstructure to avoid redundant condition evaluations.Applies To: XML parsing loops (e.g., iterating overnode.childNodesinmanifest_xml.py).Why: A sequence of independentifstatements forced unnecessary stringcomparisons even after a matching node name was found. Failing to adhere tothis typically results in CPU Overhead / Inefficient Parsing.
Trap 1: Independent `if` conditions checking `nodeName` sequentially in a loop.
Don't:
if n.nodeName == "copyfile":self._ParseCopyFile(p, n)if n.nodeName == "linkfile":self._ParseLinkFile(p, n)
Do:
if n.nodeName == "copyfile":self._ParseCopyFile(p, n)elif n.nodeName == "linkfile":self._ParseLinkFile(p, n)
T4-09: JSON Serialization for File Path State Tracking
Rule: Must persist dynamically generated manifest file outputs usingstructured JSON serialization. Never use newline-delimited plaintext for pathlists.What: Persistent tracking mechanisms for manifest-generated fileoperations must use structured JSON serialization instead of newline-delimitedplaintext to support special characters in paths.Applies To: Manifest state management (subcmds/sync.py), internal.repotracking files (e.g.,copy-link-files.json).Why: Tracking<copyfile>and<linkfile>operations via flat,newline-delimited text files broke serialization and cleanup when file pathslegally contained newline (\n) characters. Structured JSON protects againstthese bounds issues. Failing to adhere to this typically results in **ParsingErrors / Orphaned Files**.
Trap 1: Dumping file paths sequentially into a flat text file using newlines as the only delimiter.
Don't:
with open('linkfile.list', 'w') as fd:for path in new_linkfiles:fd.write(path + '\n')
Do:
with open('copy-link-files.json', 'w') as fd:json.dump({'linkfile': new_linkfiles, 'copyfile': new_copyfiles}, fd)
T4-10: Set Operations for File Deltas
Rule: Always compute the delta between unordered lists of file paths usingnative Python set operations (-).What: When computing the delta between lists of file paths (e.g., figuringout which obsolete files to remove), utilize Python set operations rather thanmanual iterations with truthiness and membership checks.Applies To: Deduplicating objects, comparing manifest states, computingfile differences.Why: Calculating the difference between historical tracking data and newtarget paths was done using O(N*M) nested iterations with redundant truthinesschecks, leading to verbose and less performant code. Failing to adhere to thistypically results in Algorithmic Inefficiency.
Trap 1: Using manual for-loops and list appends to calculate the difference between two collections.
Don't:
need_remove_files = []for old_path in old_dict.get('linkfile', []):if old_path and old_path not in new_paths:need_remove_files.append(old_path)
Do:
need_remove_files = []need_remove_files.extend(set(old_dict.get('linkfile', [])) -set(new_paths))
Exceptions: Ordered constraints where file evaluation sequence matters (sets are unordered).
T4-11: Upstream Base Revision Validation in Layered Manifests
Rule: Must assert multi-layer manifest overrides (extend-project)against the parent project's expected state by utilizing abase-revattribute.What: When overriding (extend-project) or removing (remove-project)projects in a layered manifest structure, changes should be validated againstthe expected state of the parent project via abase-revattribute.Applies To: XML Manifest parsing logic (manifest_xml.py) duringmulti-manifest ingestion.Why: Downstream projects using layered manifests would unknowingly applyoverrides (like custom revisions) to upstream components that had drasticallychanged their underlying state or branches, resulting in 'undead patches' thatsilently masked critical upstream changes. Failing to adhere to this typicallyresults in Silent Configuration Divergence.
Trap 1: Overriding a project revision without asserting the previous expected state.
Don't:
<!-- BAD: Blind override leaves system vulnerable to upstream changes --><extend-project name="my-project" revision="refs/changes/123" />
Do:
<!-- GOOD: Base-rev acts as a guardrail --><extend-project name="my-project" base-rev="upstream_hash" revision="refs/changes/123" />
Trap 2: Checking string-based manifest attributes using implicit truthiness.
Don't:
# BAD: Implicit truthiness skips validation if revisionExpr is unexpectedly emptyif base and p.revisionExpr and p.revisionExpr != base:raise Error()
Do:
# GOOD: Strict comparison catches empty/None states if a base is declaredif base and p.revisionExpr != base:raise Error()
Exceptions: The base-rev attribute is optional to maintain backward compatibility for users migrating to the new manifest schema.
Cross-Domain Dependencies
- Upstream: T2 | Filesystem Atomicity & Worktree Layout - *File path
extraction and submodule path resolution mapped here strictly govern worktree creation and legacy migration algorithms downstream.*
- Downstream: T6 | CLI Argument Parsing & UX Consistency - *Structured
JSON serialization outputted from manifest paths sets the direct format constraint for CLI UX and tooling integrations.*
Chapter: Hermetic Testing & Test Modernization
Context: This domain governs the migration of legacy unittest suites to modern pytest functional paradigms and the establishment of hermetic session fixtures. It enforces strict environment isolation to prevent global state pollution (e.g., developer .gitconfig bleeding) while safely intercepting standard streams and filesystem paths.
Summary
: : : : Trap :
| :-------- | :------------------------------ | :------- | :------------------ | |
|---|---|---|---|---|
| T5-01 | Idiomatic Truthiness Validation | Medium | Asserting strict |
: : in Tests : : identity against : : : : : Python boolean : : : : : singletons. :
: : Framework : : unittest.TestCase : : : : : and configuring : : : : : state inside a : : : : : setUp method for : : : : : new test files. :
: : API Helpers : : utility functions : : : : : across test modules : : : : : or placing standard : : : : : functions into : : : : : pytest conftest : : : : : files. :
: : Pytest : : environment : : : : : variables globally : : : : : at module load to : : : : : support tests. :
: : Context Managers : : framework to : : : : : intercept a core : : : : : language stream. :
: : Fixture Factories : : fixture that yields : : : : : a nested function : : : : : to bypass global : : : : : state limitations. :
: : Assertions : : existence checks : : : : : before access : : : : : checks. :
: : Test Path Resolution : : os.path.dirname : : : : : and os.path.join : : : : : to traverse back to : : : : : the parent : : : : : directory. :
: : Definition : : classes that : : : : : inherit from : : : : : unittest.TestCase : : : : : and asserting via : : : : : self.assertEqual. :
: : Test Reliability : : decorators for : : : : : non-relevant : : : : : sub-routines (e.g., : : : : : standard error : : : : : outputs or : : : : : colorizers) just to : : : : : trigger an embedded : : : : : autocorrection : : : : : flow. :
: : Library Mocks : : time.sleep by : : : : : referencing the : : : : : specific host : : : : : application file : : : : : where it was : : : : : locally imported. :
: : Clearing in Setup : : underlying behavior : : : : : of a cached : : : : : function but : : : : : leaving the LRU : : : : : cache intact across : : : : : tests. :
: : Redirection : : to manually inject : : : : : a StringIO object : : : : : over sys.stderr. :
: : Consolidation : : of indentation for : : : : : every context : : : : : manager invoked. :
: : : : equality of string : : : : : outputs including : : : : : standardized : : : : : prefixes. :
: : vpython : : that dynamically : : : : : build Python from : : : : : source to test : : : : : across multiple : : : : : versions. :
: : Pathlib : : os.path.join and : : : : : with open(..., : : : : : 'w') for basic : : : : : text file creation : : : : : in tests. :
: : Imports : : classes or : : : : : exceptions directly : : : : : from test targets : : : : : or standard : : : : : libraries. :
: : Modules : : of : : : : : unittest.TestCase : : : : : and using : : : : : self.assertEqual. :
: : Permissive Mocks : : to bypass : : : : : instantiating core : : : : : models. :
: : Identity Injection : : config` inside : : : : : individual test : : : : : setup blocks to : : : : : fake a user : : : : : identity. :
: : for Test Filesystem Artifacts : : temporary : : : : : directories and : : : : : manually : : : : : maintaining cleanup : : : : : blocks. :
: : Mocked Test Streams : : string splits and : : : : : manually validating : : : : : line length to : : : : : count valid output : : : : : strings. :
: : Configuration Directories in : : system paths for : : : Tests : : the home directory : : : : : during test : : : : : execution. :
: : Pytest Fixtures : : tmp_path into a : : : : : fixture decorated : : : : : with : : : : : scope="session". :
: : Compatibility for Third-Party : : third-party test : : : Plugins : : dependencies to : : : : : legacy-supported : : : : : projects without : : : : : validating the : : : : : minimum required : : : : : Python constraints. :
: : UI Color Configurations : : default state of : : : : : the Coloring : : : : : class without : : : : : forcing it during : : : : : setup, implicitly : : : : : depending on : : : : : environmental : : : : : variables. :
: : in Unit Tests : : data values being : : : : : asserted directly : : : : : in the test : : : : : docstring. :
: : mock.patch.object : : string target to : : : : : mock.patch : : : : : instead of using : : : : : mock.patch.object : : : : : on the object. :
Rules
T5-01: Idiomatic Truthiness Validation in Tests
Rule: Always use implicit truthiness or falsiness evaluations in testassertions unless strict type matching is explicitly required.What: Test suites must use implicit truthy/falsy validations rather thanasserting strict identity against boolean singletons unless exact typeenforcement is necessary.Applies To: Python assertions in test frameworks (pytest, unittest).Why: Tests relying on strict boolean identity (is True) became brittlewhen refactoring configurations or flag implementations that returnedalternative truthy values. Failing to adhere to this typically results inBrittle Assertions.
Trap 1: Asserting strict identity against Python boolean singletons.
Don't:
assert opts.include_summary is True
Do:
assert opts.include_summary
Exceptions: Situations where distinguishing between None and False is structurally critical to the application logic.
T5-02: Pytest Over Legacy Unittest Framework
Rule: Must implement new test suites using modularpytestdefinitionsinstead of propagatingunittest.TestCaseboilerplate.What: New test modules must be implemented using standalonepytestfunctional constructs rather than inheriting fromunittest.TestCaseto avoidheavy class-based boilerplate.Applies To: Test module architecture (tests/test_*.py).Why: The project previously utilized deeply nestedunittest.TestCasestructures with complexsetUpinheritance, which obfuscated testinitialization and hindered code reusability. Failing to adhere to thistypically results in High Boilerplate / Lock-In.
Trap 1: Subclassing `unittest.TestCase` and configuring state inside a `setUp` method for new test files.
Don't:
class InfoCommand(unittest.TestCase):def setUp(self):self.cmd = build_cmd()
Do:
def _get_cmd():return build_cmd()def test_command_defaults():cmd = _get_cmd()assert cmd.is_valid()
T5-03: Dedicated Test Utilities for API Helpers
Rule: Never overloadconftest.pywith generic API helpers; always placereusable test queries in dedicated utility modules.What: Shared test APIs and environment-probing logic (e.g., checking Gitfeature support) must be placed in dedicated utility modules (likeutils_for_test.py) rather than duplicated or shoved intoconftest.py.Applies To: Test suite architecture and environment scaffolding.Why: Developers were duplicating identical environment checks acrossdifferent test files or misusingconftest.py(which should only containfixtures) to store functional APIs. Failing to adhere to this typicallyresults in Test Code Duplication.
Trap 1: Copy-pasting utility functions across test modules or placing standard functions into pytest conftest files.
Don't:
# Inside test_project.py AND test_git_refs.pydef _SupportsReftable():return check_git_support()
Do:
# Inside tests/utils_for_test.pydef supports_reftable():return check_git_support()# Inside test_project.pyimport utils_for_test@unittest.skipUnless(utils_for_test.supports_reftable(), "...")
Exceptions: Test fixtures (such as initialized directories or mock generators) which belong in conftest.py.
T5-04: Test Framework Modernization to Pytest
Rule: Avoid global module-level environment mutations; consistentlyleveragepytestglobal configuration fixtures.What: Legacyunittest.TestCasestructures must be migrated to functionalpytestparadigms, leveraging global configuration fixtures over class-basedsetUpandtearDownmethods.Applies To: Entire Python test suite and all new unit tests.Why: Heavy inheritance and isolated setup code withinunittest.TestCaseresulted in repeated environment mutation logic, obscured dependencies, and aninability to easily share global setup mechanisms like dummy user identitiesor tracing control. Failing to adhere to this typically results in **GlobalState Pollution**.
Trap 1: Modifying environment variables globally at module load to support tests.
Don't:
import osos.environ['REPO_TRACE'] = '0'class GitRefsTest(unittest.TestCase):def setUp(self):self.tempdir = tempfile.TemporaryDirectory()
Do:
# Rely on conftest.py fixtures automatically handling environments.def test_git_refs(tmp_path, disable_repo_trace, setup_user_identity):gitdir = tmp_path / '.git'# Run assertions using standard assert statementsassert head == refs.get('HEAD')
T5-05: Standard Output Capture via Context Managers
Rule: Must utilizecontextlib.redirect_stdoutto capture standard outputstreams rather than injecting raw stream mocks.What: Use the standard librarycontextlib.redirect_stdoutfor capturingcommand output in test scopes, instantiated directly as a one-liner, ratherthan utilizing theunittest.mockframework to patch system streams.Applies To: Python test suites (Pytest/Unittest) intercepting CLI stdoutpayloads.Why: Tests were previously relying on@mock.patchforsys.stdoutorutilizing multi-line context manager instantiations, which unnecessarilycoupled output capture to the mocking engine and added boilerplate. Failing toadhere to this typically results in Unnecessary Mocking / Test Bloat.
Trap 1: Using the mock framework to intercept a core language stream.
Don't:
@mock.patch("sys.stdout", new_callable=io.StringIO)def test_something(self, mock_stdout):# test logic
Do:
import contextlibimport iodef test_something():with contextlib.redirect_stdout(io.StringIO()) as stdout:# test logic
Trap 2: Creating the string buffer variable outside the context manager scope unnecessarily.
Don't:
stdout = io.StringIO()with contextlib.redirect_stdout(stdout):_run_status(manifest, ["-o"])
Do:
with contextlib.redirect_stdout(io.StringIO()) as stdout:_run_status(manifest, ["-o"])
T5-06: Direct Helper Functions Over Fixture Factories
Rule: Avoid defining dummypytestfixtures solely to return nestedfunction callbacks; use straightforward module-level helpers instead.What: Do not abuse the Pytest fixture system to generate and return localfunctions. If a utility does not benefit from the fixture lifecycle management(setup/teardown), it should be a standard module-level or private helperfunction.Applies To: Pytest files requiring test data initialization or repetitivesetup procedures.Why: Test frameworks became overly complex when developers wrapped simpleinitialization logic in@pytest.fixtureannotations just to yield a callablefunction to the test case. Failing to adhere to this typically results inFixture Graph Bloat.
Trap 1: Defining a pytest fixture that yields a nested function to bypass global state limitations.
Don't:
@pytest.fixturedef init_temp_git_tree():def _init_temp_git_tree(git_dir: Path) -> None:# init logicreturn _init_temp_git_tree
Do:
def _init_temp_git_tree(git_dir: Path) -> None:# init logic
T5-07: Elimination of Redundant Path Assertions
Rule: Never prepend path existence assertions prior to invokingpermissions or loading assertions that implicitly validate existence.What: Do not assert the existence of a file prior to asserting itsspecific permissions or state. Subsequent OS-level operations implicitlyvalidate path existence.Applies To: Python unittests validating filesystem layouts, binaryconfigurations, or hook executable permissions.Why: Tests contained boilerplate blocks invokingos.path.isfile()purelyto offer a custom string format failure, even though the immediate next lineinvokingos.access()would fail correctly with an implicit lack ofexistence. Failing to adhere to this typically results in **TestBoilerplate**.
Trap 1: Chaining explicit existence checks before access checks.
Don't:
self.assertTrue(os.path.isfile(repo_path), f"{repo_path} does not exist")self.assertTrue(os.access(repo_path, os.X_OK), f"{repo_path} is not executable")
Do:
self.assertTrue(os.access(repo_path, os.X_OK), f"{repo_path} is not executable")
T5-08: Pathlib Utility Constants for Test Path Resolution
Rule: Always resolve test filesystem boundaries using centralizedpathlibobjects instead of string-concatenating legacyos.pathoperations.What: Path constructions in test files should utilize modern pathlibobjects via centralized utility constants (e.g.,utils_for_test.THIS_DIR)instead of verboseos.pathoperations.Applies To: Python test suites interacting with the file system.Why: Manual path constructions using nestedos.path.dirname(__file__)calls created verbose, hard-to-read boilerplate that cluttered the test logic.Failing to adhere to this typically results in Verbose Code Base.
Trap 1: Using nested `os.path.dirname` and `os.path.join` to traverse back to the parent directory.
Don't:
repo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "repo")
Do:
repo_path = utils_for_test.THIS_DIR.parent / "repo"
T5-09: Pytest Adoption for Test Suite Definition
Rule: Must author all file-level test assertions utilizingpytestsyntaxconstructs over legacyunittestequivalents.What: Test files must be defined using the modernpytestframework,avoiding class-basedunittest.TestCaseinheritance and relying on standardassertsemantics.Applies To: The entire Python testing suite.Why: The legacyunitteststructure required extensive, verboseboilerplate for state setup, test case classes, and specific assertion methodsthat restricted readability. Failing to adhere to this typically results inTest Verbosity.
Trap 1: Creating test case classes that inherit from `unittest.TestCase` and asserting via `self.assertEqual`.
Don't:
import unittestclass RepoTests(unittest.TestCase):def test_example(self):self.assertEqual(a, b)
Do:
# Standalone pytest functionsdef test_example():assert a == b
T5-10: Minimal Mocking Isolation for Test Reliability
Rule: Avoid deeply nested or exhaustively mocked test wrappers; isolateand invoke inner target logic primitives instead.What: Mock usage must be limited strictly to necessary externalintercepts. Exhaustive mock environments must not be created just to drive asmall piece of inner logic; instead, structural refactoring must isolate thelogical boundary.Applies To: Test suites involving deep API structures and side-effects.Why: Relying on heavily nested, brittle 'house of cards' mockconfigurations meant tests frequently failed when unrelated code modificationsbroke the strict internal mock assumptions, turning tests into throwawayartifacts. Failing to adhere to this typically results in **Fragile MockCollapse**.
Trap 1: Using stacked patch decorators for non-relevant sub-routines (e.g., standard error outputs or colorizers) just to trigger an embedded autocorrection flow.
Don't:
with mock.patch("main.RepoClient", return_value=mock_client):with mock.patch("main.SetDefaultColoring"):repo._RunLong("tart", gopts, argv, log)
Do:
- Isolate the logic into
_autocorrect_command_name()and test it by passing
minimal data primitives: res = self.repo._autocorrect_command_name("tart", mock_config).
Exceptions: Testing hard, native OS-level boundary bindings.
T5-11: Canonical Resolution for System Library Mocks
Rule: Always patch standard libraries at their canonical origin namespacerather than targeting the local module import resolution boundary.What: Standard library functions must be targeted for testing patches attheir canonical origin namespace rather than the local import footprint of thetarget module.Applies To: Test configuration definingmock.patchpaths.Why: Patching against the local module import representation strictlycoupled tests to a given file's exact inclusion syntax. Minor refactorsaltering module import aliases completely disabled testing verification.Failing to adhere to this typically results in Brittle Patch Routing.
Trap 1: Patching `time.sleep` by referencing the specific host application file where it was locally imported.
Don't:
@mock.patch.object(main.time, "sleep")
Do:
@mock.patch.object(time, "sleep")
T5-12: Memoized Function Cache Clearing in Setup
Rule: Always flush thelru_cacheof mocked globally-accessible memoizedfunctions within the test initialization sequence.What: When mocking globally accessible functions decorated with@functools.lru_cache, the cache must be explicitly cleared in the testsuite'ssetUproutine.Applies To: Unit test suites interacting with memoized functions.Why: Failing to clear thelru_cacheof globally executed functionsduring testing caused subsequent tests in the runner to receive cached mockresults injected by prior tests, leading to non-deterministic, cascadingfailures. Failing to adhere to this typically results in **State Contamination/ Flaky Tests**.
Trap 1: Mocking the underlying behavior of a cached function but leaving the LRU cache intact across tests.
Don't:
class SshTests(unittest.TestCase):def test_version(self):with mock.patch.object(ssh, "_run_ssh_version", return_value="OpenSSH_1.2\n"):self.assertEqual(ssh.version(), (1, 2))
Do:
class SshTests(unittest.TestCase):def setUp(self):ssh.version.cache_clear()def test_version(self):with mock.patch.object(ssh, "_run_ssh_version", return_value="OpenSSH_1.2\n"):self.assertEqual(ssh.version(), (1, 2))
T5-13: Idiomatic Standard Stream Redirection
Rule: Always employcontextlib.redirect_stderrdirectly instead ofoverwriting standard stream objects globally using patch frameworks.What: To interceptstderrorstdoutin testing, utilize the standardlibrary's context managers (contextlib.redirect_stderr) instead ofoverriding the stream objects globally usingmock.patch.Applies To: Unit testing standard output logs and error streams.Why: Using generic mocks to replacesys.stderrcreates brittle testswith broader side effects. The standard library provides dedicated toolsstrictly designed for capturing stream text safely. Failing to adhere to thistypically results in Non-Idiomatic Tooling / Brittle Mocks.
Trap 1: Using `mock.patch` to manually inject a `StringIO` object over `sys.stderr`.
Don't:
with mock.patch("sys.stderr", new=io.StringIO()) as mock_stderr:run_command()
Do:
f = io.StringIO()with contextlib.redirect_stderr(f):run_command()
T5-14: Context Manager Nesting Consolidation
Rule: Consolidate contiguous mock or context manager deployments intosingle-line definitions to minimize indentation footprints.What: Contiguous, deeply nested context managers (withblocks) should beconsolidated into a singlewithstatement to reduce horizontal indentationand structural complexity.Applies To: Complex test fixtures or code paths requiring multiplesynchronized states or file handles.Why: Individual context managers per line resulted in excessive codeindentation (pyramid of doom), harming readability and consuming unnecessaryscreen space. Failing to adhere to this typically results in **ExcessiveIndentation / Pyramid of Doom**.
Trap 1: Adding a new level of indentation for every context manager invoked.
Don't:
with mock.patch.object(time, "sleep") as mock_sleep:with mock.patch.object(socket, "socket") as ms:run_test()
Do:
with mock.patch.object(time, "sleep") as mock_sleep, mock.patch.object(socket, "socket") as ms:run_test()
T5-15: Anti-Change Detector Tests
Rule: Avoid exact full-string assertions when evaluating formatted logs orstringified error conditions to prevent brittle side-effect maintenance.What: When verifying error logging or outputs, tests must assert onflexible core substrings rather than exact line matches, and exceptionsconfigured as mock side effects should use class types rather thaninstantiated string objects.Applies To: Unit testing string outputs, logs, and simulated mockfailures.Why: Tests acting as 'change detectors' failed unnecessarily when minorformatting, capitalization, or prefix strings (e.g., 'WARNING' vs 'warning')were updated in the underlying code, despite the core logic remainingfunctional. Failing to adhere to this typically results in **Brittle Tests /Extraneous Boilerplate**.
Trap 1: Asserting exact equality of string outputs including standardized prefixes.
Don't:
self.assertEqual(stderr.getvalue(), "repo: warning: git trace2 logging failed: Mock error")
Do:
self.assertIn("git trace2 logging failed", stderr.getvalue())
Trap 2: Instantiating an exception with a dummy string for a simple side-effect mock.
Don't:
mock_socket.connect.side_effect = OSError("Mock error")
Do:
mock.patch.object(socket, "socket", side_effect=OSError)
Exceptions: Tests explicitly verifying exact formatting serialization (e.g., JSON schema adherence).
T5-16: Infrastructure Prebuilts via vpython
Rule: Must execute continuous integration environments usingvpythonwrappers instead of relying on legacy source-compiling orchestrationframeworks likepyenv.What: Leveragevpythonfor multi-version Python testing rather thantoxcombined withpyenvto utilize prebuilt binaries and minimizeenvironment setup overhead.Applies To: Hermetic testing setups, CI pipelines, and multi-versioncoverage scripts.Why: Usingpyenvandtoxforced CI and local test runs to download andcompile Python versions from source on the fly, adding minutes of overhead toevery test run. Shifting tovpythonleveraged prebuilt infrastructureruntimes. Failing to adhere to this typically results in Slow CI Builds.
Trap 1: Relying on tools that dynamically build Python from source to test across multiple versions.
Don't:
- Using
tox.iniwithpyenvto orchestrate matrix testing across Python
versions, incurring source-compilation penalties.
Do:
- Invoking tests via
vpython, which provisions hermetic virtual environments
rapidly using precompiled infrastructure binaries.
T5-17: Modernized Filesystem Paths via Pathlib
Rule: Always employpathlibobjects for mock file I/O operations ratherthan manual string handling and context managers.What: Test case file system operations should use the modernpathliblibrary rather than legacyos.pathand manual file handles.Applies To: Unit tests and file system operations across the codebase.Why: Legacy tests relied heavily onos.path.joinandwith open(...)which led to verbose, repetitive boilerplate when constructing mock repositorystates. Failing to adhere to this typically results in **Verbose Boilerplate /Maintainability Overhead**.
Trap 1: Using `os.path.join` and `with open(..., 'w')` for basic text file creation in tests.
Don't:
# BAD: Verbose manual file writingroot_m = os.path.join(self.manifest_dir, "root.xml")with open(root_m, "w") as fp:fp.write("<manifest>...")
Do:
# GOOD: Pathlib usage for concise writesroot_m = self.manifest_dir / "root.xml"root_m.write_text("<manifest>...")
T5-18: Standardized Module-Level Mock Imports
Rule: Import external test dependencies and internal domain targets ascomplete module spaces rather than cherry-picking precise classes.What: Test files must importmockas a module (`from unittest importmock) and internal targets as a module (from subcmds import wipe`), ratherthan importing specific classes directly.Applies To: All unit tests.Why: Direct class imports caused namespace pollution and deviated from theGoogle Python Style Guide, making it harder to track the origin ofdependencies. Failing to adhere to this typically results in **Style GuideViolation / Namespace Pollution**.
Trap 1: Importing specific classes or exceptions directly from test targets or standard libraries.
Don't:
from unittest.mock import MagicMockfrom subcmds.wipe import Wipe, WipeErrormock_obj = MagicMock()
Do:
from unittest import mockfrom subcmds import wipemock_obj = mock.MagicMock()
T5-19: Pytest Adoption for New Test Modules
Rule: Must restrict the creation of newunittest.TestCasefiles strictlyunless explicitly bypassing native pytest infrastructure constraints.What: New test modules must be written using thepytestframework ratherthan the legacyunitteststructure.Applies To: All newly added test files.Why: The project was modernizing its testing infrastructure, aiming toeliminateunittestboilerplate and leverage nativepytestfixtures forglobal state management. Failing to adhere to this typically results inTechnical Debt / Legacy Test Framework Propagation.
Trap 1: Creating subclasses of `unittest.TestCase` and using `self.assertEqual`.
Don't:
class WipeUnitTest(unittest.TestCase):def test_wipe(self):self.assertTrue(os.path.exists(path))
Do:
def test_wipe(tmp_path):assert os.path.exists(path)
Exceptions: Unless a compelling reason exists requiring native unittest mechanics.
T5-20: High-Fidelity Test Targets over Permissive Mocks
Rule: Avoid stubbing robust architectural models likeProjectorManifestvia permissiveMagicMockallocations; instantiate genuine domainclasses instead.What: Tests should instantiate and utilize real domain objects (e.g., theProjectclass) rather than relying heavily on genericMagicMockinstances,to ensure test fidelity.Applies To: Unit testing, particularly for core models likeProjectorManifest.Why: Overuse ofMagicMockled to tests passing despite brokenimplementations because the mocks lacked side-effects and realistic attributevalidation. Failing to adhere to this typically results in **False PositiveTest Results**.
Trap 1: Using `MagicMock` to bypass instantiating core models.
Don't:
# BAD: Mocks won't fail if the API changesproj = mock.MagicMock()proj.name = "test"proj.DeleteWorktree.side_effect = lambda: True
Do:
# GOOD: Using actual domain objects for accurate side-effectsproj = Project(manifest=mock_manifest, name="test", ...)
Exceptions: External network calls or complex, deeply decoupled subsystems where instantiating the real object is prohibitively difficult.
T5-21: Session-Scoped Hermetic Git Identity Injection
Rule: Must inject pseudo Git commit identities as session-scopedenvironment variables rather than manually rewriting local Git configurationsper test.What: Automated test suites must globally stub Git's author and committeridentities using session-scoped environment variables to ensure execution inclean or unconfigured environments.Applies To: Pytest configuration (tests/conftest.py) and all testsexecuting raw Git subprocess commands.Why: Tests interacting with local Git repositories crashed withGitCommandErroron CI runners or clean developer machines lacking a globaluser.nameanduser.email. Patching this locally in tests viagit configcalls introduced I/O overhead and redundant code. Failing to adhere to thistypically results in GitCommandError / Test Flakiness.
Trap 1: Executing `git config` inside individual test setup blocks to fake a user identity.
Don't:
def test_commit(self):subprocess.run(["git", "config", "user.name", "Foo Bar"])subprocess.run(["git", "config", "user.email", "foo@bar.com"])# Run test logic
Do:
@pytest.fixture(autouse=True, scope="session")def setup_user_identity(monkeysession):"""Set env variables for author and committer name and email."""monkeysession.setenv("GIT_AUTHOR_NAME", "Foo Bar")monkeysession.setenv("GIT_COMMITTER_NAME", "Foo Bar")monkeysession.setenv("GIT_AUTHOR_EMAIL", "foo@bar.baz")monkeysession.setenv("GIT_COMMITTER_EMAIL", "foo@bar.baz")
T5-22: Automated Lifecycle Management for Test Filesystem Artifacts
Rule: Must utilize automatedTemporaryDirectoryconstructs integratedsecurely into test teardown sequences instead of performing unmanaged manualdisk sweeps.What: Test fixtures must use state-managed temporary directory constructs(e.g.,tempfile.TemporaryDirectory) whose lifecycle is explicitly bound tostandard unit test teardown phases, avoiding manual unmanaged path allocationand raw removal.Applies To: All test suites performing filesystem mock operations or Gitrepository initialization (tests/test_subcmds_forall.py).Why: Tests were manually allocating paths viatempfile.mkdtempandissuing rawshutil.rmtreecalls. This pattern proved fragile, resulting inleaked directories across runs or skipped cleanup phases if a test failedearly. Failing to adhere to this typically results in **Orphaned Artifacts /Resource Leaks**.
Trap 1: Spawning detached temporary directories and manually maintaining cleanup blocks.
Don't:
def setUp(self):self.tempdir = tempfile.mkdtemp()def tearDown(self):shutil.rmtree(self.tempdir, ignore_errors=True)
Do:
def setUp(self):self.tempdirobj = tempfile.TemporaryDirectory(prefix="forall_tests")self.tempdir = self.tempdirobj.namedef tearDown(self):self.tempdirobj.cleanup()
T5-23: Idiomatic String Evaluation in Mocked Test Streams
Rule: Avoid manually slicing and measuring length properties for stringevaluations; consistently evaluate standard streams using built-in truthinessroutines.What: Evaluating outputs from captured stdout or stderr in tests mustutilize Pythonic abstractions likesplitlines()and implicit truthinessevaluation, rather than raw newline splitting and explicit length checks.Applies To: Hermetic Test suites executing mock command line calls andinspectingsys.stdout.Why: Legacy test code relied on manual string manipulation likesplit("\n")and boolean evaluations likelen(line) > 0. This approach wasunidiomatic, fragile against cross-platform line endings, and bloated testsuite verbosity. Failing to adhere to this typically results in **FragileTests / Unidiomatic Logic**.
Trap 1: Iterating over raw string splits and manually validating line length to count valid output strings.
Don't:
line_count = 0for line in mock_stdout.getvalue().split("\n"):if len(line) > 0:line_count += 1
Do:
line_count = sum(1 if x else 0 for x in mock_stdout.getvalue().splitlines())
T5-24: Hermetic Isolation of Git Configuration Directories in Tests
Rule: Always isolate Git initialization by injecting temporary dummydirectories via environment overrides (HOME/USERPROFILE) to restricttest interference.What: Tests utilizing local git operations must hermetically isolateenvironment variables likeHOMEandUSERPROFILEto prevent developers'global configurations from leaking into test executions.Applies To: Global test initialization routines (conftest.py, Pytestfixtures, class-level test setup).Why: Historically, if a developer's global.gitconfigrequired GPGsigning (commit.gpgsign=true), a git subprocess spawned during test setupwould unexpectedly open an interactive prompt (e.g., vim) to solicit a signingkey, causing the test suite to deadlock permanently. Failing to adhere to thistypically results in Test Deadlock / State Bleed.
Trap 1: Relying on default system paths for the home directory during test execution.
Don't:
# BAD: Allows test subprocesses to read ~/.gitconfigsubprocess.run(['git', 'tag', '--annotate'])
Do:
# GOOD: Override environment variables to an isolated temp directory@pytest.fixture(autouse=True, scope="session")def alt_home(tmp_path_factory, monkeysession):var = "USERPROFILE" if platform_utils.isWindows() else "HOME"monkeysession.setenv(var, str(tmp_path_factory.mktemp("home")))
Exceptions: Tests that explicitly exist to validate the parsing logic of a user's real, existing .gitconfig (which is highly discouraged).
T5-25: Scope Hierarchy Enforcement in Pytest Fixtures
Rule: Never propagate lower-scoped test fixtures (e.g., function-scopedstates) into global session-scoped initialization procedures.What: A session-scoped Pytest fixture cannot depend on lower-scopedfixtures (such as a function-scopedtmp_path). To create temporary paths atthe session level,tmp_path_factory.mktempmust be utilized.Applies To: Pytest fixture definitions, specifically withinconftest.py.Why: A session-scoped setup mechanism attempted to use the function-scopedtmp_pathfixture. This caused pytest initialization failures. Furthermore,reusing function-scoped directories for session-level state caused unintendeddisk thrashing as the directory was continually wiped at the teardown of everyfunction. Failing to adhere to this typically results in **Scope Mismatch /State Masking**.
Trap 1: Injecting `tmp_path` into a fixture decorated with `scope="session"`.
Don't:
# BAD: Session fixture depending on function fixture@pytest.fixture(scope="session")def session_tmp_homedir(tmp_path):return tmp_path
Do:
# GOOD: Using the factory to generate a session-level path@pytest.fixture(scope="session")def session_tmp_homedir(tmp_path_factory):return tmp_path_factory.mktemp("home")
T5-26: Strict Python Version Compatibility for Third-Party Plugins
Rule: Must strictly align test dependency injection configurations againstthe underlying project's absolute minimum supported Python versions.What: Test tooling dependencies must strictly align with the project'sminimum supported Python version. External plugin implementation logic shouldbe inlined with proper attribution if the plugin requires a newer Pythonversion than the project supports.Applies To: Dependency management (tox.ini),conftest.py, and CIenvironments.Why: A developer introduced a new Pytest plugin to manage isolated homedirectories. However, the plugin required Python 3.8+, while the projectmaintained compatibility down to Python 3.6+. This mismatch caused post-submitCI pipeline checks to crash upon test environment installation. Failing toadhere to this typically results in CI Installation Failure.
Trap 1: Adding modern third-party test dependencies to legacy-supported projects without validating the minimum required Python constraints.
Don't:
# BAD: tox.ini adds dependency unsupported by CI targetdeps =pytestpytest-home >= 0.4
Do:
# GOOD: Inline the logic and remove the external dependency# adapted from pytest-home 0.5.1@pytest.fixture(autouse=True, scope="session")def session_tmp_homedir(tmp_path_factory, monkeysession):# implementation logic here
Exceptions: When the project's minimum supported Python version is officially bumped to match the plugin's requirement.
T5-27: Hermetic Isolation of Terminal UI Color Configurations
Rule: Must aggressively lock default terminal coloring states whengenerating UI tests to isolate regressions from variable environmentpipelines.What: Unit tests that assert on UI or logging text containing ANSI colorcodes must explicitly force the coloring state to prevent ambient gitconfigurations or CI terminal limitations from altering test outcomes.Applies To: Unit tests interacting with thecolororrepo_loggingmodules.Why: Tests validating color outputs failed non-deterministically based onthe ambient environment (e.g., CI runners lacking a TTY, or developers havingcolor.ui=falsein their global.gitconfig). Failing to adhere to thistypically results in Flaky Tests / Non-Deterministic Failures.
Trap 1: Relying on the default state of the `Coloring` class without forcing it during setup, implicitly depending on environmental variables.
Don't:
def setUp(self):config_fixture = fixture("test.gitconfig")self.config = git_config.GitConfig(config_fixture)self.color = color.Coloring(self.config, "status")
Do:
def setUp(self):config_fixture = fixture("test.gitconfig")self.config = git_config.GitConfig(config_fixture)color.SetDefaultColoring("always")self.color = color.Coloring(self.config, "status")
T5-28: Abstract Intent Documentation in Unit Tests
Rule: Never embed exact literal assertions or explicit structural valuesdirectly inside unit test docstring commentary.What: Test docstrings should describe the behavioral intent or structuralcoverage of the test rather than hardcoding the exact assertion values orlow-level implementation details.Applies To: Pythonunittestmodule docstrings.Why: Docstrings that hardcoded exact ANSI escape sequences or configvalues became stale and misleading whenever the underlying mappings orformatting codes were updated. Failing to adhere to this typically results inDocumentation Rot / Maintenance Overhead.
Trap 1: Documenting exact data values being asserted directly in the test docstring.
Don't:
def test_Color_Parse_first_parameter_none(self):"""fg is black(30), bg is red(31+10=41), attr is ul(4)"""val = self.color._parse(None, 'black', 'red', 'ul')self.assertEqual('\x1b[4;30;41m', val)
Do:
def test_Color_Parse_first_parameter_none(self):"""check fg & bg & attr"""val = self.color._parse(None, "black", "red", "ul")self.assertEqual("\x1b[4;30;41m", val)
T5-29: Object-Referenced Mocking via mock.patch.object
Rule: Never usemock.patch; always usemock.patch.object.What: All attribute and function patching in unit tests must usemock.patch.object(target, "attribute", ...)against an explicitly importedmodule or class object rather than passing dotted string paths tomock.patch("module.attribute", ...).Applies To: All unit tests utilizingunittest.mock.Why: String-basedmock.patchpaths bypass static analysis and moduleimport validation, making tests brittle during refactoring and prone to silentresolution errors or import ordering bugs. Referencing the imported objectdirectly viamock.patch.objectensures the target module is explicitlyimported and validated at load time. Failing to adhere to this typicallyresults in Brittle Patch Routing / Unvalidated String Targets.
Trap 1: Passing a dotted string target to `mock.patch` instead of using `mock.patch.object` on the object.
Don't:
with mock.patch("ssh._run_ssh_version", return_value="OpenSSH_1.2\n"):...
Do:
with mock.patch.object(ssh, "_run_ssh_version", return_value="OpenSSH_1.2\n"):...
Cross-Domain Dependencies
- Upstream: T2 | Filesystem Atomicity & Worktree Layout - *Managing safe
creation and atomic removal of temporary worktrees and .git directories supports reliable test state fixtures.*
- Downstream: T3 | Subprocess Git Integration & Error Translation -
Hermetic test constraints directly dictate how standard git streams, configuration injections, and subprocess executions are mocked or intercepted.
- Downstream: T6 | CLI Argument Parsing & UX Consistency - *Strict
terminal environment control in testing enforces deterministic verification of CLI autocorrect flows and standardized UI colorizations.*
Chapter: CLI Argument Parsing & UX Consistency
Context: This chapter governs the lifecycle, validation, and execution of command-line arguments, enforcing strict standardization for machine-readable serialization, unified logging, and deterministic, thread-safe terminal interactions.
Summary
: : Constraint : : Trap :
| :-------- | :--------------- | :------- | :-------------------- | |
|---|---|---|---|---|
| T6-01 | Deterministic | High | Providing only |
: : Machine-Readable : : aesthetically : : : Output Formats : : formatted terminal : : : : : text for diagnostic : : : : : commands. :
: : Niche Short : : option to a feature : : : Options : : that isn't commonly : : : : : used by developers. :
: : Boolean Toggle : : single-purpose : : : Flags : : boolean switches for : : : : : granular output : : : : : components. :
: : CLI Output : : formatting elements : : : Separators : : directly after a : : : : : primary block instead : : : : : of conditionally : : : : : checking the next : : : : : block. :
: : Standardization : : formatting via raw : : : via Enums : : string matching and : : : : : print() statements : : : : : without suppressing : : : : : the interactive : : : : : pager. :
: : Execution : : format's dispatch : : : Dispatching : : call with the inline : : : : : procedural logic of : : : : : the fallback format. :
: : Simulation over : : configuration : : : Internal State : : parameter directly on : : : Mutation : : the parsed namespace : : : : : object. :
: : Sorting of : : of accumulated : : : Parallel : : multi-process results : : : Execution : : without sorting. : : : Results : : :
: : to Feature : : --force-jobs CLI : : : Requests : : bypass flag : : : : : simultaneously : : : : : alongside the new : : : : : sync-j-max manifest : : : : : attribute. :
: : Exception : : typo-correction : : : Handlers : : logic, user prompts, : : : : : and command reloading : : : : : inside except : : : : : KeyError\:. :
: : Protocol via : : directly to the : : : Standard Logger : : sys.stderr stream : : : : : using the built-in : : : : : print function. :
: : Translation of : : configuration : : : Configuration : : variables inside : : : Booleans : : int() and catching : : : : : value exceptions to : : : : : deduce defaults. :
: : of Interactive : : suspension code : : : Runtime Delays : : before a return : : : : : statement without : : : : : wrapping it in a trap : : : : : for cancellation : : : : : overrides. :
: : Pre-Access : : flags before the : : : Initialization : : shared initialization : : : of CLI Options : : pipeline populates : : : : : default properties. :
: : Redundant : : configuring : : : Optparse : : destination variables : : : Destinations : : in CLI arguments. :
: : Scoping in : : global-sounding : : : Commit Messages : : commit messages for : : : : : isolated subcommand : : : : : patches. :
: : Exception Naming : : the exception name : : : : : with the module name : : : : : inside the module : : : : : definition. :
: : Terminology in : : 'worktree' in help : : : Destructive CLI : : text without explicit : : : Commands : : definition or : : : : : examples. :
: : Argument : : positional arguments : : : Validation in : : directly inside : : : Subcommands : : Execute(). :
: : Verbosity Flags : : printing progress : : : : : messages to stderr or : : : : : stdout. :
: : Terminal : : sys.stderr.fileno() : : : Querying during : : inside long-running : : : IO Capture : : concurrent loops. :
: : Persistent : : variable mappings : : : Configuration : : into command-line : : : over Environment : : parsers to support : : : Variables : : 'headless' : : : : : configurations. :
: : Parity with Git : : or environmental : : : Semantics : : metadata queries to : : : : : commands designed for : : : : : local working-tree : : : : : analysis. :
: : Sync Operation : : immediate system exit : : : Termination : : on an update failure. :
: : Codes on CLI : : return to back out : : : Cancellation : : of a declined CLI : : : : : confirmation prompt. :
: : Safeties for : : interactive prompts : : : Destructive : : without checking : : : Commands : : configuration flags : : : : : for automation modes. :
: : Interdependent : : modifier options : : : Argument : : unconditionally : : : Validation : : without checking : : : : : prerequisites. :
: : Error Messages : : operation with a : : : for : : descriptive but : : : Synchronization : : non-actionable error : : : Failures : : message. :
: : Bumping for : : standalone launcher : : : Important : : script with important : : : Changes : : changes without : : : : : incrementing its : : : : : VERSION tuple. :
Rules
T6-01: Deterministic Machine-Readable Output Formats
Rule: Always expose strict, structured serialization options (e.g., JSON)for CLI tools used in automated pipelines to prevent reliance on brittle textparsing.What: CLI tools leveraged for inspection must expose strict, structuredserialization (e.g., JSON) to negate reliance on unstable text parsing inCI/CD environments.Applies To: Command-line interface design, specifically subcommandsutilized by build pipelines or external orchestrators.Why: Downstream automated pipelines were forced to retrieve configurationdata by executing tools likerepo infoand using string matching (grep)against human-readable formatting, creating a brittle dependency susceptibleto UI modifications. Failing to adhere to this typically results in **PipelineParsing Failure**.
Trap 1: Providing only aesthetically formatted terminal text for diagnostic commands.
Don't:
- Command executes and prints human-readable strings. Consumers must run `repo
info | grep "Manifest revision"` to extract variables.
Do:
- Integrate a
--format=jsoncommand argument that bypasses human-readable
display logic and cleanly serializes underlying data models directly to standard output.
Exceptions: Interactive-only terminal prompts that are heavily stateful and fundamentally incompatible with automation.
T6-02: Elimination of Niche Short Options
Rule: Never assign single-character short options for niche or rarely usedflags to preserve namespace availability.What: Avoid assigning single-character short options for niche or rarelyused command-line flags to prevent namespace bloat.Applies To: CLI argument parsing (e.g.,optparseorargparsedefinitions).Why: Short options were being added arbitrarily for specific datasummaries, leading to a cluttered short-option namespace and hindering futureexpansion. Failing to adhere to this typically results in **Cluttered CLIUX**.
Trap 1: Assigning a short option to a feature that isn't commonly used by developers.
Don't:
p.add_option("-s", "--summary", action="store_true")
Do:
p.add_option("--include-summary", action="store_true")
T6-03: Extensible Boolean Toggle Flags
Rule: Always implement paired positive/negative toggle flags for granularoutputs rather than relying on rigid, single-purpose boolean switches.What: Conditional output sections must be controlled by pairedpositive/negative toggle flags (e.g.,--include-xand--no-include-x)rather than single-purpose boolean flags.Applies To: CLI design and option definitions for output manipulation.Why: Rigid, single-purpose flags for rendering specific summaries limitedextensibility and prevented developers from precisely tailoring outputs forscripts or automation. Failing to adhere to this typically results in **RigidOutput Rendering**.
Trap 1: Creating rigid, single-purpose boolean switches for granular output components.
Don't:
p.add_option("--summary", action="store_true", help="show only manifest summary")
Do:
p.add_option("--include-summary", action="store_true", default=True)p.add_option("--no-include-summary", dest="include_summary", action="store_false")
T6-04: Context-Aware CLI Output Separators
Rule: Must conditionally verify that succeeding content blocks will renderbefore printing visual formatting elements like horizontal separators.What: Structural visual elements, such as horizontal separators ornewlines, must only be printed if the succeeding content block is actuallyverified to render.Applies To: CLI output rendering logic.Why: Output formatting logic printed hardcoded line separators aftersummaries, resulting in dangling visual artifacts when subsequent projectdetails were dynamically excluded by user flags. Failing to adhere to thistypically results in Redundant Output Noise.
Trap 1: Hardcoding visual formatting elements directly after a primary block instead of conditionally checking the next block.
Don't:
print_summary()print_separator()if include_projects:print_projects()
Do:
print_summary()if not include_projects:returnprint_separator()print_projects()
T6-05: Output Format Standardization via Enums
Rule: Must manage and standardize target output formats using an explicitPythonEnumclass rather than brittle string matching.What: Command-line output formats (like TEXT or JSON) must be managedusing an explicit Python Enum class and standardize formatting behaviors(e.g., disabling pagers for JSON, enforcing sort keys).Applies To: CLI data serialization andOutputFormatdispatching.Why: Unstandardized JSON serialization methods across subcommands resultedin inconsistent output spacing, failure to suppress interactive pagers, andbrittle string-based format matching. Failing to adhere to this typicallyresults in Broken Machine Automation.
Trap 1: Handling output formatting via raw string matching and `print()` statements without suppressing the interactive pager.
Don't:
if opt.format == "json":print(json.dumps(data))
Do:
class OutputFormat(enum.Enum):TEXT = enum.auto()JSON = enum.auto()if output_format == OutputFormat.JSON:sys.stdout.write(json.dumps(data, indent=2, sort_keys=True) + "\n")
T6-06: Symmetric Execution Dispatching
Rule: Must symmetrically separate procedural logic into format-specifichandlers rather than mixing inline logic with format conditional statements.What: Complex commands handling multiple output formats must keep the mainexecution function clean by symmetrically dispatching logic to format-specifichandlers (e.g.,_ExecuteTextand_ExecuteJson).Applies To: Command entry points (e.g., theExecutemethod in subcommandclasses).Why: Inline output rendering mixed with conditional format dispatchingcreated monolithic execution methods that were difficult to maintain and test.Failing to adhere to this typically results in Spaghetti Logic.
Trap 1: Mixing one output format's dispatch call with the inline procedural logic of the fallback format.
Don't:
def Execute(self, opt, args):if opt.format == 'json':return self._ExecuteJson(opt, args)# 50 lines of inline text rendering logic...
Do:
def Execute(self, opt, args):if opt.format == OutputFormat.JSON:self._ExecuteJson(opt, args)else:self._ExecuteText(opt, args)
T6-07: CLI Argument Simulation over Internal State Mutation
Rule: Always inject simulated execution parameters into the command-lineargvarguments list rather than manually overwriting parsed attribute statesduring tests.What: When executing a command programmatically within a test, operationalparameters (e.g., job counts) must be injected into the simulatedargvstring list rather than manually mutating the parsed options object.Applies To: Command testing and execution harnesses where parameters altersystem behavior (e.g., multiprocessing threads).Why: Test cases were bypassing the CLI parser and manually settingopts.jobs = 1to force single-threaded execution. This prevented the testfrom exercising the command's full option-parsing and validation lifecycle.Failing to adhere to this typically results in **Test Invalidation / FalsePositives**.
Trap 1: Overriding a configuration parameter directly on the parsed namespace object.
Don't:
opts, args = cmd.OptionParser.parse_args(argv)cmd.CommonValidateOptions(opts, args)opts.jobs = 1cmd.Execute(opts, args)
Do:
opts, args = cmd.OptionParser.parse_args(argv + ["--jobs=1"])cmd.CommonValidateOptions(opts, args)cmd.Execute(opts, args)
T6-08: Deterministic Sorting of Parallel Execution Results
Rule: Must explicitly sort accumulated payload data from asynchronousthread loops before broadcasting standard outputs or logs.What: Elements collected asynchronously from a multiprocessing pool mustbe explicitly sorted before being emitted to standard output or loggingpipelines.Applies To: Command-line output rendering and any loop iterating overaggregated parallel results.Why: Warning messages regarding bloated project directories were printedbased on the order that asynchronous threads returned their payload, leadingto flaky UX and non-deterministic command outputs. Failing to adhere to thistypically results in Non-Deterministic Console Output.
Trap 1: Iterating over a list of accumulated multi-process results without sorting.
Don't:
for project_name in self._bloated_projects:logger.warning(f'warning: Project {project_name} is bloated.')
Do:
for project_name in sorted(self._bloated_projects):logger.warning(f'warning: Project {project_name} is bloated.')
T6-09: Strict Adherence to Feature Requests
Rule: Never implement speculative bypass flags, preemptive CLI overrides,or configurations without a documented and verifiable user request.What: Avoid preemptively implementing fallback features, command-lineoverrides, or configurations without a documented user request.Applies To: CLI argument parsers and manifest parsing engines.Why: Speculative feature additions, like bypass flags for manifest limits,caused feature creep and bloated the CLI toolset with unused, undocumentededge cases. Failing to adhere to this typically results in Feature Creep.
Trap 1: Adding a `--force-jobs` CLI bypass flag simultaneously alongside the new `sync-j-max` manifest attribute.
Don't:
- Implementing an override flag in
main.pyjust in case users want to bypass
the newly added manifest restriction.
Do:
- Deploying the manifest constraint directly without a CLI override, and
documenting it in docs/manifest-format.md. Wait for a bug tracker request for an override flag.
T6-10: Minimal Logic in Exception Handlers
Rule: Must restricttry...exceptblocks entirely to targeted errorhandling and never bury structural flow control or terminal loops within them.What: Exception handling blocks (try...except) must only contain thespecific error-handling logic and never encapsulate complex business logic,terminal loops, or major execution routing.Applies To: Command dispatcher routing and system control flows.Why: Burying significant CLI routing tasks—like spelling suggestions,autocorrection countdowns, and subprocess recursion—inside aKeyErrorhandler obscured program logic and suppressed nested tracebacks. Failing toadhere to this typically results in Opaque Routing State.
Trap 1: Placing the entire typo-correction logic, user prompts, and command reloading inside `except KeyError:`.
Don't:
try:cmd = self.commands[name]()except KeyError:# 50 lines of complex autocorrection logicreturn self._RunLong(...)
Do:
if name not in self.commands:name = self._autocorrect_command_name(name)if not name:return 1# Execute minimal command logic outside exceptioncmd = self.commands[name]()
T6-11: Unified Logging Protocol via Standard Logger
Rule: Dispatch all console messages using the standard centralized loggingframework. Never rely on rawerror streams.What: All console outputs must be dispatched via the system's centralizedRepoLoggermechanism, completely replacing raw terminal standard-errorprints.Applies To: CLI presentation logic and application-wide consolecommunications.Why: The use of rawprint(file=sys.stderr)bypassed the system's unifiedlogging configuration, resulting in unformatted outputs and broken terminalinteractivity. Failing to adhere to this typically results in **UnmanagedOutput Spillage**.
Trap 1: Outputting warnings directly to the `sys.stderr` stream using the built-in `print` function.
Don't:
print(f"WARNING: You called a command named '{name}'", file=sys.stderr)
Do:
logger.warning("You called a repo command named '%s'", name)
Exceptions: Prompts that require strict, synchronously unformatted interaction via input().
T6-12: Strict Translation of Configuration Booleans
Rule: Always cast string-based Git configurations to lowercase and mapthem strictly against Git's recognized array of boolean equivalents.What: Parsers querying Git configuration properties must implement stricthardcoding to safely capture Git's expansive list of non-standard booleanstring representations (e.g., 'yes', 'on', 'true', 'off').Applies To: Configuration parsers mapping usergit configstate tointernal state variables.Why: Using standard integer casts on retrieved git configuration stringscaused runtime failures when users specified string-based boolean valuessanctioned by the official Git system. Failing to adhere to this typicallyresults in Configuration Casting Panic.
Trap 1: Wrapping string-typed configuration variables inside `int()` and catching value exceptions to deduce defaults.
Don't:
try:autocorrect = int(autocorrect)except ValueError:autocorrect = 0
Do:
autocorrect = str(autocorrect).lower()if autocorrect in ("0", "false", "off", "no", "show"):autocorrect = 0elif autocorrect in ("1", "true", "on", "yes", "immediate"):autocorrect = -1
T6-13: Interruptibility of Interactive Runtime Delays
Rule: Must wrap artificially injected execution delays in handlers thatcorrectly detect and gracefully back out of operations upon a keyboardinterrupt signal.What: Any thread-blocking delay generated by the system (e.g.,autocorrection warning timers) must actively handle thread interrupt signalsso users can gracefully cancel impending state mutations.Applies To: Thread blocks, specifically interactive or automated executiondelays.Why: Forced sequential time sleeps preceding an automated commandexecution trapped users. If a user detected an erroneous correction during thesleep interval, initiating a keyboard interrupt would fail to abort execution,resulting in destructive command routing. Failing to adhere to this typicallyresults in Irrevocable Execution.
Trap 1: Placing raw time suspension code before a return statement without wrapping it in a trap for cancellation overrides.
Don't:
time.sleep(delay)return assumed_command
Do:
try:time.sleep(delay)except KeyboardInterrupt:return Nonereturn assumed_command
T6-14: Strict Pre-Access Initialization of CLI Options
Rule: Never retrieve attributes from a parsed options namespace until theshared subcommand option validation layer has fully completed processing.What: Command-line option attributes (e.g.,copts.verbose) must strictlybe accessed only after the options object has fully passed through the commonsubcommand validation layer.Applies To: CLI entry points (main.py) and option routing blocks.Why: Accessing attributes on the configuration options object prior toinvokingCommonValidateOptions(which populates global defaults) resulted inAttributeErrorcrashes, completely breaking primary application functionslikerepo sync. Failing to adhere to this typically results inAttributeError / Process Crash.
Trap 1: Consuming CLI option flags before the shared initialization pipeline populates default properties.
Don't:
git_trace2_event_log.verbose = copts.verbosecmd.CommonValidateOptions(copts, cargs)cmd.ValidateOptions(copts, cargs)
Do:
cmd.CommonValidateOptions(copts, cargs)cmd.ValidateOptions(copts, cargs)git_trace2_event_log.verbose = copts.verbose
T6-15: Omission of Redundant Optparse Destinations
Rule: Avoid manually injectingdest=bindings in argument declarationsif the implicit destination perfectly mirrors the target variable name.What: Do not explicitly passdest=arguments in CLI option definitionsif the value identically matchesoptparse's implicit fallback behavior(which strips leading dashes and replaces inner dashes with underscores).Applies To: Command-line argument definitions using theoptparselibrarywithinsubcmds/.Why: Developers repeatedly specifieddest=overrides that exactlymirrored the auto-generated variable name, adding unnecessary boilerplate andtriggering automated regression test failures. Failing to adhere to thistypically results in Code Bloat / Test Failure.
Trap 1: Redundantly configuring destination variables in CLI arguments.
Don't:
p.add_option("--no-interleaved",dest="no_interleaved",action="store_false",)
Do:
p.add_option("--no-interleaved",action="store_false",)
T6-16: Subcommand Scoping in Commit Messages
Rule: Always prefix your commit messages with the explicit CLI subcommandor modular subsystem the patch directly targets.What: Git commit message subject lines must explicitly scope changes tothe CLI subcommand or module they affect (e.g.,sync:orproject:).Applies To: Commit message authoring.Why: Vague commit messages such as 'Default to interleaved mode'obfuscated history. Scoping was mandated to ensure maintainers could quicklytrace changes within the mono-repo. Failing to adhere to this typicallyresults in Unclear Git History.
Trap 1: Writing global-sounding commit messages for isolated subcommand patches.
Don't:
- Default to interleaved mode
Do:
- sync: Default to interleaved mode
Exceptions: Changes that structurally alter the core framework or affect multiple commands concurrently.
T6-17: Module-Scoped Exception Naming
Rule: Declare isolated module exceptions natively asErrorinstead ofprefixing them with the resident module's name.What: Custom exceptions specific to a module (especially subcommands)should be namedErrorrather than prefixing them with the module name.Applies To: Module-level exception definitions, specifically withinsubcommand implementations.Why: Developers inconsistently named module exceptions (e.g.,WipeErrorinwipe.py), violating the style guide and polluting the namespace uponimport. Failing to adhere to this typically results in **Style Guide Violation/ API Inconsistency**.
Trap 1: Redundantly prefixing the exception name with the module name inside the module definition.
Don't:
# inside wipe.pyclass WipeError(RepoExitError):pass
Do:
# inside wipe.pyclass Error(RepoExitError):pass
T6-18: Explicit Terminology in Destructive CLI Commands
Rule: Must rigorously define nuanced Git terminology natively within theterminal help output if a command has destructive capabilities.What: Destructive commands must clearly define ambiguous terms (like'worktree') in their help documentation and provide concrete usage examples.Applies To: CLI help text, specificallyhelpDescriptionproperties inCommandsubclasses executing file deletion.Why: Users misunderstood destructive operations because terminologyoverlapped with internal Git jargon, increasing the risk of accidentalrepository deletions. Failing to adhere to this typically results inAccidental Data Loss.
Trap 1: Using terms like 'worktree' in help text without explicit definition or examples.
Don't:
- helpDescription = "The repo wipe command removes the specified projects from
the worktree."
Do:
- helpDescription = "The repo wipe command removes the specified projects from
the worktree (the checked out source code)... \n\nExamples:\n %prog <project>..."
T6-19: Fail-Fast Argument Validation in Subcommands
Rule: Must perform strict threshold checks for required argument counts atthe validation layer before the command is permitted to execute.What: Validation checks for mandatory command-line arguments must occur intheValidateOptionshook rather than within the coreExecuteblock.Applies To: AllCommandsubclasses.Why: Performing validation in the execution body delayed error feedback,triggering unnecessary setup logic and violating the command lifecyclearchitecture. Failing to adhere to this typically results in **DelayedExecution Errors / Architectural Inconsistency**.
Trap 1: Checking for missing positional arguments directly inside `Execute()`.
Don't:
def Execute(self, opt, args):if not args:raise UsageError("no projects specified")# ... execution logic
Do:
def ValidateOptions(self, opt, args):if not args:self.OptionParser.error("no projects specified")def Execute(self, opt, args):# ... execution logic safely assumes valid args
T6-20: Respect Global Verbosity Flags
Rule: Always wrap non-critical progress prints or logging updates behindglobal verbosity checks.What: Commands must remain silent by default. Output must be guarded bychecking the globalopt.verboseflag, preventing log noise during standardexecution.Applies To: AllCommandsubclasses executing file operations or progressupdates.Why: Commands were unconditionally printing internal states (e.g.,directory deletions), cluttering terminal output for users expecting standardsilent behavior. Failing to adhere to this typically results in **TerminalSpam / UX Degradation**.
Trap 1: Unconditionally printing progress messages to stderr or stdout.
Don't:
print(f"Deleting objects directory: {objdir}", file=sys.stderr)
Do:
if opt.verbose:print(f"Deleting objects directory: {objdir}", file=sys.stderr)
T6-21: Thread-Safe Terminal Querying during IO Capture
Rule: Must query terminal geometry using a safely cached baseline filedescriptor to prevent crash failures when the standard error stream isredirected to memory buffers.What: Background threads that query terminal properties (like width) mustreference a persistently cached file descriptor of the originalsys.stderr,as the global stream can be temporarily redirected to in-memory objectslacking file descriptors.Applies To: progress.py, UI monitoring loops, and subprocesses executedduringstderr/stdoutredirection.Why: When running parallel processes that captured output into anio.StringIO()buffer, a background progress thread attempting to dynamicallymeasure the terminal width viasys.stderr.fileno()triggered anio.UnsupportedOperation: filenoexception, crashing the entire UI loop.Failing to adhere to this typically results in **Thread Crash /io.UnsupportedOperation**.
Trap 1: Directly querying `sys.stderr.fileno()` inside long-running concurrent loops.
Don't:
# BAD: Fails if stderr is mocked to memorycol = os.get_terminal_size(sys.stderr.fileno()).columns
Do:
# GOOD: Querying a module-level cached reference mapped at bootcol = os.get_terminal_size(_STDERR.fileno()).columns
T6-22: Global State via Persistent Configuration over Environment Variables
Rule: Never propagate novel OS-level environment variables to modifyexecutable behavior, strictly enforcing the existing.repoconfig/configframework instead.What: Global user or CI settings (e.g., Git-LFS defaults) must be managedusing the explicit.repoconfig/configframework. Do not introduce novelOS-level environment variables to modify executable behavior.Applies To: Configuration parsers, command-line argument mapping, andoption handlers across the CLI.Why: A contributor attempted to add aREPO_GIT_LFSenvironment variableto ease CI automation. Maintainers rejected the patch, citing that theproliferation of disjointed environment variables builds technical debtcompared to maintaining a single, consistent file-based configuration layer.Failing to adhere to this typically results in **Configuration Fragmentation /Tech Debt**.
Trap 1: Adding environment variable mappings into command-line parsers to support 'headless' configurations.
Don't:
- Read configuration defaults from
os.environ.get("REPO_GIT_LFS")alongside
CLI flags.
Do:
- Instruct users to provision a
~/.repoconfig/configfile in automated
setups instead of changing process environment logic.
Exceptions: Legacy environment variables (e.g., REPO_URL) remain supported for backward compatibility but are explicitly designated as technical debt.
T6-23: CLI Command Parity with Git Semantics
Rule: Tightly bind local CLI utility semantics and argument definitions tomatch analogous Git operations explicitly.What: Internal CLI command responsibilities and user-facing terminologymust align with established Git semantics and project-wide conventions.Applies To: Command-line interface modules (e.g.,subcmds/status.py,subcmds/info.py).Why: Global metadata (like superproject commit IDs) was mistakenly addedtorepo status, which cluttered the local working-tree status. Additionally,the term 'hash' was used instead of the standard 'revision'. Failing to adhereto this typically results in UX Inconsistency / Clutter.
Trap 1: Adding project-wide or environmental metadata queries to commands designed for local working-tree analysis.
Don't:
- Injecting global repository state (e.g.,
--superproject-hash) into the
status command, which breaks parity with git status.
Do:
- Relocating environmental and global metadata display to the
infocommand,
integrating it cleanly into the default summary header.
Trap 2: Using non-standard terminology for Git object identifiers in user-facing CLI flags.
Don't:
# BAD: Using 'hash' which is inconsistent with existing repo terminologyp.add_option("--superproject-hash", help="print the superproject hash")
Do:
# GOOD: Using 'revision'p.add_option("--superproject-rev", help="print the superproject revision")
T6-24: Context-Aware Sync Operation Termination
Rule: Must catch and defer local sync iteration failures gracefully ratherthan forcing immediate unrecoverable exits across all active streams.What: Non-critical update failures during local sync iterations must setan error flag but must only force a hard exit if the user explicitly providedthe--fail-fastCLI argument.Applies To: All local project iteration workflows withinsubcmds/sync.py.Why: A single project failing an isolated sub-task (like a symlink update)would immediately triggersys.exit(1), aborting the entire pipeline for allother projects and ignoring standard error aggregation strategies. Failing toadhere to this typically results in Premature Pipeline Termination.
Trap 1: Triggering an immediate system exit on an update failure.
Don't:
if self.UpdateCopyLinkfileList():print('\nerror: Local update copyfile or linkfile failed.', file=sys.stderr)sys.exit(1)
Do:
if not self.UpdateCopyLinkfileList():err_event.set()err_update_linkfiles = Trueif opt.fail_fast:print('\nerror: Local update copyfile or linkfile failed.', file=sys.stderr)sys.exit(1)
T6-25: Explicit Exit Codes on CLI Cancellation
Rule: Always force the process to yield a non-zero exit code if aninteractive confirmation prompt is declined or cancelled.What: Interactive CLI workflows that are cancelled or declined by the usermust immediately return a non-zero exit code to signal termination to parentprocesses.Applies To: All interactive subcommands (gc,syncwith prompts, etc.).Why: If a tool cleanly exited (returning None / 0) after a user denied adestructive action prompt, shell automation wrappers and CI systems falselyassumed the destructive cleanup successfully completed. Failing to adhere tothis typically results in Silent Automation Failure.
Trap 1: Using an empty `return` to back out of a declined CLI confirmation prompt.
Don't:
ask = input("Proceed? [y/N] ")if ask.lower() != "y":return
Do:
ask = input("Proceed? [y/N] ")if ask.lower() != "y":return 1
T6-26: Non-Interactive Safeties for Destructive Commands
Rule: Must implement explicit automation bypass flags for any commandcapable of irreversibly destroying system state.What: Any command capable of destroying state (e.g., garbage collection,wiping local commits) must provide both a--dry-runand a--yes(or--force) flag to support safe CI automation.Applies To: Command-line definitions for potentially destructiveoperations.Why: Tools that rely exclusively oninput()prompts block automatedscripts indefinitely. By explicitly enforcing non-interactive modes, scriptscan safely trigger automated cleanups or log dry-runs without freezing.Failing to adhere to this typically results in **Automation Hang / CI PipelineFreeze**.
Trap 1: Hardcoding interactive prompts without checking configuration flags for automation modes.
Don't:
- Prompting the user with
input('Proceed?')unconditionally before executing
a destructive delete.
Do:
- Checking
if opt.dry_run:to skip execution, orif opt.yes:to skip the
confirmation prompt.
T6-27: Strict Interdependent Argument Validation
Rule: Always enforce strict prerequisites checks when parsing command-lineflags intended to modify or inherit context from other flags.What: Command-line options that exist solely to modify or qualify anotherspecific command-line option must be explicitly validated to raise an error iftheir prerequisite option is absent.Applies To: CLI argument parsing routines (subcmds/init.py,ValidateOptions).Why: A new--manifest-upstream-branchargument was added to qualify aprovided commit hash. However, without strict validation, users could supplyit independently, leading to ambiguous or unhandled configuration states.Failing to adhere to this typically results in **CLI Ambiguity / UnhandledOption State**.
Trap 1: Accepting dependent modifier options unconditionally without checking prerequisites.
Don't:
- Accepting
--manifest-upstream-branchin the CLI parser and directly
assigning it to the internal state regardless of the presence of --manifest-branch.
Do:
- Explicitly checking the parsed options and raising an
OptionParser.error
if the modifier is present but the target --manifest-branch is null.
T6-28: Actionable CLI Error Messages for Synchronization Failures
Rule: Embed direct, explicit commands and flag references within terminalerror payloads to rescue users from failing execution states.What: When a terminal failure occurs during CLI operations, the errorpayload must provide specific, actionable flags or manual steps for the userto resolve the failing state.Applies To: Sync command error reporting (subcmds/sync.py,project.py).Why: When a local branch had published commits but was behind upstream,the sync failed with a generic 'punt' message, leaving users unaware thatpassing--rebasecould force the sync. Failing to adhere to this typicallyresults in User Friction / Dead End.
Trap 1: Failing a sync operation with a descriptive but non-actionable error message.
Don't:
fail(LocalSyncFail("branch %s is published (but not merged) and is now %d commits behind"% (branch.name, len(upstream_gain)),project=self.name,))
Do:
fail(LocalSyncFail("branch %s is published (but not merged) and is now %d commits behind. ""Fix this manually or rerun with the --rebase option to force a rebase."% (branch.name, len(upstream_gain)),project=self.name,))
T6-29: Launcher Script Version Upgrades for Important Changes
Rule: Increment theVERSIONtuple within the standalonerepolauncher script when making important or significant functional changes.What: If you modify the standalonerepolauncher file with an important or large change (e.g., updates to Python version checks, significant logic fixes, or major argument parsing updates), you must increment theVERSION = (X, Y)tuple.Applies To: Standalonerepolauncher script, release engineering workflows.Why: The repo source code entry point (main.py) compares the runner wrapper version to the copy of the launcher in the source tree to prompt users to upgrade. If an important launcher modification is submitted without a corresponding version bump, users executing older wrappers won't receive the required update prompts. Failing to adhere to this typically results in Launcher Version Skew / Missing Update Warnings.Exceptions: Minor or cosmetic changes (like fixing typos in comments or minor docstrings) do not require a version bump.
Trap 1: Submitting a major or important patch to the `repo` launcher script without updating its `VERSION` definition.
Don't:
# Making significant changes to Python version handling logic# but leaving VERSION unchanged:VERSION = (2, 65)
Do:
# Incrementing the minor version tuple to signal the update:VERSION = (2, 66)
Cross-Domain Dependencies
- Upstream: T1 | Concurrent Synchronization & IPC - *CLI rendering relies
on sorted, deterministic results emitted from asynchronous multiprocessing pools.*
- Downstream: T3 | Subprocess Git Integration & Error Translation -
Command-line terminology and state configurations must tightly align with wrapped Git subprocess semantics.
Chapter: Repo Hooks Framework
Context: The Repo Hooks Framework governs the execution, parameter validation, and lifecycle management of user-defined scripts within the repository ecosystem. It ensures seamless integration of extensions like post-sync or pre-upload while strictly isolating their execution failures from core operational workflows.
Summary
: : Constraint : : :
| :-------- | :----------------- | :------- | :------------------------------- | |
|---|---|---|---|---|
| T7-01 | Explicit | Critical | Passing a new variable to |
: : Registration of : : hook.Run() without : : : Hook Parameters in : : whitelisting it in the : : : API Contract : : _API_ARGS map. :
: : Precision for Hook : : directly to integers before : : : Telemetry Metrics : : passing to downstream systems. :
: : Post-Sync Hook : : run custom scripts and tying the : : : Integration : : command's exit code to the main : : : : : tool's exit code. :
: : Injection for Repo : : parsers by passing a mock object : : : Hooks : : with hardcoded values into hook : : : : : factory methods. :
: : for Repo Hook : : method in a generic exception : : : Execution Status : : handler. :
: : Specification for : : on an idealized use-case (a full : : : Execution : : checkout) rather than the : : : Lifecycle : : literal programmatic trigger. :
: : kwargs for Repo : : a strict argument list that : : : Hooks Signatures : : cannot gracefully handle new : : : : : inputs. :
Rules
T7-01: Explicit Registration of Hook Parameters in API Contract
Rule: Always register new metadata or arguments intended for user-definedlifecycle scripts within the internal_API_ARGSvalidation dictionary.What: Any new metadata or argument passed into user-defined lifecyclescripts must be explicitly defined in the hook's internal validationdictionary (_API_ARGS).Applies To: Repo Hooks Framework (hooks.pyand Hook Runners).Why: New arguments sent to the post-sync execution context triggeredinternal exceptions because the core application strictly validates**kwargsagainst a registered list of supported arguments. Failing to adhere to thistypically results in Runtime Hook Failure.
Trap 1: Passing a new variable to `hook.Run()` without whitelisting it in the `_API_ARGS` map.
Don't:
# In subcmds/sync.pyhook.Run(repo_topdir=self.client.topdir, sync_duration_seconds=dur)# In hooks.py (Missing registration)_API_ARGS = {'post-sync': {'repo_topdir'}}
Do:
# In hooks.py_API_ARGS = {'post-sync': {'repo_topdir', 'sync_duration_seconds'}}
T7-02: Floating-Point Precision for Hook Telemetry Metrics
Rule: Must pass system telemetry and operational duration metrics todownstream extension hooks as precise floating-point values.What: System telemetry, specifically operational duration metrics, must bepassed to downstream extension hooks as granular floating-point values. Theexecuting system must not truncate or cast telemetry to integers.Applies To: Performance telemetry generation and hook contexts.Why: Internal performance timers originally cast their delta outputs tointegers before emitting the context to the hook system. This caused a loss ofsub-second precision, limiting telemetry usefulness. Failing to adhere to thistypically results in Telemetry Data Loss.
Trap 1: Casting float calculations directly to integers before passing to downstream systems.
Don't:
sync_duration_seconds = time.time() - start_timeself._RunPostSyncHook(opt, sync_duration_seconds=int(sync_duration_seconds))
Do:
sync_duration_seconds = time.time() - start_timeself._RunPostSyncHook(opt, sync_duration_seconds=sync_duration_seconds)
T7-03: Non-Blocking Post-Sync Hook Integration
Rule: Never allow post-operation custom hooks to block or alter thesuccess state of the core operation.What: Custom hooks executed strictly after an operation finishes (likepost-sync) must run via the encapsulatedRepoHookframework and beentirely non-blocking, so their failure does not negatively affect the coreoperation's recorded success state.Applies To: subcmds/sync.py andRepoHookintegrations executing afterrepository data modifications.Why: Teams needed a reliable way to provision local Gitcommit-msghookseven if developers bypassedrepo uploadwith manualgit push. Apost-synchook was added, but the rigid requirement was that if the userscript failed, the actual project synchronization must still report as asuccess to avoid corrupting UX. Failing to adhere to this typically results inBlocked Sync Operations.
Trap 1: Using raw `subprocess` calls to run custom scripts and tying the command's exit code to the main tool's exit code.
Don't:
# BAD: Post-action failure corrupts the sync outcomeif subprocess.run(["run_hooks.sh"]).returncode != 0:raise SyncError("Hook failed")
Do:
# GOOD: Managed execution safely wrapping and suppressing exceptionshook = RepoHook("post-sync")hook.Run() # Designed strictly to warn on failure
T7-04: Dynamic CLI Option Injection for Repo Hooks
Rule: Always utilize the RepoHook option group injection framework forcommand-line integration rather than synthesizing dummy configuration objects.What: Command-line integration for new hooks must utilize the RepoHookoption group injection framework rather than synthesizing dummy configurationobjects.Applies To: Repo Hooks Framework; specifically subcommand definitionsinvolving hook invocations (e.g.,subcmds/sync.py).Why: When integrating the post-sync hook, a developer initially created aminimal 'DummyOpt' object to satisfy parameter checks because the sync commandlacked native hook flags. This diverged from standard hook architecture andcould cause attribute errors. Failing to adhere to this typically results inAttributeError / Option Divergence.
Trap 1: Bypassing standard option parsers by passing a mock object with hardcoded values into hook factory methods.
Don't:
# BAD: Using a dummy object to satisfy missing CLI argumentsclass DummyOpt:bypass_hooks = Falseallow_all_hooks = Trueignore_hooks = Truehook = RepoHook.FromSubcmd(opt=DummyOpt(), ...)
Do:
# GOOD: Injecting the standard hook option group into the parserRepoHook.AddOptionGroup(parser, 'post-sync')# Later during execution, pass the actual resolved options:hook = RepoHook.FromSubcmd(opt=actual_opt, ...)
T7-05: Boolean Evaluation for Repo Hook Execution Status
Rule: Always evaluate hook execution success using the boolean returnvalue ofRun(), never by wrapping the call in external exception handlers.What: Execution wrappers for Repo Hooks must rely on the boolean returnvalue ofRun()to evaluate success, rather than wrapping the call in broadtry/except Exceptionblocks.Applies To: Repo Hooks Framework; specifically the invocation layer forany hook type (post-sync,pre-upload).Why: A developer wrapped the hook execution in a broad Exception catchblock. The hook framework inherently traps and standardizes exceptionsinternally; wrapping it externally duplicates logic, masks context, and leadsto silent failure processing. Failing to adhere to this typically results inSwallowed Exceptions / Logic Duplication.
Trap 1: Wrapping a framework execution method in a generic exception handler.
Don't:
# BAD: Redundant outer try/except block swallowing statetry:hook.Run()except Exception as e:print(f"Warning: hook failed: {e}")
Do:
# GOOD: Relying on the established boolean return contractsuccess = hook.Run()if not success:print("Warning: hook reported failure.")
T7-06: Universal Trigger Specification for Execution Lifecycle
Rule: Must document the exact, literal programmatic triggers for hooksrather than relying on idealized use-cases like full checkouts.What: Hook documentation must strictly delineate the exact success statesthat trigger execution, explicitly noting conditions where operational state(like a local checkout) might be bypassed or skipped.Applies To: Repo Hooks API contracts and documentation(docs/repo-hooks.md).Why: Users of the new post-sync hook might assume it only runs after acomplete workspace checkout. However, it effectively fires on anyzero-exit-code sync operation, including network-only fetches where the localfilesystem state remains completely untouched. Failing to adhere to thistypically results in State Assumption Bugs.
Trap 1: Documenting hook triggers based on an idealized use-case (a full checkout) rather than the literal programmatic trigger.
Don't:
- Documenting that the hook is to install post-processing tasks specifically
for successful full checkouts.
Do:
- Documenting that the hook runs when
repo synccompletes without errors,
explicitly warning that this does not guarantee all projects were synced or checked out (e.g., repo sync -n performs network fetches only).
T7-07: Forward-Compatible kwargs for Repo Hooks Signatures
Rule: Always design hook script entrypoints to accept variable keywordarguments (**kwargs) to ensure forward compatibility with future frameworkexpansions.What: All repository hook script entrypoints (mainfunctions) mustaccept variable keyword arguments (**kwargs) to maintain forwardcompatibility with future API augmentations.Applies To: Repo Hooks scripts and internal examples (e.g.,post-sync.py,pre-upload.py).Why: Historically, if therepotool evolved to pass new environmentalcontext (likerepo_topdir), user-defined scripts with strict functionsignatures would crash with a TypeError. Failing to adhere to this typicallyresults in TypeError / API Breakage.
Trap 1: Defining a hook entrypoint with a strict argument list that cannot gracefully handle new inputs.
Don't:
# BAD: Strict signature that will crash on API updatedef main(repo_topdir=None):print("Running tasks...")
Do:
# GOOD: Accepts forward-compatible **kwargsdef main(repo_topdir=None, **kwargs):"""Args:kwargs: Leave this here for forward-compatibility."""print("Running tasks...")
Cross-Domain Dependencies
- Upstream: T6 | CLI Argument Parsing & UX Consistency - *The dynamic hook
injection framework fundamentally relies on standardized option parsers to map CLI flags cleanly into hook runner contexts.*