@jeiemgi/cckit 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/AGENTS.md +15 -4
  3. package/README.md +25 -3
  4. package/bin/cckit +91 -8
  5. package/cckit.config.json +1 -1
  6. package/kit.config.schema.json +43 -2
  7. package/package.json +1 -1
  8. package/scripts/autopilot-test.sh +68 -0
  9. package/scripts/autopilot.sh +16 -10
  10. package/scripts/check.sh +14 -1
  11. package/scripts/copilot-loop-test.sh +3 -0
  12. package/scripts/guard-raw-git-ops-test.sh +73 -0
  13. package/scripts/init.sh +68 -8
  14. package/scripts/lib/agent-profile-test.sh +151 -0
  15. package/scripts/lib/agent-profile.sh +195 -0
  16. package/scripts/lib/agent-resolve-test.sh +156 -0
  17. package/scripts/lib/agent-resolve.sh +177 -0
  18. package/scripts/lib/branch-owner-test.sh +99 -0
  19. package/scripts/lib/branch-owner.sh +194 -0
  20. package/scripts/lib/captain-test.sh +86 -0
  21. package/scripts/lib/captain.sh +142 -7
  22. package/scripts/lib/contribute-root-test.sh +40 -0
  23. package/scripts/lib/contribute-root.sh +22 -0
  24. package/scripts/lib/effort-metrics.sh +14 -1
  25. package/scripts/lib/effort-ops-test.sh +54 -2
  26. package/scripts/lib/effort-ops.sh +243 -23
  27. package/scripts/lib/effort-parity-test.sh +5 -3
  28. package/scripts/lib/effort-slug.sh +16 -2
  29. package/scripts/lib/effort.sh +49 -15
  30. package/scripts/lib/gh-project.sh +14 -0
  31. package/scripts/lib/gh-rest-test.sh +301 -0
  32. package/scripts/lib/gh-rest.sh +289 -0
  33. package/scripts/lib/hook-refresh-test.sh +65 -0
  34. package/scripts/lib/hook-refresh.sh +62 -0
  35. package/scripts/lib/kit-config.sh +6 -0
  36. package/scripts/lib/kit-gc-test.sh +178 -1
  37. package/scripts/lib/kit-gc.sh +251 -55
  38. package/scripts/lib/kit-task-ops-test.sh +15 -0
  39. package/scripts/lib/kit-task-ops.sh +231 -58
  40. package/scripts/lib/kto-task-close-test.sh +83 -0
  41. package/scripts/lib/kto-task-pr-merge-test.sh +129 -0
  42. package/scripts/lib/kto-task-pr-test.sh +59 -0
  43. package/scripts/lib/orchestration-runtime-test.sh +142 -0
  44. package/scripts/lib/orchestration-runtime.sh +171 -0
  45. package/scripts/lib/review-stage-test.sh +241 -0
  46. package/scripts/lib/review-stage.sh +259 -0
  47. package/scripts/lib/stage-receipt-test.sh +252 -0
  48. package/scripts/lib/stage-receipt.sh +442 -0
  49. package/scripts/lib/test-env-test.sh +25 -0
  50. package/scripts/lib/test-env.sh +33 -0
  51. package/scripts/lib/worker-brief-test.sh +120 -0
  52. package/scripts/lib/worker-brief.sh +185 -0
  53. package/scripts/lib/worktree-issue.sh +14 -0
  54. package/scripts/lib/worktree-ports-test.sh +146 -0
  55. package/scripts/lib/worktree-start.sh +153 -8
  56. package/scripts/lib/zsh-safety-test.sh +67 -0
  57. package/scripts/orchestrate.sh +124 -22
  58. package/scripts/portable-test.sh +22 -1
  59. package/scripts/review-lint-baseline.txt +28 -0
  60. package/scripts/review-lint-test.sh +271 -0
  61. package/scripts/review-lint.sh +259 -0
  62. package/scripts/review-rules.conf +55 -0
  63. package/scripts/setup-labels.sh +21 -1
  64. package/scripts/skill-frontmatter-baseline.txt +24 -0
  65. package/scripts/skill-frontmatter-lint-test.sh +156 -0
  66. package/scripts/skill-frontmatter-lint.sh +182 -0
  67. package/scripts/task-sync.sh +8 -0
  68. package/scripts/test.sh +10 -1
  69. package/skills/kit-autopilot/SKILL.md +13 -1
  70. package/skills/kit-cleanup/SKILL.md +5 -3
  71. package/skills/kit-contribute/SKILL.md +6 -5
  72. package/skills/kit-effort-close/SKILL.md +8 -3
  73. package/skills/kit-effort-pr/SKILL.md +16 -95
  74. package/skills/kit-gc/SKILL.md +15 -10
  75. package/skills/kit-security-sweep/SKILL.md +4 -6
  76. package/skills/kit-ship/SKILL.md +1 -1
  77. package/skills/kit-task-pr/SKILL.md +2 -0
  78. package/templates/hooks/guard-raw-git-ops.sh.tmpl +193 -0
  79. package/templates/rules/branch-naming.md +6 -0
  80. package/templates/rules/effort-model.md +3 -0
  81. package/templates/rules/naming-and-ids.md +4 -1
  82. package/templates/settings/settings.json.tmpl +4 -2
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env bash
2
+ # agent-resolve-test.sh — the profile RESOLUTION precedence contract (#319).
3
+ #
4
+ # Hermetic: the precedence walk takes label strings as arguments, so nothing here calls gh or the
5
+ # network. That is the reason ap_resolve is pure and ap_labels_fetch is a separate, thin helper.
6
+ # Run: bash scripts/lib/agent-resolve-test.sh
7
+ # errors: strict — a test runner: rc 1 on any failed assertion
8
+ # shellcheck shell=bash
9
+ set -u
10
+ ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
11
+ # shellcheck source=/dev/null
12
+ source "$ROOT/scripts/lib/agent-resolve.sh"
13
+
14
+ command -v jq >/dev/null 2>&1 || { echo "agent-resolve-test: jq absent — skipping"; exit 0; }
15
+
16
+ fail=0
17
+ t() { if [ "$2" = "$3" ]; then echo "ok: $1"; else echo "FAIL: $1 -> got '[$2]' want '[$3]'"; fail=1; fi; }
18
+ rc() { if [ "$2" = "$3" ]; then echo "ok: $1"; else echo "FAIL: $1 -> rc '[$2]' want '[$3]'"; fail=1; fi; }
19
+
20
+ tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
21
+ CFG="$tmp/kit.config.json"
22
+ cat > "$CFG" <<'JSON'
23
+ {
24
+ "agents": {
25
+ "default": "build",
26
+ "profiles": {
27
+ "build": { "kind": "claude", "stages": ["build"], "write": true },
28
+ "review": { "kind": "codex", "stages": ["review"] },
29
+ "both": { "kind": "claude", "stages": ["build", "review"] }
30
+ }
31
+ }
32
+ }
33
+ JSON
34
+
35
+ # ── label parsing ──────────────────────────────────────────────────────────────────────────────
36
+ t "reads an agent: label" "$(ap_profile_from_labels 'agent:review,priority:p1')" "review"
37
+ t "label order does not matter" "$(ap_profile_from_labels 'priority:p1,agent:review')" "review"
38
+ t "newline-separated labels work" "$(printf 'ctx:M\nagent:build' | { read -r a; read -r b; ap_profile_from_labels "$a,$b"; })" "build"
39
+ t "surrounding spaces are trimmed" "$(ap_profile_from_labels ' agent:build , ctx:M ')" "build"
40
+ t "no agent: label yields empty" "$(ap_profile_from_labels 'priority:p1,ctx:M')" ""
41
+ t "empty label set yields empty" "$(ap_profile_from_labels '')" ""
42
+ t "a bare 'agent:' is not a profile" "$(ap_profile_from_labels 'agent:')" ""
43
+ t "the same label twice is not ambiguous" "$(ap_profile_from_labels 'agent:build,agent:build')" "build"
44
+
45
+ # Two DIFFERENT agent labels must refuse, not pick one — a silent pick runs an unchosen agent.
46
+ ap_profile_from_labels 'agent:build,agent:review' >/dev/null 2>&1
47
+ rc "two different agent labels are ambiguous" "$?" "2"
48
+
49
+ # ── parent effort number ───────────────────────────────────────────────────────────────────────
50
+ t "parent number from a sub title" "$(ap_parent_effort_num '[Effort 318] 3 · resolve profiles')" "318"
51
+ t "standalone issue has no parent" "$(ap_parent_effort_num 'fix: a plain bug')" ""
52
+ t "an umbrella title is not a sub" "$(ap_parent_effort_num '[Effort] 318 · agents by profile')" ""
53
+
54
+ # ── precedence: override > issue > parent > default ────────────────────────────────────────────
55
+ t "override wins over everything" "$(ap_resolve "$CFG" build 'both' 'agent:review' 'agent:review' 2>/dev/null)" "both"
56
+ t "issue label beats parent label" "$(ap_resolve "$CFG" review '' 'agent:review' 'agent:both' 2>/dev/null)" "review"
57
+ t "parent label beats the default" "$(ap_resolve "$CFG" review '' '' 'agent:review' 2>/dev/null)" "review"
58
+ t "default applies when nothing else does" "$(ap_resolve "$CFG" build '' '' '' 2>/dev/null)" "build"
59
+
60
+ t "source: override" "$(ap_resolve_source "$CFG" 'both' 'agent:review' '')" "command override"
61
+ t "source: issue label" "$(ap_resolve_source "$CFG" '' 'agent:review' 'agent:both')" "issue label"
62
+ t "source: parent label" "$(ap_resolve_source "$CFG" '' '' 'agent:review')" "parent effort label"
63
+ t "source: the default" "$(ap_resolve_source "$CFG" '' '' '')" "agents.default"
64
+
65
+ # ── the resolved name is validated against the stage before it is returned ─────────────────────
66
+ # review is stages:[review], so resolving it for `build` must fail even though the label is explicit.
67
+ ap_resolve "$CFG" build '' 'agent:review' '' >/dev/null 2>&1
68
+ rc "a label naming a profile barred from the stage is refused" "$?" "2"
69
+ ap_resolve "$CFG" build 'ghost' '' '' >/dev/null 2>&1
70
+ rc "an override naming an undeclared profile is refused" "$?" "2"
71
+ ap_resolve "$CFG" build '' 'agent:build,agent:review' '' >/dev/null 2>&1
72
+ rc "ambiguity propagates out of resolve" "$?" "2"
73
+ t "a profile listing both stages resolves at either" "$(ap_resolve "$CFG" review 'both' '' '' 2>/dev/null)" "both"
74
+
75
+ # The refusal must say which precedence level supplied the bad name.
76
+ case "$(ap_resolve "$CFG" build '' 'agent:review' '' 2>&1 >/dev/null)" in
77
+ *"issue label"*) echo "ok: the refusal names the precedence level" ;;
78
+ *) echo "FAIL: the refusal does not name the precedence level"; fail=1 ;;
79
+ esac
80
+
81
+ # ── nothing resolves at all ────────────────────────────────────────────────────────────────────
82
+ # With no agents.default, level 4 is the CHEAPEST declared profile, not a failure — an
83
+ # unconfigured project runs the inexpensive path rather than refusing.
84
+ cat > "$tmp/nodefault.json" <<'JSON'
85
+ { "agents": { "profiles": {
86
+ "spendy": { "kind": "claude", "tier": "high", "stages": ["build"] },
87
+ "thrifty": { "kind": "claude", "tier": "low", "stages": ["build"] }
88
+ } } }
89
+ JSON
90
+ t "no override/label/default resolves to the CHEAPEST profile" "$(ap_resolve "$tmp/nodefault.json" build '' '' '' 2>/dev/null)" "thrifty"
91
+ # Only a config declaring NO profiles at all resolves nothing.
92
+ echo '{}' > "$tmp/empty.json"
93
+ ap_resolve "$tmp/empty.json" build '' '' '' >/dev/null 2>&1
94
+ rc "a config with no profiles at all is rc 4" "$?" "4"
95
+
96
+ # A dangling agents.default must still refuse through the resolver, not fall through to rc 4.
97
+ cat > "$tmp/dangling.json" <<'JSON'
98
+ { "agents": { "default": "missing", "profiles": { "b": { "kind": "claude", "stages": ["build"] } } } }
99
+ JSON
100
+ ap_resolve "$tmp/dangling.json" build '' '' '' >/dev/null 2>&1
101
+ rc "a dangling default refuses rather than resolving nothing" "$?" "2"
102
+
103
+ # ── the impure helper degrades instead of dying ────────────────────────────────────────────────
104
+ t "labels_fetch with no args is empty" "$(ap_labels_fetch)" ""
105
+ t "labels_fetch with no issue is empty" "$(ap_labels_fetch 'o/r')" ""
106
+ t "issue_title with no args is empty" "$(ap_issue_title)" ""
107
+ t "issue_title with no issue is empty" "$(ap_issue_title 'o/r')" ""
108
+ t "pr_issue with no args is empty" "$(ap_pr_issue)" ""
109
+ t "pr_issue with no pr is empty" "$(ap_pr_issue 'o/r')" ""
110
+
111
+ # ── resolving for a pull request (#345) ────────────────────────────────────────────────────────
112
+ # The three fetchers are shadowed, so this exercises the REAL ap_pr_context / ap_resolve_pr
113
+ # composition — the field packing and the precedence hand-off — without gh or a network.
114
+ FX_BRANCH="" FX_TITLE="" FX_LABELS_345="" FX_LABELS_PARENT=""
115
+ ap_pr_issue() { [ -n "$FX_BRANCH" ] && wt_issue_number "$FX_BRANCH"; return 0; }
116
+ ap_issue_title() { printf '%s' "$FX_TITLE"; }
117
+ ap_labels_fetch() {
118
+ case "${2:-}" in
119
+ 345) printf '%s' "$FX_LABELS_345" ;;
120
+ 344) printf '%s' "$FX_LABELS_PARENT" ;;
121
+ esac
122
+ return 0
123
+ }
124
+
125
+ # A sub-branch PR: the issue, its labels, and the parent effort's labels all land in one row.
126
+ FX_BRANCH="sub/345a-resolve" FX_TITLE="[Effort 344] 1 · resolve the review profile"
127
+ FX_LABELS_345="ctx:S,agent:review" FX_LABELS_PARENT="flow:core,agent:both"
128
+ t "pr_context packs issue + own labels + parent labels" \
129
+ "$(ap_pr_context 'o/r' 9 | tr '\t' '|')" "345|ctx:S,agent:review|flow:core,agent:both"
130
+ t "the issue label wins over the parent's" "$(ap_resolve_pr "$CFG" 'o/r' 9 review)" "review"
131
+ t "an override still outranks both labels" "$(ap_resolve_pr "$CFG" 'o/r' 9 review both)" "both"
132
+
133
+ # No agent: label on the sub, so the parent effort's label decides.
134
+ FX_LABELS_345="ctx:S"
135
+ t "the parent effort label is the fallback" "$(ap_resolve_pr "$CFG" 'o/r' 9 review)" "both"
136
+
137
+ # Neither carries one: agents.default. It is `build`, which does NOT list the review stage —
138
+ # so a review stage refuses rather than launching a build agent against a PR.
139
+ FX_LABELS_PARENT="flow:core"
140
+ ap_resolve_pr "$CFG" 'o/r' 9 review >/dev/null 2>&1
141
+ rc "a default barred from the stage refuses" "$?" "2"
142
+ t "the same default resolves for its own stage" "$(ap_resolve_pr "$CFG" 'o/r' 9 build)" "build"
143
+
144
+ # A standalone issue has no parent, so the parent lookup is skipped, not guessed.
145
+ FX_BRANCH="fix/345-thing" FX_TITLE="a standalone fix" FX_LABELS_345="agent:review"
146
+ t "a standalone title yields no parent labels" \
147
+ "$(ap_pr_context 'o/r' 9 | tr '\t' '|')" "345|agent:review|"
148
+
149
+ # An unreadable PR (or a bot branch) must not fetch labels for issue "" and must not die:
150
+ # the row is empty and the walk falls through to agents.default.
151
+ FX_BRANCH=""
152
+ t "an unresolvable PR yields an empty row" "$(ap_pr_context 'o/r' 9 | tr '\t' '|')" "||"
153
+ t "an unresolvable PR falls through to the default" "$(ap_resolve_pr "$CFG" 'o/r' 9 build)" "build"
154
+
155
+ [ "$fail" -eq 0 ] && echo "agent-resolve-test: PASS" || echo "agent-resolve-test: FAILED"
156
+ exit "$fail"
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env bash
2
+ # agent-resolve.sh — choose WHICH agent profile a piece of work runs under (#319).
3
+ #
4
+ # Precedence, highest first (the research decision on #326):
5
+ # 1. an explicit command override — the operator said so on this invocation
6
+ # 2. the issue's own `agent:<profile>` label
7
+ # 3. the parent effort's `agent:<profile>` label
8
+ # 4. `agents.default` — or, when that is unset, the CHEAPEST declared profile, so an
9
+ # unconfigured project lands on the inexpensive path instead of an arbitrary one
10
+ #
11
+ # The walk is PURE: it takes label strings as arguments rather than fetching them, so the precedence
12
+ # rules are testable without gh, a network, or a fixture repo. The gh-touching helpers are kept
13
+ # separate and thin for exactly that reason: ap_labels_fetch, ap_issue_title and ap_pr_issue each
14
+ # make one call, ap_pr_context composes the three, and every one is best-effort — a failure echoes
15
+ # empty so the walk falls through a precedence level instead of dying.
16
+ #
17
+ # A resolved name is always validated against the stage before it is returned, so a caller can treat
18
+ # a rc-0 result as launchable and never has to re-check.
19
+ # errors: mixed — the resolution walk is pure string work; ap_resolve propagates rc 2 from
20
+ # ap_profile_validate (undeclared profile, missing kind, bad stage) or on an ambiguous label set,
21
+ # and rc 4 when nothing resolves at all. ap_labels_fetch is best-effort and echoes empty on failure.
22
+ # shellcheck shell=bash
23
+
24
+ # BASH_SOURCE is bash-only and empty under zsh, the session shell here; `dirname ""` then yields
25
+ # "." and the sibling source below silently missed. Same defect and same fix as kit-gc.sh:38 (#219):
26
+ # `${BASH_SOURCE[0]:-$0}` covers zsh, CDPATH='' and the redirect stop an interactive zsh echoing the
27
+ # directory into the substitution.
28
+ _ar_dir="$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" >/dev/null 2>&1 && pwd)"
29
+ # shellcheck source=/dev/null
30
+ [ -n "${AP_STAGES_DEFAULT:-}" ] || . "$_ar_dir/agent-profile.sh"
31
+ # shellcheck source=/dev/null
32
+ # wt_issue_number owns the branch -> issue forms, the effort sub-branch suffix included (#345).
33
+ command -v wt_issue_number >/dev/null 2>&1 || . "$_ar_dir/worktree-issue.sh"
34
+
35
+ # ap_profile_from_labels <labels> — echo the profile named by a single `agent:<name>` label.
36
+ # Labels may be comma- or newline-separated. TWO different agent: labels is ambiguous and refused
37
+ # (rc 2) rather than resolved by picking one — a silent pick would run an agent nobody chose.
38
+ ap_profile_from_labels() {
39
+ local raw="${1:-}" l seen="" count=0
40
+ [ -n "$raw" ] || return 0
41
+ while IFS= read -r l; do
42
+ case "$l" in
43
+ agent:?*)
44
+ l="${l#agent:}"
45
+ case ",$seen," in *",$l,"*) continue ;; esac
46
+ seen="${seen:+$seen,}$l"; count=$((count + 1)) ;;
47
+ esac
48
+ done <<EOF
49
+ $(printf '%s' "$raw" | tr ',' '\n' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
50
+ EOF
51
+ [ "$count" -gt 0 ] || return 0
52
+ if [ "$count" -gt 1 ]; then
53
+ echo "agent-resolve: ambiguous agent labels ($seen) — an issue may carry only one" >&2
54
+ return 2
55
+ fi
56
+ printf '%s\n' "$seen"
57
+ }
58
+
59
+ # ap_parent_effort_num <title> — echo the parent effort number from a sub-issue title
60
+ # (`[Effort 318] 3 · thing` -> 318). Empty for a standalone issue. Pure.
61
+ ap_parent_effort_num() {
62
+ printf '%s' "${1:-}" | sed -n 's/^\[Effort \([0-9][0-9]*\)\].*/\1/p'
63
+ }
64
+
65
+ # ap_labels_fetch <repo> <issue> — echo an issue's labels, comma-separated. Best-effort: any gh
66
+ # failure echoes nothing, so a resolver falls through to the next precedence level instead of dying.
67
+ # Uses the REST endpoint rather than `gh issue view`, which goes through GraphQL and has its own,
68
+ # separately-exhaustible rate limit.
69
+ ap_labels_fetch() {
70
+ local repo="${1:-}" num="${2:-}"
71
+ [ -n "$repo" ] && [ -n "$num" ] || return 0
72
+ command -v gh >/dev/null 2>&1 || return 0
73
+ gh api "repos/$repo/issues/$num" --jq '[.labels[].name] | join(",")' 2>/dev/null || true
74
+ }
75
+
76
+ # ap_resolve <cfg> <stage> <override> <issue-labels> <parent-labels> — echo the resolved profile.
77
+ # Pure given its arguments. rc 2 on an invalid/ambiguous selection, rc 4 when nothing resolves.
78
+ ap_resolve() {
79
+ local cfg="${1:-}" stage="${2:-}" override="${3:-}" ilabels="${4:-}" plabels="${5:-}"
80
+ local name src rc_
81
+ if [ -n "$override" ]; then
82
+ name="$override"; src="command override"
83
+ else
84
+ name="$(ap_profile_from_labels "$ilabels")" || return 2
85
+ if [ -n "$name" ]; then src="issue label"
86
+ else
87
+ name="$(ap_profile_from_labels "$plabels")" || return 2
88
+ if [ -n "$name" ]; then src="parent effort label"
89
+ else
90
+ name="$(ap_default_profile "$cfg")" || return 2
91
+ src="agents.default"
92
+ fi
93
+ fi
94
+ fi
95
+
96
+ if [ -z "$name" ]; then
97
+ echo "agent-resolve: no profile resolved for stage '${stage:-?}' — no override, no agent: label, no agents.default" >&2
98
+ return 4
99
+ fi
100
+
101
+ ap_profile_validate "$cfg" "$name" "$stage" || { rc_=$?; echo "agent-resolve: rejected '$name' (from $src)" >&2; return "$rc_"; }
102
+ printf '%s\n' "$name"
103
+ }
104
+
105
+ # ap_resolve_source <cfg> <override> <issue-labels> <parent-labels> — echo WHICH precedence level
106
+ # supplied the name, for the stage receipt. Mirrors ap_resolve's walk without re-validating.
107
+ ap_resolve_source() {
108
+ local cfg="${1:-}" override="${2:-}" ilabels="${3:-}" plabels="${4:-}" n
109
+ [ -n "$override" ] && { printf 'command override\n'; return 0; }
110
+ n="$(ap_profile_from_labels "$ilabels" 2>/dev/null)" && [ -n "$n" ] && { printf 'issue label\n'; return 0; }
111
+ n="$(ap_profile_from_labels "$plabels" 2>/dev/null)" && [ -n "$n" ] && { printf 'parent effort label\n'; return 0; }
112
+ n="$(ap_default_profile "$cfg" 2>/dev/null)" && [ -n "$n" ] && { printf 'agents.default\n'; return 0; }
113
+ return 4
114
+ }
115
+
116
+ # ── resolving for a pull request (#345) ─────────────────────────────────────────────────────────
117
+ # A build stage resolves ONE profile for a whole run, which is why orchestrate.sh passes empty label
118
+ # strings: it has no single issue to read them from. A review stage runs against ONE pull request,
119
+ # so it is the first caller that CAN supply them — and the first to use ap_labels_fetch and
120
+ # ap_parent_effort_num, both written for this walk and without a caller until now.
121
+ #
122
+ # The labels come from the linked ISSUE, not the PR. `agent:` is applied to issues; the PR-side
123
+ # labels a repo applies automatically (size:, risk:) name the diff, not who should run.
124
+ #
125
+ # Every fetch here is best-effort by the same rule ap_labels_fetch already follows: a gh failure
126
+ # echoes empty and the walk falls through to the next precedence level. A review stage that cannot
127
+ # reach GitHub should land on agents.default, not die.
128
+
129
+ # ap_pr_issue <repo> <pr> — the issue number a PR's head branch encodes. Empty when gh is absent,
130
+ # the PR is unreadable, or the branch carries no issue segment (a bot branch).
131
+ # Delegates to wt_issue_number, which also parses the effort sub form `sub/<N><letter>-<slug>`.
132
+ # A local regex would miss those, and every sub-branch PR would resolve to no issue and no labels.
133
+ ap_pr_issue() {
134
+ local repo="${1:-}" pr="${2:-}" br
135
+ [ -n "$repo" ] && [ -n "$pr" ] || return 0
136
+ command -v gh >/dev/null 2>&1 || return 0
137
+ br="$(gh pr view "$pr" --repo "$repo" --json headRefName --jq '.headRefName' 2>/dev/null)" || return 0
138
+ [ -n "$br" ] || return 0
139
+ wt_issue_number "$br"
140
+ }
141
+
142
+ # ap_issue_title <repo> <issue> — an issue's title, for ap_parent_effort_num. Best-effort; REST for
143
+ # the same reason ap_labels_fetch uses it (GraphQL has a separately-exhaustible rate limit).
144
+ ap_issue_title() {
145
+ local repo="${1:-}" num="${2:-}"
146
+ [ -n "$repo" ] && [ -n "$num" ] || return 0
147
+ command -v gh >/dev/null 2>&1 || return 0
148
+ gh api "repos/$repo/issues/$num" --jq '.title // ""' 2>/dev/null || true
149
+ }
150
+
151
+ # ap_pr_context <repo> <pr> — echo "<issue>\t<issue-labels>\t<parent-labels>", TAB-separated.
152
+ # The issue number is carried alongside the labels because the stage that follows records its
153
+ # receipt against that issue (sr_record takes an issue, not a PR), and re-deriving it there would
154
+ # mean a second round of the same three fetches.
155
+ ap_pr_context() {
156
+ local repo="${1:-}" pr="${2:-}" issue="" ilabels="" plabels="" title="" parent=""
157
+ issue="$(ap_pr_issue "$repo" "$pr")"
158
+ if [ -n "$issue" ]; then
159
+ ilabels="$(ap_labels_fetch "$repo" "$issue")"
160
+ title="$(ap_issue_title "$repo" "$issue")"
161
+ parent="$(ap_parent_effort_num "$title")"
162
+ [ -n "$parent" ] && plabels="$(ap_labels_fetch "$repo" "$parent")"
163
+ fi
164
+ printf '%s\t%s\t%s\n' "$issue" "$ilabels" "$plabels"
165
+ }
166
+
167
+ # ap_resolve_pr <cfg> <repo> <pr> <stage> [override] — resolve the profile for a stage that runs
168
+ # against one pull request. The precedence walk is ap_resolve's, unchanged; the only difference
169
+ # from a build stage is that the labels are fetched rather than left empty. rc is ap_resolve's:
170
+ # 2 on an invalid or ambiguous selection, 4 when nothing resolves.
171
+ ap_resolve_pr() {
172
+ local cfg="${1:-}" repo="${2:-}" pr="${3:-}" stage="${4:-}" override="${5:-}" ctx
173
+ ctx="$(ap_pr_context "$repo" "$pr")"
174
+ ap_resolve "$cfg" "$stage" "$override" \
175
+ "$(printf '%s' "$ctx" | cut -f2)" \
176
+ "$(printf '%s' "$ctx" | cut -f3)"
177
+ }
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # branch-owner-test.sh — the one-writer-per-branch lease (#323). Hermetic: a throwaway git repo and
4
+ # a KIT_STATE_DIR of its own, no network and no gh. Run: bash scripts/lib/branch-owner-test.sh
5
+ # errors: strict — a test runner: rc 1 on any failed assertion
6
+ set -u
7
+ ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
8
+ LIB="$ROOT/scripts/lib"
9
+ fail=0
10
+ t() { if [ "$2" = "$3" ]; then echo "ok: $1"; else echo "FAIL: $1 -> got '[$2]' want '[$3]'"; fail=1; fi; }
11
+ rc() { t "$1" "$2" "$3"; }
12
+
13
+ tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
14
+ mkdir -p "$tmp/repo" && cd "$tmp/repo" || exit 1
15
+ git init -q . && git config user.email t@t && git config user.name t
16
+ echo x > f && git add f && git commit -qm init
17
+
18
+ export KIT_STATE_DIR="$tmp/state"
19
+ # shellcheck source=/dev/null
20
+ . "$LIB/branch-owner.sh"
21
+
22
+ WT_A="$tmp/wt-a"; WT_B="$tmp/wt-b"; mkdir -p "$WT_A" "$WT_B"
23
+
24
+ # ── a first claim is granted, and the ledger says who holds it ─────────────────────────────────
25
+ bo_claim feat/1 agent-a "$WT_A" 2>/dev/null; rc "a free branch is claimable" "$?" "0"
26
+ t "the owner is recorded" "$(bo_owner feat/1)" "agent-a"
27
+ t "one live lease" "$(bo_list | wc -l | tr -d ' ')" "1"
28
+
29
+ # ── a SECOND owner on the same branch is refused, and the refusal names the holder ─────────────
30
+ err="$(bo_claim feat/1 agent-b "$WT_B" 2>&1 >/dev/null)"; second=$?
31
+ rc "a second owner is refused" "$second" "3"
32
+ case "$err" in *agent-a*) echo "ok: the refusal names the current owner" ;; *) echo "FAIL: refusal did not name the owner -> '$err'"; fail=1 ;; esac
33
+ t "the refusal did not steal the lease" "$(bo_owner feat/1)" "agent-a"
34
+
35
+ # ── the same owner renews rather than colliding with itself ────────────────────────────────────
36
+ bo_claim feat/1 agent-a "$WT_A" 2>/dev/null; rc "the holder may re-claim (idempotent)" "$?" "0"
37
+ t "re-claiming does not duplicate the row" "$(bo_list | wc -l | tr -d ' ')" "1"
38
+
39
+ # ── different branches do not contend ──────────────────────────────────────────────────────────
40
+ bo_claim feat/2 agent-b "$WT_B" 2>/dev/null; rc "a different branch is independent" "$?" "0"
41
+ t "two live leases" "$(bo_list | wc -l | tr -d ' ')" "2"
42
+
43
+ # ── release is owner-scoped ────────────────────────────────────────────────────────────────────
44
+ bo_release feat/2 agent-a 2>/dev/null; rc "releasing someone else's lease is refused" "$?" "3"
45
+ t "and it stays held" "$(bo_owner feat/2)" "agent-b"
46
+ bo_release feat/2 agent-b 2>/dev/null; rc "the owner may release" "$?" "0"
47
+ t "released leaves no owner" "$(bo_owner feat/2)" ""
48
+ bo_release feat/2 agent-b 2>/dev/null; rc "releasing an unheld branch is a no-op" "$?" "0"
49
+
50
+ # ── liveness: a lease whose worktree is gone is reclaimable ────────────────────────────────────
51
+ # Positive evidence the holder ended — cckit owns worktree creation and removal.
52
+ rm -rf "$WT_A"
53
+ t "a dead holder is not reported as owner" "$(bo_owner feat/1)" ""
54
+ bo_claim feat/1 agent-b "$WT_B" 2>/dev/null; rc "a dead holder's branch is claimable" "$?" "0"
55
+ t "the new owner holds it" "$(bo_owner feat/1)" "agent-b"
56
+
57
+ # ── liveness: a dead pid on THIS host is reclaimable ───────────────────────────────────────────
58
+ # Write the row directly so it names a pid that cannot be running. Same host, existing worktree —
59
+ # the pid is the only signal, which is exactly what this asserts.
60
+ dead=99999; while kill -0 "$dead" 2>/dev/null; do dead=$((dead + 1)); done
61
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' feat/3 ghost "$dead" "$(hostname 2>/dev/null || echo unknown)" "$WT_B" "$(date +%s)" >> "$(bo_file)"
62
+ t "a dead pid on this host is not an owner" "$(bo_owner feat/3)" ""
63
+ bo_claim feat/3 agent-b "$WT_B" 2>/dev/null; rc "a dead pid's branch is claimable" "$?" "0"
64
+
65
+ # ── a live row from ANOTHER host is NOT pid-reclaimed ──────────────────────────────────────────
66
+ # pids are not comparable across hosts; stealing a live remote worker's branch is the corruption
67
+ # this lib exists to prevent. It may expire on age, never on a pid check.
68
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' feat/4 remote "$dead" other-host "$WT_B" "$(date +%s)" >> "$(bo_file)"
69
+ t "a remote host's lease survives a dead-pid check" "$(bo_owner feat/4)" "remote"
70
+ bo_claim feat/4 agent-b "$WT_B" 2>/dev/null; rc "and it still refuses a second writer" "$?" "3"
71
+
72
+ # ── but it expires on age ──────────────────────────────────────────────────────────────────────
73
+ old=$(( $(date +%s) - 90000 ))
74
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' feat/5 stale "$dead" other-host "$WT_B" "$old" >> "$(bo_file)"
75
+ t "a lease past BO_LEASE_TTL is not an owner" "$(bo_owner feat/5)" ""
76
+ t "a longer TTL keeps it" "$(BO_LEASE_TTL=999999 bo_owner feat/5)" "stale"
77
+
78
+ # ── an empty pid means worktree-only liveness (what orchestrate relies on) ─────────────────────
79
+ # The launcher exits while its panes keep writing. Recording the launcher's own pid would have the
80
+ # lease reclaimed the instant it returns — the claim would enforce nothing.
81
+ WT_C="$tmp/wt-c"; mkdir -p "$WT_C"
82
+ ( bo_claim feat/6 launcher "$WT_C" "" 2>/dev/null ) # subshell: its pid is gone afterwards
83
+ t "a pid-less lease survives its claimant exiting" "$(bo_owner feat/6)" "launcher"
84
+ bo_claim feat/6 other "$WT_C" "" 2>/dev/null; rc "and it still refuses a second writer" "$?" "3"
85
+ rm -rf "$WT_C"
86
+ t "removing the worktree releases it" "$(bo_owner feat/6)" ""
87
+
88
+
89
+ # ── reap compacts the ledger to live rows only ─────────────────────────────────────────────────
90
+ bo_reap; rc "reap succeeds" "$?" "0"
91
+ t "reap dropped the expired row" "$(grep -c 'stale' "$(bo_file)" 2>/dev/null || true)" "0"
92
+ t "reap kept the live remote row" "$(grep -c 'remote' "$(bo_file)" 2>/dev/null || true)" "1"
93
+
94
+ # ── a branch name with a slash survives the TSV round-trip ─────────────────────────────────────
95
+ bo_claim effort/318-agents-run-by-profile-in-herdr agent-c "$WT_B" 2>/dev/null
96
+ t "a slashed branch name round-trips" "$(bo_owner effort/318-agents-run-by-profile-in-herdr)" "agent-c"
97
+
98
+ [ "$fail" -eq 0 ] && echo "ALL OK (branch-owner)" || echo "branch-owner: FAILURES"
99
+ exit "$fail"
@@ -0,0 +1,194 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # branch-owner.sh — one writer per branch, enforced by a lease (#323).
4
+ #
5
+ # `rules/branch-naming.md` states the invariant: two agents sharing a branch's working tree, index
6
+ # and HEAD clobber each other, and git has no locking for it. Git refuses to check one branch out
7
+ # in two worktrees, which is NOT the same guarantee — it says nothing about two agent processes
8
+ # driving one worktree, or a second wave launching onto a branch a live worker is already pushing.
9
+ # `ap_profile_writes` (agent-profile.sh) declares whether a profile MAY write; this file decides
10
+ # which single claimant actually does, at any moment.
11
+ #
12
+ # The lease is a row in a TSV under the shared state dir, so every worktree of the repo reads the
13
+ # same ledger (kit-state.sh explains why `--git-common-dir`, not `--show-toplevel`).
14
+ #
15
+ # <branch>\t<owner>\t<pid>\t<host>\t<worktree>\t<claimed-epoch>
16
+ #
17
+ # No field is ever written EMPTY. `read` with IFS=<tab> collapses runs of tabs, because tab is IFS
18
+ # whitespace — one blank field would shift every field after it by one, so a pid-less lease would
19
+ # parse its timestamp as the worktree path and read as dead. `-` is the absent marker.
20
+ #
21
+ # LIVENESS is what keeps a crashed worker from wedging a branch forever, and it is deliberately
22
+ # conservative — a lease is dropped only on POSITIVE evidence the holder is gone:
23
+ # • the recorded worktree path no longer exists, or
24
+ # • the row was written on THIS host and `kill -0 <pid>` says that pid is gone.
25
+ # A row from another host is never reclaimed on a pid check: pids are not comparable across hosts,
26
+ # and stealing a live remote worker's branch is the corruption this file exists to prevent. Such a
27
+ # row expires on age alone (BO_LEASE_TTL, default 24h) so a decommissioned host cannot wedge a
28
+ # branch permanently either.
29
+ #
30
+ # bo_file the ledger's absolute path
31
+ # bo_claim <branch> <owner> [<wt>] [<pid>] take or renew the lease (empty <pid> = worktree liveness)
32
+ # bo_release <branch> <owner> give it up (only your own)
33
+ # bo_owner <branch> echo the live owner, or nothing
34
+ # bo_list one `branch owner pid host worktree epoch` row per lease
35
+ # bo_reap drop every lease whose holder is provably gone
36
+ #
37
+ # Requires: git, awk. bash 3.2 compatible. No jq — this runs on the launch path, before a worktree
38
+ # exists, and must not add a dependency to it.
39
+ #
40
+ # errors: strict — a contested claim returns 3 and a caller must not launch; a state-dir failure
41
+ # returns 1. Silently succeeding here means two writers on one branch.
42
+
43
+ _bo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
44
+ # shellcheck source=/dev/null
45
+ command -v kit_state_dir >/dev/null 2>&1 || . "$_bo_dir/kit-state.sh"
46
+
47
+ BO_LEASE_TTL="${BO_LEASE_TTL:-86400}" # seconds before a lease is considered expired outright
48
+ _BO_LOCK_WAIT="${_BO_LOCK_WAIT:-10}" # seconds to wait for the ledger lock
49
+
50
+ bo_file() { kit_state_file branch-owners.tsv; }
51
+
52
+ _bo_now() { date +%s 2>/dev/null || echo 0; }
53
+ _bo_host() { hostname 2>/dev/null || echo unknown; }
54
+
55
+ # _bo_lock / _bo_unlock — the same mkdir primitive the port-slot ledger uses (worktree-start.sh):
56
+ # a stock macOS has no flock(1), and `set -C` redirection is not atomic on every filesystem.
57
+ #
58
+ # Unlike the port lock, a caller that CANNOT lock here must NOT proceed. That lock guards an
59
+ # allocation whose worst case is a duplicate port; this one guards the answer to "is someone else
60
+ # writing this branch?", and answering it without the lock is how both claimants get a yes.
61
+ _bo_lock() {
62
+ local d="$1" tries=0 max
63
+ max=$(( _BO_LOCK_WAIT * 10 ))
64
+ while [ "$tries" -lt "$max" ]; do
65
+ mkdir "$d" 2>/dev/null && return 0
66
+ sleep 0.1 2>/dev/null || sleep 1
67
+ tries=$(( tries + 1 ))
68
+ done
69
+ # A lock directory older than a minute is abandoned: the age floor sits well above _BO_LOCK_WAIT,
70
+ # so a slow-but-live holder is never stolen from.
71
+ if [ -n "$(find "$d" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then
72
+ rm -rf "$d" 2>/dev/null
73
+ mkdir "$d" 2>/dev/null && { echo "branch-owner: broke an abandoned ledger lock ($d)" >&2; return 0; }
74
+ fi
75
+ return 1
76
+ }
77
+ _bo_unlock() { rmdir "$1" 2>/dev/null || rm -rf "$1" 2>/dev/null; }
78
+
79
+ # _bo_alive <pid> <host> <worktree> — rc 0 when the lease holder may still be running.
80
+ _bo_alive() {
81
+ local pid="$1" host="$2" wt="$3"
82
+ [ "$pid" = "-" ] && pid=""
83
+ [ "$wt" = "-" ] && wt=""
84
+ # A recorded worktree that is gone is positive evidence: cckit owns worktree creation and removal,
85
+ # so its absence means the flow ended.
86
+ [ -n "$wt" ] && [ ! -d "$wt" ] && return 1
87
+ # pids are only comparable on the host that wrote them.
88
+ if [ "$host" = "$(_bo_host)" ] && [ -n "$pid" ]; then
89
+ kill -0 "$pid" 2>/dev/null || return 1
90
+ fi
91
+ return 0
92
+ }
93
+
94
+ # _bo_rows_live <file> — echo the ledger keeping only rows whose holder is still alive and whose
95
+ # lease has not aged out. Pure read; the caller holds the lock and decides what to write.
96
+ _bo_rows_live() {
97
+ local f="$1" now br ow pid host wt ts
98
+ [ -f "$f" ] || return 0
99
+ now="$(_bo_now)"
100
+ while IFS="$(printf '\t')" read -r br ow pid host wt ts; do
101
+ [ -n "$br" ] || continue
102
+ case "$ts" in ''|*[!0-9]*) ts=0 ;; esac
103
+ [ "$ts" -gt 0 ] && [ $(( now - ts )) -ge "$BO_LEASE_TTL" ] && continue
104
+ _bo_alive "$pid" "$host" "$wt" || continue
105
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$br" "$ow" "$pid" "$host" "$wt" "$ts"
106
+ done < "$f"
107
+ }
108
+
109
+ # bo_claim <branch> <owner> [<worktree>] [<pid>] — 0 when <owner> holds the lease on <branch>
110
+ # (taken fresh or renewed), 3 when a different LIVE owner holds it (named on stderr), 1 when the
111
+ # ledger is unwritable or the lock cannot be taken.
112
+ #
113
+ # <pid> defaults to this shell. Pass an EMPTY pid when the claimant is not the process that will
114
+ # keep writing: a launcher that hands each branch to a pane and then exits would otherwise record
115
+ # its own pid and have every lease reclaimed the moment it returns. With no pid, liveness rests on
116
+ # the worktree alone — the durable signal for a launched flow, since cckit owns worktree removal.
117
+ bo_claim() {
118
+ local branch="${1:-}" owner="${2:-}" wt="${3:-}" pid="${4-$$}" f lock held_owner tmp
119
+ [ -n "$branch" ] && [ -n "$owner" ] || { echo "bo_claim: <branch> and <owner> required" >&2; return 2; }
120
+ kit_state_ensure || { echo "bo_claim: could not create the cckit state directory" >&2; return 1; }
121
+ f="$(bo_file)"; lock="$f.lock"
122
+ _bo_lock "$lock" || { echo "bo_claim: could not lock the branch-owner ledger ($lock)" >&2; return 1; }
123
+
124
+ tmp="$(mktemp 2>/dev/null)" || { _bo_unlock "$lock"; echo "bo_claim: no temp file" >&2; return 1; }
125
+ _bo_rows_live "$f" > "$tmp"
126
+
127
+ held_owner="$(awk -F"\t" -v b="$branch" '$1==b {print $2; exit}' "$tmp" 2>/dev/null)"
128
+ if [ -n "$held_owner" ] && [ "$held_owner" != "$owner" ]; then
129
+ local held_wt
130
+ held_wt="$(awk -F"\t" -v b="$branch" '$1==b {print $5; exit}' "$tmp" 2>/dev/null)"
131
+ [ "$held_wt" = "-" ] && held_wt="" # the absent marker is not a path to show a person
132
+ rm -f "$tmp"; _bo_unlock "$lock"
133
+ echo "bo_claim: '$branch' is already owned by '$held_owner'${held_wt:+ (worktree $held_wt)} — refusing a second writer" >&2
134
+ return 3
135
+ fi
136
+
137
+ # Take it, or renew our own with a fresh pid/worktree/timestamp.
138
+ awk -F"\t" -v b="$branch" '$1!=b' "$tmp" > "$tmp.keep" 2>/dev/null || : > "$tmp.keep"
139
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$branch" "$owner" "${pid:--}" "$(_bo_host)" "${wt:--}" "$(_bo_now)" >> "$tmp.keep"
140
+ mv "$tmp.keep" "$f" 2>/dev/null || { rm -f "$tmp" "$tmp.keep"; _bo_unlock "$lock"; echo "bo_claim: could not write $f" >&2; return 1; }
141
+ rm -f "$tmp"
142
+ _bo_unlock "$lock"
143
+ return 0
144
+ }
145
+
146
+ # bo_release <branch> <owner> — 0 when the lease is gone (including when it was never held), 3 when
147
+ # it belongs to someone else and was left alone, 1 on a ledger failure.
148
+ bo_release() {
149
+ local branch="${1:-}" owner="${2:-}" f lock held tmp
150
+ [ -n "$branch" ] && [ -n "$owner" ] || { echo "bo_release: <branch> and <owner> required" >&2; return 2; }
151
+ f="$(bo_file)"; [ -f "$f" ] || return 0
152
+ lock="$f.lock"
153
+ _bo_lock "$lock" || { echo "bo_release: could not lock the branch-owner ledger ($lock)" >&2; return 1; }
154
+ held="$(awk -F"\t" -v b="$branch" '$1==b {print $2; exit}' "$f" 2>/dev/null)"
155
+ if [ -n "$held" ] && [ "$held" != "$owner" ]; then
156
+ _bo_unlock "$lock"
157
+ echo "bo_release: '$branch' is owned by '$held', not '$owner' — left alone" >&2
158
+ return 3
159
+ fi
160
+ tmp="$(mktemp 2>/dev/null)" || { _bo_unlock "$lock"; return 1; }
161
+ awk -F"\t" -v b="$branch" '$1!=b' "$f" > "$tmp" 2>/dev/null || : > "$tmp"
162
+ mv "$tmp" "$f" 2>/dev/null || { rm -f "$tmp"; _bo_unlock "$lock"; return 1; }
163
+ _bo_unlock "$lock"
164
+ return 0
165
+ }
166
+
167
+ # bo_owner <branch> — echo the live owner's name, or nothing. Read-only: it never reaps, so a
168
+ # caller can ask without changing state.
169
+ bo_owner() {
170
+ local branch="${1:-}" f
171
+ [ -n "$branch" ] || return 2
172
+ f="$(bo_file)"; [ -f "$f" ] || return 0
173
+ _bo_rows_live "$f" | awk -F"\t" -v b="$branch" '$1==b {print $2; exit}'
174
+ }
175
+
176
+ # bo_list — every live lease, one row per line.
177
+ bo_list() {
178
+ local f; f="$(bo_file)"; [ -f "$f" ] || return 0
179
+ _bo_rows_live "$f"
180
+ }
181
+
182
+ # bo_reap — compact the ledger to its live rows. Claim and release already skip dead rows, so this
183
+ # is housekeeping (gc), not a correctness step.
184
+ bo_reap() {
185
+ local f lock tmp
186
+ f="$(bo_file)"; [ -f "$f" ] || return 0
187
+ lock="$f.lock"
188
+ _bo_lock "$lock" || return 1
189
+ tmp="$(mktemp 2>/dev/null)" || { _bo_unlock "$lock"; return 1; }
190
+ _bo_rows_live "$f" > "$tmp"
191
+ mv "$tmp" "$f" 2>/dev/null || { rm -f "$tmp"; _bo_unlock "$lock"; return 1; }
192
+ _bo_unlock "$lock"
193
+ return 0
194
+ }