Git Workstreams
Goal
Identify normalized repositories and protect their main working tree with an isolated worktree by default; for other repositories, enable worktree only after explicit user selection or when PR creation requests allow it by default. Select reviewable branch/PR topology for dependent changes, determine whether repository changes stay local, are committed, pushed, or submitted as Draft PRs based on a single delivery priority, and follow up on conflicts and CI for existing PRs until they are mergeable or a clear blocker is identified. GitHub native stack is just one execution path and does not take over workstream ownership or domain authorization. Upon completion, judgment evidence, actual topology, baseline, verification results, commit/push status, PR status, and unauthorized actions should be provided.
Choose the topology
- Current checkout: Used as default only when the repository is not a normalized repository, the user has not explicitly enabled worktree, and no PR creation is requested. Normalized repositories do not write to the current checkout of the main working tree by default; if the current checkout itself is a confirmed owning worktree, it is reused directly.
- Main working tree: The main working tree from
git worktree list --porcelain
. Publish requests must not implicitly switch it from the default branch to a temporary branch.
- Independent workstream: Parallel tasks that can be modified, verified, and delivered independently; after user enablement, each workstream uses one writable worktree and branch.
- Dependent stack: When subsequent changes depend on the previous layer, but each layer is worth independent review, maintain a linear branch chain within one owning checkout; the base of each PR is the next layer closer to the trunk. GitHub repositories use native Stacked PRs by default; the stack itself does not require worktree or local CLI.
- Multiple independent stacks: After user enablement, each stack uses a different owning worktree; do not split layers of the same stack across multiple writable worktrees. If the user does not enable this, keep the current checkout and proceed serially.
Classify a normalized repository
Before starting writes, use read-only evidence to determine whether the repository already has a formal collaboration or release lifecycle that needs protection. A repository is classified as normalized if any of the following strong evidence holds:
- In-repository rules or remote branch protection/rulesets explicitly prohibit direct push to the default branch, or require changes to land via PR, review, or required checks.
- Packages/releases produced by the repository already exist in package registries, GitHub Releases, or other release systems; only metadata is read, no login, release, or credential printing is performed.
- A non-placeholder version number in the manifest is corroborated by at least one of version tags, release configuration, changelog, or version CI, proving that the version is not a scaffold default but an actually maintained release state.
Prioritize reading
,
, release documentation, manifests, tags, and release workflows, then query remote ruleset, release, and package metadata as needed. A standalone directory name, an uncorroborated
/
field, the mere presence of a package manifest, or an unexecuted release workflow are not sufficient for classification. When evidence is insufficient, treat the repository as non-normalized and do not upgrade guesses to default worktree permissions.
Once a normalized repository is confirmed, creation or reuse of an owning worktree is allowed by default for regular implementations, fixes, refactors, and
operations, without further asking whether to enable it; the main working tree write flow is only used when the user explicitly requests the current checkout. This default only determines the local isolation topology, does not expand the scope of stage/commit/push tasks, and does not authorize force-push, retarget, merge, package/release publishing, or cleanup.
Route
- This skill is the sole result owner of the workstream: it determines owning checkout, branch/PR topology, native or fallback routes, authorization scope, verification, and stop conditions.
- The CLI is an optional execution tool and does not require another skill to use. First read the local version and target subcommand help, then select the minimal non-interactive command; do not treat static command tables as interface contracts.
- Do not proactively combine with external skills. If loaded due to explicit user request, it can only provide capability hints to be verified; this skill and local help have final interpretation authority over commands, permissions, preflight, fallback, retry, and stop conditions.
- The presence of CLI or skill does not expand permissions: you must not install extensions, write Git configurations, switch/create worktrees, rewrite published branches, push, retarget, merge, retry remote writes, or perform cleanup based on their existence. If the CLI is missing, do not install it without user request; first determine whether GitHub UI/API can complete the selected native route.
Directory policy
Worktrees created by this skill are uniformly placed under
./.agents/worktrees/<forge>/<owner>/<repo>/<task>
in the current repository root. Prioritize obtaining the repository namespace from the normalized remote URL; use
local/<repo>-<common-dir-short-hash>
when there is no remote. The target must resolve within the repository's
root directory and must not overwrite existing paths.
Platform-hosted worktrees such as those from Codex can also use this root directory, without further subdirectory division by app. Management authority cannot be judged solely by path: first identify the owner by combining current platform capabilities, Git worktree metadata, and task context. Platform-hosted worktrees are responsible for snapshots and automatic cleanup by the platform, and the skill does not manually move, delete, or prune them; worktrees created by native Git have no platform snapshot or automatic cleanup guarantees. When unified Codex paths are needed, point to the current repository's
via Codex's
Settings > Worktrees > Worktree root.
This directory is local runtime state, not a configuration source of truth. Do not include it in Git, cloud storage, or cross-machine sync; it is created independently on each machine. Git's own
git worktree list --porcelain
is the authoritative state for a single repository, and no separate global registry is created.
Discover the local interface
First confirm the local version and discover exact syntax along the current command tree:
text
git --version
git worktree --help
git worktree list --porcelain
git branch --help
git rebase --help
gh pr --help # 仅当任务需要 GitHub PR 且 gh 可用
gh stack --help # GitHub stack 请求;用于发现本地扩展是否可用
Only read the help branches needed for the target; do not guess fast-evolving flags from memory or static command tables of external skills. GitHub stack requests follow the native path below by default, and do not require prior proof of support from repository configuration. If the CLI is unavailable, standard Git can still be used to manage branches, and native stacks can be established via GitHub UI/API when server-side capabilities exist. Do not install or upgrade extensions without user request.
Workflow
- Confirm outcome: Distinguish between regular single-threaded tasks, independent worktrees, dependent stacks, native stack CLI operations, stack landing, PR follow-up, read-only diagnostics, migration, or cleanup; this skill only owns Git topology and delivery, and identifies whether the user has explicitly specified delivery endpoints such as local-only, commit, commit+push, or PR.
- Inspect the scene: Parse repo root, absolute/common git dir, superproject, main working tree path and starting branch/HEAD, current branch/HEAD, dirty status, remote, remote default branch, and
git worktree list --porcelain
, and determine whether the repository is normalized based on the read-only criteria in the previous section; also check the head/base, conflicts, checks, write permissions, and repository PR template for task-related PRs. GitHub stack requests check local capabilities and feature status returned by the repository, but do not directly determine that the repository is unsupported due to missing CLI. Regular local tasks do not implicitly fetch; PR follow-up itself depends on current remote state, and can update related refs and read PR/check status.
- Select workspace: Determine the isolation method based on the normalization judgment above and the Worktree boundaries below. Existing authorization remains valid within the same workstream and does not need to be reconfirmed when resuming tasks or loading skills. For non-normalized repositories where worktree is not selected, continue using the current checkout; only when a change to workspace arrangement is truly necessary, explain the reason and specific goals before asking, and continue independent and authorized work while waiting. When the target workstream, owner, or topology changes substantially, the workspace is no longer secure, or new permissions are required, re-judge based on the change.
- Select and draw topology: When enabled, separate independent tasks by worktree; dependent changes, regardless of whether worktree is enabled, are arranged upward from the trunk by reviewable concern. GitHub repositories retain native stack metadata by default; ordinary chained PR fallback is only used when GitHub explicitly returns not enabled/unsupported, the repository is not on GitHub, or the user explicitly opts out. Once a native stack has entered the landing phase, it does not fall back to per-PR merging. Keep serial execution when one result will change upper-layer design.
- Execute minimal actions: Reuse existing isolation environments or create owning worktrees based on user selection and repository classification; new implementations create branches from a clear baseline, and worktrees are only created, entered, or handed over when opt-in is confirmed. Normalized repositories and PR creation requests already provide this opt-in; standalone in non-normalized repositories does not. Apply the main working tree protection below before publishing; do not treat any publish request as authorization to implicitly switch the main working tree. Obtain selection first when a new detached worktree is needed for temporary read-only checks. Do not use force to bypass branch occupancy or target path protection.
- Prepare and verify: Read and project setup, run necessary checks covering affected behaviors and repository-required checks; after passing, expand or repeat verification only due to new changes, failures, or unresolved specific doubts, and do not judge risk by the number of changed lines. Do not automatically copy , credentials, ignored files, or caches, nor install dependencies unconditionally.
- Handle PR follow-up: When the current workstream has a confirmed PR and the user requests implementation, fix, follow-up, or keeping it mergeable, handle in-scope conflicts and CI according to the closed loop below, and commit verified local fixes in small steps and push them to the resolved PR head in a timely manner. Read-only diagnostics do not obtain these write permissions.
- Select delivery endpoint: Determine local-only, commit, push, or Draft PR based on the single priority below: first comply with user-specified explicit endpoints of local-only, commit, commit+push, or PR; if not specified, regular implementations in normalized repositories are committed, pushed, and a Draft PR is created, while non-normalized repositories only retain verified local changes. Use the repository template when creating PRs. Force-push, retarget, Ready, merge, deploy, and release still require respective explicit authorization; first parse exact refs, PR base, and affected layers, then select required native commands from local help.
- Report and stop: After achieving isolation, stack, or PR-ready goals, report topology, ownership, commit/push, checks, and remaining blockers; do not incidentally clean up, merge, or rewrite other workstreams.
Delivery endpoint
- Delivery priority is fixed as: user explicit endpoint > normalized repository default Draft PR > non-normalized repository default local-only. Explicit endpoints include local-only, commit, commit+push, and PR; stop once the endpoint is reached, and do not perform subsequent actions with broader default values.
- When the user does not specify an endpoint, only regular implementations, fixes, or refactors in repositories that have been judged as normalized by read-only evidence will have their verified changes committed, pushed, and a Draft PR created; no separate confirmation wait for "whether to submit a PR" is needed. Non-normalized repositories stop locally after modification and verification, without committing, pushing, or creating PRs. Read-only, diagnostic, review, planning, and answering requests do not trigger any implementation delivery.
- When the user explicitly requests a PR, regardless of whether the repository is normalized, commit, push, and create a PR according to the confirmed scope; create a Draft PR if Ready status is not specified. Explicit PR requests also provide the option to create or reuse an owning worktree as needed on site, but do not force creating another one on an already safely isolated checkout.
- One independently reviewable concern corresponds to one Draft PR by default. Stacked Draft PRs are only created when subsequent concerns truly depend on the previous layer and each layer is worth independent review; independent concerns use independent PRs, and dependencies are not created just to display a stack.
- Default delivery only covers non-destructive commit, push, and Draft PR creation within the confirmed scope of the current task. It does not authorize changing unconfirmed checkout/worktree topology, nor does it authorize force-push, retarget, marking as Ready, merge, cleanup, deploy, or release.
- Main working tree protection, repository contribution guidelines, and local verification must still be met before publishing. Stop and report specific blockers when owning branch/checkout, remote write permissions, or compliant PR base cannot be safely obtained, and do not treat default delivery as a reason to bypass permission and topology boundaries.
- After PR creation, read back head/base, Draft status, and CI. When the user explicitly requests to advance to Ready, only mark it after the exact head has not drifted, required checks are in a repository-allowed final state, and there are no repository-defined Ready blockers; review approval and final mergeability are left to post-Ready review or merge preflight. Continue waiting or handle in-scope failures when CI is still running or the head has drifted.
PR template
- PR templates are required input for PR creation actions, not optional copy references. The creation route must generate the body starting from the selected template; you must not directly pass in a separately written , commit auto-fill, or other free text to bypass the template.
- Before each PR creation, first read the template actually provided by the target base repository. Check for single-template in the root directory, , or , as well as multiple templates under
.github/PULL_REQUEST_TEMPLATE/
; follow the convention if repository contribution documentation explicitly specifies another entry point. Use the template effective on the base branch as the default source of truth; if the current task itself explicitly adds or fixes the template, use the version from this change.
- Use directly when there is only one template. When multiple templates exist, select a clearly matching one based on the template description and current change type; do not splice mutually exclusive templates. If reliable judgment is not possible, stop after push, list candidates and differences, wait for user selection, and do not create speculative PRs.
- The PR body must retain the sections, order, required prompts, and checklist of the selected template, and fill in item by item with the current diff and evidence required by the template: if the template has a verification column, write the actually run checks and results; if the template does not have a verification column, do not additionally list local test conditions, commands, paths, or CI status in the body, checks are executed as usual, and records remain in CI and task reports. Purely instructional HTML comments can be deleted after completing the corresponding requirements, but the template must not be replaced with free text, inconvenient-to-fill columns silently deleted, or items without evidence support checked; inapplicable items are clearly explained in the way allowed by the template.
- When the repository has no available template, PR creation is a blocker: you must not temporarily fabricate a free-text body only for this PR. Only when the current task explicitly includes establishing or restoring the repository template, first add the template as a reviewed repository change to the same workstream, then create the PR using that version.
- When updating an existing PR body, retain the template structure it uses; adjust to the new template only when the repository template has been explicitly changed or the user requests migration. Read back the body after creation or update to confirm that template sections and checklists are not corrupted by CLI, API, or escaping processing.
Worktree boundaries
- Worktree is enabled by default for normalized repositories; it is usually disabled by default for non-normalized repositories. For the latter, if there is no affirmative answer and the user does not request PR creation, keep the current checkout. PR creation requests allow creating or reusing an owning worktree as needed by default. Listing existing worktrees, checking occupancy, and judging normalization are read-only discovery.
- If the platform has already placed the current task in a worktree, but the user has not selected it in the conversation, has not requested PR creation, and the repository is not judged as normalized, first explain the current environment and manager, and ask whether to continue working in this worktree before starting task changes. PR creation or normalized repositories already allow reusing this secure owning worktree by default.
- A writable worktree is only assigned to one agent or one explicit task at a time; multiple agents do not share the same mutable checkout.
- Git refs and object databases are shared between worktrees. Creating, resetting, or deleting branches affects other workspaces of the same repository, so branch actions must be part of the user's request.
- If the target branch is already in another worktree, first return its path; reuse it as a writable environment only after explicit user selection, PR creation request, or the repository is judged as normalized. When independent read-only verification is truly needed, a detached worktree can be created from the same commit, but also confirm existing opt-in before creation, and do not force repeated checkout of that branch.
- Uncommitted and ignored files in the main working tree are not automatically carried into new worktrees by native Git. If the task depends on these contents, first explain the gap and obtain a clear handling method; do not automatically stash, copy secrets, or disguise as the same environment.
- If creation fails and isolation is a prerequisite for the task, stop and report the blocker; do not quietly fall back to the user's current checkout and start modifying.
Primary checkout publish guard
Publish authorization only covers stage, commit, push, and PR within the confirmed scope; it does not automatically authorize changing the current branch of the main working tree.
- Record the main working tree absolute path, starting branch/HEAD, dirty status, and remote default branch before publishing. Do not guess the main working tree or default branch based on directory names.
- If currently on the default branch of the main working tree, and the user has not explicitly selected "switch branch in current checkout", do not execute , , or equivalent branch-changing commands. For normalized repositories or when the user requests PR creation, use an owning worktree by default without further asking whether to enable it; if existing WIP cannot be safely migrated, only ask about the handling method of WIP. For other publish requests, explain that existing WIP cannot be safely implicitly migrated, and ask whether to enable an owning worktree or explicitly allow the temporary branch flow of the current checkout.
- If the user explicitly selects the current checkout, you can create a branch from the confirmed baseline, but must record the return point; after publishing is complete and the working tree is clean, return to the starting branch by default and verify HEAD/upstream. Stop and report if safe return is not possible, do not stash, reset, or overwrite files.
- If the main working tree is already on the target non-default branch, or the current is a confirmed linked worktree, stay on the original branch to complete publishing; do not switch branches again to comply with naming conventions.
- The GitHub publishing capability actually provided by the host can be responsible for stage/commit/push/PR within the selected delivery scope, but checkout/worktree topology and permissions are first parsed by this skill; no execution capability may override the main working tree protection here or expand authorization.
- Finally report the starting and ending branch of the main working tree, current dirty status, and the owning checkout created or reused. If the main working tree branch change is not explicitly selected, the task must not be marked as completed.
Branch and PR stacks
The stable representation of a linear stack is:
text
main <- data-model <- api <- ui
PR head PR base
data-model -> main
api -> data-model
ui -> api
- Each layer contains only one independently understandable and verifiable concern; dependencies must be in the same layer or a layer closer to the trunk.
- A stack is owned by one writable checkout; when worktree is enabled, the entire stack uses only one owning worktree. Do not create a worktree for each PR layer; Git's branch occupancy rules and cross-layer rebase will cause such layouts to block each other.
- Create and commit branches from bottom to top; when publishing, first ensure the corresponding base branch is on the remote, then verify PR layer by layer, with the bottom pointing to the trunk and the rest pointing to the lower-layer branch.
- After modifying a lower layer, replay subsequent branches upward from that layer in dependency order, and run relevant verification on each layer. If the branch has been published, the affected refs/PRs must be clarified before rewriting and force-push; execute only when the user explicitly requests to sync that remote stack.
- The landing order is bottom-up. After the lower layer is merged, re-parse the base of remaining branches, trunk diff, and PR status, then decide on retarget/rebase; do not assume the hosting platform will automatically fix it.
GitHub native stack route
- Try GitHub native Stacked PRs by default. Prioritize reusing local ; when the CLI is unavailable but server-side capabilities exist, use standard Git to manage branches and create or connect native stacks via GitHub UI/API.
- capabilities include initializing/extending stacks, pushing, submitting or updating PRs, viewing, syncing, reordering, and cascading rebase. Exact commands and flags must be obtained from local and related subcommand help.
- , , , , , , or reordering may fetch, rewrite branches, push, update PRs, merge, or clean up local branches; split according to actual help and user authorization, and do not treat combined commands as read-only operations.
- Do not mechanically concatenate combined commands. Re-read branch/PR/stack after each state-changing command; for example, when has completed push or PR sync, only if there is still a target state gap and the user authorizes override, to avoid duplicate remote writes.
- Fall back to standard Git branch/rebase/push and ordinary PR chains only when GitHub explicitly returns that the feature is not enabled/unsupported, the repository is not on GitHub, or the user explicitly requests not to use native stack. Fallback still requires reporting the full mapping.
Landing an official GitHub stack
The user must explicitly request merge/land; "follow to mergeable", fixing CI, or publishing a stack do not authorize merging. After obtaining authorization:
- Re-read the live base/head, exact head OID, draft/review/check/merge status of each target PR, and query the server-side official stack object. The base chain is only used to establish expectations; the number, trunk, entries, and position of the official stack are the authority for membership/order.
- Require all head branches to be in the same repository, the target to form a unique bottom-to-top chain, and the official stack to contain no unexpected members or order. Stop and request user decision in case of cross-fork, multiple stack numbers, unknown members, or order conflicts.
- If expected members are not all linked yet, is an independent remote modification. Supplementary linking is only allowed when the user's landing request explicitly covers the complete chain, all PR authors are the same, and the existing official stack is a subset with consistent order; otherwise, ask first. After supplementary linking, you must re-query and verify the complete stack.
- Before merging, require each PR in the selected scope to be open, non-draft, and respectively meet repository review, required checks, and mergeability rules; a ready upper layer does not prove the lower layer is ready. Full stack landing selects all layers; partial landing must have a clear boundary and include the continuous prefix from bottom to boundary.
- Select the official stack merge command from local help. Stop when CLI/server-side capabilities are unavailable or native merge reports a blocker; when the remote write result is unclear, first perform a read-only check back, do not automatically retry. Do not fall back to , layer-by-layer retarget, or manually simulate atomic merge.
- Wait for the live state of each selected PR to be ; queued is not completion. After partial landing, re-verify that remaining layers still belong to the expected official stack, and re-check head, review, and CI that may have been rewritten by GitHub. Branch deletion is a subsequent independent action; first confirm that no open PR still uses it as base.
Read official documentation according to the task:
- Overview: stack semantics, CI/rules, merge, and rebase.
- Quick Start: prerequisites, CLI/agent setup, and first stack.
- Working with Stacked PRs: push, submit, review, merge, and sync.
- Typical Workflows: daily commits, review feedback, sync, rebase, and existing branches.
- Restructuring Stacks: reorder, fold, drop, insert, and rename.
- CLI reference: command capabilities; actual execution is still subject to local help.
- GitHub UI and FAQ: UI operations, limitations, and troubleshooting.
PR follow-up loop
"Check/summarize/explain PR" is a read-only request; for implementation, fix, follow-up, conflict resolution, or making mergeable for existing PRs, local editing, commit, and push to the PR's confirmed head branch are authorized within scope; when the same target and permissions have not changed, commit/push authorization is not requested again due to task resumption or skill loading. It does not authorize force-push, modifying other branches, retarget, or merge.
- Parse target and ownership: Confirm the exact PR, head repo/branch, base, current checkout/worktree manager, dirty content, conflicts, checks, and push permissions. Do not mix uncommitted changes from the user or other tasks into the PR.
- Resolve conflicts: Choose merge or rebase according to repository conventions, understand the intentions of both parties to the conflict item by item, and run relevant verification. Stacks are processed from bottom to top; lower-layer changes are replayed to subsequent layers and verified separately. When a published branch needs to be rewritten, stop and obtain explicit authorization before force-push.
- Locate CI: Discover exact commands from the current CLI's PR/check/run help; read failed jobs and logs, and distinguish between problems caused by this change, flaky/infrastructure failures, and unrelated failures. If the host provides applicable GitHub CI capabilities, they can be used within the targets and permissions confirmed by this skill; only fix reproducible problems within the current PR scope.
- Commit and push in time: After a focused fix is completed and relevant checks pass, create small-step commits according to repository commit specifications and immediately push to the confirmed PR head; do not leave verified fixes locally for a long time, nor use to cover up hook failures.
- Re-check: Re-read conflicts and checks after push; continue handling new and still in-scope problems until the PR is conflict-free and required checks pass, or a clear blocker that requires user, permission, or external system handling arises.
Cleanup and migration
Cleanup and migration are independent destructive processes. First perform a read-only inventory, then execute a single explicit target:
- Confirm that the target is not the main worktree, current working directory, platform-hosted directory, or directory still used by running tasks.
- Check risks related to tracked, untracked, ignored files, as well as unpushed or unmerged commits of the branch relative to upstream/target branch. Stop when it cannot be proven that they can be discarded.
- Normal cleanup uses Git's worktree remove mechanism; do not use , do not force by default, and do not incidentally delete branches.
- Prune only cleans up missing worktree metadata; dry-run first, then execute for the current repository. It is not a tool for deleting active worktrees.
- Existing worktrees are not automatically relocated due to directory specifications. When the user explicitly requests migration, check dirty, locked, submodule, and platform ownership one by one, then use Git's move/repair capabilities and verify links at both ends.
If the user does require discarding a dirty worktree or unmerged branch, you should re-parse the exact path and ref, clearly explain the unrecoverable content, and obtain confirmation for that target before using force or deleting the branch.
Boundaries
- This skill manages worktree lifecycle, dependent branch/PR topology, as well as conflicts for target PRs, in-scope CI fixes, and continuous delivery of the head branch; it does not make merge decisions for the user, but is responsible for preflight, tool routing, stop conditions, and completion verification after explicit landing authorization. It does not take over pure review comment handling, unrelated CI, or release orchestration.
- PR metadata, GitHub Actions logs, and review threads can use the GitHub capabilities actually provided by the host; the exact CLI operations of native stacks are discovered by this skill from local help. Can fall back to ordinary chained PRs when explicitly unsupported during the creation/publishing phase, official stack landing cannot fall back to per-PR merge.
- Dependencies, ports, databases, and container isolation belong to the project environment. Only reuse when the repository already has a clear setup mechanism, and do not invent one in the general worktree skill.
- Ignored file copying and snapshots for Codex-hosted worktrees are handled by Codex; manual Git worktrees do not assume the same capabilities.
Output
Worktree requests first report normalization judgment evidence and whether the user has opted in; after enablement, report the manager, absolute path, baseline ref, branch/HEAD, setup, and verification. Repository modification reports the delivery endpoint hit by priority, as well as actual local changes, commit, push, and PR; unexecuted subsequent actions must also be clarified. Stack requests report the sole Git outcome owner, owning checkout, worktree enablement status, execution route, trunk, bottom-to-top branch order, and PR base/head for each layer; landing also reports the official stack number, selected scope, final status of each layer, and remaining blockers. PR follow-up reports conflict status, failed checks and judgments, created commits, push target, re-check results, and blockers. Cleanup requests report the exact targets to retain and those that can be safely removed.