@jeiemgi/cckit 0.2.0 → 0.3.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 (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/AGENTS.md +21 -8
  3. package/README.md +63 -5
  4. package/bin/cckit +37 -16
  5. package/cckit.config.json +1 -1
  6. package/commands/kit-doctor.md +3 -1
  7. package/kit.config.schema.json +24 -0
  8. package/package.json +1 -1
  9. package/scripts/annotate-setup.sh +7 -2
  10. package/scripts/capture-project-ids.sh +23 -10
  11. package/scripts/init.sh +22 -4
  12. package/scripts/kit-doctor.sh +185 -7
  13. package/scripts/kit-version-check-test.sh +36 -0
  14. package/scripts/kit-version-check.sh +19 -4
  15. package/scripts/knowledge-lint.sh +4 -1
  16. package/scripts/lib/board-view-test.sh +54 -0
  17. package/scripts/lib/board-view.sh +80 -0
  18. package/scripts/lib/captain-test.sh +18 -0
  19. package/scripts/lib/captain.sh +92 -5
  20. package/scripts/lib/config-path-test.sh +47 -0
  21. package/scripts/lib/config-path.sh +29 -0
  22. package/scripts/lib/copilot.sh +9 -9
  23. package/scripts/lib/effort-metrics-test.sh +57 -0
  24. package/scripts/lib/effort-metrics.sh +19 -5
  25. package/scripts/lib/effort-ops-test.sh +51 -2
  26. package/scripts/lib/effort-ops.sh +314 -49
  27. package/scripts/lib/effort-parity-test.sh +128 -0
  28. package/scripts/lib/effort-slug-test.sh +87 -0
  29. package/scripts/lib/effort-slug.sh +104 -0
  30. package/scripts/lib/effort.sh +34 -0
  31. package/scripts/lib/gh-project-test.sh +95 -0
  32. package/scripts/lib/gh-project.sh +22 -7
  33. package/scripts/lib/git-remote-test.sh +57 -0
  34. package/scripts/lib/git-remote.sh +21 -0
  35. package/scripts/lib/kit-config-test.sh +37 -0
  36. package/scripts/lib/kit-config.sh +33 -13
  37. package/scripts/lib/kit-events.sh +5 -3
  38. package/scripts/lib/kit-gc-test.sh +88 -0
  39. package/scripts/lib/kit-gc.sh +136 -19
  40. package/scripts/lib/kit-local.sh +8 -1
  41. package/scripts/lib/next.sh +3 -3
  42. package/scripts/lib/plan-next-test.sh +87 -0
  43. package/scripts/lib/plan-next.sh +212 -0
  44. package/scripts/lib/project-scan.sh +7 -1
  45. package/scripts/lib/worktree-start.sh +12 -3
  46. package/scripts/lib/zsh-safety-test.sh +73 -0
  47. package/scripts/portable-test.sh +62 -20
  48. package/scripts/setup-labels.sh +13 -2
  49. package/scripts/showcase.sh +13 -4
  50. package/scripts/status-test.sh +63 -0
  51. package/scripts/status.sh +12 -4
  52. package/scripts/task-sync.sh +79 -10
  53. package/skills/kit-autopilot/SKILL.md +5 -0
  54. package/skills/{docs-writer → kit-docs-writer}/SKILL.md +2 -2
  55. package/skills/kit-effort-new/SKILL.md +39 -111
  56. package/skills/kit-effort-pr/SKILL.md +6 -2
  57. package/skills/kit-next/SKILL.md +4 -0
  58. package/skills/kit-plan-next/SKILL.md +82 -0
  59. package/templates/hooks/mempal_session_start.sh.tmpl +36 -2
  60. package/templates/rules/effort-model.md +26 -6
  61. package/templates/rules/mempalace.md +1 -0
  62. package/templates/rules/plan-next.md +58 -0
@@ -61,29 +61,111 @@ cap_action() {
61
61
  CHECKS_FAILING) echo fix ;;
62
62
  CHECKS_PENDING) echo wait ;;
63
63
  DRAFT) echo wait ;;
64
+ HELD) echo hold ;;
64
65
  *) echo skip ;;
65
66
  esac
66
67
  }
67
68
 
