diff --git a/.claude/agents/os-dev.md b/.claude/agents/os-dev.md index 1c5c96be443..18ca7bbe1ac 100644 --- a/.claude/agents/os-dev.md +++ b/.claude/agents/os-dev.md @@ -24,11 +24,11 @@ model: opus ## 六条基本规则 1. **Worktree-first。** 任何编辑之前建专用 worktree,`cd` 进去 `pnpm install`。 - - `git fetch origin main && git worktree add --no-track ../-issue- -b claude/issue-- origin/main` + - `bash scripts/pm/dev-worktree.sh --branch=claude/issue--`:自 `origin/main` 建 `../-issue-`。 - 认领带 `Resume-from: BRANCH@SHA` ⇒ 从 `origin/BRANCH` 建同名分支续写,先合 `origin/main`。 - ⛔ 永不编辑共享检出;修复横跨姊妹仓时一仓一 worktree。 - 动笔前记下基点 `BASE=$(git rev-parse HEAD)`,它是标准条款节里家族规则的锚。 - - 建好分支后先推空分支(任何编辑前 `git push -u origin `):落地标记兼写路由探针。 + - 建好分支后先推空分支(任何编辑前 `dev-worktree.sh --probe`):落地标记兼写路由探针。 - 卡线程分支由平台指定、harness 推送,⛔ 不推空分支;探针规则只对自建分支。 - 探针遇 403 ⇒ 停下报 `blocked`,⛔ 不进重试循环;只有网络错误才退避重试。 - Scratchpad 按 issue 隔离:在 scratchpad 目录下建 `issue-/` 子目录,临时文件全写进去。 diff --git a/.claude/skills/pm-dispatch/references/dev-traps.md b/.claude/skills/pm-dispatch/references/dev-traps.md index 693605ee8ac..201da8130fa 100644 --- a/.claude/skills/pm-dispatch/references/dev-traps.md +++ b/.claude/skills/pm-dispatch/references/dev-traps.md @@ -21,7 +21,7 @@ - 失效单向:exit 0(是祖先)自证,任何检出里都作数;只有 exit 1 要控制腿。 - 还没发布、不在 main 上、`Blocked-by` 已落地这些前提核验,要的恰是 exit 1。 - 阴性读数按两条腿写:同一检出、同一目标 ref 上再跑一个已知在其历史里的 commit。 -- 它必须答 exit 0;否则阴性作废,`git fetch --deepen` / `--unshallow` 到控制腿转 0 再重读。 +- 它必须答 exit 0;否则阴性作废,加深到控制腿转 0 重读;现读 `git-history.mjs ancestor`。 - ⛔ 控制腿别挑浅窗内的近亲:控制 commit 至少与被测那个同深;两条腿的退出码都进报告。 - `--is-shallow-repository` 是便宜的触发器不是判据,判据是控制腿。 diff --git a/package.json b/package.json index 7ddd6a8ba16..3acdf76d4c4 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,7 @@ "check:pm-fleet-token": "node scripts/pm/fleet-token.mjs --self-test", "check:pm-issue-create": "node scripts/pm/issue-create.mjs --self-test", "check:pm-issue-transfer": "node scripts/pm/issue-transfer.mjs --self-test", - "check:pm-with-fleet": "bash scripts/pm/with-fleet.sh --self-test", + "check:pm-with-fleet": "bash scripts/pm/with-fleet.sh --self-test && bash scripts/pm/dev-worktree.sh --self-test", "check:pm-post-stamped": "node scripts/pm/post-stamped.mjs --self-test", "check:pm-label-write": "node scripts/pm/label-write.mjs --self-test", "check:pm-close-cards": "node scripts/pm/close-cards.mjs --self-test", diff --git a/scripts/pm/dev-worktree.sh b/scripts/pm/dev-worktree.sh new file mode 100644 index 00000000000..beb048af127 --- /dev/null +++ b/scripts/pm/dev-worktree.sh @@ -0,0 +1,935 @@ +#!/usr/bin/env bash +# Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +# +# dev-worktree.sh — the worktree-first procedure of `.claude/agents/os-dev.md` +# basic rule 1, as one command. Run it from the checkout of the repository the +# task lands in; it builds the task's own worktree BESIDE that checkout and +# never edits the checkout itself. +# +# bash scripts/pm/dev-worktree.sh --branch=claude/issue-- [--probe] +# [--worktree=] [--resume-from=BRANCH@SHA] [--no-probe] +# [--scratchpad=] [--no-install] [--backoff=] +# bash scripts/pm/dev-worktree.sh --base # inside a worktree: print the pinned base +# bash scripts/pm/dev-worktree.sh --pin-base # inside a worktree: pin HEAD as the base, once +# bash scripts/pm/dev-worktree.sh --self-test # offline: fixture repos, no network +# +# ## What it runs, in this order — each step is a line of rule 1 +# +# 1. `git fetch origin main`, then +# `git worktree add --no-track ../-issue- -b origin/main`. +# `` is the checkout's own directory name and `` is read from the +# branch, so the tree and the branch cannot disagree; `--worktree=` +# names the tree when the claim does. +# 2. `--resume-from=BRANCH@SHA` (a claim's `Resume-from:` line): the same-name +# branch is built from `origin/BRANCH` instead, after checking that its tip +# IS that sha. The merge of `origin/main` the rule orders next is +# `bash scripts/pm/os-regen-merge.sh`, run inside the new tree; this script +# names it and does not run it. +# 3. the base is PINNED: `git rev-parse HEAD`, written to a file in the +# worktree's own git dir, where it survives every shell and leaves with +# `git worktree remove`. `--base` prints it. A resumed branch is pinned +# after its merge, with `--pin-base`; a pin is never moved. +# 4. with `--probe`, and ONLY with it: the empty-branch probe, +# `git push -u origin `, before any edit. A 403 stops at once +# (exit 3: report `blocked`, no retry). Only a network error is retried, +# on the `--backoff` schedule, and then given up (exit 4). Any other +# refusal stops without a retry (exit 5). +# 5. `--scratchpad=` (the session's scratchpad directory): `issue-/` +# is made under it. +# 6. `pnpm install` inside the new tree (`--no-install` leaves it to you). +# +# ## Nothing is pushed unless you say `--probe` +# +# The probe is for a branch you build yourself. A card thread's branch is +# assigned by the platform and pushed by the harness, and rule 1 forbids the +# empty-branch push there. A branch NAME cannot tell the two apart: a card +# thread that builds its tree under the `claude/issue--` spelling +# would have that alias pushed under a name the platform never assigned. So +# no spelling is ever probed by default. The dev who owns a self-built branch +# says `--probe`; without it the tree is built, the base is pinned, and +# `PROBE=skipped` is printed with the line that says what is still owed. +# `--no-probe` says the default out loud. +# +# ## What it will not do +# +# It never forces: no `--force`, no `-B`, no checkout in the shared tree. An +# existing path, an existing local branch, or a branch already on `origin` +# with no `--resume-from` is REFUSED before anything is created — the last one +# is either a claim whose `Resume-from:` you did not pass, or another session's +# work in flight (rule 2: stop and report `blocked`). +# +# Running it again for a tree it already built is safe: nothing is re-created, +# the pin is read back, and with `--probe` the probe is sent only if the +# branch is still empty and still absent from `origin` — so a network give-up +# (exit 4), or a first run that did not say `--probe`, is completed by the +# same command. +# +# ## Output +# +# stdout is `KEY=value` lines and one last `VERDICT …` line; the narration is +# on stderr. +# +# WORKTREE= BRANCH= +# BASE= | unpinned PROBE=pushed | on-origin | skipped | owed | 403 | network | refused +# SCRATCH= INSTALL=done | skipped | failed +# +# Exit codes: 0 ready · 1 refused, no tree was built · 2 usage · +# 3 the probe answered 403 · 4 the probe was not delivered (network, retries +# spent) · 5 the probe was refused for another reason · 6 `pnpm install` +# failed. From 3 up the worktree exists; the VERDICT line says what is owed. +# +# Bash 3.2 clean (`pnpm check:bash32-floor`): no associative array, no +# `mapfile`, no case-modifying expansion. + +set -euo pipefail + +SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")" + +EXIT_REFUSED=1 +EXIT_USAGE=2 +EXIT_PROBE_403=3 +EXIT_PROBE_NETWORK=4 +EXIT_PROBE_REFUSED=5 +EXIT_INSTALL=6 + +BASE_FILE_NAME='os-dev-worktree-base' +DEFAULT_BACKOFF='2,4,8,16' + +log() { printf 'dev-worktree: %s\n' "$*" >&2; } + +usage() { + cat >&2 << 'USAGE' +usage: + bash scripts/pm/dev-worktree.sh --branch=claude/issue-- [--probe] [--worktree=] + [--resume-from=BRANCH@SHA] [--no-probe] [--scratchpad=] [--no-install] + [--backoff=] + bash scripts/pm/dev-worktree.sh --base (inside a worktree) print the pinned base + bash scripts/pm/dev-worktree.sh --pin-base (inside a worktree) pin HEAD as the base, once + bash scripts/pm/dev-worktree.sh --self-test + + Builds the task's worktree beside the current checkout from a freshly fetched origin/main + (or, with --resume-from, from origin/BRANCH at the claimed sha), pins the base, makes the + issue's scratchpad directory and runs pnpm install. + --probe: also send the empty-branch push, before any edit — for a branch you build yourself. + Without it NOTHING is pushed, whatever the branch is called: a platform-assigned branch + (a card thread) is never pushed from here. --no-probe says that default out loud. + Exits: 0 ready · 1 refused, no tree built · 2 usage · 3 probe 403 (report blocked, no retry) + · 4 probe not delivered (network) · 5 probe refused otherwise · 6 pnpm install failed +USAGE +} + +die_usage() { + log "$*" + usage + exit "$EXIT_USAGE" +} + +refuse() { + log "REFUSED — $*" + printf 'VERDICT refused — nothing was created\n' + exit "$EXIT_REFUSED" +} + +# --------------------------------------------------------------------------- +# The probe's failure, classified from what git printed. 403 is checked FIRST: +# git reports a refused push as `RPC failed; HTTP 403`, which also carries the +# words of a transport failure, and a 403 read as "network" would be retried. +# The two misreadings are not equal: a failure wrongly read as 403 stops one +# run early, and one wrongly read as network costs a bounded handful of pushes +# — neither is a loop, and anything this cannot place is `other`: stop. +# --------------------------------------------------------------------------- +classify_push_failure() { + local out="$1" + if printf '%s\n' "$out" | grep -Eq '(error:|HTTP(/[0-9.]+)?|status|code|response)[ :]+403([^0-9]|$)|Permission to .+ denied'; then + printf '403\n' + return 0 + fi + if printf '%s\n' "$out" | grep -Eiq 'Could not resolve host|Temporary failure in name resolution|Failed to connect|Network is unreachable|Connection (refused|reset|timed out)|Operation timed out|Empty reply from server|remote end hung up unexpectedly|unexpected disconnect|early EOF|RPC failed|(error:|HTTP)[ :]+5[0-9][0-9]([^0-9]|$)|gnutls_handshake|SSL_ERROR_SYSCALL|SSL_connect|TLS connection was non-properly terminated'; then + printf 'network\n' + return 0 + fi + printf 'other\n' +} + +# The pin lives in the worktree's OWN git dir: private to it, outside the tree, +# and gone with `git worktree remove`. +base_file_of() { printf '%s/%s\n' "$(git -C "$1" rev-parse --absolute-git-dir)" "$BASE_FILE_NAME"; } + +read_base() { + local file sha + file="$(base_file_of "$1")" + [ -f "$file" ] || return 1 + sha="$(head -n 1 "$file" | tr -d '[:space:]')" + [ -n "$sha" ] || return 1 + git -C "$1" cat-file -e "${sha}^{commit}" 2> /dev/null || return 1 + printf '%s\n' "$sha" +} + +is_shared_checkout() { + local git_dir common + git_dir="$(git -C "$1" rev-parse --absolute-git-dir)" + common="$(cd "$1" && cd "$(git rev-parse --git-common-dir)" && pwd -P)" + [ "$git_dir" = "$common" ] +} + +mode_base() { + local top sha + top="$(git rev-parse --show-toplevel 2> /dev/null)" || { log 'not inside a git checkout'; exit "$EXIT_REFUSED"; } + if sha="$(read_base "$top")"; then + printf '%s\n' "$sha" + return 0 + fi + log "no base is pinned for $top — a tree this script built fresh pins one at creation; a resumed or hand-built tree pins with --pin-base, before its first edit" + exit "$EXIT_REFUSED" +} + +mode_pin_base() { + local top sha file + top="$(git rev-parse --show-toplevel 2> /dev/null)" || { log 'not inside a git checkout'; exit "$EXIT_REFUSED"; } + if is_shared_checkout "$top"; then + log "REFUSED — $top is the shared checkout, never a task tree (rule 1: worktree first); nothing was pinned" + exit "$EXIT_REFUSED" + fi + if sha="$(read_base "$top")"; then + log "REFUSED — a base is already pinned here ($sha) and a pin is never moved: it anchors every diff, log and reset of this task" + exit "$EXIT_REFUSED" + fi + sha="$(git -C "$top" rev-parse HEAD)" + file="$(base_file_of "$top")" + printf '%s\n' "$sha" > "$file" + log "pinned BASE=$sha for $top" + printf '%s\n' "$sha" +} + +# The branch a registered worktree at exactly this path has checked out; empty +# when no worktree is registered there. +worktree_branch_at() { + git worktree list --porcelain | awk -v want="$1" ' + $1 == "worktree" { path = substr($0, 10); branch = "" } + $1 == "branch" && path == want { sub(/^refs\/heads\//, "", $2); print $2 } + ' +} + +# Sends the probe. Sets PROBE and returns 0, or one of the EXIT_PROBE_* codes. +PROBE='' +PROBE_ATTEMPTS=0 +probe_push() { + local wt="$1" branch="$2" out rc kind + # The positional parameters become the delays still to spend. + # shellcheck disable=SC2046 + set -- $(printf '%s' "$BACKOFF" | tr ',' ' ') + while :; do + PROBE_ATTEMPTS=$((PROBE_ATTEMPTS + 1)) + if out="$(git -C "$wt" push -u origin "$branch" 2>&1)"; then rc=0; else rc=$?; fi + printf '%s\n' "$out" | sed 's/^/ | /' >&2 + if [ "$rc" -eq 0 ]; then + PROBE='pushed' + return 0 + fi + kind="$(classify_push_failure "$out")" + case "$kind" in + 403) + PROBE='403' + log "the probe answered 403 (git exit $rc) — STOP: report \`blocked\`; a 403 is never retried" + return "$EXIT_PROBE_403" + ;; + network) + if [ "$#" -eq 0 ]; then + PROBE='network' + log "the probe was not delivered: a network error on each of $PROBE_ATTEMPTS attempt(s) — run this command again to retry it" + return "$EXIT_PROBE_NETWORK" + fi + log "the probe hit a network error (git exit $rc, attempt $PROBE_ATTEMPTS) — retrying in $1 s" + sleep "$1" + shift + ;; + *) + PROBE='refused' + log "the probe was refused (git exit $rc) and it is neither a 403 nor a network error — not retried; read the lines above" + return "$EXIT_PROBE_REFUSED" + ;; + esac + done +} + +# Called as `mode_build || rc=$?`, so errexit is OFF inside it: every step that +# can fail is checked where it stands. +mode_build() { + local top main_checkout parent repo issue='' path start resume_branch='' resume_sha='' built=0 + local existing remote_line tip base='' scratch='' install='skipped' rc=0 verdict head probe_declared + + top="$(git rev-parse --show-toplevel 2> /dev/null)" || refuse 'not inside a git checkout: run this from the repository the task lands in' + main_checkout="$(git -C "$top" worktree list --porcelain | sed -n '1s/^worktree //p')" + [ -n "$main_checkout" ] || refuse "cannot read the main checkout of $top" + parent="$(cd "$(dirname "$main_checkout")" && pwd -P)" + repo="$(basename "$main_checkout")" + + if [ -n "$RESUME_FROM" ]; then + case "$RESUME_FROM" in + *@*) ;; + *) die_usage "--resume-from takes BRANCH@SHA, exactly as the claim's Resume-from: line spells it (got: $RESUME_FROM)" ;; + esac + resume_branch="${RESUME_FROM%@*}" + resume_sha="$(printf '%s' "${RESUME_FROM##*@}" | tr 'A-F' 'a-f')" + if ! printf '%s' "$resume_sha" | grep -Eq '^[0-9a-f]{7,64}$'; then + die_usage "--resume-from: '$resume_sha' is not a sha of 7 or more hex digits" + fi + if [ -n "$BRANCH" ] && [ "$BRANCH" != "$resume_branch" ]; then + die_usage "--branch=$BRANCH and --resume-from name different branches: a resume continues the SAME branch ($resume_branch)" + fi + BRANCH="$resume_branch" + fi + [ -n "$BRANCH" ] || die_usage '--branch= is required' + git check-ref-format --branch "$BRANCH" > /dev/null 2>&1 || die_usage "'$BRANCH' is not a branch name git accepts" + case "$BRANCH" in + main | master) die_usage "'$BRANCH' is the trunk, never a task branch" ;; + esac + + if printf '%s' "$BRANCH" | grep -Eq '^claude/issue-[0-9]+(-|$)'; then + issue="$(printf '%s' "$BRANCH" | sed -E 's|^claude/issue-([0-9]+).*$|\1|')" + fi + if [ -z "$WORKTREE" ]; then + [ -n "$issue" ] || die_usage "the branch '$BRANCH' carries no issue number, so the tree has no default name: pass --worktree=" + WORKTREE="${repo}-issue-${issue}" + fi + if ! printf '%s' "$WORKTREE" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]*$'; then + die_usage "--worktree takes a directory NAME (letters, digits, dot, dash, underscore), built beside the checkout — not a path: $WORKTREE" + fi + # No spelling is probed by default: a name cannot tell a self-built branch + # from a card thread's alias, and pushing the second is what rule 1 forbids. + probe_declared="$PROBE_MODE" + [ -n "$PROBE_MODE" ] || PROBE_MODE='no-probe' + if ! printf '%s\n' "$BACKOFF" | grep -Eq '^([0-9]+(,[0-9]+)*)?$'; then + die_usage "--backoff takes seconds separated by commas (got: $BACKOFF)" + fi + if [ -n "$SCRATCHPAD" ]; then + [ -d "$SCRATCHPAD" ] || die_usage "--scratchpad=$SCRATCHPAD is not a directory (pass the session's scratchpad directory)" + [ -n "$issue" ] || die_usage "--scratchpad makes issue-/ and '$BRANCH' carries no issue number: make the task's subdirectory yourself" + fi + path="${parent}/${WORKTREE}" + + if [ -e "$path" ]; then + existing="$(worktree_branch_at "$path")" + [ "$existing" = "$BRANCH" ] || refuse "$path exists and is not the worktree of $BRANCH${existing:+ (it holds $existing)} — nothing is ever forced; read what is there (git -C $path status). A second branch of the same card takes its own tree: --worktree=" + built=1 + log "$path is already the worktree of $BRANCH — nothing is re-created" + else + if git -C "$top" show-ref --verify --quiet "refs/heads/$BRANCH"; then + refuse "a local branch $BRANCH already exists (another worktree holds it, or an earlier run left it) — it is never reset; read \`git worktree list\`" + fi + if [ -n "$resume_branch" ]; then + git -C "$top" fetch origin main "+refs/heads/${resume_branch}:refs/remotes/origin/${resume_branch}" >&2 \ + || refuse "git fetch of origin main and $resume_branch failed" + tip="$(git -C "$top" rev-parse --verify --quiet "refs/remotes/origin/${resume_branch}^{commit}")" \ + || refuse "origin/$resume_branch does not resolve after the fetch" + case "$tip" in + "$resume_sha"*) ;; + *) refuse "origin/$resume_branch is at $tip, and the claim's Resume-from names $resume_sha: the branch moved after the Release (or the line is stale) — read who pushed it before building on it" ;; + esac + start="origin/$resume_branch" + else + git -C "$top" fetch origin main >&2 || refuse 'git fetch origin main failed' + remote_line="$(git -C "$top" ls-remote --heads origin "refs/heads/$BRANCH")" \ + || refuse "cannot read origin's heads, so whether $BRANCH is already there is unknown" + if [ -n "$remote_line" ]; then + refuse "$BRANCH is already on origin (${remote_line%%[[:space:]]*}): a claim with a Resume-from: line ⇒ pass --resume-from=BRANCH@SHA; otherwise it is another session's work in flight (rule 2: stop and report \`blocked\`)" + fi + start='origin/main' + fi + if ! git -C "$top" worktree add --no-track "$path" -b "$BRANCH" "$start" >&2; then + # git can fail after it has made the branch. Say what is really there + # instead of "nothing was created". + if git -C "$top" show-ref --verify --quiet "refs/heads/$BRANCH"; then + log "REFUSED — git worktree add failed for $path, and it left the local branch $BRANCH behind: no tree was built; read \`git worktree list\` and remove that branch before the next run" + printf 'VERDICT refused — no tree was built; the local branch %s was left behind\n' "$BRANCH" + exit "$EXIT_REFUSED" + fi + refuse "git worktree add failed for $path" + fi + if [ -z "$resume_branch" ]; then + head="$(git -C "$path" rev-parse HEAD)" + printf '%s\n' "$head" > "$(base_file_of "$path")" \ + || log "could not write the pin file for $path — BASE reads unpinned below; pin it before the first edit (--pin-base)" + fi + fi + + if base="$(read_base "$path")"; then :; else base=''; fi + + # ── the empty-branch probe ─────────────────────────────────────────────── + if [ "$PROBE_MODE" = 'no-probe' ]; then + PROBE='skipped' + if [ -n "$probe_declared" ]; then + log "no probe: --no-probe was given, and nothing is pushed from here" + else + log "no probe: --probe was not given, so NOTHING was pushed. A branch you build yourself owes the empty-branch push before any edit — run this command again with --probe. A platform-assigned branch (a card thread) is never pushed." + fi + elif [ "$built" -eq 1 ]; then + remote_line="$(git -C "$path" ls-remote --heads origin "refs/heads/$BRANCH")" \ + || refuse "cannot read origin's heads, so whether the probe landed is unknown" + if [ -n "$remote_line" ]; then + PROBE='on-origin' + elif [ -n "$base" ] && [ "$(git -C "$path" rev-parse HEAD)" = "$base" ]; then + probe_push "$path" "$BRANCH" || rc=$? + elif [ -z "$base" ]; then + PROBE='owed' + log "$BRANCH is not on origin, and this tree has no pinned base, so an empty branch cannot be told from one that carries work — your own first push is the probe" + else + PROBE='owed' + log "$BRANCH is not on origin and is no longer an empty branch — your own first push is the probe now" + fi + else + probe_push "$path" "$BRANCH" || rc=$? + fi + + # ── scratchpad, install ────────────────────────────────────────────────── + if [ "$rc" -eq 0 ] && [ -n "$SCRATCHPAD" ]; then + scratch="$(cd "$SCRATCHPAD" && pwd -P)/issue-${issue}" + mkdir -p "$scratch" + fi + if [ "$rc" -eq 0 ] && [ "$INSTALL" -eq 1 ]; then + if (cd "$path" && pnpm install) >&2; then + install='done' + else + install='failed' + rc="$EXIT_INSTALL" + log "pnpm install failed in $path — the tree, the pin and the probe stand; run it again there" + fi + fi + + printf 'WORKTREE=%s\n' "$path" + printf 'BRANCH=%s\n' "$BRANCH" + printf 'BASE=%s\n' "${base:-unpinned}" + printf 'PROBE=%s\n' "$PROBE" + [ -z "$scratch" ] || printf 'SCRATCH=%s\n' "$scratch" + printf 'INSTALL=%s\n' "$install" + if [ -z "$base" ] && [ -n "$resume_branch" ]; then + log "BASE is unpinned: a resumed branch merges origin/main first (cd $path && bash scripts/pm/os-regen-merge.sh), then pins the base before its first edit (bash scripts/pm/dev-worktree.sh --pin-base)" + elif [ -z "$base" ]; then + log "BASE is unpinned: this tree was not built fresh by this script. --pin-base pins HEAD, so it is the base only while the tree's first edit is still ahead" + fi + case "$rc" in + 0) verdict="ready — cd $path" ;; + "$EXIT_PROBE_403") verdict='blocked-403 — the write route refused the probe: stop, report blocked, do not retry' ;; + "$EXIT_PROBE_NETWORK") verdict="probe-network — not delivered after $PROBE_ATTEMPTS attempt(s); the same command retries it" ;; + "$EXIT_PROBE_REFUSED") verdict='probe-refused — neither a 403 nor a network error; not retried' ;; + *) verdict="install-failed — run pnpm install in $path" ;; + esac + printf 'VERDICT %s\n' "$verdict" + return "$rc" +} + +# --------------------------------------------------------------------------- +# self-test — offline. A bare repository stands in for origin; a `git` shim on +# PATH answers the probe from a plan file and hands every other call to the +# real git, and a `pnpm` shim records the install it was asked for. +# --------------------------------------------------------------------------- + +# name=minimum, one per line. A battery below its minimum means cases stopped +# running; the roster's own length is pinned too, so a deleted row cannot take +# its floor with it. +ST_BATTERIES='the probe failure classifier=12 +a fresh worktree=13 +refusals before anything is created=12 +resume from a claimed sha=11 +the probe=19 +re-run, scratchpad and install=14 +what the script never spells=4' +ST_BATTERY_FLOOR=7 +ST_OPEN='' +ST_SEEN='' +ST_FAIL=0 +ST_DIR='' +SELF_TEST_REACHED_VERDICT=0 + +st_battery() { ST_OPEN="$1"; } +st_case() { + local name="$1" got="$2" want="$3" + ST_SEEN="${ST_SEEN}${ST_OPEN:-(no battery open)} +" + if [ "$got" = "$want" ]; then + return 0 + fi + ST_FAIL=$((ST_FAIL + 1)) + printf ' ✗ [%s] %s — got %s, want %s\n' "${ST_OPEN:-(no battery open)}" "$name" "$got" "$want" >&2 +} + +self_test() { + set +e # every case below reads a status; a failing case is a finding, not an abort + local dir real_git shim out rc err sha wt base main_sha origin tip plan + dir="$(mktemp -d "${TMPDIR:-/tmp}/dev-worktree-XXXXXX")" + dir="$(cd "$dir" && pwd -P)" + # Global and removed at EXIT: the self-test always ends in the dispatch's + # `exit`, and a function-local name would be gone by the time a trap ran. + ST_DIR="$dir" + trap 'rm -rf "$ST_DIR"' EXIT + real_git="$(command -v git)" + # Hermetic: no user or system git config reaches the fixture repositories or + # the script under test (a host's `push.negotiate`, hooks path or identity + # would otherwise be part of what these cases measure). + export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 + shim="$dir/shim" + err="$dir/stderr.log" + mkdir -p "$shim" "$dir/bin" + + cat > "$dir/bin/git" << 'SHIM' +#!/bin/sh +# Answers `push` from the plan (line N = attempt N: 403 | network | other | +# anything else = the real push) and counts the attempts; every other call is +# the real git. +if [ -f "$OS_TEST_DEV_WORKTREE_SHIM/worktree.fail" ]; then + case " $* " in + *" worktree add "*) + prev='' + top='' + br='' + for a in "$@"; do + [ "$prev" = -C ] && top="$a" + [ "$prev" = -b ] && br="$a" + prev="$a" + done + "$OS_TEST_DEV_WORKTREE_REAL_GIT" -C "$top" branch "$br" origin/main + echo 'fatal: could not create the worktree directory' >&2 + exit 128 + ;; + esac +fi +for a in "$@"; do + if [ "$a" = push ]; then + n=$(cat "$OS_TEST_DEV_WORKTREE_SHIM/push.count" 2> /dev/null || echo 0) + n=$((n + 1)) + echo "$n" > "$OS_TEST_DEV_WORKTREE_SHIM/push.count" + mode=$(sed -n "${n}p" "$OS_TEST_DEV_WORKTREE_SHIM/push.plan" 2> /dev/null) + case "$mode" in + 403) + echo 'remote: Permission to objectstack-ai/objectstack.git denied to someone.' >&2 + echo "fatal: unable to access 'https://github.com/objectstack-ai/objectstack/': The requested URL returned error: 403" >&2 + exit 128 + ;; + network) + echo "fatal: unable to access 'https://github.com/objectstack-ai/objectstack/': Could not resolve host: github.com" >&2 + exit 128 + ;; + other) + echo ' ! [remote rejected] HEAD -> branch (pre-receive hook declined)' >&2 + exit 1 + ;; + esac + fi +done +exec "$OS_TEST_DEV_WORKTREE_REAL_GIT" "$@" +SHIM + cat > "$dir/bin/pnpm" << 'SHIM' +#!/bin/sh +printf '%s|%s\n' "$PWD" "$*" >> "$OS_TEST_DEV_WORKTREE_SHIM/pnpm.log" +exit "$(cat "$OS_TEST_DEV_WORKTREE_SHIM/pnpm.exit" 2> /dev/null || echo 0)" +SHIM + chmod +x "$dir/bin/git" "$dir/bin/pnpm" + + # origin (bare) · seed (a second clone, to move origin) · objectstack (the shared checkout) + origin="$dir/origin.git" + "$real_git" init --quiet --bare --initial-branch=main "$origin" + "$real_git" clone --quiet "$origin" "$dir/seed" 2> /dev/null + ( + cd "$dir/seed" || exit 1 + "$real_git" config user.email selftest@objectstack.ai + "$real_git" config user.name selftest + echo one > f.txt + "$real_git" add f.txt + "$real_git" commit --quiet -m c1 + "$real_git" push --quiet origin HEAD:main + ) + "$real_git" clone --quiet "$origin" "$dir/objectstack" + ( + cd "$dir/objectstack" || exit 1 + "$real_git" config user.email selftest@objectstack.ai + "$real_git" config user.name selftest + ) + # origin moves AFTER the shared checkout was cloned: a tree built from the + # checkout's stale origin/main would miss this commit. + ( + cd "$dir/seed" || exit 1 + echo two > f.txt + "$real_git" commit --quiet -am c2 + "$real_git" push --quiet origin HEAD:main + ) + main_sha="$("$real_git" -C "$dir/seed" rev-parse HEAD)" + + # run — the script under the shims, stdout captured, stderr to $err + run() { + local cwd="$1" + shift + ( + cd "$cwd" || exit 97 + env -u GIT_DIR -u GIT_WORK_TREE PATH="$dir/bin:$PATH" \ + OS_TEST_DEV_WORKTREE_SHIM="$shim" OS_TEST_DEV_WORKTREE_REAL_GIT="$real_git" \ + bash "$SELF" "$@" 2> "$err" + ) + } + reset_shim() { + rm -f "$shim/push.count" "$shim/push.plan" "$shim/pnpm.log" "$shim/pnpm.exit" "$shim/worktree.fail" + [ -z "${1:-}" ] || printf '%s\n' "$1" | tr ',' '\n' > "$shim/push.plan" + } + pushes() { cat "$shim/push.count" 2> /dev/null || echo 0; } + field() { printf '%s\n' "$1" | sed -n "s/^$2=//p"; } + on_origin() { "$real_git" -C "$origin" rev-parse --verify --quiet "refs/heads/$1" 2> /dev/null || echo absent; } + + # ── the probe failure classifier ────────────────────────────────────────── + st_battery 'the probe failure classifier' + st_case "git's own 403 line" \ + "$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 403")" 403 + st_case "GitHub's permission line, with no number on it" \ + "$(classify_push_failure 'remote: Permission to o/r.git denied to someone.')" 403 + st_case '⛔ `RPC failed; HTTP 403` is a 403, although it carries the words of a transport failure — checked first, or it would be retried' \ + "$(classify_push_failure 'error: RPC failed; HTTP 403 curl 22 The requested URL returned error: 403')" 403 + st_case 'an HTTP/2 status line carrying 403 is a 403' \ + "$(classify_push_failure 'error: RPC failed; HTTP/2 403')" 403 + st_case 'a proxy that refuses the CONNECT with 403 is a 403: the host is not allowed, and that is not retried either' \ + "$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': Received HTTP code 403 from proxy after CONNECT")" 403 + st_case 'a name that does not resolve is a network error' \ + "$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': Could not resolve host: github.com")" network + st_case 'a reset connection is a network error' \ + "$(classify_push_failure 'fatal: unable to access: Recv failure: Connection reset by peer')" network + st_case 'a hung-up remote is a network error' \ + "$(classify_push_failure 'fatal: the remote end hung up unexpectedly')" network + st_case 'a gateway 502 is a network error' \ + "$(classify_push_failure 'error: RPC failed; HTTP 502 curl 22 The requested URL returned error: 502')" network + st_case 'a declined hook is neither — it is not retried' \ + "$(classify_push_failure ' ! [remote rejected] HEAD -> b (pre-receive hook declined)')" other + st_case 'a 401 is neither: only a 403 is the blocked verdict and only a network error is retried' \ + "$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 401")" other + st_case 'a byte count that happens to read 403 is not a 403' \ + "$(classify_push_failure 'Writing objects: 100% (3/3), 403 bytes | 403.00 KiB/s, done.')" other + + # ── a fresh worktree ────────────────────────────────────────────────────── + st_battery 'a fresh worktree' + reset_shim + mkdir -p "$dir/pad" + out="$(run "$dir/objectstack" --branch=claude/issue-7-demo --probe --no-install --scratchpad="$dir/pad")" + rc=$? + wt="$dir/objectstack-issue-7" + st_case 'it exits 0 and the last line is the ready verdict' "$rc|$(printf '%s\n' "$out" | tail -n 1)" "0|VERDICT ready — cd $wt" + st_case 'the tree is built BESIDE the checkout, named -issue- from the branch' "$(field "$out" WORKTREE)|$([ -d "$wt" ] && echo dir)" "$wt|dir" + st_case 'it is on the branch asked for' "$("$real_git" -C "$wt" rev-parse --abbrev-ref HEAD)|$(field "$out" BRANCH)" 'claude/issue-7-demo|claude/issue-7-demo' + st_case 'it starts from the FETCHED origin/main — the commit that landed after the checkout was cloned' \ + "$("$real_git" -C "$wt" rev-parse HEAD)" "$main_sha" + st_case 'the base printed is that commit' "$(field "$out" BASE)" "$main_sha" + st_case '--base inside the tree reads the pin back' "$(run "$wt" --base)" "$main_sha" + st_case 'the pin is a file in the worktree'\''s own git dir, not in the tree' \ + "$(cat "$("$real_git" -C "$wt" rev-parse --absolute-git-dir)/$BASE_FILE_NAME")|$("$real_git" -C "$wt" status --porcelain | wc -l | tr -d ' ')" "$main_sha|0" + st_case 'with --probe the probe was pushed once, and origin now holds the empty branch at that commit' \ + "$(field "$out" PROBE)|$(pushes)|$(on_origin claude/issue-7-demo)" "pushed|1|$main_sha" + st_case 'the push set the upstream the branch was created without' \ + "$("$real_git" -C "$wt" rev-parse --abbrev-ref '@{upstream}' 2> /dev/null)" 'origin/claude/issue-7-demo' + st_case 'the scratchpad got its issue-/ directory' "$(field "$out" SCRATCH)|$([ -d "$dir/pad/issue-7" ] && echo dir)" "$dir/pad/issue-7|dir" + st_case '--no-install ran no pnpm' "$(field "$out" INSTALL)|$([ -f "$shim/pnpm.log" ] && echo ran || echo none)" 'skipped|none' + st_case 'the shared checkout was not touched: same branch, clean tree' \ + "$("$real_git" -C "$dir/objectstack" rev-parse --abbrev-ref HEAD)|$("$real_git" -C "$dir/objectstack" status --porcelain | wc -l | tr -d ' ')" 'main|0' + st_case '--base in the shared checkout has nothing to print and exits 1' "$(run "$dir/objectstack" --base)|$?" '|1' + + # ── refusals before anything is created ─────────────────────────────────── + st_battery 'refusals before anything is created' + reset_shim + mkdir -p "$dir/objectstack-issue-8" + out="$(run "$dir/objectstack" --branch=claude/issue-8-x --no-install)" + rc=$? + st_case 'a path that already exists is refused (1) and the branch was not created' \ + "$rc|$("$real_git" -C "$dir/objectstack" show-ref --verify --quiet refs/heads/claude/issue-8-x && echo branch || echo none)|$(pushes)" '1|none|0' + st_case '…and the verdict says nothing was created' "$(printf '%s\n' "$out" | tail -n 1)" 'VERDICT refused — nothing was created' + rmdir "$dir/objectstack-issue-8" + "$real_git" -C "$dir/objectstack" branch claude/issue-8-x main + out="$(run "$dir/objectstack" --branch=claude/issue-8-x --no-install)" + st_case 'a local branch that already exists is refused (1), never reset, and no tree is built' \ + "$?|$([ -e "$dir/objectstack-issue-8" ] && echo built || echo none)|$(grep -c 'never reset' "$err")" '1|none|1' + "$real_git" -C "$dir/objectstack" branch -D claude/issue-8-x > /dev/null + "$real_git" -C "$dir/seed" push --quiet origin HEAD:refs/heads/claude/issue-8-x + out="$(run "$dir/objectstack" --branch=claude/issue-8-x --no-install)" + st_case 'a branch already on origin with no --resume-from is refused (1): no tree, no local branch, no push' \ + "$?|$([ -e "$dir/objectstack-issue-8" ] && echo built || echo none)|$("$real_git" -C "$dir/objectstack" show-ref --verify --quiet refs/heads/claude/issue-8-x && echo branch || echo none)|$(pushes)" '1|none|none|0' + st_case '…and the refusal names both readings: the resume flag, and another session'\''s work in flight' \ + "$(grep -c -- '--resume-from=BRANCH@SHA' "$err")|$(grep -c 'in flight' "$err")" '1|1' + : > "$shim/worktree.fail" + out="$(run "$dir/objectstack" --branch=claude/issue-8-z --no-install)" + rc=$? + st_case 'a `git worktree add` that fails after making the branch is refused (1) WITHOUT the words "nothing was created": the verdict names the branch it left' \ + "$rc|$(printf '%s\n' "$out" | tail -n 1)|$([ -e "$dir/objectstack-issue-8" ] && echo built || echo none)" \ + '1|VERDICT refused — no tree was built; the local branch claude/issue-8-z was left behind|none' + rm -f "$shim/worktree.fail" + "$real_git" -C "$dir/objectstack" branch -D claude/issue-8-z > /dev/null + out="$(run "$dir/objectstack" --branch=claude/project-thread-abc123 --no-probe --no-install)" + st_case 'a branch with no issue number has no default tree name: usage (2)' "$?" 2 + out="$(run "$dir/objectstack" --no-install)" + st_case 'no --branch is usage (2)' "$?" 2 + out="$(run "$dir/objectstack" --branch=claude/issue-8-y --worktree=../elsewhere --no-install)" + st_case '--worktree takes a NAME beside the checkout, never a path: usage (2)' "$?|$([ -e "$dir/elsewhere" ] && echo built || echo none)" '2|none' + out="$(run "$dir/objectstack" --branch=main --worktree=objectstack-main --no-install)" + st_case 'the trunk is never a task branch: usage (2)' "$?" 2 + out="$(run "$dir/objectstack" --branch=claude/issue-8-y --frobnicate)" + st_case 'an unknown flag is usage (2)' "$?" 2 + mkdir -p "$dir/plain" + out="$(run "$dir/plain" --branch=claude/issue-8-y --no-install)" + st_case 'outside any git checkout it is refused (1)' "$?" 1 + + # ── resume from a claimed sha ───────────────────────────────────────────── + st_battery 'resume from a claimed sha' + reset_shim + ( + cd "$dir/seed" || exit 1 + "$real_git" checkout --quiet -b claude/issue-9-resume "$main_sha~1" + echo resumed > g.txt + "$real_git" add g.txt + "$real_git" commit --quiet -m 'work in flight' + "$real_git" push --quiet origin claude/issue-9-resume + "$real_git" checkout --quiet main + ) + tip="$("$real_git" -C "$dir/seed" rev-parse claude/issue-9-resume)" + out="$(run "$dir/objectstack" --resume-from="claude/issue-9-resume@deadbeef" --no-install)" + st_case 'a Resume-from sha that is not the tip of origin/BRANCH is refused (1) before anything is built' \ + "$?|$([ -e "$dir/objectstack-issue-9" ] && echo built || echo none)|$(grep -c 'the branch moved after the Release' "$err")" '1|none|1' + out="$(run "$dir/objectstack" --branch=claude/issue-9-other --resume-from="claude/issue-9-resume@$tip" --no-install)" + st_case 'a --branch that differs from the resumed one is usage (2): a resume continues the SAME branch' "$?" 2 + out="$(run "$dir/objectstack" --resume-from=claude/issue-9-resume --no-install)" + st_case '--resume-from without @SHA is usage (2)' "$?" 2 + out="$(run "$dir/objectstack" --resume-from="claude/issue-9-resume@$(printf '%s' "$tip" | cut -c1-12 | tr 'a-f' 'A-F')" --probe --no-install)" + rc=$? + wt="$dir/objectstack-issue-9" + st_case 'with the claimed sha (abbreviated, any case) the same-name branch is built from origin/BRANCH, at that commit' \ + "$rc|$("$real_git" -C "$wt" rev-parse --abbrev-ref HEAD)|$("$real_git" -C "$wt" rev-parse HEAD)" "0|claude/issue-9-resume|$tip" + st_case 'a resumed tree is NOT pinned at creation: the base is taken after the merge of origin/main' "$(field "$out" BASE)" unpinned + st_case '…and the line that says so names the merge script and --pin-base' \ + "$(grep -c 'os-regen-merge.sh' "$err")|$(grep -c -- '--pin-base' "$err")" '1|1' + st_case 'the probe on a resumed branch pushes nothing new: origin keeps the claimed commit' "$(field "$out" PROBE)|$(on_origin claude/issue-9-resume)" "pushed|$tip" + st_case '--pin-base inside the tree pins HEAD and prints it' "$(run "$wt" --pin-base)|$(run "$wt" --base)" "$tip|$tip" + "$real_git" -C "$wt" -c user.email=selftest@objectstack.ai -c user.name=selftest commit --quiet --allow-empty -m later + out="$(run "$wt" --pin-base)" + st_case '⛔ a second --pin-base is refused (1) and the pin has not moved, although HEAD has' "$?|$(run "$wt" --base)" "1|$tip" + out="$(run "$dir/objectstack" --pin-base)" + st_case '⛔ --pin-base in the shared checkout is refused (1): it is never a task tree' \ + "$?|$([ -f "$("$real_git" -C "$dir/objectstack" rev-parse --absolute-git-dir)/$BASE_FILE_NAME" ] && echo pinned || echo none)" '1|none' + out="$(run "$dir/plain" --base)" + st_case '--base outside any git checkout exits 1 with empty stdout' "$?|$out" '1|' + + # ── the probe ───────────────────────────────────────────────────────────── + st_battery 'the probe' + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-30-noflag --no-install)" + rc=$? + st_case '⛔ NO FLAG, the very spelling rule 1 prints (claude/issue--): the tree is built and NOTHING is pushed — zero pushes, origin has no such branch' \ + "$rc|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-30-noflag)|$([ -d "$dir/objectstack-issue-30" ] && echo dir)" '0|0|skipped|absent|dir' + st_case '…the base is pinned all the same, and the line printed says what a self-built branch still owes' \ + "$(field "$out" BASE)|$(grep -c 'run this command again with --probe' "$err")" "$main_sha|1" + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-30-noflag --probe --no-install)" + st_case '…and the same command WITH --probe completes it: one push, the empty branch on origin, nothing re-created' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-30-noflag)|$(grep -c 'nothing is re-created' "$err")" "0|1|pushed|$main_sha|1" + reset_shim + out="$(run "$dir/objectstack" --branch=claude/project-thread-noflag --worktree=objectstack-thread-noflag --no-install)" + st_case 'a branch under any other spelling needs no flag to be built, and is not pushed either' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/project-thread-noflag)" '0|0|skipped|absent' + reset_shim 403 + out="$(run "$dir/objectstack" --branch=claude/issue-10-denied --probe --backoff=0,0)" + rc=$? + st_case '⛔ a 403 exits 3 after exactly ONE push — it is never retried' "$rc|$(pushes)|$(field "$out" PROBE)" '3|1|403' + st_case '…the verdict is the blocked one' "$(printf '%s\n' "$out" | tail -n 1 | cut -c1-19)" 'VERDICT blocked-403' + st_case '…the tree stands and its base is pinned, so the report can name both' \ + "$([ -d "$dir/objectstack-issue-10" ] && echo dir)|$(field "$out" BASE)" "dir|$main_sha" + st_case '…and it STOPPED there: no pnpm install ran after a refused probe' "$(field "$out" INSTALL)|$([ -f "$shim/pnpm.log" ] && echo ran || echo none)" 'skipped|none' + reset_shim network,network + out="$(run "$dir/objectstack" --branch=claude/issue-11-flaky --probe --no-install --backoff=0,0)" + st_case 'two network errors, then the real push: retried on the backoff schedule, exit 0 after 3 attempts' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-11-flaky)" "0|3|pushed|$main_sha" + reset_shim network,network,network + out="$(run "$dir/objectstack" --branch=claude/issue-12-down --probe --no-install --backoff=0,0)" + rc=$? + st_case 'a network error on every attempt is given up at 1 + the schedule'\''s length: exit 4, three pushes, never a loop' \ + "$rc|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-12-down)" '4|3|network|absent' + st_case '…and the verdict says the same command retries it' "$(printf '%s\n' "$out" | tail -n 1 | grep -c 'the same command retries it')" 1 + reset_shim network + out="$(run "$dir/objectstack" --branch=claude/issue-13-once --probe --no-install --backoff=)" + st_case 'an empty --backoff spends no retry: one push, exit 4' "$?|$(pushes)" '4|1' + reset_shim other + out="$(run "$dir/objectstack" --branch=claude/issue-14-hook --probe --no-install --backoff=0,0)" + st_case 'a refusal that is neither is exit 5 after ONE push — only a network error is retried' "$?|$(pushes)|$(field "$out" PROBE)" '5|1|refused' + reset_shim + out="$(run "$dir/objectstack" --branch=claude/project-thread-abc123 --worktree=objectstack-thread --no-probe --no-install)" + rc=$? + st_case '--no-probe is still accepted and says the default out loud: the tree is built, zero pushes, origin has no such branch' \ + "$rc|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/project-thread-abc123)|$([ -d "$dir/objectstack-thread" ] && echo dir)|$(grep -c -- '--no-probe was given' "$err")" '0|0|skipped|absent|dir|1' + st_case '…and it still pins the base' "$(field "$out" BASE)" "$main_sha" + reset_shim + out="$(run "$dir/objectstack" --branch=release-notes-fix --worktree=objectstack-notes --probe --no-install)" + st_case 'a self-built branch with another spelling is probed when the caller says --probe' \ + "$?|$(pushes)|$(on_origin release-notes-fix)" "0|1|$main_sha" + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-15-both --probe --no-probe --no-install)" + st_case '--probe and --no-probe together are usage (2)' "$?|$(pushes)" '2|0' + out="$(run "$dir/objectstack" --branch=claude/issue-15-both --no-install --backoff=soon)" + st_case 'a --backoff that is not seconds is usage (2), before anything is built' "$?|$([ -e "$dir/objectstack-issue-15" ] && echo built || echo none)" '2|none' + st_case 'the default schedule is four retries, 30 seconds in all' "$DEFAULT_BACKOFF" '2,4,8,16' + + # ── re-run, scratchpad and install ──────────────────────────────────────── + st_battery 're-run, scratchpad and install' + reset_shim + wt="$dir/objectstack-issue-7" + out="$(run "$dir/objectstack" --branch=claude/issue-7-demo --probe --no-install)" + st_case 'a re-run with --probe for a tree already built and already on origin exits 0, re-creates nothing and pushes nothing' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(grep -c 'nothing is re-created' "$err")" '0|0|on-origin|1' + st_case '…and reads the SAME base back' "$(field "$out" BASE)" "$main_sha" + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-12-down --probe --no-install)" + st_case 'the re-run after a network give-up sends the probe that was owed: one push, exit 0, the branch on origin' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-12-down)" "0|1|pushed|$main_sha" + reset_shim + "$real_git" -C "$dir/objectstack-issue-13" -c user.email=selftest@objectstack.ai -c user.name=selftest commit --quiet --allow-empty -m 'work' + out="$(run "$dir/objectstack" --branch=claude/issue-13-once --probe --no-install)" + st_case '⛔ a re-run never pushes WORK as a probe: a branch with commits and absent from origin reads `owed`, zero pushes' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-13-once)" '0|0|owed|absent' + out="$(run "$dir/objectstack" --branch=claude/issue-99-other --worktree=objectstack-issue-7 --no-install)" + st_case 'a path that is another branch'\''s worktree is refused (1); the refusal names the branch it holds and the flag a second branch of one card takes' \ + "$?|$(grep -c 'it holds claude/issue-7-demo' "$err")|$(grep -c -- '--worktree=' "$err")" '1|1|1' + reset_shim + "$real_git" -C "$dir/objectstack" worktree add --quiet --no-track "$dir/objectstack-issue-21" -b claude/issue-21-hand origin/main 2> /dev/null + out="$(run "$dir/objectstack" --branch=claude/issue-21-hand --probe --no-install)" + st_case 'a hand-built tree with no pin is never probed on a guess that it is empty: `owed`, zero pushes, and the line says the base is unpinned rather than "no longer empty"' \ + "$?|$(pushes)|$(field "$out" PROBE)|$(field "$out" BASE)|$(grep -c 'has no pinned base' "$err")|$(grep -c 'no longer an empty branch' "$err")" '0|0|owed|unpinned|1|0' + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-16-install)" + rc=$? + st_case 'without --no-install, pnpm install runs once, inside the NEW tree' \ + "$rc|$(field "$out" INSTALL)|$(cat "$shim/pnpm.log")" "0|done|$dir/objectstack-issue-16|install" + reset_shim + echo 1 > "$shim/pnpm.exit" + out="$(run "$dir/objectstack" --branch=claude/issue-17-broken --probe)" + rc=$? + st_case 'a failing pnpm install is exit 6, with the tree, the pin and the probe standing' \ + "$rc|$(field "$out" INSTALL)|$(field "$out" PROBE)|$(field "$out" BASE)" "6|failed|pushed|$main_sha" + st_case '…and the verdict names the directory to run it in' "$(printf '%s\n' "$out" | tail -n 1)" "VERDICT install-failed — run pnpm install in $dir/objectstack-issue-17" + reset_shim + out="$(run "$dir/objectstack" --branch=claude/issue-18-pad --no-install --scratchpad="$dir/no-such-dir")" + st_case 'a --scratchpad that is not a directory is usage (2), before anything is built' "$?|$([ -e "$dir/objectstack-issue-18" ] && echo built || echo none)" '2|none' + out="$(run "$dir/objectstack" --branch=release-notes-2 --worktree=objectstack-notes-2 --probe --no-install --scratchpad="$dir/pad")" + st_case '--scratchpad with a branch that carries no issue number is usage (2): there is no issue-/ to make' "$?" 2 + reset_shim + out="$(run "$dir/objectstack-issue-7" --branch=claude/issue-19-nested --no-install)" + st_case 'run from INSIDE another worktree, the new tree is still built beside the shared checkout' \ + "$?|$(field "$out" WORKTREE)" "0|$dir/objectstack-issue-19" + mkdir -p "$dir/hotcrm-src" + "$real_git" clone --quiet "$origin" "$dir/hotcrm" + out="$(run "$dir/hotcrm" --branch=claude/issue-20-sibling --no-install)" + st_case 'run from a SIBLING repository'\''s checkout, the tree takes that repository'\''s name' \ + "$?|$(field "$out" WORKTREE)" "0|$dir/hotcrm-issue-20" + st_case 'every stdout of a build is KEY=value lines and one VERDICT line' \ + "$(printf '%s\n' "$out" | grep -Evc '^(WORKTREE|BRANCH|BASE|PROBE|SCRATCH|INSTALL)=|^VERDICT ')" 0 + + # ── what the script never spells ────────────────────────────────────────── + # Read from the part of this file ABOVE the self-test, with comment lines + # dropped: the cases below would otherwise match their own text. + st_battery 'what the script never spells' + plan="$(sed -n '1,/^# self-test — offline/p' "$SELF" | grep -v '^[[:space:]]*#')" + st_case '⛔ no force anywhere: not on a push, a worktree, a branch or a checkout' \ + "$(printf '%s\n' "$plan" | grep -Ec -- '--force|git[^|;]*[[:space:]](-f|-B)([[:space:]]|$)')" 0 + st_case 'the one `worktree add` carries --no-track and a NEW branch (-b)' \ + "$(printf '%s\n' "$plan" | grep -c 'worktree add --no-track "$path" -b "$BRANCH" "$start"')|$(printf '%s\n' "$plan" | grep -c '" worktree add ')" '1|1' + st_case 'the one push is `push -u origin `, and nothing deletes or rewrites a remote ref' \ + "$(printf '%s\n' "$plan" | grep -c 'push -u origin "$branch"')|$(printf '%s\n' "$plan" | grep -Ec 'push .*(--delete|--mirror|:refs/)|git .*reset --hard|git .*checkout ')" '1|0' + st_case 'the shared checkout is only ever READ through -C "$top": fetch, ls-remote, show-ref, rev-parse, worktree' \ + "$(printf '%s\n' "$plan" | grep -Eo 'git -C "\$top" [a-z-]+' | sort -u | tr '\n' ' ')" 'git -C "$top" fetch git -C "$top" ls-remote git -C "$top" rev-parse git -C "$top" show-ref git -C "$top" worktree ' + + # ── the floor: every declared battery ran, and ran its cases ────────────── + local declared line name min count breached=0 + declared="$(printf '%s\n' "$ST_BATTERIES" | grep -c '=')" + if [ "$declared" -lt "$ST_BATTERY_FLOOR" ]; then + breached=1 + printf ' ✗ ST_BATTERIES declares %s batteries, below the pinned %s — a battery deleted from the roster takes its floor with it.\n' "$declared" "$ST_BATTERY_FLOOR" >&2 + fi + while IFS= read -r line; do + [ -n "$line" ] || continue + name="${line%=*}" + min="${line##*=}" + count="$(printf '%s' "$ST_SEEN" | grep -cFx -- "$name")" + if [ "$count" -lt "$min" ]; then + breached=1 + printf ' ✗ self-test battery "%s" registered %s case(s), below its pinned floor of %s — cases that used to run no longer do.\n' "$name" "$count" "$min" >&2 + fi + done << EOF +$ST_BATTERIES +EOF + while IFS= read -r line; do + [ -n "$line" ] || continue + if ! printf '%s\n' "$ST_BATTERIES" | grep -qF -- "${line}="; then + breached=1 + printf ' ✗ a case registered under "%s", which is not a declared battery — nothing floors it.\n' "$line" >&2 + fi + done << EOF +$(printf '%s' "$ST_SEEN" | sort -u) +EOF + + local total + total="$(printf '%s' "$ST_SEEN" | grep -c '')" + if [ "$breached" -ne 0 ] || [ "$ST_FAIL" -gt 0 ]; then + printf '✗ dev-worktree self-test: %s of %s case(s) failed%s.\n' "$ST_FAIL" "$total" "$([ "$breached" -ne 0 ] && printf ', and a battery floor was breached')" >&2 + return 1 + fi + printf '✓ dev-worktree self-test: %s cases pass across %s batteries — offline, a bare fixture origin, no network.\n' "$total" "$declared" + SELF_TEST_REACHED_VERDICT=1 + return 0 +} + +# --------------------------------------------------------------------------- +# dispatch +# --------------------------------------------------------------------------- + +BRANCH='' +WORKTREE='' +RESUME_FROM='' +PROBE_MODE='' +SCRATCHPAD='' +INSTALL=1 +BACKOFF="$DEFAULT_BACKOFF" +MODE='build' + +set_probe_mode() { + if [ -n "$PROBE_MODE" ] && [ "$PROBE_MODE" != "$1" ]; then + die_usage '--probe and --no-probe contradict each other' + fi + PROBE_MODE="$1" +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --self-test) + rc=0 + self_test || rc=$? + if [ "$rc" -eq 0 ] && [ "$SELF_TEST_REACHED_VERDICT" -ne 1 ]; then + printf '✗ dev-worktree self-test: returned without reaching its verdict.\n' >&2 + exit 1 + fi + exit "$rc" + ;; + --base) MODE='base' ;; + --pin-base) MODE='pin-base' ;; + --branch=*) BRANCH="${1#--branch=}" ;; + --worktree=*) WORKTREE="${1#--worktree=}" ;; + --resume-from=*) RESUME_FROM="${1#--resume-from=}" ;; + --scratchpad=*) SCRATCHPAD="${1#--scratchpad=}" ;; + --backoff=*) BACKOFF="${1#--backoff=}" ;; + --probe) set_probe_mode 'probe' ;; + --no-probe) set_probe_mode 'no-probe' ;; + --no-install) INSTALL=0 ;; + --help | -h) + usage + exit 0 + ;; + *) die_usage "unrecognised argument: $1" ;; + esac + shift +done + +case "$MODE" in + base) mode_base ;; + pin-base) mode_pin_base ;; + *) + rc=0 + mode_build || rc=$? + exit "$rc" + ;; +esac diff --git a/scripts/pm/git-history.mjs b/scripts/pm/git-history.mjs index 1a54ee0b67d..b93de769ed7 100644 --- a/scripts/pm/git-history.mjs +++ b/scripts/pm/git-history.mjs @@ -3,9 +3,10 @@ /** * git-history.mjs — answer a "how many commits on in " question, - * or a "which commit last touched on " question, or REFUSE, so - * neither a churn number nor a provenance sha can ever be quoted from - * truncated history (#9878). + * or a "which commit last touched on " question, or an "is + * in 's history" question, or REFUSE, so neither a churn number, nor a + * provenance sha, nor a "not an ancestor" can ever be quoted from truncated + * history (#9878). * * node scripts/pm/git-history.mjs count --since=2026-07-19 [--until=2026-08-19] * node scripts/pm/git-history.mjs count --days=30 [--ref=origin/main] [--path=packages/core] @@ -13,11 +14,15 @@ * node scripts/pm/git-history.mjs ensure --since=2026-07-19 # deepen + prove, answer nothing * node scripts/pm/git-history.mjs touch --path= [--ref=origin/main] [--format=%H] * # the last commit on that touched , PROVEN + * node scripts/pm/git-history.mjs ancestor --commit= [--ref=origin/main] [--control=] + * # is in 's history: yes or no, PROVEN * node scripts/pm/git-history.mjs --self-test * * Exit codes: **0** answered, and the answer is provable · **2** refused — the - * window (or the touch) is not provably present locally and could not be made - * so · **1** usage or environment. + * window (or the touch, or the negative) is not provably present locally and + * could not be made so · **1** usage or environment. `ancestor` alone has one + * more: **0** is a proven yes and **3** a proven no (the sixth trap below says + * why a no is neither 0 nor 1). * * On success the ANSWER alone goes to stdout (so `$(...)` capture works) and a * one-line method receipt goes to stderr, ready to paste beside the number. @@ -176,6 +181,56 @@ * The self-test pins a piped `log`, many buffers long, byte for byte against * the same `log` sent to a file. * + * ## The sixth trap, same graft: `merge-base --is-ancestor` says "no" for a real ancestor + * + * A shallow clone can only WITHHOLD an ancestor path; it never invents one. So + * the containment reading fails in one direction: exit 0 (an ancestor) proves + * itself in any clone, and exit 1 (not an ancestor) is what a cut produces for + * a commit that sits below it. The checks that want the negative — not yet + * released, not on main, a blocker not landed — are the ones that get it free. + * Measured on this file's 40-commit self-test fixture cloned at `--depth=5` + * (floor c35), git 2.43.0: + * + * | `git merge-base --is-ancestor origin/main` | exit | + * |-----------------------------------------------------------------------|------| + * | c38 — inside the window | 0 | + * | c2 — in main's real history, its object not in the clone | 128 | + * | c2 — the same commit after `git fetch origin ` put the object in | **1** | + * | a commit built on c2 that never merged | 1 | + * + * Rows three and four are one exit code for opposite facts, and row two is a + * third number that `if ! git merge-base --is-ancestor …` reads as the same + * "no". The prose procedure that used to stand here in a skill file was to run + * a second leg by hand: a commit known to be in the ref's history and at least + * as deep as the tested one must answer 0 on the same clone, or the negative + * is void. `ancestor` runs both legs and names its control itself: + * + * - a YES is printed at once — the path exists here, so it exists; + * - a NO stands when no cut can hide the tested commit: either the ref's + * history carries no graft at all (every root under it is a real root), or + * every graft boundary under the ref is OLDER than the tested commit by the + * skew margin. A real ancestor that the walk missed must sit below a + * boundary, and a boundary is its descendant, so it cannot predate it. The + * newest boundary is therefore the control leg: it is in the ref's history + * (it is where the walk stopped; the leg is still run, and its exit code + * is the one the receipt prints) and it is deeper than the tested commit. + * `--control=` adds the operator's own leg on top: it must answer 0 + * and must not be newer than the tested commit. A walk that could not be + * read is never "no graft": it is refused; + * - otherwise it deepens (`--deepen=N` doubling, then `--unshallow`, the same + * additive ladder `touch` climbs) and reads again, and REFUSES with exit 2 + * and empty stdout when the negative still cannot be told from a cut. + * + * "Deeper" is read by COMMITTER DATE, the reading the windowed commands + * already rest on. A history whose committer dates run backwards along + * ancestry (a `--committer-date-is-author-date` rebase) defeats it; + * `--margin-days` (default 7) is the slack, and a complete clone needs none. + * + * A proven no exits **3**, not 0 and not 1. Not 0, so `ancestor … && echo + * landed` cannot read a no as a yes. Not 1, because 1 is this tool's usage + * exit: a mistyped flag must never be readable as "not an ancestor", which is + * the exact false negative this command exists to end. + * * ## Cost, measured — because a tool nobody runs fixes nothing * * | case | wall | @@ -218,11 +273,12 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'bare dates: the instant the proof reads is the instant git counts': 16, 'touch: the provenance reading a shallow clone fabricates': 26, 'piped stdout: the answer a pipe reads is the answer a file holds': 4, + 'ancestor: the negative a shallow clone fabricates': 38, }); // DELETING an entry silences that battery's floor exactly as effectively as // zeroing it, so the roster's own size is pinned too. -const SELF_TEST_BATTERY_FLOOR = 6; +const SELF_TEST_BATTERY_FLOOR = 7; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -701,6 +757,329 @@ export function ensureTouchProvable({ return { answered: false, sha: r.sha, verdict: r.verdict, steps, reason: r.verdict.reason }; } +// ── ancestor: the containment reading ──────────────────────────────────────── + +/** + * `ancestor`'s exit code for a PROVEN no. Its own number: 1 is this tool's + * usage exit, and a mistyped flag must never be readable as "not an ancestor" + * (the sixth trap in the header). + */ +export const EXIT_NOT_ANCESTOR = 3; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** The full sha `rev` names as a COMMIT here, or null when it resolves to none. */ +function commitShaOf(cwd, rev) { + if (typeof rev !== 'string' || rev === '' || rev.startsWith('-')) return null; + const out = git(['rev-parse', '--verify', '--quiet', `${rev}^{commit}`], { cwd, allowFail: true }); + const sha = (out || '').trim(); + return /^[0-9a-f]{40,64}$/.test(sha) ? sha : null; +} + +/** + * Why a hex string that resolves to no commit is NOT simply absent, or null + * when it is: git lists every object the prefix can mean, and two or more is + * an ambiguous prefix, one is an object that is not a commit. Either read as + * "not in this clone" would print a receipt that is untrue. + * + * @param {string} cwd + * @param {string} hex + * @param {(cwd: string, hex: string) => string[]} [candidatesOf] injected by the self-test + * @returns {string|null} + */ +export function hexPrefixProblem(cwd, hex, candidatesOf = disambiguate) { + const candidates = candidatesOf(cwd, hex); + if (candidates.length > 1) { + return `is ambiguous here: ${candidates.length} objects begin with it (give more digits)`; + } + if (candidates.length === 1) return `names an object that is not a commit (${candidates[0].slice(0, 9)})`; + return null; +} + +/** Every object id in this clone that begins with `hex`. */ +function disambiguate(cwd, hex) { + const out = git(['rev-parse', `--disambiguate=${hex}`], { cwd, allowFail: true }); + return (out || '').split('\n').map((l) => l.trim()).filter(Boolean); +} + +/** Committer date of `sha` in ms, or null when it cannot be read. */ +function commitDateMs(cwd, sha) { + const out = git(['log', '-1', '--format=%cI', sha], { cwd, allowFail: true }); + const ms = out === null ? NaN : Date.parse(out.trim()); + return Number.isFinite(ms) ? ms : null; +} + +/** + * `git merge-base --is-ancestor `, raw: the exit status as git + * gave it, never thrown. 0 is an ancestor, 1 is not one AS FAR AS THIS CLONE + * CAN SEE, and anything else (128 for an object that is not here) is no + * reading at all. + * + * @returns {{status: number|null, stderr: string}} + */ +export function rawIsAncestor(cwd, commit, ref) { + const r = spawnSync('git', ['merge-base', '--is-ancestor', commit, ref], { + cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + return { status: r.status, stderr: String(r.stderr || '').trim() }; +} + +/** + * Every commit under `ref` where the walk is CUT: the parentless commits + * reachable from it that are grafted rather than real roots, each with its + * committer date. Empty means the history under `ref` is complete here, + * whatever the repository's shallow flag says about some other ref. + * + * Empty is the one value that PROVES a negative, so nothing unread may turn + * into it. A walk that could not run at all answers `null` — for ANY failure + * of the `rev-list`, not only a ref that does not resolve — and the caller + * refuses. A parentless commit whose parents could not be read is neither a + * boundary nor a real root: it comes back marked `undecided`, which + * `negativeIsProven()` refuses on. (`isGraftBoundary()` answers false for + * that commit, which is right for `touch`, where unreadable is refused on its + * own leg, and would be a "real root" here.) + * + * `read` injects the two parent readers, for the self-test only. + * + * @returns {Array<{sha: string, ms: number|null, undecided?: true}>|null} null when the walk could not be read. + */ +export function graftBoundaries(cwd, ref, read = {}) { + const parentsOf = read.parentsOf ?? objectParents; + const traversalOf = read.traversalOf ?? traversalParents; + const out = git(['rev-list', '--max-parents=0', '--format=%cI', ref], { cwd, allowFail: true }); + if (out === null) return null; + const found = []; + let sha = null; + for (const line of out.split('\n')) { + if (line.startsWith('commit ')) { sha = line.slice('commit '.length).trim(); continue; } + if (line === '' || sha === null) continue; + const parsed = Date.parse(line.trim()); + const ms = Number.isFinite(parsed) ? parsed : null; + const named = parentsOf(cwd, sha); + const used = named === null ? null : traversalOf(cwd, sha); + if (named === null || used === null) { + found.push({ sha, ms, undecided: true }); + } else if (named.map((p) => p.sha).sort().join(' ') !== [...used].sort().join(' ')) { + found.push({ sha, ms }); + } + sha = null; + } + return found; +} + +/** + * Does a NEGATIVE stand — can no cut under the ref be hiding the tested + * commit? Pure, so the self-test pins every arm with injected numbers. + * + * - no boundary at all: the history under the ref is complete, and a walk of + * a complete history that missed the commit missed nothing (`by: complete`); + * - otherwise the NEWEST boundary decides, as it does for a window: a real + * ancestor the walk missed sits below some boundary, a boundary is its + * descendant, and a descendant does not predate its ancestor. So when even + * the newest boundary is older than the tested commit by the skew margin, + * none can hide it (`by: floor`), and that boundary is the control leg: + * in the ref's history by construction, and deeper than the tested commit; + * - a tested commit with no date here (its object is absent) can be placed + * against nothing, a boundary with no readable date decides nothing, and + * a parentless commit that could not be read (`undecided`) is not known to + * be a real root, so it proves nothing either. + * + * @param {{boundaries: Array<{sha: string, ms: number|null, undecided?: true}>, testedMs: number|null, marginDays?: number}} input + * @returns {{proven: boolean, by: 'complete'|'floor'|null, + * control: {sha: string, ms: number|null}|null, + * why: 'boundary-unread'|'tested-absent'|'boundary-undated'|'floor-intrudes'|null}} + */ +export function negativeIsProven({ boundaries, testedMs, marginDays = DEFAULT_MARGIN_DAYS }) { + if (boundaries.length === 0) return { proven: true, by: 'complete', control: null, why: null }; + const unread = boundaries.find((b) => b.undecided === true); + if (unread) return { proven: false, by: null, control: unread, why: 'boundary-unread' }; + const undated = boundaries.find((b) => b.ms === null); + if (undated) return { proven: false, by: null, control: undated, why: 'boundary-undated' }; + const newest = boundaries.reduce((a, b) => (b.ms > a.ms ? b : a)); + if (testedMs === null) return { proven: false, by: null, control: newest, why: 'tested-absent' }; + if (newest.ms < testedMs - marginDays * DAY_MS) return { proven: true, by: 'floor', control: newest, why: null }; + return { proven: false, by: null, control: newest, why: 'floor-intrudes' }; +} + +const isoDay = (ms) => (ms === null ? 'undated' : new Date(ms).toISOString().slice(0, 10)); +const short9 = (sha) => String(sha).slice(0, 9); + +/** + * One reading of "is `commit` in `ref`'s history", fetching nothing. Both + * legs, with the exit code each one gave, travel in the result so the receipt + * can print them. + * + * @returns {{state: 'yes'|'no'|'unproven'|'unreadable', deepenCanHelp?: boolean, refSha: string|null, tested: string|null, + * testedStatus: number|null, testedMs: number|null, by: 'complete'|'floor'|null, + * boundaries: Array<{sha: string, ms: number|null, undecided?: true}>, + * control: {sha: string, ms: number|null}|null, controlStatus: number|null, + * operator: {sha: string|null, status: number|null, ms: number|null, ok: boolean}|null, + * reason: string|null}} + */ +export function ancestorReading({ + cwd, commit, ref, control, marginDays = DEFAULT_MARGIN_DAYS, readBoundaries = graftBoundaries, +}) { + const base = { + refSha: null, tested: null, testedStatus: null, testedMs: null, by: null, boundaries: [], control: null, + controlStatus: null, operator: null, + }; + const refSha = commitShaOf(cwd, ref); + if (refSha === null) { + return { ...base, state: 'unreadable', reason: `ref '${ref}' does not resolve to a commit in this checkout` }; + } + const tested = commitShaOf(cwd, commit); + let testedStatus = null; + let testedMs = null; + if (tested !== null) { + const raw = rawIsAncestor(cwd, tested, refSha); + testedStatus = raw.status; + if (raw.status === 0) { + return { ...base, state: 'yes', refSha, tested, testedStatus, reason: null }; + } + if (raw.status !== 1) { + return { + ...base, state: 'unreadable', refSha, tested, testedStatus, + reason: `git merge-base --is-ancestor exited ${raw.status}, which is neither answer${raw.stderr ? ` (${raw.stderr})` : ''}`, + }; + } + testedMs = commitDateMs(cwd, tested); + } + // ⛔ Never `?? []`: an empty list is "the history is complete", the one + // value that proves a negative, and a walk that could not be read is not it. + const boundaries = readBoundaries(cwd, refSha); + if (boundaries === null) { + return { + ...base, state: 'unreadable', refSha, tested, testedStatus, testedMs, + reason: + `the graft boundaries under '${ref}' could not be read (git rev-list failed), so whether this clone's ` + + 'history of it is cut is unknown — and an unread history is not a complete one', + }; + } + const neg = negativeIsProven({ boundaries, testedMs, marginDays }); + // The floor's control leg is RUN, not assumed: the receipt prints the exit + // code git gave for it, and a boundary that does not answer 0 voids the no. + const controlStatus = neg.by === 'floor' ? rawIsAncestor(cwd, neg.control.sha, refSha).status : null; + const reading = { ...base, refSha, tested, testedStatus, testedMs, boundaries, control: neg.control, controlStatus }; + + // The operator's own control leg, when one was named. It can only ADD a + // requirement: it never stands in for the floor, because a commit the + // operator knows to be in the history says nothing about a second cut on + // another line of it. + let operator = null; + if (control !== undefined) { + const sha = commitShaOf(cwd, control); + const status = sha === null ? null : rawIsAncestor(cwd, sha, refSha).status; + const ms = sha === null ? null : commitDateMs(cwd, sha); + let problem = null; + if (sha === null) problem = `the control ${control} is not a commit in this clone`; + else if (status !== 0) { + problem = + `the control leg answered exit ${status}: ${short9(sha)} is not in '${ref}' as this clone sees it, so the ` + + "negative is void (a control is a commit KNOWN to be in the ref's history)"; + } else if (testedMs !== null && ms !== null && ms > testedMs) { + problem = + `the control ${short9(sha)} (${isoDay(ms)}) is NEWER than the tested commit (${isoDay(testedMs)}) — a near ` + + 'relative inside the shallow window answers 0 on every clone and proves nothing about a deeper commit'; + } + operator = { sha, status, ms, ok: problem === null }; + // A control that is too SHALLOW is the operator's choice of commit, and no + // deepen changes which commit was named; one that is absent or answers 1 + // is what a deepen exists to turn. + const nearRelative = sha !== null && status === 0 && problem !== null; + if (problem !== null) return { ...reading, state: 'unproven', deepenCanHelp: !nearRelative, operator, reason: problem }; + } + + if (neg.proven && neg.by === 'floor' && controlStatus !== 0) { + return { + ...reading, state: 'unproven', deepenCanHelp: true, operator, + reason: + `the control leg answered exit ${controlStatus}: the graft boundary ${short9(neg.control.sha)} did not read as ` + + `in '${ref}', so the negative is void`, + }; + } + if (neg.proven) return { ...reading, state: 'no', by: neg.by, operator, reason: null }; + + const cut = `this clone's history of '${ref}' is cut at ${boundaries.length} graft boundar${boundaries.length === 1 ? 'y' : 'ies'}`; + let reason; + if (neg.why === 'boundary-unread') { + reason = + `the parentless commit ${short9(neg.control.sha)} under '${ref}' could not be read, so whether the history is ` + + 'cut there or really begins there is unknown — it is not counted as a real root'; + } else if (neg.why === 'tested-absent' && tested !== null) { + reason = + `the commit date of ${short9(tested)} could not be read, and ${cut} (newest ${short9(neg.control.sha)}, ` + + `${isoDay(neg.control.ms)}) — the commit cannot be placed against the cut`; + } else if (neg.why === 'tested-absent') { + reason = + `${commit} is not an object in this clone, and ${cut} (newest ${short9(neg.control.sha)}, ${isoDay(neg.control.ms)}) — ` + + 'it may sit below one of them, or nowhere in this history at all, and nothing here tells those apart'; + } else if (neg.why === 'boundary-undated') { + reason = `${cut} and ${short9(neg.control.sha)} carries no readable commit date, so the cut cannot be placed against the tested commit`; + } else { + reason = + `raw git says exit 1, and ${cut} whose newest, ${short9(neg.control.sha)} (${isoDay(neg.control.ms)}), is not ` + + `${marginDays} day(s) older than the tested commit ${short9(tested)} (${isoDay(testedMs)}) — the commit can sit ` + + 'BELOW that cut, where a real ancestor reads exactly like this'; + } + return { ...reading, state: 'unproven', deepenCanHelp: true, operator, reason }; +} + +/** + * Take the containment reading, deepening only as far as proving a negative + * needs. A yes never fetches. The ladder is `touch`'s: `--deepen=N` (counted + * from the current boundary, so it can only ADD history), N doubling from + * `deepenStep`, then `--unshallow`. Fetching also moves the remote-tracking + * ref, so a deepened answer is read at the fetched tip and the receipt names + * the sha it was read against. + * + * @returns {ReturnType & {steps: string[]}} + */ +export function ensureAncestorProvable({ + cwd, commit, ref, control, allowFetch = true, allowUnshallow = true, deepenStep = DEFAULT_DEEPEN_STEP, marginDays, +}) { + const steps = []; + const attempt = () => ancestorReading({ cwd, commit, ref, control, marginDays }); + const settled = (r) => r.state === 'yes' || r.state === 'no'; + + let r = attempt(); + if (settled(r)) { + steps.push(isShallow(cwd) ? 'read without fetching' : 'complete clone (no fetch)'); + return { ...r, steps }; + } + // Unreadable is about the question (a ref that names nothing here), and a + // clone with no cut under the ref has nothing a deepen could add. + if (r.state === 'unreadable' || r.boundaries.length === 0 || r.deepenCanHelp === false) return { ...r, steps }; + if (!allowFetch) return { ...r, steps, reason: `${r.reason}; --no-fetch was given` }; + + const remotes = (git(['remote'], { cwd, allowFail: true }) || '').split('\n').filter(Boolean); + const target = splitRemoteRef(ref, remotes); + if (!target) { + return { + ...r, + steps, + reason: + `${r.reason}; '${ref}' names no remote to deepen from ` + + `(remotes here: ${remotes.length ? remotes.join(', ') : 'none'})`, + }; + } + for (let n = deepenStep; n <= MAX_DEEPEN_STEP && isShallow(cwd); n *= 2) { + const fetched = git(['fetch', `--deepen=${n}`, target.remote, target.branch], { cwd, allowFail: true }); + steps.push(`fetch --deepen=${n} ${target.remote} ${target.branch}${fetched === null ? ' (failed)' : ''}`); + if (fetched === null) break; + r = attempt(); + if (settled(r)) return { ...r, steps }; + } + if (allowUnshallow && isShallow(cwd)) { + const un = git(['fetch', '--unshallow', target.remote], { cwd, allowFail: true }); + steps.push(`fetch --unshallow ${target.remote}${un === null ? ' (failed)' : ''}`); + r = attempt(); + if (settled(r)) return { ...r, steps }; + } + return { ...r, steps }; +} + // ── CLI ────────────────────────────────────────────────────────────────────── function usage(msg) { @@ -713,8 +1092,11 @@ function usage(msg) { ' node scripts/pm/git-history.mjs ensure --since=|--days= [--ref=]\n' + ' node scripts/pm/git-history.mjs touch --path= [--ref=] [--format=%H] [--deepen=]\n' + ' [--no-fetch] [--no-unshallow]\n' + + ' node scripts/pm/git-history.mjs ancestor --commit= [--ref=] [--control=] [--margin-days=]\n' + + ' [--deepen=] [--no-fetch] [--no-unshallow]\n' + ' node scripts/pm/git-history.mjs --self-test\n\n' + - 'exit 0 answered · 2 refused (window or touch not provably complete) · 1 usage/environment\n', + 'exit 0 answered · 2 refused (window, touch or negative not provably complete) · 1 usage/environment\n' + + 'ancestor: exit 0 = yes · 3 = no, PROVEN (its control leg is in the receipt) · 2 refused · 1 usage\n', ); process.exit(1); } @@ -732,6 +1114,8 @@ function parseArgs(argv) { case '--days': opts.days = Number(v); break; case '--ref': opts.ref = v; break; case '--path': opts.paths.push(v); break; + case '--commit': opts.commit = v; break; + case '--control': opts.control = v; break; case '--format': opts.format = v; opts.formatGiven = true; break; case '--deepen': opts.deepen = Number(v); break; case '--margin-days': opts.marginDays = Number(v); break; @@ -791,8 +1175,12 @@ function main(argv) { } const { cmd, opts } = parseArgs(argv); if (cmd === null) usage('a command is required'); - if (!['count', 'log', 'ensure', 'touch'].includes(cmd)) usage(`unknown command '${cmd}'`); + if (!['count', 'log', 'ensure', 'touch', 'ancestor'].includes(cmd)) usage(`unknown command '${cmd}'`); + if (cmd !== 'ancestor' && (opts.commit !== undefined || opts.control !== undefined)) { + usage(`--commit and --control belong to 'ancestor', not '${cmd}'`); + } if (cmd === 'touch') return touchMain(opts); + if (cmd === 'ancestor') return ancestorMain(opts); const since = resolveSince(opts); const until = resolveUntil(opts); @@ -905,6 +1293,111 @@ function touchMain(opts) { return 0; } +/** + * `ancestor`: is `--commit` in `--ref`'s history? Prints `yes` or `no` alone + * on stdout and the two legs with their exit codes on stderr. Exit 0 for a + * yes, {@link EXIT_NOT_ANCESTOR} for a PROVEN no, 2 with EMPTY stdout when the + * negative cannot be told from a shallow cut. + */ +function ancestorMain(opts) { + if (opts.since !== undefined || opts.days !== undefined || opts.until !== undefined) { + usage('ancestor takes no window — drop --since/--days/--until'); + } + if (opts.paths.length > 0 || opts.formatGiven) usage('ancestor takes no --path and no --format'); + if (opts.commit === undefined || opts.commit === '') usage('ancestor needs --commit='); + if (opts.control === '') usage('--control needs a value'); + if (opts.deepen !== undefined && (!Number.isInteger(opts.deepen) || opts.deepen <= 0)) usage('--deepen must be a positive integer'); + if (opts.marginDays !== undefined && (!Number.isFinite(opts.marginDays) || opts.marginDays < 0)) usage('--margin-days must be zero or more'); + const cwd = opts.cwd || process.cwd(); + // A sha this clone does not have is a legitimate question (it may sit below + // the floor). A NAME that resolves to nothing is a typo, and must not ride + // the same path to a "no". + if (commitShaOf(cwd, opts.commit) === null && !/^[0-9a-f]{7,64}$/.test(opts.commit)) { + usage(`--commit=${opts.commit} names no commit here (give a sha, or a ref this checkout has)`); + } + // …and a hex prefix that resolves to nothing because it names TOO MUCH is not + // an absent sha either: "is not an object in this clone" would be untrue. + const prefixProblem = commitShaOf(cwd, opts.commit) === null ? hexPrefixProblem(cwd, opts.commit) : null; + if (prefixProblem !== null) usage(`--commit=${opts.commit} ${prefixProblem}`); + const marginDays = opts.marginDays ?? DEFAULT_MARGIN_DAYS; + + const r = ensureAncestorProvable({ + cwd, + commit: opts.commit, + ref: opts.ref, + control: opts.control, + allowFetch: opts.fetch, + allowUnshallow: opts.unshallow, + deepenStep: opts.deepen, + marginDays, + }); + + const testedLeg = r.tested === null + ? `tested leg: ${opts.commit} is not an object in this clone` + : `tested leg ${short9(r.tested)} exit ${r.testedStatus}`; + + if (r.state !== 'yes' && r.state !== 'no') { + const remote = splitRemoteRef(opts.ref, ['origin']) ? 'origin' : ''; + // Three refusals, three remedies: a ref that names nothing is fetched, a + // control that is too shallow is re-chosen, and only a cut is deepened. + let remedy; + if (r.state === 'unreadable' && r.refSha !== null) { + remedy = ` Remedy: ask again; a read that keeps failing is about the repository (git -C ${cwd} fsck), not the commit.\n`; + } else if (r.state === 'unreadable') { + remedy = ` Remedy: name a ref this checkout has (git -C ${cwd} fetch ${remote}), then ask again.\n`; + } else if (r.deepenCanHelp === false) { + remedy = + ' Remedy: name a control at least as old as the tested commit, or drop --control and let the\n' + + ' floor be the control leg.\n'; + } else if (r.boundaries.length === 0) { + remedy = + " Remedy: this clone's history of the ref is complete, so no fetch turns that leg — the control,\n" + + ' or the ref, is not the commit you take it for. Re-read both.\n'; + } else { + remedy = + ' A shallow clone withholds ancestor paths and never adds one: exit 0 proves itself, and exit 1\n' + + ' is what a cut produces for a commit that sits below it. No answer was printed.\n' + + ` Remedy: git -C ${cwd} fetch --deepen=${opts.deepen ?? DEFAULT_DEEPEN_STEP} ${remote} ${opts.ref.replace(/^[^/]+\//, '')}` + + ` # or: git -C ${cwd} fetch --unshallow ${remote}\n`; + } + process.stderr.write( + `⛔ git-history REFUSES to say "not an ancestor" — ${r.reason}.\n` + + ` ref: ${opts.ref}${r.refSha ? ` (${short9(r.refSha)})` : ''} commit: ${opts.commit}\n` + + `${r.refSha + ? ` ${testedLeg}${r.operator ? ` · operator control ${opts.control} exit ${r.operator.status ?? 'unreadable'}` : ''}\n` + : ''}` + + `${r.steps.length ? ` tried: ${r.steps.join(' · ')}\n` : ''}` + + remedy, + ); + return 2; + } + + const head = `method: git merge-base --is-ancestor ${short9(r.tested ?? opts.commit)} ${opts.ref}@${short9(r.refSha)}`; + const tail = ` · tip ${refTip(cwd, opts.ref)} · ${r.steps.join(' · ')}`; + if (r.state === 'yes') { + process.stdout.write('yes\n'); + process.stderr.write( + `${head} · ${testedLeg} — an ancestor path present here is present in the full history ` + + `(a shallow clone withholds paths, it never adds one), so no control leg is owed${tail}\n`, + ); + return 0; + } + + const controlLeg = r.by === 'complete' + ? "control leg: none is owed — every root under the ref is a real root, so this clone's history of it is " + + 'complete and the walk that missed the commit missed nothing' + : `control leg ${short9(r.control.sha)} exit ${r.controlStatus} — the newest of ${r.boundaries.length} graft boundar` + + `${r.boundaries.length === 1 ? 'y' : 'ies'} under the ref (${isoDay(r.control.ms)}), in its history by ` + + `construction and at least ${marginDays} day(s) older than the tested commit (${isoDay(r.testedMs)}): ` + + 'no cut sits where that commit could hide'; + const operatorLeg = r.operator + ? ` · operator control ${short9(r.operator.sha)} exit ${r.operator.status} (${isoDay(r.operator.ms)}, not newer than the tested commit)` + : ''; + process.stdout.write('no\n'); + process.stderr.write(`${head} · ${testedLeg} · ${controlLeg}${operatorLeg}${tail}\n`); + return EXIT_NOT_ANCESTOR; +} + // ── self-test ──────────────────────────────────────────────────────────────── // Set by `selfTest()` only after its verdict is printed, and read at the @@ -1506,6 +1999,237 @@ function selfTest() { early.code === 0 && early.bytes > 0 && early.bytes < fileBytes.length && /^method: git log [^\n]*\n$/.test(early.stderr ?? '') && !/EPIPE/.test(early.stderr ?? ''), JSON.stringify(early)); + + // ── ancestor: the negative a shallow clone fabricates ─────────────────── + // The sixth trap in the header. Last, because it adds two never-merged + // commits to `up` and deepens its own clones; nothing above reads either. + battery('ancestor: the negative a shallow clone fabricates'); + const bnd = (sha, iso) => ({ sha, ms: iso === null ? null : Date.parse(iso) }); + const tested0 = Date.parse('2026-07-11T12:00:00Z'); + const vComplete = negativeIsProven({ boundaries: [], testedMs: tested0 }); + t('no graft under the ref: a negative stands by COMPLETENESS and owes no control — even for a commit with no ' + + 'date here, because a walk of a complete history that missed it missed nothing', + vComplete.proven === true && vComplete.by === 'complete' && vComplete.control === null + && negativeIsProven({ boundaries: [], testedMs: null }).proven === true, JSON.stringify(vComplete)); + const vFloor = negativeIsProven({ boundaries: [bnd('old', '2026-06-01T00:00:00Z'), bnd('new', '2026-06-21T12:00:00Z')], testedMs: tested0 }); + t('every boundary older than the tested commit by the margin: the negative stands by the FLOOR, and the control ' + + 'leg it names is the NEWEST boundary — the one a hidden ancestor would have to predate', + vFloor.proven === true && vFloor.by === 'floor' && vFloor.control.sha === 'new', JSON.stringify(vFloor)); + const vIntrude = negativeIsProven({ boundaries: [bnd('old', '2026-06-01T00:00:00Z'), bnd('new', '2026-07-06T12:00:00Z')], testedMs: tested0 }); + t('the NEWEST boundary decides, not the oldest — one cut inside the margin is enough to void the negative', + vIntrude.proven === false && vIntrude.why === 'floor-intrudes' && vIntrude.control.sha === 'new', JSON.stringify(vIntrude)); + t('the margin is the whole difference between those two: the same cut five days below the tested commit is ' + + 'refused at the default 7 days and stands at --margin-days=1', + negativeIsProven({ boundaries: [bnd('new', '2026-07-06T12:00:00Z')], testedMs: tested0, marginDays: 1 }).proven === true + && negativeIsProven({ boundaries: [bnd('new', '2026-07-06T12:00:00Z')], testedMs: tested0, marginDays: 7 }).proven === false); + t('a tested commit with no date here (its object is absent) is placed against nothing, and a boundary with no ' + + 'readable date decides nothing — neither is rounded to a "no"', + negativeIsProven({ boundaries: [bnd('b', '2026-06-01T00:00:00Z')], testedMs: null }).why === 'tested-absent' + && negativeIsProven({ boundaries: [bnd('b', null)], testedMs: tested0 }).why === 'boundary-undated'); + + g(['config', 'uploadpack.allowAnySHA1InWant', 'true'], up); + const cAt = (i) => g(['rev-parse', `origin/main~${FIXTURE_COMMITS - 1 - i}`], full).trim(); + const c2 = cAt(2); + const c38 = cAt(38); + // Two commits that never merged, built in `up` and fetched by sha: one on + // c2, dated below every shallow floor cut here, and one on c38, dated a + // day after the tip. + const neverMerged = (parent, iso, msg) => execFileSync( + 'git', ['commit-tree', g(['rev-parse', `${parent}^{tree}`], up).trim(), '-p', parent, '-m', msg], + { cwd: up, encoding: 'utf8', env: { ...process.env, GIT_AUTHOR_DATE: iso, GIT_COMMITTER_DATE: iso } }, + ).trim(); + const oldSide = neverMerged(c2, '2026-06-04T00:00:00Z', 'never merged, old'); + const newSide = neverMerged(c38, '2026-07-11T12:00:00Z', 'never merged, new'); + const rawAnc = (cwd, x) => spawnSync('git', ['merge-base', '--is-ancestor', x, 'origin/main'], { cwd, stdio: 'ignore' }).status; + const anc = (args, cwd) => runCliAllowFail(['ancestor', ...args], cwd); + const shallowWith = (name, depth, shas) => { + const dir = join(root, name); + g(['clone', '--quiet', `--depth=${depth}`, `file://${up}`, dir], root); + if (shas.length > 0) g(['fetch', '--quiet', 'origin', ...shas], dir); + return dir; + }; + + const anc5 = shallowWith('anc5', 5, []); + const b5anc = boundaryOf(anc5); + t('BASELINE — c2 is in main\'s real history, and on a depth-5 clone that does not hold its object raw git ' + + 'exits 128: a third number, which `if ! git merge-base --is-ancestor …` reads as "not an ancestor"', + rawAnc(full, c2) === 0 && rawAnc(anc5, c2) === 128, `full ${rawAnc(full, c2)} shallow ${rawAnc(anc5, c2)}`); + g(['fetch', '--quiet', 'origin', c2, oldSide, newSide], anc5); + t('FIXTURE — fetching those shas by name puts the objects in and moves no cut: the clone is still shallow and ' + + 'its one graft boundary under origin/main is the one it was cloned with', + isShallow(anc5) === true && boundaryOf(anc5) === b5anc + && JSON.stringify(graftBoundaries(anc5, 'origin/main').map((b) => b.sha)) === JSON.stringify([b5anc]) + && graftBoundaries(full, 'origin/main').length === 0, + JSON.stringify(graftBoundaries(anc5, 'origin/main'))); + t('BASELINE — with its object present, the SAME real ancestor now reads exit 1 (the defect, reproduced: the ' + + 'cut withheld the path, at an ordinary exit code and with no warning)', + rawAnc(anc5, c2) === 1, `raw ${rawAnc(anc5, c2)}`); + t('BASELINE — and a commit that truly never merged reads exit 1 too: one exit code for opposite facts', + rawAnc(anc5, oldSide) === 1 && rawAnc(full, c2) === 0, `raw ${rawAnc(anc5, oldSide)}`); + + const refusedAnc = anc([`--commit=${c2}`, '--no-fetch'], anc5); + t('the CLI REFUSES that reading with exit 2 and EMPTY stdout — a captured answer is empty rather than "no"', + refusedAnc.code === 2 && refusedAnc.stdout === '', JSON.stringify(refusedAnc)); + t('and the refusal prints the tested leg\'s own exit code, the cut it could not rule out with its date, and a ' + + '--deepen remedy', + refusedAnc.stderr.includes(`tested leg ${short(c2)} exit 1`) && refusedAnc.stderr.includes(`${short(b5anc)} (2026-07-06)`) + && /Remedy: git -C \S+ fetch --deepen=/.test(refusedAnc.stderr), refusedAnc.stderr); + const libReading = ancestorReading({ cwd: anc5, commit: c2, ref: 'origin/main' }); + t('ancestorReading is the read-only form of the same refusal: unproven, both numbers in the result, and it ' + + 'fetched nothing (the cut is where it was)', + libReading.state === 'unproven' && libReading.testedStatus === 1 && libReading.deepenCanHelp === true + && libReading.control.sha === b5anc && boundaryOf(anc5) === b5anc, JSON.stringify(libReading)); + + const yesAnc = anc([`--commit=${c38}`, '--no-fetch'], anc5); + t('FIRING CONTROL — a commit inside the window answers `yes`, exit 0, on the same shallow clone without any ' + + 'fetch: a yes proves itself, so the command discriminates rather than refusing every shallow clone', + yesAnc.code === 0 && yesAnc.stdout === 'yes\n' && /no control leg is owed/.test(yesAnc.stderr) + && /read without fetching/.test(yesAnc.stderr) && isShallow(anc5) === true, JSON.stringify(yesAnc)); + + const marginRefusal = anc([`--commit=${newSide}`, '--no-fetch'], anc5); + t('a never-merged commit dated five days above the cut is REFUSED at the default margin: the cut is not 7 ' + + 'days older than it, so the cut is not yet a control', + marginRefusal.code === 2 && marginRefusal.stdout === '' && /is not 7 day\(s\) older/.test(marginRefusal.stderr), + JSON.stringify(marginRefusal)); + const noAnc = anc([`--commit=${newSide}`, '--no-fetch', '--margin-days=1'], anc5); + t('with the margin it can meet, the same commit answers `no` WITHOUT fetching, and the clone is still shallow ' + + '— the predicate is the cut\'s place against the commit, never the shallow flag', + noAnc.stdout === 'no\n' && /read without fetching/.test(noAnc.stderr) && isShallow(anc5) === true, JSON.stringify(noAnc)); + t(`a proven no exits ${EXIT_NOT_ANCESTOR}: not 0, so \`ancestor … && echo landed\` cannot read it as a yes, and not 1, ` + + 'which is this tool\'s usage exit', + noAnc.code === EXIT_NOT_ANCESTOR && EXIT_NOT_ANCESTOR !== 0 && EXIT_NOT_ANCESTOR !== 1 && EXIT_NOT_ANCESTOR !== 2, + `exit ${noAnc.code}`); + t('and the receipt carries BOTH legs with their exit codes: the tested commit at 1, and the control — the ' + + 'graft boundary itself — at 0', + noAnc.stderr.includes(`tested leg ${short(newSide)} exit 1`) && noAnc.stderr.includes(`control leg ${short(b5anc)} exit 0`) + && rawAnc(anc5, b5anc) === 0, noAnc.stderr); + + const withControl = anc([`--commit=${newSide}`, '--no-fetch', '--margin-days=1', `--control=${c38}`], anc5); + t('--control adds the operator\'s own leg to the receipt when it holds: in the ref\'s history (exit 0) and not ' + + 'newer than the tested commit', + withControl.code === EXIT_NOT_ANCESTOR && withControl.stderr.includes(`operator control ${short(c38)} exit 0`), + JSON.stringify(withControl)); + const nearRelative = anc([`--commit=${oldSide}`, `--control=${c38}`], anc5); + t('⛔ a control NEWER than the tested commit is refused as a near relative, exit 2 with empty stdout — it ' + + 'answers 0 on every clone and says nothing about a deeper commit', + nearRelative.code === 2 && nearRelative.stdout === '' && /NEWER than the tested commit/.test(nearRelative.stderr), + JSON.stringify(nearRelative)); + t('and that refusal climbed no ladder although fetching was allowed: no deepen changes which commit the ' + + 'operator named, so the cut is where it was and nothing was tried', + boundaryOf(anc5) === b5anc && !/tried:/.test(nearRelative.stderr) && /name a control at least as old/.test(nearRelative.stderr), + nearRelative.stderr); + const absentShallow = anc(['--commit=deadbeefdeadbeef', '--no-fetch'], anc5); + t('a sha this shallow clone does not hold is REFUSED, exit 2 — below the cut or nowhere at all, and nothing ' + + 'here tells those apart', + absentShallow.code === 2 && absentShallow.stdout === '' && /is not an object in this clone/.test(absentShallow.stderr), + JSON.stringify(absentShallow)); + + const anc20 = shallowWith('anc20', 20, [newSide]); + const deepFloor = anc([`--commit=${newSide}`, '--no-fetch'], anc20); + t('on a depth-20 clone the cut sits weeks below that commit, and the DEFAULT margin answers `no` without ' + + 'fetching — the common case pays nothing', + deepFloor.code === EXIT_NOT_ANCESTOR && deepFloor.stdout === 'no\n' && /at least 7 day\(s\) older/.test(deepFloor.stderr) + && isShallow(anc20) === true, JSON.stringify(deepFloor)); + + const anc5b = shallowWith('anc5b', 5, [c2]); + const deepenedYes = anc([`--commit=${c2}`, '--deepen=8'], anc5b); + t('with fetching allowed the refused reading deepens and answers the TRUTH: c2 is an ancestor, `yes`, exit 0 ' + + '— the answer the complete clone gives, where raw git had said 1', + deepenedYes.code === 0 && deepenedYes.stdout === 'yes\n' && /fetch --deepen=8 origin main/.test(deepenedYes.stderr) + && anc([`--commit=${c2}`], full).stdout === 'yes\n', JSON.stringify(deepenedYes)); + + const anc5c = shallowWith('anc5c', 5, [oldSide]); + const deepenedNo = anc([`--commit=${oldSide}`], anc5c); + t('and the never-merged commit built on c2 deepens to a PROVEN `no`: the ladder ends on a complete history, ' + + 'whose negative owes no control', + deepenedNo.code === EXIT_NOT_ANCESTOR && deepenedNo.stdout === 'no\n' && /fetch --deepen=64 origin main/.test(deepenedNo.stderr) + && /every root under the ref is a real root/.test(deepenedNo.stderr), JSON.stringify(deepenedNo)); + + const anc5d = shallowWith('anc5d', 5, [oldSide]); + const voidControl = anc([`--commit=${oldSide}`, `--control=${c2}`, '--no-fetch'], anc5d); + t('an operator control that answers 1 on this clone VOIDS the negative: refused, exit 2, and the line says ' + + 'which leg failed', + voidControl.code === 2 && voidControl.stdout === '' && /control leg answered exit 1/.test(voidControl.stderr) + && rawAnc(anc5d, c2) === 1, JSON.stringify(voidControl)); + const curedControl = anc([`--commit=${oldSide}`, `--control=${c2}`], anc5d); + t('and with fetching allowed the SAME clone deepens until that control turns 0, then reads again: `no`, with ' + + 'the operator leg at exit 0 in the receipt — the hand procedure, run', + curedControl.code === EXIT_NOT_ANCESTOR && curedControl.stdout === 'no\n' && /fetch --deepen=/.test(curedControl.stderr) + && curedControl.stderr.includes(`operator control ${short(c2)} exit 0`) && rawAnc(anc5d, c2) === 0, + JSON.stringify(curedControl)); + + g(['fetch', '--quiet', 'origin', oldSide, newSide], full); + const fullNo = anc([`--commit=${oldSide}`], full); + t('a complete clone answers `no` without fetching and says the history is complete rather than naming a floor', + fullNo.code === EXIT_NOT_ANCESTOR && fullNo.stdout === 'no\n' && /complete clone \(no fetch\)/.test(fullNo.stderr) + && /control leg: none is owed/.test(fullNo.stderr), JSON.stringify(fullNo)); + const fullAbsent = anc(['--commit=deadbeefdeadbeef'], full); + t('there a sha the clone does not hold IS a no — absent from a complete history — and the receipt says the ' + + 'object is not here instead of quoting an exit code git never gave', + fullAbsent.code === EXIT_NOT_ANCESTOR && /is not an object in this clone/.test(fullAbsent.stderr) + && !/tested leg \S+ exit/.test(fullAbsent.stderr), JSON.stringify(fullAbsent)); + const fullBadControl = anc([`--commit=${oldSide}`, `--control=${newSide}`], full); + t('a control that is NOT in the ref\'s history is refused even on a complete clone, with no fetch tried and ' + + 'no deepen prescribed: the control or the ref is not the commit the operator takes it for', + fullBadControl.code === 2 && fullBadControl.stdout === '' && /control leg answered exit 1/.test(fullBadControl.stderr) + && !/tried:/.test(fullBadControl.stderr) && !/--deepen=/.test(fullBadControl.stderr), JSON.stringify(fullBadControl)); + + const noCommit = anc([], full); + const typoName = anc(['--commit=not-a-ref-here'], full); + t('ancestor without --commit is usage, and so is a NAME that resolves to nothing: exit 1 with empty stdout, ' + + `never the ${EXIT_NOT_ANCESTOR} a typo could otherwise ride to a "no"`, + noCommit.code === 1 && noCommit.stdout === '' && typoName.code === 1 && typoName.stdout === '' + && /names no commit here/.test(typoName.stderr), JSON.stringify({ noCommit: noCommit.code, typoName })); + const windowed = anc([`--commit=${c2}`, '--since=2026-06-01'], full); + const strayCommit = runCliAllowFail(['count', `--since=${WINDOW_SINCE}`, `--commit=${c2}`], full); + t('ancestor takes no window, and no other command takes --commit: both are usage', + windowed.code === 1 && windowed.stdout === '' && strayCommit.code === 1 && strayCommit.stdout === '', + JSON.stringify({ windowed: windowed.code, strayCommit: strayCommit.code })); + const noRef = anc([`--commit=${c38}`, '--ref=origin/nope'], anc5); + t('an unresolvable ref is REFUSED (exit 2, empty stdout) with its own remedy, not read as "not in it"', + noRef.code === 2 && noRef.stdout === '' && /does not resolve to a commit/.test(noRef.stderr) + && !/--deepen=/.test(noRef.stderr), JSON.stringify(noRef)); + + // An UNREAD history is not a complete one. "No graft boundary" is the one + // value that proves a negative, so each way of not having looked is pinned + // to a refusal, with the reader injected: on `full`, where the honest + // reading of this very commit is the `no` asserted above. + const unreadWalk = ancestorReading({ cwd: full, commit: oldSide, ref: 'origin/main', readBoundaries: () => null }); + t('⛔ a boundary walk that could not be read (null) is UNREADABLE, never "complete history ⇒ no" — on the ' + + 'clone and the commit whose honest reading is `no`', + unreadWalk.state === 'unreadable' && /could not be read/.test(unreadWalk.reason ?? '') + && ancestorReading({ cwd: full, commit: oldSide, ref: 'origin/main' }).state === 'no', JSON.stringify(unreadWalk)); + const rootOfFull = g(['rev-list', '--max-parents=0', 'origin/main'], full).trim(); + const unreadParents = graftBoundaries(full, 'origin/main', { parentsOf: () => null }); + const unreadTraversal = graftBoundaries(full, 'origin/main', { traversalOf: () => null }); + t('a parentless commit whose parents cannot be read is an UNDECIDED boundary, not a real root: the complete ' + + 'clone that lists none lists its root, marked, under either unreadable parent read', + unreadParents.length === 1 && unreadParents[0].sha === rootOfFull && unreadParents[0].undecided === true + && unreadTraversal.length === 1 && unreadTraversal[0].undecided === true + && graftBoundaries(full, 'origin/main').length === 0, JSON.stringify({ unreadParents, unreadTraversal })); + const vUnread = negativeIsProven({ boundaries: unreadParents, testedMs: tested0 }); + const undecidedReading = ancestorReading({ cwd: full, commit: oldSide, ref: 'origin/main', readBoundaries: () => unreadParents }); + t('and an undecided boundary proves nothing, whatever its date: the negative is refused, and the reason says ' + + 'the commit could not be read rather than naming a floor', + vUnread.proven === false && vUnread.why === 'boundary-unread' && undecidedReading.state === 'unproven' + && /could not be read/.test(undecidedReading.reason ?? ''), JSON.stringify({ vUnread, undecidedReading })); + const floorReading = ancestorReading({ cwd: anc20, commit: newSide, ref: 'origin/main' }); + t('the floor\'s control leg is RUN: the reading carries the exit code git gave for the boundary, and that is ' + + 'the number the receipt prints', + floorReading.state === 'no' && floorReading.by === 'floor' && floorReading.controlStatus === 0 + && rawAnc(anc20, floorReading.control.sha) === 0 && deepFloor.stderr.includes(`control leg ${short(floorReading.control.sha)} exit 0`), + JSON.stringify(floorReading)); + t('a hex string that resolves to no commit because it names TOO MUCH is not an absent sha: two candidates is ' + + 'ambiguous, one is an object that is not a commit, none is absent', + /ambiguous/.test(hexPrefixProblem(full, '0148abc', () => [c2, c38]) ?? '') + && /not a commit/.test(hexPrefixProblem(full, '0148abc', () => [c2]) ?? '') + && hexPrefixProblem(full, 'deadbeefdeadbeef') === null); + const blobSha = g(['rev-parse', 'origin/main:f.txt'], full).trim(); + const blobAsCommit = anc([`--commit=${blobSha}`], full); + t('and the CLI refuses such a string as usage, exit 1 with empty stdout — on a complete clone, where it ' + + 'would otherwise be answered `no` with "is not an object in this clone" (a real blob\'s sha, no injection)', + blobAsCommit.code === 1 && blobAsCommit.stdout === '' && /names an object that is not a commit/.test(blobAsCommit.stderr), + JSON.stringify(blobAsCommit)); } finally { rmSync(root, { recursive: true, force: true }); }