Integrate current task recovery and accepted planning contracts

Why:
Preserve work merged by concurrent tasks while adopting versioned dependency workspaces.

Evidence:
SELF task receipts record conflict detection, all 96 task/recovery/cutover cases, all 33 evidence cases and 5 component identity cases. Documents links and requirements were replayed after preserving both planning entries.

Impact:
Keep upstream idempotent sync, local resume and source-external receipt rules; adapt fixed-guidelines readiness and ignored component identity validation. Remove only obsolete index links and retain their physical Git metadata.

Refs:
Authoritative main57bcb17ea212a531186b6e21617a7f3bea65a791; Documents4a26798000c39cc59ba0c2cc6328f5c8f10dcb32; dependency-workspace R15.
This commit is contained in:
2026-10-13 17:38:24 +00:00
72 changed files with 8387 additions and 98 deletions
+77 -6
View File
@@ -249,19 +249,83 @@ def read_receipt(filename):
return value
def validate_precheck(receipt):
def task_context(current=None):
"""Verify an existing task checkout; this is not an approval identity."""
current = snapshot() if current is None else current
root = Path(git_text("rev-parse", "--show-toplevel")).resolve()
branch = current["branch"]
if not re.fullmatch(r"(?:feature|fix|hotfix|release)/[A-Za-z0-9._-]+", branch):
raise EvidenceError("Local recovery requires a task branch")
records = [row.split(b"\0") for row in git("worktree", "list", "--porcelain", "-z").split(b"\0\0") if row]
matches = [row for row in records if row[0].startswith(b"worktree ")
and Path(os.fsdecode(row[0][9:])).resolve() == root]
if len(matches) != 1 or not records or matches[0] == records[0]:
raise EvidenceError("Recovery requires a registered linked task worktree")
entry = matches[0]
if any(field.startswith((b"bare", b"detached", b"prunable")) for field in entry) or (
b"branch refs/heads/" + branch.encode() not in entry):
raise EvidenceError("Task worktree registration is not valid")
if (root / ".task").is_symlink():
raise EvidenceError("Task registration must belong to the current checkout")
card = find_card()
if card.is_symlink() or card.resolve().parent != root / ".task":
raise EvidenceError("Task registration must belong to the current checkout")
content = card.read_text()
locations = re.findall(r"^- 工作区:(.+?)\s*[((]worktree[))];分支:([^\s]+)\s*$", content, re.M)
bases = re.findall(r"^- 权威仓:.*;目标分支:([^;]+);R0(initial_base_sha)= ([0-9a-f]+)\s*$", content, re.M)
if len(locations) != 1 or Path(locations[0][0]).resolve() != root or locations[0][1] != branch:
raise EvidenceError("Task card belongs to a different worktree or branch")
if len(bases) != 1 or bases[0][0] != current["target_branch"] or not GIT_SHA.fullmatch(bases[0][1]):
raise EvidenceError("Task card has no valid target and initial baseline")
r0 = bases[0][1]
if not current["target_head"]:
raise EvidenceError("Task target is unverified; fetch it first")
for tip in (current["head"], current["target_head"]):
git("merge-base", "--is-ancestor", r0, tip)
check = subprocess.run([sys.executable, str(Path(__file__).with_name("check-worktree.py")), "before-sync"],
capture_output=True, text=True)
if check.returncode:
raise EvidenceError("Task workspace is not ready: " + (check.stdout + check.stderr).strip())
return {"root": root, "r0": r0}
def validate_precheck(receipt, purpose="start"):
if purpose not in ("start", "resume-delivery", "resume-local"):
raise EvidenceError("Unknown precheck validation purpose")
after = receipt["after"]
current = snapshot()
if receipt["command"] not in ("make precheck", "bash scripts/task.sh precheck"):
raise EvidenceError("Task start requires a precheck receipt")
if receipt["exit_code"] != 0 or not re.search(r"^\[verdict\] READY(?:\s|$)", receipt["output"], re.M):
raise EvidenceError("Precheck receipt is not READY")
expected = "LOCAL_READY" if purpose == "resume-local" else "READY"
verdicts = re.findall(r"^\[verdict\] ([A-Z_]+)(?:\s|$)", receipt["output"], re.M)
if receipt["exit_code"] != 0 or verdicts != [expected]:
raise EvidenceError("Precheck receipt is not " + expected)
if after is None or receipt["after_error"] is not None:
raise EvidenceError("Precheck object capture is incomplete")
if receipt["before"]["head"] != current["head"] or after["head"] != current["head"]:
raise EvidenceError("Precheck source HEAD has changed")
if after["target_branch"] != current["target_branch"] or not after["target_head"] or after["target_head"] != current["target_head"]:
if current.get("components") is not None and any(
obj.get("components") != current["components"] for obj in (receipt["before"], after)):
raise EvidenceError("Precheck ordinary component objects have changed or are missing")
if after["target_branch"] != current["target_branch"] or not after["target_head"]:
raise EvidenceError("Precheck authoritative target has changed")
if purpose != "resume-local" and after["target_head"] != current["target_head"]:
raise EvidenceError("Precheck authoritative target has changed")
if purpose.startswith("resume-"):
context = task_context(current)
try:
Path(receipt["cwd"]).resolve().relative_to(context["root"])
except ValueError:
raise EvidenceError("Precheck belongs to a different task worktree")
if any(obj["branch"] != current["branch"] or obj["target_branch"] != current["target_branch"]
for obj in (receipt["before"], after)):
raise EvidenceError("Precheck belongs to a different task branch")
git("merge-base", "--is-ancestor", context["r0"], after["target_head"])
if purpose == "resume-local":
try:
git("merge-base", "--is-ancestor", after["target_head"], current["target_head"])
except EvidenceError:
raise EvidenceError("Precheck target history has rewound or diverged") from None
def find_card():
@@ -313,6 +377,12 @@ def main():
try:
if os.environ.get("SRC", "SELF") not in ("", "SELF"):
raise EvidenceError("Local evidence is SELF; GATE/REPLAY require external execution identity")
if sys.argv[1:] == ["--local-context"]:
context = task_context()
print("[task-state] registered=" + str(context["root"]) + " initial_base=" + context["r0"])
return 0
if sys.argv[1:]:
raise EvidenceError("Unknown evidence arguments")
capture, imported, validated = (os.environ.get(key) for key in
("RECEIPT", "IMPORT_RECEIPT", "VALIDATE_RECEIPT"))
command = os.environ.get("CMD", "")
@@ -321,7 +391,7 @@ def main():
if imported or validated:
receipt = read_receipt(imported or validated)
if validated:
validate_precheck(receipt)
validate_precheck(receipt, os.environ.get("VALIDATE_RECEIPT_PURPOSE", "start"))
report(receipt, "precheck validated")
else:
card = find_card()
@@ -338,7 +408,8 @@ def main():
source_cwd, source_common = str(Path.cwd().resolve()), common_dir()
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
child_env = os.environ.copy()
for key in ("CMD", "SRC", "RECEIPT", "IMPORT_RECEIPT", "VALIDATE_RECEIPT", "TAIL"):
for key in ("CMD", "SRC", "RECEIPT", "IMPORT_RECEIPT", "VALIDATE_RECEIPT", "TAIL",
"VALIDATE_RECEIPT_PURPOSE"):
child_env.pop(key, None)
result = subprocess.run(["bash", "-o", "pipefail", "-c", command],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=child_env)
+80 -24
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# 任务启动门禁:precheck / start / sync / close / finish(配套 Makefile 同名目标)。
# 任务启动门禁:precheck / start / resume / sync / close / finish(配套 Makefile 同名目标)。
# 规范依据:collaboration.md 共同基线与同步节点、治理清理;delivery.md §1/§5。
set -euo pipefail
@@ -19,10 +19,25 @@ fetch_target() {
|| { echo "[verdict] REMOTE_UNVERIFIED — target commit missing" >&2; return 6; }
}
check_worktree() { python3 "${SCRIPT_DIR}/check-worktree.py" "$1"; }
check_startup_rules() {
if ! check_worktree rules; then
echo "[verdict] RULES_UNVERIFIED — fixed startup reading unavailable; preserve the workspace and retry" >&2
return 7
fi
}
main_worktree_root() { git worktree list --porcelain -z | python3 -c 'import os,sys; print(os.fsdecode(sys.stdin.buffer.read().split(bytes([0]),1)[0][9:]))'; }
work_mode() {
case "${TASK_WORK_MODE:-delivery}" in
delivery|local) printf '%s\n' "${TASK_WORK_MODE:-delivery}" ;;
*) die "TASK_WORK_MODE must be delivery or local" ;;
esac
}
cmd_precheck() {
need_repo
local mode
mode=$(work_mode)
fetch_target
local branch head rmain dirty sub_drift sub_uninit
branch=$(git rev-parse --abbrev-ref HEAD)
@@ -100,11 +115,21 @@ cmd_precheck() {
echo "[facts] WARN policy/facts.md 不存在——外部事实登记表缺失(AGENTS.md 证据与验证门禁)"
fi
echo "[required-reading] core/baseline.md, workflows/delivery.md §1$([ -f policy/delivery.md ] && echo ", policy/delivery.md")$([ "$dirty" -gt 0 ] && echo ", standards/collaboration.md(树脏=他人或未收尾现场,不得写入)")"
echo "[R0] $(echo "$rmain" | cut -c1-10)(完整:$rmain)"
if [ "$mode" = local ]; then
echo "[target] ${rmain}(observed; task initial baseline is reported separately)"
else
echo "[R0] $(echo "$rmain" | cut -c1-10)(完整:$rmain)"
fi
if [ "$dirty" -gt 0 ] || [ "${sub_drift:-0}" -gt 0 ]; then
echo "[verdict] SHARED_WORKSPACE_BUSY — 工作树不干净,不得写入;先收尾或经 owner 确认"
exit 3
fi
if [ "$mode" = local ]; then
python3 "${SCRIPT_DIR}/evidence.py" --local-context || return 2
check_startup_rules || return $?
echo "[verdict] LOCAL_READY — existing task may continue authorized local work; final delivery still requires latest-target sync and checks"
return 0
fi
if ! check_worktree before-sync; then
echo "[verdict] SHARED_WORKSPACE_BUSY — component or active operation check failed; preserve the workspace"
exit 3
@@ -113,10 +138,7 @@ cmd_precheck() {
echo "[verdict] SYNC_REQUIRED — ${branch} 缺少 origin/${TARGET_BRANCH} 的 ${behind} 个提交;主检出 pull --ff-only,任务分支 make task-sync"
exit 4
fi
if ! check_worktree rules; then
echo "[verdict] RULES_UNVERIFIED — fixed startup reading unavailable; preserve the workspace and retry" >&2
return 7
fi
check_startup_rules || return $?
echo "[verdict] READY — 保留本次 precheck receipt 后建任务工作区:PRECHECK_RECEIPT=/tmp/task-precheck.json make task-start NAME=feature/your-branch"
}
@@ -127,7 +149,7 @@ cmd_start() {
fetch_target
[ -n "${PRECHECK_RECEIPT:-}" ] || die "PRECHECK_RECEIPT required: capture RECEIPT=/tmp/task-precheck.json CMD='make precheck' make evidence first"
PRECHECK_RECEIPT=$(realpath -- "$PRECHECK_RECEIPT")
VALIDATE_RECEIPT="$PRECHECK_RECEIPT" bash "${SCRIPT_DIR}/evidence.sh"
VALIDATE_RECEIPT="$PRECHECK_RECEIPT" VALIDATE_RECEIPT_PURPOSE=start bash "${SCRIPT_DIR}/evidence.sh"
check_worktree before-sync
# 已合入的同名分支不得重建(2026-10-05 实测:合入后再 task-start 同名会从新 main 长出
# 第二段历史,空卡覆盖已合入任务卡,两轮证据差点丢失)。复核/追加沿用原分支或换新 slug。
@@ -246,6 +268,14 @@ ${parent_note}
| 时间(UTC) | 命令 | 被测HEAD | exit | 来源 | sha256(16) |
|---|---|---|---|---|---|
## 交付调度
- 调度状态:未入队;调度记录:无
- entry_id:无;attempt_id:无;窗口执行者:无
- 固定候选:无(base/head、组件与相关配置引用实际尝试)
- 调度依据:policy/merge-queue.md;新模式启用前按既有交付门禁
- 固定后证据:源码外 RECEIPT;实际结果后按授权原样导入和闭合
## 结果与验证(完成后填写)
- 结果:
@@ -281,22 +311,44 @@ EOF
echo "[started] branch=${name} worktree=${wt} R0=$(echo "$rmain" | cut -c1-10)"
}
cmd_resume() {
need_repo
local mode
mode=$(work_mode)
fetch_target
[ -n "${PRECHECK_RECEIPT:-}" ] || die "PRECHECK_RECEIPT required: capture the current task precheck before resume"
local receipt
receipt=$(realpath -- "$PRECHECK_RECEIPT")
VALIDATE_RECEIPT="$receipt" VALIDATE_RECEIPT_PURPOSE="resume-${mode}" bash "${SCRIPT_DIR}/evidence.sh"
check_startup_rules || return $?
IMPORT_RECEIPT="$receipt" bash "${SCRIPT_DIR}/evidence.sh"
echo "[resumed] work_mode=${mode} source_head=$(git rev-parse HEAD) observed_target=$(git rev-parse "origin/${TARGET_BRANCH}")"
}
cmd_sync() {
need_repo
fetch_target
check_worktree before-sync
git merge --no-edit "origin/${TARGET_BRANCH}" \
-m "Merge authoritative ${TARGET_BRANCH} into the task branch" \
-m "Why: include the current integration baseline before verification." \
-m "Evidence: fetched origin/${TARGET_BRANCH}=$(git rev-parse "origin/${TARGET_BRANCH}")." \
-m "Impact: integrate upstream changes without rewriting task history." \
-m "Refs: task-sync"
git merge-base --is-ancestor "origin/${TARGET_BRANCH}" HEAD || die "sync incomplete"
local base head card branch slug pc changed=0 ancestry_status
base=$(git rev-parse "origin/${TARGET_BRANCH}")
if git merge-base --is-ancestor "$base" HEAD; then
:
else
ancestry_status=$?
[ "$ancestry_status" -eq 1 ] || die "cannot verify target ancestry"
git merge --no-edit "$base" \
-m "Merge authoritative ${TARGET_BRANCH} into the task branch" \
-m "Why: include the current integration baseline before verification." \
-m "Evidence: fetched origin/${TARGET_BRANCH}=${base}." \
-m "Impact: integrate upstream changes without rewriting task history." \
-m "Refs: task-sync"
changed=1
fi
git merge-base --is-ancestor "$base" HEAD || die "sync incomplete"
check_worktree before-update
check_worktree materialize
check_worktree after-sync
local base head card branch slug pc
base=$(git rev-parse "origin/${TARGET_BRANCH}"); head=$(git rev-parse HEAD)
head=$(git rev-parse HEAD)
branch=$(git rev-parse --abbrev-ref HEAD)
slug=$(echo "$branch" | tr '/' '-')
card=".task/${slug}.md"
@@ -311,18 +363,21 @@ cmd_sync() {
done
fi
if [ -n "$card" ] && [ -f "$card" ]; then
printf '| 同步前验收 | %s | %s | %s |\n' "$base" "$head" "$(date -u +%FT%TZ)" >> "$card"
git add "$card"
git commit -q -m "Record the sync checkpoint" \
-m "Why: bind the task validation checkpoint to the latest integration baseline." \
-m "Evidence: SELF component ownership and fixed-source checks; sync_base=${base}; candidate=${head}." \
-m "Impact: task metadata only." -m "Refs: ${card}"
if [ "$changed" -eq 1 ]; then
printf '| 同步(记录前对象) | %s | %s | %s |\n' "$base" "$head" "$(date -u +%FT%TZ)" >> "$card"
git add "$card"
git commit -q -m "Record the sync checkpoint" \
-m "Why: bind the task validation checkpoint to the integration baseline." \
-m "Evidence: SELF component ownership and fixed-source checks; sync_base=${base}; before_record=${head}." \
-m "Impact: task metadata only." -m "Refs: ${card}" -- "$card"
fi
# JSON receipts carry before/after state; older table rows remain readable.
python3 "${SCRIPT_DIR}/check-evidence.py" "$card"
else
echo "[warn] 找不到分支 ${branch} 的任务卡,同步记录未写入" >&2
fi
echo "[synced] sync_base=$(echo "$base" | cut -c1-10) tested_head=$(echo "$head" | cut -c1-10) checked_at=$(date -u +%FT%TZ)"
head=$(git rev-parse HEAD)
echo "[synced] sync_base=${base} tested_head=${head} checked_at=$(date -u +%FT%TZ) changed=${changed}"
echo "[next] 跑正式验收(make test 等),证据写入任务卡"
}
@@ -538,8 +593,9 @@ cmd_finish() {
case "${1:-}" in
precheck) shift; cmd_precheck "$@" ;;
start) shift; cmd_start "$@" ;;
resume) shift; cmd_resume "$@" ;;
sync) shift; cmd_sync "$@" ;;
close) shift; cmd_close "$@" ;;
finish) shift; cmd_finish "$@" ;;
*) echo "usage: task.sh <precheck|start|sync|close|finish> [args]"; exit 2 ;;
*) echo "usage: task.sh <precheck|start|resume|sync|close|finish> [args]"; exit 2 ;;
esac