69
+ # cap_policy_floor <files-newline> <labels-space> — echo a non-empty REASON when a PR must NOT be
70
+ # auto-merged by the captain (a policy floor tripped), else empty. Floors are DEFAULT ON so an
71
+ # unattended captain never lands a change a human must sign off on. They trip on:
72
+ # • a `hold` label (an explicit human stop)
73
+ # • any changed file under .github/workflows/** (CI/CD — a supply-chain surface)
74
+ # • lockfile / dependency-graph files: pnpm-lock.yaml, package.json, package-lock.json, yarn.lock,
75
+ # turbo.json, *-workspace.yaml/.yml
76
+ # • security-sensitive paths: *.pem, *.key, .env / .env.*, any secret(s) path segment
77
+ # Disable entirely with KIT_CAPTAIN_FLOORS=0 (or captain.mergePolicy.floors:false in config). Extend
78
+ # the protected set with KIT_CAPTAIN_EXTRA_GLOBS (space-separated case-globs). Draft state is honored
79
+ # separately by cap_classify (DRAFT -> wait). Pure — no gh; unit-tested. bash 3.2 / zsh safe.
80
+ cap_policy_floor() {
81
+ local files="$1" labels="$2" f g extra hit
82
+ [ "${KIT_CAPTAIN_FLOORS:-1}" = "0" ] && return 0
83
+ case " $labels " in *" hold "*) printf 'hold label'; return 0 ;; esac
84
+ extra="${KIT_CAPTAIN_EXTRA_GLOBS:-}"
85
+ while IFS= read -r f; do
86
+ [ -n "$f" ] || continue
87
+ case "$f" in
88
+ .github/workflows/*) printf 'workflow file (%s)' "$f"; return 0 ;;
89
+ esac
90
+ case "${f##*/}" in
91
+ pnpm-lock.yaml|package.json|package-lock.json|yarn.lock|turbo.json)
92
+ printf 'lockfile/graph (%s)' "$f"; return 0 ;;
93
+ *-workspace.yaml|*-workspace.yml)
94
+ printf 'workspace graph (%s)' "$f"; return 0 ;;
95
+ *.pem|*.key) printf 'security-sensitive (%s)' "$f"; return 0 ;;
96
+ .env|.env.*) printf 'security-sensitive (%s)' "$f"; return 0 ;;
97
+ esac
98
+ case "/$f/" in */secret/*|*/secrets/*) printf 'security-sensitive (%s)' "$f"; return 0 ;; esac
99
+ # Extra protected globs from config (space-separated). Split on spaces via a here-string (no
100
+ # subshell, so `return` still exits the function), and inline each glob into an eval'd case so it
101
+ # is a LITERAL pattern — matching identically under bash and zsh (a variable in a case pattern is
102
+ # treated literally by zsh, so `case $f in $g` would silently never match there).
103
+ if [ -n "$extra" ]; then
104
+ hit=""
105
+ while IFS= read -r g; do
106
+ [ -n "$g" ] || continue
107
+ eval "case \"\$f\" in ($g) hit=1 ;; esac"
108
+ [ -n "$hit" ] && break
109
+ done <<EOF2
110
+ $(printf '%s' "$extra" | tr ' ' '\n')
111
+ EOF2
112
+ [ -n "$hit" ] && { printf 'protected by config (%s)' "$f"; return 0; }
113
+ fi
114
+ done <<EOF
115
+ $files
116
+ EOF
117
+ return 0
118
+ }
119
+
120
+ # _cap_load_policy_config — bridge captain.mergePolicy from the kit config into the env the pure
121
+ # floor helper reads, so a project can override the floors declaratively. Env always wins (a value
122
+ # already set is left untouched). Best-effort: no config / no jq -> defaults (floors ON).
123
+ _cap_load_policy_config() {
124
+ command -v jq >/dev/null 2>&1 || return 0
125
+ local cfg="${KIT_CONFIG:-}"
126
+ [ -n "$cfg" ] || { [ -f cckit.config.json ] && cfg=cckit.config.json || cfg=.claude/kit.config.json; }
127
+ [ -f "$cfg" ] || return 0
128
+ if [ -z "${KIT_CAPTAIN_FLOORS:-}" ]; then
129
+ case "$(jq -r '.captain.mergePolicy.floors // empty' "$cfg" 2>/dev/null)" in
130
+ false) KIT_CAPTAIN_FLOORS=0 ;; true) KIT_CAPTAIN_FLOORS=1 ;;
131
+ esac
132
+ fi
133
+ if [ -z "${KIT_CAPTAIN_EXTRA_GLOBS:-}" ]; then
134
+ KIT_CAPTAIN_EXTRA_GLOBS="$(jq -r '(.captain.mergePolicy.protectedGlobs // []) | join(" ")' "$cfg" 2>/dev/null || echo "")"
135
+ fi
136
+ export KIT_CAPTAIN_FLOORS KIT_CAPTAIN_EXTRA_GLOBS
137
+ }
138
+
68
139
  # _cap_issue_of_branch <branch> — issue number a flow branch encodes (task/47-x, fix/9-y, effort/12-z).
69
140
  _cap_issue_of_branch() {
70
141
  printf '%s' "$1" | sed -nE 's#^[a-z]+/([0-9]+)-.*#\1#p'
71
142
  }
72
143
 
73
- # captain_gate <pr#> — fetch + classify one PR. Echoes "pr<TAB>issue<TAB>state<TAB>action<TAB>title".
144
+ # captain_gate <pr#> — fetch + classify one PR. Echoes
145
+ # "pr<TAB>issue<TAB>state<TAB>action<TAB>title<TAB>reason". A CLEAN PR that trips a policy floor
146
+ # (cap_policy_floor) is downgraded to HELD/hold so the captain never auto-merges it; `reason` carries
147
+ # the floor that tripped (empty otherwise).
74
148
  captain_gate() {
75
- local repo="$CAPTAIN_REPO" pr="$1" j mergeable mss checks issue state action title branch
76
- j="$(gh pr view "$pr" --repo "$repo" --json number,title,headRefName,mergeable,mergeStateStatus,statusCheckRollup 2>/dev/null)" \
149
+ local repo="$CAPTAIN_REPO" pr="$1" j mergeable mss checks issue state action title branch files labels reason
150
+ j="$(gh pr view "$pr" --repo "$repo" --json number,title,headRefName,mergeable,mergeStateStatus,statusCheckRollup,files,labels 2>/dev/null)" \
77
151
  || { echo "captain: cannot read PR #$pr" >&2; return 1; }
78
152
  mergeable="$(printf '%s' "$j" | jq -r '.mergeable // "UNKNOWN"')"
79
153
  mss="$(printf '%s' "$j" | jq -r '.mergeStateStatus // "UNKNOWN"')"
80
154
  checks="$(printf '%s' "$j" | jq -c '.statusCheckRollup // []' | cap_checks_summary)"
81
155
  branch="$(printf '%s' "$j" | jq -r '.headRefName // ""')"
82
156
  title="$(printf '%s' "$j" | jq -r '.title // ""')"
157
+ files="$(printf '%s' "$j" | jq -r '.files[]?.path // empty')"
158
+ labels="$(printf '%s' "$j" | jq -r '[.labels[]?.name] | join(" ")')"
83
159
  issue="$(_cap_issue_of_branch "$branch")"
84
160
  state="$(cap_classify "$mergeable" "$mss" "$checks")"
85
161
  action="$(cap_action "$state")"
86
- printf '%s\t%s\t%s\t%s\t%s\n' "$pr" "${issue:-—}" "$state" "$action" "$title"
162
+ reason=""
163
+ # Policy floor: only a would-be merge is at risk, so gate only the CLEAN/merge verdict.
164
+ if [ "$action" = "merge" ]; then
165
+ reason="$(cap_policy_floor "$files" "$labels")"
166
+ [ -n "$reason" ] && { state="HELD"; action="hold"; }
167
+ fi
168
+ printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$pr" "${issue:-—}" "$state" "$action" "$title" "$reason"
87
169
  }
88
170
 
89
171
  # _cap_open_prs [effort] — open PR numbers, optionally only those whose branch-issue is a sub of <effort>.
@@ -119,8 +201,9 @@ captain_pass() {
119
201
  done
120
202
  [ -n "$repo" ] || { echo "captain: no repo (set KIT_REPO / CAPTAIN_REPO)" >&2; return 1; }
121
203
  CAPTAIN_MERGED=0
204
+ _cap_load_policy_config # bridge captain.mergePolicy from config into the floor env (env wins)
122
205
 
123
- local prs pr row state action issue title merged_any=0
206
+ local prs pr row state action issue title reason merged_any=0
124
207
  prs="$(_cap_open_prs "$effort")"
125
208
  [ -n "$prs" ] || { echo "captain: no open PRs in scope"; return 0; }
126
209
 
@@ -132,6 +215,7 @@ captain_pass() {
132
215
  action="$(printf '%s' "$row" | cut -f4)"
133
216
  issue="$(printf '%s' "$row" | cut -f2)"
134
217
  title="$(printf '%s' "$row" | cut -f5)"
218
+ reason="$(printf '%s' "$row" | cut -f6)"
135
219
  printf '%s\t%s\n' "$pr" "$state" >> "$CAPTAIN_STATE" 2>/dev/null || true
136
220
  if [ "$action" = "merge" ] && [ "$do_merge" = "1" ] && [ "$dry" = "0" ]; then
137
221
  if gh pr merge "$pr" --repo "$repo" --squash --delete-branch >/dev/null 2>&1; then
@@ -140,6 +224,9 @@ captain_pass() {
140
224
  else
141
225
  printf ' PR #%-4s %-14s merge FAILED (re-check) (#%s %s)\n' "$pr" "$state" "$issue" "$title"
142
226
  fi
227
+ elif [ "$action" = "hold" ]; then
228
+ printf ' PR #%-4s %-14s -> HELD (#%s %s) — policy floor: %s [human review; C overrides]\n' \
229
+ "$pr" "$state" "$issue" "$title" "${reason:-protected}"
143
230
  else
144
231
  printf ' PR #%-4s %-14s -> %-7s (#%s %s)\n' "$pr" "$state" "$action" "$issue" "$title"
145
232
  fi
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # config-path-test.sh — covers the ONE shared config-path resolver (#69): kit_config_find (pure walk)
4
+ # and kit_config_path (KIT_CONFIG wins, else walk). Every kit entrypoint discovers the project config
5
+ # through these. Hermetic: throwaway dirs. Run: bash scripts/lib/config-path-test.sh
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() { if [ "$2" = "$3" ]; then echo "ok: $1"; else echo "FAIL: $1 -> rc '$2' want '$3'"; fail=1; fi; }
12
+
13
+ # shellcheck source=/dev/null
14
+ . "$LIB/config-path.sh"
15
+
16
+ tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
17
+
18
+ # A) root cckit.config.json (self-host / current layout)
19
+ mkdir -p "$tmp/a"; printf '{}' > "$tmp/a/cckit.config.json"
20
+ t "finds a root cckit.config.json" "$(kit_config_find "$tmp/a")" "$tmp/a/cckit.config.json"
21
+
22
+ # B) scaffolded .claude/kit.config.json
23
+ mkdir -p "$tmp/b/.claude"; printf '{}' > "$tmp/b/.claude/kit.config.json"
24
+ t "finds a scaffolded .claude/kit.config.json" "$(kit_config_find "$tmp/b")" "$tmp/b/.claude/kit.config.json"
25
+
26
+ # C) cckit.config.json wins over .claude/kit.config.json in the same dir
27
+ mkdir -p "$tmp/c/.claude"; printf '{}' > "$tmp/c/cckit.config.json"; printf '{}' > "$tmp/c/.claude/kit.config.json"
28
+ t "root cckit.config.json wins over .claude/" "$(kit_config_find "$tmp/c")" "$tmp/c/cckit.config.json"
29
+
30
+ # D) walk up: a nested start dir resolves an ancestor's config
31
+ mkdir -p "$tmp/a/deep/nested"
32
+ t "walks up to an ancestor config" "$(kit_config_find "$tmp/a/deep/nested")" "$tmp/a/cckit.config.json"
33
+
34
+ # E) no config anywhere in the (isolated) tree -> rc 1, empty
35
+ mkdir -p "$tmp/empty"
36
+ out="$(kit_config_find "$tmp/empty" 2>/dev/null)"; r=$?
37
+ # (mktemp lives under /var|/tmp with no ancestor kit config, so this is a clean miss)
38
+ rc "no config -> rc 1" "$r" "1"
39
+ t "no config -> empty output" "$out" ""
40
+
41
+ # F) kit_config_path: an explicit KIT_CONFIG always wins, regardless of the start dir
42
+ t "KIT_CONFIG wins in kit_config_path" "$(KIT_CONFIG=/explicit/override.json kit_config_path "$tmp/a")" "/explicit/override.json"
43
+ # without KIT_CONFIG, kit_config_path delegates to the walk
44
+ t "kit_config_path walks when KIT_CONFIG unset" "$(KIT_CONFIG= kit_config_path "$tmp/b")" "$tmp/b/.claude/kit.config.json"
45
+
46
+ [ "$fail" -eq 0 ] && echo "ALL OK (config-path)" || echo "config-path: FAILURES"
47
+ exit "$fail"
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # config-path.sh — the ONE project-config-path resolver (#69). Every kit entrypoint discovers the
4
+ # project config the SAME way instead of re-deriving it inline: an explicit KIT_CONFIG always wins,
5
+ # otherwise walk up from a start dir for a root `cckit.config.json` (self-host / current layout) or a
6
+ # `.claude/kit.config.json` (scaffolded layout). Dependency-free pure shell (no jq, no other kit
7
+ # libs) so it is safe to source from anywhere — including bin/cckit before anything else loads.
8
+ # bash 3.2 + zsh compatible.
9
+ #
10
+ # kit_config_find <startdir> walk startdir -> / for a project config; prints path (rc 0) or rc 1.
11
+ # Ignores KIT_CONFIG — a pure "is <dir> under a kit project?" answer.
12
+ # kit_config_path [startdir] KIT_CONFIG wins, else kit_config_find; prints path (rc 0) or rc 1.
13
+
14
+ kit_config_find() {
15
+ local d="${1:-$PWD}"
16
+ d="$(cd "$d" 2>/dev/null && pwd)" || return 1
17
+ while [ -n "$d" ]; do
18
+ [ -f "$d/cckit.config.json" ] && { printf '%s\n' "$d/cckit.config.json"; return 0; }
19
+ [ -f "$d/.claude/kit.config.json" ] && { printf '%s\n' "$d/.claude/kit.config.json"; return 0; }
20
+ [ "$d" = "/" ] && break
21
+ d="$(dirname "$d")"
22
+ done
23
+ return 1
24
+ }
25
+
26
+ kit_config_path() {
27
+ if [ -n "${KIT_CONFIG:-}" ]; then printf '%s\n' "$KIT_CONFIG"; return 0; fi
28
+ kit_config_find "${1:-$PWD}"
29
+ }
@@ -7,10 +7,10 @@
7
7
  # Task-subagent prompt per issue (worktree-isolated, background), and the between-waves drive (gate +
8
8
  # merge with the captain, then re-run for the next wave). The agent reads the brief and acts.
9
9
  #
10
- # cckit copilot brief for the open board: wave 0 fan-out + the loop
11
- # cckit copilot --effort <N> brief scoped to effort #N's sub-issues
12
- # cckit copilot --cap <K> session ctx budget per wave (passed to the plan machine)
13
- # cckit copilot --llm the fan-out as TOON rows (wave,number,ctx,prompt) for an agent
10
+ # cckit wave brief for the open board: wave 0 fan-out + the loop
11
+ # cckit wave --effort <N> brief scoped to effort #N's sub-issues
12
+ # cckit wave --cap <K> session ctx budget per wave (passed to the plan machine)
13
+ # cckit wave --llm the fan-out as TOON rows (wave,number,ctx,prompt) for an agent
14
14
  #
15
15
  # Requires: gh, jq (via the plan machine). bash 3.2 / zsh compatible.
16
16
 
@@ -19,7 +19,7 @@ COPILOT_REPO="${COPILOT_REPO:-${KIT_REPO:-}}"
19
19
  # _copilot_seed <num> <title> — the headless subagent prompt for one issue (worktree already isolated).
20
20
  _copilot_seed() {
21
21
  local num="$1" title="$2"
22
- printf 'You are a Task subagent in a cckit copilot run — NO human is present, so never ask: decide autonomously and apply effort proportional to the task. Your worktree and branch for issue #%s are already isolated. Do: `gh issue view %s`, implement "%s", run `bash scripts/check.sh` until green, then open the PR with `cckit pr %s "<summary>"`. If it is a no-op, run `cckit close %s "<reason>"` with why. Return a one-line result.' \
22
+ printf 'You are a Task subagent in a cckit wave run — NO human is present, so never ask: decide autonomously and apply effort proportional to the task. Your worktree and branch for issue #%s are already isolated. Do: `gh issue view %s`, implement "%s", run `bash scripts/check.sh` until green, then open the PR with `cckit pr %s "<summary>"`. If it is a no-op, run `cckit close %s "<reason>"` with why. Return a one-line result.' \
23
23
  "$num" "$num" "$title" "$num" "$num"
24
24
  }
25
25
 
@@ -46,7 +46,7 @@ copilot_brief() {
46
46
  local rows
47
47
  rows="$(CCKIT_OUTPUT=tsv plan_machine "${planargs[@]+"${planargs[@]}"}" 2>/dev/null)"
48
48
  if [ -z "$rows" ]; then
49
- [ "$out" = "json" ] && echo "[]" || echo "copilot: nothing to drive (no open issues in scope)"
49
+ [ "$out" = "json" ] && echo "[]" || echo "wave: nothing to drive (no open issues in scope)"
50
50
  return 0
51
51
  fi
52
52
 
@@ -78,7 +78,7 @@ copilot_brief() {
78
78
  local n0 esfx; n0="$(printf '%s\n' "$wave0" | grep -c .)"
79
79
  esfx="$([ -n "$effort" ] && echo " --effort $effort")"
80
80
  {
81
- printf '# cckit copilot — %s%s\n' "$repo" "$([ -n "$effort" ] && echo " · effort #$effort")"
81
+ printf '# cckit wave — %s%s\n' "$repo" "$([ -n "$effort" ] && echo " · effort #$effort")"
82
82
  printf '\nThe plan machine laid out %s wave(s). You are the orchestrator: fan wave 0 out as parallel\nTask subagents, gate + merge with the captain, then re-run this brief for the next wave.\n' "$((waves_total + 1))"
83
83
 
84
84
  printf '\n## Wave 0 — spawn %s parallel Task subagent(s)\n\n' "$n0"
@@ -95,7 +95,7 @@ copilot_brief() {
95
95
  printf '1. When the wave-0 subagents have opened their PRs, gate + merge them:\n'
96
96
  printf ' ```\n cckit watch --merge%s\n ```\n' "$esfx"
97
97
  printf '2. Merging unblocks the next wave. Re-run this brief to get it:\n'
98
- printf ' ```\n cckit copilot%s\n ```\n' "$esfx"
99
- printf '3. Repeat until `cckit copilot` reports nothing to drive. To let the captain self-pace the\n gate/merge passes, use `cckit watch --loop` (or drive this brief under `/loop`).\n\n'
98
+ printf ' ```\n cckit wave%s\n ```\n' "$esfx"
99
+ printf '3. Repeat until `cckit wave` reports nothing to drive. To let the captain self-pace the\n gate/merge passes, use `cckit watch --loop` (or drive this brief under `/loop`).\n\n'
100
100
  } | cckit_render
101
101
  }
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # effort-metrics-test.sh — covers _em_token_sum's branch ∪ time-window attribution (#124). Token
4
+ # actuals must count sessions that match the effort BRANCH as well as sessions that fall inside the
5
+ # effort's build WINDOW [start,end] — the window recovers sessions logged before the branch field
6
+ # existed or from a detached/worktree checkout. Hermetic: a throwaway repo + a stubbed usage log +
7
+ # stubbed transcripts under a temp HOME. Run: bash scripts/lib/effort-metrics-test.sh
8
+ set -u
9
+ ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
10
+ LIB="$ROOT/scripts/lib"
11
+ fail=0
12
+ t() { if [ "$2" = "$3" ]; then echo "ok: $1"; else echo "FAIL: $1 -> got '[$2]' want '[$3]'"; fi; [ "$2" = "$3" ] || fail=1; }
13
+ command -v jq >/dev/null 2>&1 || { echo "effort-metrics-test: jq required — skipping"; exit 0; }
14
+ command -v git >/dev/null 2>&1 || { echo "effort-metrics-test: git required" >&2; exit 1; }
15
+
16
+ tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
17
+ export HOME="$tmp/home"; mkdir -p "$HOME/.claude/projects"
18
+
19
+ # A repo so git-common-dir resolves; kit-usage.jsonl lives under it.
20
+ cd "$tmp"; git init -q repo; cd repo; git config user.email t@t; git config user.name t
21
+ git commit -q --allow-empty -m init
22
+ GCD="$(git rev-parse --git-common-dir)"; case "$GCD" in /*) : ;; *) GCD="$PWD/$GCD" ;; esac
23
+
24
+ # Usage log: A matches the branch; B matches the window (different branch, ts inside); C matches
25
+ # neither (different branch, ts outside the window).
26
+ START=1000000000; END=1000000900 # a 900s window
27
+ {
28
+ printf '{"session":"AAA","branch":"effort/5-x","ts":"2001-09-09T01:46:20Z"}\n' # branch match (ts irrelevant)
29
+ printf '{"session":"BBB","branch":"other/9-y","ts":"2001-09-09T01:55:00Z"}\n' # ~1000000500 — inside window
30
+ printf '{"session":"CCC","branch":"other/9-z","ts":"2020-01-01T00:00:00Z"}\n' # far outside window
31
+ } > "$GCD/kit-usage.jsonl"
32
+
33
+ # Transcripts: A=100 in, B=50 in, C=999 in. Only A+B should be counted.
34
+ printf '{"message":{"usage":{"input_tokens":100,"output_tokens":10,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}\n' > "$HOME/.claude/projects/AAA.jsonl"
35
+ printf '{"message":{"usage":{"input_tokens":50,"output_tokens":5,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}\n' > "$HOME/.claude/projects/BBB.jsonl"
36
+ printf '{"message":{"usage":{"input_tokens":999,"output_tokens":99,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}}\n' > "$HOME/.claude/projects/CCC.jsonl"
37
+
38
+ # shellcheck source=/dev/null
39
+ source "$LIB/effort-metrics.sh"
40
+
41
+ # branch only: counts A (100/10); window given but branch alone would miss B if window absent.
42
+ read -r i o _ _ <<< "$(_em_token_sum 'effort/5-x' 0 0)"
43
+ t "branch-only counts the branch session" "$i $o" "100 10"
44
+
45
+ # branch ∪ window: counts A (branch) + B (window) = 150 in / 15 out; C excluded (outside window).
46
+ read -r i o _ _ <<< "$(_em_token_sum 'effort/5-x' "$START" "$END")"
47
+ t "branch ∪ window counts branch + window sessions" "$i $o" "150 15"
48
+
49
+ # window only (no branch): counts just B (inside window), never C.
50
+ read -r i o _ _ <<< "$(_em_token_sum '' "$START" "$END")"
51
+ t "window-only counts the in-window session" "$i $o" "50 5"
52
+
53
+ # no branch, no window: nothing attributable.
54
+ t "no branch + no window sums to zero" "$(_em_token_sum '' 0 0)" "0 0 0 0"
55
+
56
+ [ "$fail" -eq 0 ] && echo "ALL OK (effort-metrics)" || echo "effort-metrics: FAILURES"
57
+ exit "$fail"
@@ -105,12 +105,26 @@ effort_ctx_bucket() {
105
105
  # ~/.claude/projects/*/. Echoes "in out cache_read cache_write" (0s when unmappable). Going-forward
