@jeiemgi/cckit 0.7.1 → 0.8.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 (75) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/AGENTS.md +15 -4
  3. package/README.md +11 -3
  4. package/bin/cckit +86 -7
  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 +65 -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-ops-test.sh +42 -2
  25. package/scripts/lib/effort-ops.sh +157 -14
  26. package/scripts/lib/effort-parity-test.sh +5 -3
  27. package/scripts/lib/effort.sh +38 -14
  28. package/scripts/lib/hook-refresh-test.sh +65 -0
  29. package/scripts/lib/hook-refresh.sh +62 -0
  30. package/scripts/lib/kit-config.sh +6 -0
  31. package/scripts/lib/kit-gc-test.sh +178 -1
  32. package/scripts/lib/kit-gc.sh +233 -55
  33. package/scripts/lib/kit-task-ops-test.sh +15 -0
  34. package/scripts/lib/kit-task-ops.sh +65 -21
  35. package/scripts/lib/kto-task-pr-merge-test.sh +72 -0
  36. package/scripts/lib/kto-task-pr-test.sh +59 -0
  37. package/scripts/lib/orchestration-runtime-test.sh +142 -0
  38. package/scripts/lib/orchestration-runtime.sh +171 -0
  39. package/scripts/lib/review-stage-test.sh +241 -0
  40. package/scripts/lib/review-stage.sh +259 -0
  41. package/scripts/lib/stage-receipt-test.sh +252 -0
  42. package/scripts/lib/stage-receipt.sh +442 -0
  43. package/scripts/lib/test-env-test.sh +25 -0
  44. package/scripts/lib/test-env.sh +30 -0
  45. package/scripts/lib/worker-brief-test.sh +120 -0
  46. package/scripts/lib/worker-brief.sh +185 -0
  47. package/scripts/lib/worktree-ports-test.sh +146 -0
  48. package/scripts/lib/worktree-start.sh +137 -7
  49. package/scripts/lib/zsh-safety-test.sh +67 -0
  50. package/scripts/orchestrate.sh +124 -22
  51. package/scripts/portable-test.sh +22 -1
  52. package/scripts/review-lint-baseline.txt +28 -0
  53. package/scripts/review-lint-test.sh +271 -0
  54. package/scripts/review-lint.sh +259 -0
  55. package/scripts/review-rules.conf +55 -0
  56. package/scripts/setup-labels.sh +21 -1
  57. package/scripts/skill-frontmatter-baseline.txt +24 -0
  58. package/scripts/skill-frontmatter-lint-test.sh +156 -0
  59. package/scripts/skill-frontmatter-lint.sh +182 -0
  60. package/scripts/task-sync.sh +8 -0
  61. package/scripts/test.sh +10 -1
  62. package/skills/kit-autopilot/SKILL.md +13 -1
  63. package/skills/kit-cleanup/SKILL.md +5 -3
  64. package/skills/kit-contribute/SKILL.md +6 -5
  65. package/skills/kit-effort-close/SKILL.md +8 -3
  66. package/skills/kit-effort-pr/SKILL.md +16 -95
  67. package/skills/kit-gc/SKILL.md +15 -10
  68. package/skills/kit-security-sweep/SKILL.md +4 -6
  69. package/skills/kit-ship/SKILL.md +1 -1
  70. package/skills/kit-task-pr/SKILL.md +2 -0
  71. package/templates/hooks/guard-raw-git-ops.sh.tmpl +180 -0
  72. package/templates/rules/branch-naming.md +6 -0
  73. package/templates/rules/effort-model.md +3 -0
  74. package/templates/rules/naming-and-ids.md +4 -1
  75. package/templates/settings/settings.json.tmpl +4 -2
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # worker-brief.sh — compose the ONE prompt a headless worker receives, bounded (#321).
4
+ #
5
+ # `cckit brief` (kit-brief.sh) answers "what does this issue involve". This file answers a different
6
+ # question: what may a worker be TOLD, and how much of it fits. Three constraints, none of which the
7
+ # brief itself can enforce because it does not know the profile:
8
+ #
9
+ # 1. BOUNDED. A profile's `contextBudget` was declared in the schema and read by nothing. An
10
+ # unbounded brief spends the worker's window before it has read a line of code.
11
+ # 2. NAMED OMISSIONS. Truncating mid-sentence hands the worker a brief it believes is complete.
12
+ # Whole sections are dropped from the END and the cut is stated, with the command that
13
+ # recovers them, so a partial brief reads as partial.
14
+ # 3. INVARIANTS SURVIVE. The headless framing and the receipt contract are never cut. A worker
15
+ # that loses the framing asks a human who is not there; one that loses the contract reports in
16
+ # whatever shape it likes and the receipt (#322) has nothing to parse.
17
+ #
18
+ # What is NOT here, deliberately: the board, other issues, and prior conversations. The worker gets
19
+ # its own issue and nothing else — `wb_has_board` is the check that keeps it that way.
20
+ # errors: strict — wb_fit returns 2 when the budget cannot hold the invariants; the rest are pure.
21
+
22
+ # wb_preamble <num> <branch> — the headless framing. Never truncated.
23
+ wb_preamble() {
24
+ local num="${1:-?}" branch="${2:-?}"
25
+ cat <<EOF
26
+ You are running HEADLESS inside a cckit orchestration. There is no human in this worker session:
27
+ decide within the issue's scope and proceed. Do not read the board, do not open another issue, and
28
+ do not act on work that is not issue #$num. Work only on issue #$num in branch $branch.
29
+ EOF
30
+ }
31
+
32
+ # wb_receipt_contract <num> — the shape the worker must report back in. Never truncated.
33
+ #
34
+ # The five fields are #318's acceptance, in that order. `outcome` and `next stage` were missing from
35
+ # the seed's closing line, so a receipt could not say whether the work landed or what follows it —
36
+ # the two things a captain needs to decide the next wave without reading the transcript.
37
+ wb_receipt_contract() {
38
+ local num="${1:-?}"
39
+ cat <<EOF
40
+ ## Finish like this
41
+
42
+ Run the gate above until it is green, then open the PR:
43
+
44
+ cckit pr $num "<summary>"
45
+
46
+ If no change is needed, close the issue yourself with the reason:
47
+
48
+ cckit close $num "<reason>"
49
+
50
+ Then RECORD your receipt — this is the only durable record of the run, and your pane is not one:
51
+
52
+ cckit receipt $num --stage <your stage> <<'RECEIPT'
53
+ outcome: merged | pr-open | closed-no-op | blocked
54
+ url: <PR or issue URL>
55
+ gate: pass | fail — <the failing check, if any>
56
+ blocker: <what stopped you, or: none>
57
+ next stage: build | review | design | docs | none
58
+ RECEIPT
59
+
60
+ Re-running that with the same five values is safe — it rewrites its own attempt rather than
61
+ recording a second one. Then report the same five lines and nothing else: no transcript, no
62
+ summary of your reasoning.
63
+ EOF
64
+ }
65
+
66
+ # wb_profile_budget <cfg> <profile> — echo the profile's contextBudget in bytes, empty when unset
67
+ # or when it is not a positive integer. An unparseable budget is treated as absent rather than as
68
+ # zero: refusing to brief a worker because a config value was misspelled is the worse failure.
69
+ wb_profile_budget() {
70
+ local cfg="${1:-}" name="${2:-}" v
71
+ [ -n "$cfg" ] && [ -f "$cfg" ] && [ -n "$name" ] || return 0
72
+ command -v jq >/dev/null 2>&1 || return 0
73
+ v="$(jq -r --arg n "$name" '(.agents.profiles[$n].contextBudget) // "" | tostring' "$cfg" 2>/dev/null)"
74
+ case "$v" in
75
+ ''|*[!0-9]*) return 0 ;;
76
+ 0) return 0 ;;
77
+ *) printf '%s\n' "$v" ;;
78
+ esac
79
+ }
80
+
81
+ # wb_has_board — rc 0 when stdin looks like it carries board state rather than one issue. The test
82
+ # for constraint 3: a brief naming several issue numbers in list position is the board leaking in.
83
+ # Deliberately crude — it guards a property, it does not parse markdown.
84
+ wb_has_board() {
85
+ grep -qE '^[[:space:]]*[-|*][[:space:]]*#[0-9]+|^\|[[:space:]]*#?[0-9]+[[:space:]]*\|'
86
+ }
87
+
88
+ # wb_sections — stdin is markdown; echo each `## ` heading's title, one per line, in order.
89
+ wb_sections() {
90
+ sed -n 's/^##[[:space:]]\{1,\}//p'
91
+ }
92
+
93
+ # wb_fit <budget> <head-file> <tail-file> — stdin is the cuttable middle. Emit head + as many of
94
+ # the middle's `## ` sections as fit + tail, within <budget> bytes.
95
+ #
96
+ # Sections are dropped from the END because the brief orders them that way already: what the issue
97
+ # owns, then the helpers, then the standing gotchas. The first is unrecoverable from elsewhere; the
98
+ # last is a rule file the worker can read on its own.
99
+ #
100
+ # rc 2 when head + tail alone exceed the budget. They are still emitted — a worker with no framing
101
+ # and no receipt contract is worse than one that overran a number — and the caller is told, because
102
+ # a budget that cannot hold the invariants is a config error someone has to fix.
103
+ _wb_note() {
104
+ local kept="${1:-0}" n_total="${2:-0}" names="${3:-}" dropped
105
+ [ "$kept" -lt "$n_total" ] || return 0
106
+ # `paste -d` takes a LIST of delimiters and cycles them, so `-d', '` joins with a comma, then a
107
+ # space, then a comma — `a,b c,d`. One delimiter, then widen it.
108
+ dropped="$(printf '%s\n' "$names" | grep . | tail -n +$(( kept + 1 )) | paste -sd, - | sed 's/,/, /g')"
109
+ printf '\n_%s section(s) omitted to fit this profile'"'"'s contextBudget: %s. Read them with `cckit brief`._\n' \
110
+ "$(( n_total - kept ))" "$dropped"
111
+ }
112
+
113
+ wb_fit() {
114
+ local budget="${1:-}" head="${2:-}" tail="${3:-}" mid base kept=0 out sec_names n_total try i
115
+ mid="$(cat)"
116
+ if [ -z "$budget" ]; then
117
+ cat "$head"; printf '%s\n' "$mid"; cat "$tail"
118
+ return 0
119
+ fi
120
+
121
+ base=$(( $(wc -c < "$head") + $(wc -c < "$tail") ))
122
+ sec_names="$(printf '%s\n' "$mid" | wb_sections)"
123
+ n_total="$(printf '%s\n' "$sec_names" | grep -c . || true)"
124
+
125
+ # The floor is head + tail + the WORST-CASE omission note (every section dropped). The note is an
126
+ # invariant too: a truncated brief that cannot afford to say it was truncated reads as complete,
127
+ # which is the failure this whole file exists to avoid. Leaving it out of the floor is how the
128
+ # first version overran its budget by the width of the sentence announcing the truncation.
129
+ if [ $(( base + $(_wb_note 0 "$n_total" "$sec_names" | wc -c) )) -ge "$budget" ]; then
130
+ cat "$head"; cat "$tail"
131
+ echo "worker-brief: contextBudget $budget cannot hold the framing, the receipt contract and a truncation notice (${base}+ bytes); nothing else was included" >&2
132
+ return 2
133
+ fi
134
+
135
+ # Grow the kept prefix one section at a time. Counting up rather than trimming down means the
136
+ # answer is the same whether a section is 10 bytes or 10 kilobytes.
137
+ #
138
+ # The omission note is measured INSIDE the loop, for the exact number of sections that candidate
139
+ # drops. Reserving it up front would be circular — how long the note is depends on how many
140
+ # sections drop, which depends on whether the note fits — and leaving it out entirely is how the
141
+ # first version overran its own budget by the width of the sentence announcing the truncation.
142
+ out=""
143
+ i=1
144
+ while [ "$i" -le "${n_total:-0}" ]; do
145
+ try="$(printf '%s\n' "$mid" | awk -v want="$i" '
146
+ /^##[[:space:]]/ { n++ }
147
+ (n == 0 || n <= want) { print }
148
+ ')"
149
+ if [ $(( base + $(printf '%s\n' "$try" | wc -c) + $(_wb_note "$i" "$n_total" "$sec_names" | wc -c) )) -le "$budget" ]; then
150
+ out="$try"; kept="$i"
151
+ else
152
+ break
153
+ fi
154
+ i=$(( i + 1 ))
155
+ done
156
+
157
+ cat "$head"
158
+ [ -n "$out" ] && printf '%s\n' "$out"
159
+ _wb_note "$kept" "$n_total" "$sec_names"
160
+ cat "$tail"
161
+ return 0
162
+ }
163
+
164
+ # wb_compose <num> <branch> <budget> — stdin is the issue brief. Emit the whole worker prompt.
165
+ #
166
+ # The brief's text BEFORE its first `## ` heading joins the head rather than the cuttable middle.
167
+ # That preamble is the issue title, the worktree, the branch, the seed freshness and the gate
168
+ # command — where to work and what must pass. A worker that loses it cannot start, so it is an
169
+ # invariant on the same footing as the framing and the receipt contract, not the cheapest section
170
+ # to drop. Only the `## ` sections below it compete for the remaining budget.
171
+ wb_compose() {
172
+ local num="${1:-?}" branch="${2:-?}" budget="${3:-}" tmp rc=0 brief
173
+ brief="$(cat)"
174
+ tmp="$(mktemp -d)" || return 1
175
+ {
176
+ wb_preamble "$num" "$branch"
177
+ printf '\n'
178
+ printf '%s\n' "$brief" | awk '/^##[[:space:]]/ { exit } { print }'
179
+ } > "$tmp/head"
180
+ { printf '\n'; wb_receipt_contract "$num"; } > "$tmp/tail"
181
+ printf '%s\n' "$brief" | awk 'f || /^##[[:space:]]/ { f = 1; print }' \
182
+ | wb_fit "$budget" "$tmp/head" "$tmp/tail" || rc=$?
183
+ rm -rf "$tmp"
184
+ return $rc
185
+ }
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env bash
2
+ # worktree-ports-test.sh — the per-worktree dev-port contract: a port is NEVER handed to two
3
+ # worktrees at once. Three separate defects lived here, all of which shipped silently because a
4
+ # wrong port looks exactly like a working one until a second lane starts.
5
+ #
6
+ # 1. CONFIG LAYOUT. wt_assign_ports read only `<root>/.claude/kit.config.json`, while the sibling
7
+ # `_wt_cfg` in the same file supported both layouts. In a self-hosting repo (root
8
+ # `cckit.config.json` — cckit itself) the whole function was a silent no-op: it reported
9
+ # nothing, wrote nothing, and the ports read as "assigned".
10
+ #
11
+ # 2. STRIDE == SERVICE COUNT. port = base + (issue % 40) * <count>. With bases 3001/3003/3004 and
12
+ # count 3, worktree offset k+1's admin port (3004+3k) IS worktree offset k's api port. Two
13
+ # lanes, one port, on the second worktree of every wave.
14
+ #
15
+ # 3. HASH, NOT ALLOCATION. `issue % 40` gives two issues 40 apart byte-identical ports. In a repo
16
+ # numbering in the thousands that is routine (#1700 and #1740 in one wave). Slots are now
17
+ # RECORDED under the git-common-dir, so uniqueness is by construction and an issue keeps its
18
+ # slot for as long as its worktree lives.
19
+ #
20
+ # The bar: N worktrees over arbitrary issue numbers, in either config layout, produce N disjoint
21
+ # port sets — and re-running for a live issue never renumbers it.
22
+ #
23
+ # Run: bash scripts/lib/worktree-ports-test.sh
24
+ # errors: strict — rc 1 on any failed assertion
25
+
26
+ set -uo pipefail
27
+ dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
28
+ # shellcheck source=/dev/null
29
+ . "$dir/worktree-start.sh"
30
+
31
+ TMP="$(mktemp -d)" || exit 1
32
+ trap 'rm -rf "$TMP"' EXIT
33
+ fail=0; n=0
34
+ ok() { n=$((n+1)); }
35
+ # `grep -c` prints 0 AND exits 1 on no match, so the familiar `grep -c … || echo 0` yields "0\n0"
36
+ # and every arithmetic comparison against it breaks. Read the count once and default only the
37
+ # genuinely empty case (no such file).
38
+ lines_in() { local c; c="$(grep -c . "$1" 2>/dev/null)"; [ -n "$c" ] || c=0; printf '%s' "$c"; }
39
+ bad() { n=$((n+1)); echo "FAIL: $1"; fail=1; }
40
+
41
+ APPS="admin console api"
42
+
43
+ mk_project() { # <dir> <root|scaffold>
44
+ local d="$1" layout="$2" cfg
45
+ mkdir -p "$d"; git -C "$d" init -q 2>/dev/null
46
+ if [ "$layout" = scaffold ]; then mkdir -p "$d/.claude"; cfg="$d/.claude/kit.config.json"
47
+ else cfg="$d/cckit.config.json"; fi
48
+ cat > "$cfg" <<'J'
49
+ { "worktree": { "devPorts": [
50
+ { "path": "apps/admin/.env.local", "base": 3001 },
51
+ { "path": "apps/console/.env.local", "base": 3003 },
52
+ { "path": "apps/api/.env.local", "base": 3004 } ] } }
53
+ J
54
+ }
55
+ mk_worktree() { local wt="$1" a; for a in $APPS; do mkdir -p "$wt/apps/$a"; : > "$wt/apps/$a/.env.local"; done; }
56
+ ports_of() { local wt="$1" a; for a in $APPS; do grep -hE '^PORT=' "$wt/apps/$a/.env.local" 2>/dev/null | cut -d= -f2; done; }
57
+
58
+ # ── 1. both config layouts are read ───────────────────────────────────────────────────────────
59
+ for layout in root scaffold; do
60
+ P="$TMP/$layout"; mk_project "$P" "$layout"
61
+ W="$P/wt7"; mk_worktree "$W"
62
+ wt_assign_ports "$W" 7 "$P" >/dev/null 2>&1
63
+ got="$(ports_of "$W" | grep -c .)"
64
+ [ "$got" = 3 ] && ok || bad "$layout layout: expected 3 ports written, got $got"
65
+ done
66
+
67
+ # ── 2 + 3. disjoint across worktrees, including the %40-apart pairs ───────────────────────────
68
+ P="$TMP/many"; mk_project "$P" scaffold
69
+ all=""
70
+ for num in 1 2 3 4 5 6 7 8 41 42 1700 1740; do
71
+ W="$P/wt$num"; mk_worktree "$W"
72
+ wt_assign_ports "$W" "$num" "$P" >/dev/null 2>&1
73
+ for p in $(ports_of "$W"); do all="$all$p"$'\n'; done
74
+ done
75
+ total="$(printf '%s' "$all" | grep -c .)"
76
+ uniq_n="$(printf '%s' "$all" | sort -u | grep -c .)"
77
+ [ "$total" = 36 ] && ok || bad "expected 36 ports over 12 worktrees, got $total"
78
+ if [ "$total" = "$uniq_n" ]; then ok; else
79
+ bad "port collision: $total ports but only $uniq_n distinct ($(printf '%s' "$all" | sort | uniq -d | tr '\n' ' '))"
80
+ fi
81
+
82
+ # ── 4. idempotent: a live issue keeps its slot ────────────────────────────────────────────────
83
+ W="$P/wt7"; before="$(ports_of "$W" | tr '\n' ' ')"
84
+ wt_assign_ports "$W" 7 "$P" >/dev/null 2>&1
85
+ after="$(ports_of "$W" | tr '\n' ' ')"
86
+ [ "$before" = "$after" ] && ok || bad "re-run renumbered a live lane: '$before' -> '$after'"
87
+
88
+ # ── 5. a freed slot is reclaimed, not leaked ──────────────────────────────────────────────────
89
+ slots="$(git -C "$P" rev-parse --git-common-dir 2>/dev/null)"
90
+ case "$slots" in /*) : ;; *) slots="$(cd "$P" && cd "$slots" && pwd)" ;; esac
91
+ rows_before="$(lines_in "$slots/kit-portslots.tsv")"
92
+ rm -rf "$P/wt1" # that worktree is gone
93
+ W="$P/wt999"; mk_worktree "$W"
94
+ wt_assign_ports "$W" 999 "$P" >/dev/null 2>&1
95
+ rows_after="$(lines_in "$slots/kit-portslots.tsv")"
96
+ [ "$rows_after" -le "$rows_before" ] && ok || bad "slot ledger grew instead of reclaiming ($rows_before -> $rows_after)"
97
+
98
+ # ── 6. parallel allocation: concurrent starts never share a slot ──────────────────────────────
99
+ # Slot selection is a read-modify-write over one ledger file. Unserialized, N processes all read
100
+ # the same `held` set and all take the same lowest free slot; the reclaim rewrite also `mv`s a
101
+ # snapshot over rows a sibling appended. Both produce duplicate port blocks — the exact failure the
102
+ # ledger was added to prevent, reappearing only under contention.
103
+ P="$TMP/race"; mk_project "$P" scaffold
104
+ RACE_NUMS="101 102 103 104 105 106 107 108"
105
+ RACE_N=8
106
+
107
+ # START BARRIER. Backgrounding eight jobs does not make them contend: the first can finish its whole
108
+ # allocation before the eighth is forked, and a sequential run passes under any implementation. Each
109
+ # worker registers, then blocks until all eight have registered, so they enter allocation together
110
+ # and an unlocked implementation is actually exercised. Appending one short line is atomic (well
111
+ # under PIPE_BUF), and the wait is bounded so a lost worker times out instead of hanging the suite.
112
+ barrier="$P/.barrier"; : > "$barrier"
113
+ pids=""
114
+ for num in $RACE_NUMS; do
115
+ W="$P/wt$num"; mk_worktree "$W"
116
+ (
117
+ echo ready >> "$barrier"
118
+ waited=0
119
+ while [ "$(lines_in "$barrier")" -lt "$RACE_N" ] && [ "$waited" -lt 50 ]; do
120
+ sleep 0.1; waited=$(( waited + 1 ))
121
+ done
122
+ wt_assign_ports "$W" "$num" "$P" >/dev/null 2>&1
123
+ ) &
124
+ pids="$pids $!"
125
+ done
126
+ for pid in $pids; do wait "$pid"; done
127
+
128
+ race=""
129
+ for num in $RACE_NUMS; do
130
+ for p in $(ports_of "$P/wt$num"); do race="$race$p"$'\n'; done
131
+ done
132
+ race_total="$(printf '%s' "$race" | grep -c .)"
133
+ race_uniq="$(printf '%s' "$race" | sort -u | grep -c .)"
134
+ [ "$race_total" = 24 ] && ok || bad "parallel: expected 24 ports over 8 concurrent worktrees, got $race_total"
135
+ if [ "$race_total" = "$race_uniq" ]; then ok; else
136
+ bad "parallel port collision: $race_total ports but only $race_uniq distinct ($(printf '%s' "$race" | sort | uniq -d | tr '\n' ' '))"
137
+ fi
138
+
139
+ # The lock is released on the way out — a leftover lock directory wedges every later start until
140
+ # the one-minute abandonment window elapses.
141
+ race_gcd="$(git -C "$P" rev-parse --git-common-dir 2>/dev/null)"
142
+ case "$race_gcd" in /*) : ;; *) race_gcd="$(cd "$P" && cd "$race_gcd" && pwd)" ;; esac
143
+ [ ! -d "$race_gcd/kit-portslots.tsv.lock" ] && ok || bad "the port-slot lock was left behind after allocation"
144
+
145
+ echo "worktree-ports-test: $n assertion(s), $([ "$fail" = 0 ] && echo "all passed" || echo "FAILURES")"
146
+ exit "$fail"
@@ -16,7 +16,15 @@ WT_START_REPO="${WT_START_REPO:-${KIT_REPO:-}}"
16
16
 
17
17
  # _wt_set_port <app-env-file> <port> <issue-num> — append a per-worktree dev PORT to an app's
18
18
  # .env.local, but only where one exists (i.e. the app is locally runnable). Idempotent: an existing
19
- # PORT= line wins. The app dev scripts read ${PORT:-300X} (sub B) so this assignment takes effect.
19
+ # PORT= line wins.
20
+ #
21
+ # BEST-EFFORT, NOT A GUARANTEE. This write only takes effect for an app that actually reads the
22
+ # file. A script like `next dev -p ${PORT:-3003}` is expanded by the npm-script shell, which never
23
+ # reads .env.local, so the value is INERT for it and every worktree falls back to the same default.
24
+ # cckit therefore does not RELY on it: everything cckit launches itself passes the port explicitly
25
+ # (scripts/lib/qa-lane.sh injects one QA_PORT_<service> per service). Treat the .env.local write as
26
+ # a convenience for apps that do read it — and if you start a dev server by hand in a worktree,
27
+ # check which port you actually got.
20
28
  _wt_set_port() {
21
29
  local file="$1" port="$2" num="$3"
22
30
  [[ -f "$file" ]] || return 0
@@ -27,14 +35,117 @@ _wt_set_port() {
27
35
 
28
36
  # wt_assign_ports <worktree> <issue-num> <root> — assign a per-worktree dev PORT to each app whose
29
37
  # env file is listed in `.worktree.devPorts` of <root>/.claude/kit.config.json. Each entry is
30
- # {path, base}; the port = base + (issue % 40) * <count> so lanes stay disjoint within and across
31
- # worktrees. Config-driven (no hardcoded app paths) so the kit stays portable: a project with no
38
+ # {path, base}; the port = base + (issue % 40) * <stride> so lanes stay disjoint within and across
39
+ # worktrees (stride = `worktree.devPortStride`, default 10 — never the service count, see below). Config-driven (no hardcoded app paths) so the kit stays portable: a project with no
32
40
  # `.worktree.devPorts` (or no kit.config.json) is a silent no-op. bash 3.2.
41
+ # ── port SLOTS: an allocation, not a hash (the QA lane depends on lanes never colliding) ──────
42
+ # `issue % 40` is a hash: two issues 40 apart get byte-identical ports, and a repo whose numbers are
43
+ # in the thousands hits that constantly (#1700 and #1740 in the same wave is unremarkable). A slot is
44
+ # RECORDED instead, so uniqueness is by construction rather than by hoping about issue numbers.
45
+ #
46
+ # State lives beside the event log under the git-common-dir, so it is worktree-durable and shared by
47
+ # every checkout. Each line: <issue>\t<slot>\t<worktree-path>. A slot whose worktree is gone is
48
+ # reclaimed on the next call, which is what keeps the 40 slots from leaking away over a long project.
49
+ _wt_slots_file() {
50
+ local gcd
51
+ gcd="$(git -C "${1:-.}" rev-parse --git-common-dir 2>/dev/null)" || return 1
52
+ case "$gcd" in /*) : ;; *) gcd="$(cd "${1:-.}" && cd "$gcd" 2>/dev/null && pwd)" || return 1 ;; esac
53
+ printf '%s/kit-portslots.tsv' "$gcd"
54
+ }
55
+
56
+ # ── the ledger LOCK: allocation is a read-modify-write, so it has to be serialized ────────────
57
+ # Two `cckit start` processes racing through _wt_slot_alloc both read the same `held` set, both
58
+ # pick the same lowest free slot, and both append it — two worktrees, one port block, which is the
59
+ # very defect the slot ledger exists to remove. The reclaim rewrite races worse than the append:
60
+ # it `mv`s a snapshot over the ledger, silently dropping any row another process added in between.
61
+ #
62
+ # mkdir is the lock primitive. A stock macOS has no flock(1) and this file targets bash 3.2, while
63
+ # `set -C` redirection is not atomic on every filesystem; mkdir is atomic everywhere and fails when
64
+ # the name already exists.
65
+ _WT_LOCK_WAIT="${_WT_LOCK_WAIT:-10}" # seconds to wait for a held lock before giving up
66
+
67
+ # _wt_lock <lockdir> — 0 when the lock is held, 1 when it is not. A caller that fails to lock
68
+ # proceeds ANYWAY: an unserialized allocation can collide, but a `cckit start` that refuses to run
69
+ # cannot be worked around. Degrade, don't block.
70
+ #
71
+ # A lock directory older than a minute is treated as abandoned and broken, so a process killed
72
+ # mid-allocation cannot wedge every future start. The age floor is well above _WT_LOCK_WAIT, so a
73
+ # slow-but-live holder is never stolen from.
74
+ _wt_lock() {
75
+ local d="$1" tries=0 max
76
+ max=$(( _WT_LOCK_WAIT * 10 ))
77
+ while [[ "$tries" -lt "$max" ]]; do
78
+ mkdir "$d" 2>/dev/null && return 0
79
+ sleep 0.1 2>/dev/null || sleep 1
80
+ tries=$(( tries + 1 ))
81
+ done
82
+ if [[ -n "$(find "$d" -maxdepth 0 -mmin +1 2>/dev/null)" ]]; then
83
+ rm -rf "$d" 2>/dev/null
84
+ mkdir "$d" 2>/dev/null && { echo "warn: broke an abandoned port-slot lock ($d)" >&2; return 0; }
85
+ fi
86
+ return 1
87
+ }
88
+
89
+ _wt_unlock() { rmdir "$1" 2>/dev/null || rm -rf "$1" 2>/dev/null; }
90
+
91
+ # _wt_slot_alloc <ledger> <issue-num> <worktree> — the ledger transaction: reclaim dead rows,
92
+ # return the issue's existing allocation if it has one, else take the lowest free slot and append
93
+ # it. Every step reads and writes <ledger>, so the CALLER must hold the lock around the whole
94
+ # function — splitting any step out of it reopens the race.
95
+ _wt_slot_alloc() {
96
+ local f="$1" num="$2" wt="$3" i held mine tmp i_num i_slot i_path
97
+
98
+ # Reclaim: keep only rows whose worktree still exists (or that have no path recorded).
99
+ tmp="$(mktemp 2>/dev/null)" || tmp=""
100
+ if [[ -n "$tmp" ]]; then
101
+ while IFS="$(printf '\t')" read -r i_num i_slot i_path; do
102
+ [[ -n "$i_num" ]] || continue
103
+ if [[ -z "$i_path" || -d "$i_path" ]]; then printf '%s\t%s\t%s\n' "$i_num" "$i_slot" "$i_path" >> "$tmp"; fi
104
+ done < "$f"
105
+ mv "$tmp" "$f" 2>/dev/null || rm -f "$tmp"
106
+ fi
107
+
108
+ # Already allocated? Keep it.
109
+ mine="$(awk -F"\t" -v n="$num" '$1==n {print $2; exit}' "$f" 2>/dev/null)"
110
+ if [[ "$mine" =~ ^[0-9]+$ ]]; then printf '%s' "$mine"; return 0; fi
111
+
112
+ held="$(cut -f2 "$f" 2>/dev/null | tr '\n' ' ')"
113
+ i=0
114
+ while [[ "$i" -lt 40 ]]; do
115
+ case " $held " in *" $i "*) : ;; *) printf '%s\t%s\t%s\n' "$num" "$i" "$wt" >> "$f" 2>/dev/null; printf '%s' "$i"; return 0 ;; esac
116
+ i=$(( i + 1 ))
117
+ done
118
+ echo "[#$num] warn: all 40 dev-port slots are held — falling back to a hashed port (collisions possible); run cckit gc" >&2
119
+ printf '%s' $(( num % 40 ))
120
+ }
121
+
122
+ # _wt_slot_for <root> <issue-num> <worktree> — echo this issue's slot (0-39), allocating on first
123
+ # call under the ledger lock. IDEMPOTENT: an issue keeps its slot for as long as its worktree
124
+ # exists, so re-running `cckit start` never renumbers a live lane. Falls back to the old hash (with
125
+ # a warning) only when every slot is genuinely held.
126
+ _wt_slot_for() {
127
+ local root="$1" num="$2" wt="$3" f lock out locked=0
128
+ f="$(_wt_slots_file "$root")" || { printf '%s' $(( num % 40 )); return 0; }
129
+ [[ -f "$f" ]] || : > "$f" 2>/dev/null || { printf '%s' $(( num % 40 )); return 0; }
130
+
131
+ lock="$f.lock"
132
+ if _wt_lock "$lock"; then locked=1; else
133
+ echo "[#$num] warn: the port-slot ledger stayed locked — allocating unserialized, so two lanes can land on one slot" >&2
134
+ fi
135
+ out="$(_wt_slot_alloc "$f" "$num" "$wt")"
136
+ [[ "$locked" = 1 ]] && _wt_unlock "$lock"
137
+ printf '%s' "$out"
138
+ }
139
+
33
140
  wt_assign_ports() {
34
141
  # `apppath`, not `path`: under zsh `path` is tied to PATH (special array); a bare `path` local
35
142
  # would clobber the command search path on assignment. A namespaced name is inert.
36
- local wt="$1" num="$2" root="$3" cfg ports n offset i apppath base
37
- cfg="$root/.claude/kit.config.json"
143
+ local wt="$1" num="$2" root="$3" cfg ports n offset i apppath base stride spread
144
+ # Both supported layouts (self-host root cckit.config.json · scaffolded
145
+ # .claude/kit.config.json) via the same resolver used below. Hardcoding the scaffolded
146
+ # path made this a silent no-op in every self-hosting repo: ports read as "assigned"
147
+ # and nothing was ever written.
148
+ cfg="$(_wt_cfg "$root")" || return 0
38
149
  # jq is a stated requirement of this file (see header) — don't pre-check `command -v jq` here: the
39
150
  # `command -v … || return` idiom mis-fires under zsh, and the jq read below already no-ops on a
40
151
  # missing config / missing jq. Guard only on the config file existing.
@@ -42,11 +153,30 @@ wt_assign_ports() {
42
153
  ports="$(jq -c '.worktree.devPorts // []' "$cfg" 2>/dev/null)" || return 0
43
154
  [[ -n "$ports" && "$ports" != "[]" ]] || return 0
44
155
  n="$(jq 'length' <<<"$ports" 2>/dev/null)"; [[ "$n" =~ ^[0-9]+$ && "$n" -gt 0 ]] || return 0
45
- offset=$(( num % 40 )); i=0
156
+
157
+ # STRIDE — the distance between one worktree's port block and the next. It must NOT be the
158
+ # service count: with stride == n, two bases that are congruent mod n hand the same port to two
159
+ # different worktrees. Real example (bases 3001/3003/3004, n=3): worktree offset k+1's admin port
160
+ # (3004+3k) IS worktree offset k's api port. Configurable as `worktree.devPortStride`; the default
161
+ # leaves room for up to 10 services per project.
162
+ stride="$(jq -r '.worktree.devPortStride // empty' "$cfg" 2>/dev/null)"
163
+ [[ "$stride" =~ ^[0-9]+$ && "$stride" -gt 0 ]] || stride=10
164
+
165
+ # The invariant that keeps blocks disjoint: every base must sit inside ONE stride-wide window.
166
+ # Warn rather than fail — the ports still work, they just stop being collision-proof, and a
167
+ # config the owner can fix should not break `cckit start`.
168
+ spread="$(jq -r '[.[].base] | (max - min)' <<<"$ports" 2>/dev/null)"
169
+ if [[ "$spread" =~ ^[0-9]+$ && "$spread" -ge "$stride" ]]; then
170
+ echo "[#$num] warn: worktree.devPorts bases span $spread >= stride $stride — port blocks can overlap across worktrees; widen worktree.devPortStride" >&2
171
+ fi
172
+
173
+ offset="$(_wt_slot_for "$root" "$num" "$wt")"
174
+ [[ "$offset" =~ ^[0-9]+$ ]] || offset=$(( num % 40 ))
175
+ i=0
46
176
  while [[ "$i" -lt "$n" ]]; do
47
177
  apppath="$(jq -r ".[$i].path // empty" <<<"$ports")"
48
178
  base="$(jq -r ".[$i].base // empty" <<<"$ports")"
49
- [[ -n "$apppath" && "$base" =~ ^[0-9]+$ ]] && _wt_set_port "$wt/$apppath" $(( base + offset * n )) "$num"
179
+ [[ -n "$apppath" && "$base" =~ ^[0-9]+$ ]] && _wt_set_port "$wt/$apppath" $(( base + offset * stride )) "$num"
50
180
  i=$(( i + 1 ))
51
181
  done
52
182
  }
@@ -14,10 +14,14 @@
14
14
  # errors: strict — a test runner: rc 1 on any failed assertion
15
15
  set -u
16
16
  ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
17
+ # Sealed from the caller's KIT_*/CCKIT_*/EFFORT_* (#369): this suite builds its own fixture.
18
+ # shellcheck source=/dev/null
19
+ . "$ROOT/scripts/lib/test-env.sh" && test_env_seal
17
20
  LIB="$ROOT/scripts/lib"
18
21
  fail=0
19
22
  ok() { echo "ok: $1"; }
20
23
  bad() { echo "FAIL: $1"; fail=1; }
24
+ t() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 -> got '$2' want '$3'"; fi; }
21
25
 
22
26
  if ! command -v zsh >/dev/null 2>&1; then
23
27
  echo "zsh-safety-test: zsh absent — skipping (dependency-light gate)"
@@ -56,6 +60,21 @@ run_zsh "kit-gc.sh :: kit_gc_analyze" \
56
60
  run_zsh "kit-gc.sh :: sibling worktree-issue.sh actually loads" \
57
61
  "cd '$ROOT'; unset -f wt_protected_reason 2>/dev/null; source scripts/lib/kit-gc.sh; _kit_gc_load_deps >/dev/null 2>&1; command -v wt_protected_reason >/dev/null 2>&1"
58
62
 
63
+ # agent-resolve.sh / stage-receipt.sh / review-stage.sh — the same sibling-load defect as kit-gc
64
+ # above (#346). Both E318 files resolved their lib dir from a bare `${BASH_SOURCE[0]}`, which is
65
+ # empty under zsh: `dirname ""` is ".", so the sources missed and the walk lost ap_profile_validate
66
+ # and kit_state_dir. Nothing sourced them under zsh until the captain did, so it never fired.
67
+ # `unset -f` first for the same reason kit-gc's case does it — a user init that already defined the
68
+ # symbol would pass the case without resolving anything.
69
+ run_zsh "agent-resolve.sh :: sibling agent-profile.sh actually loads" \
70
+ "cd '$ROOT'; unset -f ap_profile_validate 2>/dev/null; source scripts/lib/agent-resolve.sh; command -v ap_profile_validate >/dev/null 2>&1"
71
+
72
+ run_zsh "stage-receipt.sh :: sibling kit-state.sh actually loads" \
73
+ "cd '$ROOT'; unset -f kit_state_dir 2>/dev/null; source scripts/lib/stage-receipt.sh; command -v kit_state_dir >/dev/null 2>&1"
74
+
75
+ run_zsh "review-stage.sh :: loads both of its dependencies" \
76
+ "cd '$ROOT'; unset -f ap_resolve_pr sr_record 2>/dev/null; source scripts/lib/review-stage.sh; command -v ap_resolve_pr >/dev/null 2>&1 && command -v sr_record >/dev/null 2>&1"
77
+
59
78
  # worktree-start.sh — the `path` local in wt_assign_ports (no-op without .worktree.devPorts).
60
79
  run_zsh "worktree-start.sh :: wt_assign_ports" \
61
80
  "cd '$ROOT'; source scripts/lib/worktree-start.sh; wt_assign_ports '$ROOT' 1 '$ROOT' >/dev/null 2>&1"
@@ -64,6 +83,54 @@ run_zsh "worktree-start.sh :: wt_assign_ports" \
64
83
  run_zsh "kit-events.sh :: emit_event" \
65
84
  "cd '$ROOT'; source scripts/lib/kit-events.sh; emit_event test op '{}' >/dev/null 2>&1"
66
85
 
86
+ # effort.sh :: effort_snapshot_subs — the work-record collapse (#339). `for sha in $shas` relied on
87
+ # the shell word-splitting an unquoted expansion. bash splits on IFS; zsh does not, so the loop ran
88
+ # ONCE with every SHA as a single argument, `git rev-parse --short` failed, and the run still printed
89
+ # "✓ snapshotted 1 commit(s)" and exited 0. This is a BEHAVIOURAL case, not a source-and-run one: a
90
+ # collapsed snapshot returns 0, so only counting the output files catches it.
91
+ #
92
+ # Throwaway repo, 3 commits past the base, snapshot under zsh, then assert one .diff and one
93
+ # index.jsonl line per commit. The trace lands under that repo's git-common-dir, so it goes with the
94
+ # tmpdir.
95
+ snap_tmp="$(mktemp -d)"
96
+ (
97
+ cd "$snap_tmp" || exit 1
98
+ git init -q .
99
+ git config user.email t@t && git config user.name t
100
+ echo base > f.txt && git add f.txt && git commit -qm "base"
101
+ git branch -q effortbase
102
+ for n in 1 2 3; do
103
+ echo "$n" >> f.txt && git add f.txt && git commit -qm "feat: step $n [E99.$n] (#10$n)"
104
+ done
105
+ ) >/dev/null 2>&1
106
+
107
+ # `zsh -fc`, not `-ic`: this case reads the function's STDOUT (the trace dir), and an interactive zsh
108
+ # sources the user's rc, which can print shell-integration escapes into it. The cases above only
109
+ # check exit codes, so they can afford `-i`; this one cannot. Word-splitting — what #339 is about —
110
+ # does not depend on interactivity, so `-f` exercises the same behavior.
111
+ snap_out="$(zsh -fc "cd ${snap_tmp}; source ${LIB}/effort.sh; effort_snapshot_subs 99 effortbase" 2>/dev/null)"
112
+ if [ -z "$snap_out" ] || [ ! -d "$snap_out" ]; then
113
+ bad "effort.sh :: effort_snapshot_subs ran under zsh (no trace dir echoed)"
114
+ else
115
+ ndiff="$(ls "$snap_out"/[0-9][0-9]-*.diff 2>/dev/null | wc -l | tr -d ' ')"
116
+ nidx="$(wc -l < "$snap_out/index.jsonl" 2>/dev/null | tr -d ' ')"
117
+ t "effort_snapshot_subs :: one .diff per commit under zsh" "$ndiff" "3"
118
+ t "effort_snapshot_subs :: one index.jsonl line per commit" "$nidx" "3"
119
+ # A `for sha in $shas` collapse names its stub `NN-` — rev-parse --short fails on the joined list.
120
+ if ls "$snap_out"/[0-9][0-9]-.diff >/dev/null 2>&1; then
121
+ bad "effort_snapshot_subs — wrote a short-sha-less NN-.diff stub (the #339 collapse)"
122
+ else
123
+ ok "effort_snapshot_subs — no short-sha-less stub"
124
+ fi
125
+ # index.jsonl must be true JSONL: one parseable record per line, no `jq -s` needed.
126
+ if jq -e . "$snap_out/index.jsonl" >/dev/null 2>&1; then
127
+ ok "effort_snapshot_subs — index.jsonl is line-parseable JSONL"
128
+ else
129
+ bad "effort_snapshot_subs — index.jsonl is not one JSON record per line"
130
+ fi
131
+ fi
132
+ rm -rf "$snap_tmp"
133
+
67
134
  # ── static regression guard: no bare reserved-name local reintroduced ──────────────────────────
68
135
  # Match a `local` declaration listing a bare `path` word, or a bare `g()` function definition. The
69
136
  # fixed files use namespaced names (wtpath / apppath / logpath / _kit_cfg_get); a plain word here