106
106
  # only — the usage log is empty for the past (backtrace left tokens null, by design).
107
107
  _em_token_sum() {
108
- local branch="$1" gcd ulog sids sid tx tin=0 tout=0 tcr=0 tcw=0 sums
108
+ # <branch> [start-epoch] [end-epoch] — attribute usage sessions to the effort by branch UNION a
109
+ # time window (#124). Branch alone misses sessions logged before the branch field was recorded or
110
+ # from a detached/worktree checkout; the [start,end] window (the effort's build span) recovers them.
111
+ local branch="$1" start="${2:-0}" end="${3:-0}" gcd ulog sids sid tx tin=0 tout=0 tcr=0 tcw=0 sums
109
112
  local IFS=' ' # force space-split for `set --` (ambient IFS may carry a NUL — see ifs landmine)
113
+ [[ "$start" =~ ^[0-9]+$ ]] || start=0; [[ "$end" =~ ^[0-9]+$ ]] || end=0
110
114
  gcd="$(git rev-parse --git-common-dir 2>/dev/null)" || { echo "0 0 0 0"; return 0; }
111
115
  ulog="$gcd/kit-usage.jsonl"
112
- [[ -f "$ulog" && -n "$branch" ]] || { echo "0 0 0 0"; return 0; }
113
- sids="$(jq -r --arg b "$branch" 'select(.branch==$b and .session!="")|.session' "$ulog" 2>/dev/null | sort -u)"
116
+ [[ -f "$ulog" ]] || { echo "0 0 0 0"; return 0; }
117
+ # A session counts when it matches the branch OR falls inside the [start,end] window (when given).
118
+ # `try … catch 0` keeps a malformed .ts row from aborting the whole filter.
119
+ sids="$(jq -r --arg b "$branch" --argjson s "$start" --argjson e "$end" '
120
+ select(.session != "")
121
+ | select(
122
+ ($b != "" and .branch == $b)
123
+ or ($s > 0 and $e > 0
124
+ and (try (.ts | fromdateiso8601) catch 0) >= $s
125
+ and (try (.ts | fromdateiso8601) catch 0) <= $e)
126
+ )
127
+ | .session' "$ulog" 2>/dev/null | sort -u)"
114
128
  [[ -n "$sids" ]] || { echo "0 0 0 0"; return 0; }
115
129
  while IFS= read -r sid; do
116
130
  [[ -n "$sid" ]] || continue
@@ -156,8 +170,8 @@ capture_effort_metrics() {
156
170
  echo "effort-metrics: WARN #$num — capture on '$branch' with an empty diff; run it PRE-close (the effort branch is gone). Recording zeros." >&2
157
171
  fi
158
172
 
159
- # token/cost actuals (#807) — going-forward only.
160
- toks="$(_em_token_sum "$branch")"; read -r tin tout tcr tcw <<< "$toks"
173
+ # token/cost actuals (#807) — attribute by branch UNION the effort's build window [start,now] (#124).
174
+ toks="$(_em_token_sum "$branch" "${start:-0}" "${now:-0}")"; read -r tin tout tcr tcw <<< "$toks"
161
175
  tin=${tin:-0}; tout=${tout:-0}; tcr=${tcr:-0}; tcw=${tcw:-0}
162
176
  if (( tin + tout + tcr + tcw > 0 )); then
163
177
  tokens_real=$(( tin + tout + tcr + tcw ))
@@ -38,6 +38,7 @@ SH
38
38
  chmod +x "$stub/gh"
39
39
  export PATH="$stub:$PATH"
40
40
  export KIT_REPO="o/r" EFFORT_REPO="o/r" KIT_BASE_BRANCH="main"
41
+ export KIT_WT_INSTALL=0 # #119: skip the dependency install during the hermetic worktree bootstrap
41
42
  # shellcheck source=/dev/null
42
43
  source "$LIB/effort.sh" 2>/dev/null
43
44
  # shellcheck source=/dev/null
@@ -63,21 +64,69 @@ t "effort_new creates nothing on a bad title" "$(grep -c 'issue create' "$G
63
64
  && git push -q origin HEAD:main )
64
65
  cd "$tmp/work"
65
66
 
67
+ # #119: a gitignored local env in the root must be copied into the fresh worktree by wt_bootstrap.
68
+ printf 'SECRET=from-root\n' > "$tmp/work/.env.local"
69
+
66
70
  start_out="$(effort_start 99 demo 2>/dev/null)"
67
71
  t "effort_start echoes wt|branch|num" "${start_out##*|}" "99"
68
72
  t "effort_start created the branch" "$(git show-ref --verify --quiet refs/heads/effort/99-demo && echo yes)" "yes"
73
+ # #119: worktree dir follows the kind+N-slug convention (gc-recognizable), not the old effort-N form.
74
+ # (compare the trailing path segments — mktemp's /var may resolve to /private/var on macOS)
75
+ t "effort_start worktree dir is effort+N-slug" \
76
+ "$(printf '%s' "${start_out%%|*}" | sed -E 's#^.*/(\.claude/worktrees/.*)$#\1#')" \
77
+ ".claude/worktrees/effort+99-demo"
78
+ t "effort_start bootstrapped the worktree (.env.local copied)" \
79
+ "$(cat "$tmp/work/.claude/worktrees/effort+99-demo/.env.local" 2>/dev/null)" "SECRET=from-root"
69
80
 
70
81
  # move onto the effort branch (its worktree) for pr/close
71
- cd "$tmp/work/.claude/worktrees/effort-99"
82
+ cd "$tmp/work/.claude/worktrees/effort+99-demo"
72
83
  : > "$GH_LOG"
73
84
  effort_pr 99 >/dev/null 2>&1
74
85
  tc "$GH_LOG" 'pr create .*--base main --head effort/99-demo' "effort_pr opens effort/99 → main"
75
86
 
87
+ # ── effort_close #120: refuse-squash-without-trace backstop ────────────────────────────────────
88
+ # With NO commits on the effort branch, effort_snapshot_subs captures no trace → close must refuse
89
+ # (the squash would erase per-sub history), and must NOT merge.
90
+ : > "$GH_LOG"
91
+ close_out="$(effort_close 99 2>&1)"; rc=$?
92
+ t "effort_close refuses without a trace (rc 1)" "$rc" "1"
93
+ case "$close_out" in *"refusing to squash"*) echo "ok: refuse message explains itself" ;; *) echo "FAIL: refuse message: $close_out"; fail=1 ;; esac
94
+ t "effort_close did NOT merge without a trace" "$(grep -c 'pr merge' "$GH_LOG")" "0"
95
+
96
+ # ── effort_close #120: happy path — commit present → trace captured → full close ────────────────
97
+ # A real commit on the effort branch gives snapshot something to trace; close then proceeds through
98
+ # capture (pre-squash) → merge → judge/sync → close subs+parent → worktree GC.
99
+ echo "work" > file.txt
100
+ git -c user.email=t@t -c user.name=t add file.txt
101
+ git -c user.email=t@t -c user.name=t commit -q -m "feat: do the thing (#101)"
76
102
  : > "$GH_LOG"
77
- effort_close 99 >/dev/null 2>&1
103
+ close_out="$(effort_close 99 2>&1)"; rc=$?
104
+ cd "$tmp/work" # our cwd (the effort worktree) is GC'd by the close — step to the main checkout
105
+ t "effort_close succeeds with a trace (rc 0)" "$rc" "0"
78
106
  tc "$GH_LOG" 'pr merge effort/99-demo .*--squash' "effort_close squash-merges the PR"
79
107
  tc "$GH_LOG" 'issue close 101' "effort_close closes sub #101"
80
108
  tc "$GH_LOG" 'issue close 99 ' "effort_close closes the parent"
109
+ case "$close_out" in *"metrics:"*) echo "ok: capture_effort_metrics composed into close" ;; *) echo "FAIL: no metrics capture in close"; fail=1 ;; esac
110
+ t "effort_close GC removed the effort worktree" \
111
+ "$(git -C "$tmp/work" worktree list --porcelain | grep -c 'effort+99-demo')" "0"
112
+ t "effort_close GC deleted the local branch" \
113
+ "$(git -C "$tmp/work" show-ref --verify --quiet refs/heads/effort/99-demo && echo yes || echo no)" "no"
114
+
115
+ # ── effort_close #120: KIT_FORCE=1 override + config-gated knowledge-ingest hook ───────────────
116
+ # A second effort with no commits: close refuses by default, but KIT_FORCE=1 proceeds to merge. A
117
+ # configured knowledge-ingest hook runs post-close with the effort number (no-op when unset).
118
+ cat > "$stub/khook" <<'SH'
119
+ #!/usr/bin/env bash
120
+ printf 'ingested %s\n' "$1" > "$KHOOK_MARKER"
121
+ SH
122
+ chmod +x "$stub/khook"
123
+ start_out="$(effort_start 88 forced 2>/dev/null)"
124
+ cd "$tmp/work/.claude/worktrees/effort+88-forced"
125
+ : > "$GH_LOG"
126
+ KHOOK_MARKER="$tmp/khook.out" KIT_EFFORT_KNOWLEDGE_HOOK="$stub/khook" KIT_FORCE=1 effort_close 88 >/dev/null 2>&1
127
+ cd "$tmp/work"
128
+ tc "$GH_LOG" 'pr merge effort/88-forced .*--squash' "KIT_FORCE=1 close merges despite no trace"
129
+ t "knowledge-ingest hook ran with the effort number" "$(cat "$tmp/khook.out" 2>/dev/null)" "ingested 88"
81
130
 
82
131
  [ "$fail" -eq 0 ] && echo "ALL OK (effort-ops)" || echo "effort-ops: FAILURES"
83
132
  exit "$fail"