@jeiemgi/cckit 0.6.1 → 0.7.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 (114) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/AGENTS.md +34 -3
  3. package/README.md +86 -5
  4. package/bin/cckit +72 -3
  5. package/cckit.config.json +6 -1
  6. package/kit.config.schema.json +26 -1
  7. package/package.json +1 -1
  8. package/profiles/automation.json +2 -1
  9. package/profiles/content.json +2 -1
  10. package/profiles/minimal.json +2 -1
  11. package/profiles/research.json +2 -1
  12. package/profiles/software.json +2 -1
  13. package/scripts/init.sh +31 -1
  14. package/scripts/lib/board-view-test.sh +1 -0
  15. package/scripts/lib/board-view.sh +1 -0
  16. package/scripts/lib/captain-test.sh +62 -0
  17. package/scripts/lib/captain.sh +105 -17
  18. package/scripts/lib/cckit-output.sh +1 -0
  19. package/scripts/lib/commitlint.sh +1 -0
  20. package/scripts/lib/config-path-test.sh +1 -0
  21. package/scripts/lib/config-path.sh +1 -0
  22. package/scripts/lib/copilot-test.sh +1 -0
  23. package/scripts/lib/copilot.sh +1 -0
  24. package/scripts/lib/effort-dispatch-test.sh +10 -0
  25. package/scripts/lib/effort-flows-test.sh +1 -0
  26. package/scripts/lib/effort-metrics-test.sh +1 -0
  27. package/scripts/lib/effort-metrics.sh +1 -0
  28. package/scripts/lib/effort-ops-test.sh +360 -0
  29. package/scripts/lib/effort-ops.sh +372 -16
  30. package/scripts/lib/effort-parity-test.sh +1 -0
  31. package/scripts/lib/effort-plan.sh +1 -0
  32. package/scripts/lib/effort-slug-test.sh +32 -0
  33. package/scripts/lib/effort-slug.sh +72 -8
  34. package/scripts/lib/effort.sh +1 -0
  35. package/scripts/lib/engine-adapter.sh +1 -0
  36. package/scripts/lib/errors-header-test.sh +86 -0
  37. package/scripts/lib/gh-log.sh +1 -0
  38. package/scripts/lib/gh-project-test.sh +1 -0
  39. package/scripts/lib/gh-project.sh +1 -0
  40. package/scripts/lib/git-remote-test.sh +1 -0
  41. package/scripts/lib/git-remote.sh +1 -0
  42. package/scripts/lib/handoff.sh +23 -2
  43. package/scripts/lib/kit-brief-test.sh +292 -0
  44. package/scripts/lib/kit-brief.sh +376 -0
  45. package/scripts/lib/kit-cli-test.sh +1 -0
  46. package/scripts/lib/kit-cli.sh +1 -0
  47. package/scripts/lib/kit-config-resolve.sh +1 -0
  48. package/scripts/lib/kit-config-test.sh +14 -0
  49. package/scripts/lib/kit-config.sh +7 -0
  50. package/scripts/lib/kit-engine-test.sh +1 -0
  51. package/scripts/lib/kit-events.sh +1 -0
  52. package/scripts/lib/kit-gc-test.sh +125 -0
  53. package/scripts/lib/kit-gc.sh +193 -5
  54. package/scripts/lib/kit-interview-test.sh +1 -0
  55. package/scripts/lib/kit-interview.sh +1 -0
  56. package/scripts/lib/kit-lib-test.sh +226 -0
  57. package/scripts/lib/kit-lib.sh +308 -0
  58. package/scripts/lib/kit-local.sh +1 -0
  59. package/scripts/lib/kit-manifest.sh +1 -0
  60. package/scripts/lib/kit-mode-test.sh +1 -0
  61. package/scripts/lib/kit-mode.sh +1 -0
  62. package/scripts/lib/kit-msg-test.sh +1 -0
  63. package/scripts/lib/kit-msg.sh +1 -0
  64. package/scripts/lib/kit-operate.sh +1 -0
  65. package/scripts/lib/kit-profile-test.sh +1 -0
  66. package/scripts/lib/kit-profile.sh +1 -0
  67. package/scripts/lib/kit-state-test.sh +89 -0
  68. package/scripts/lib/kit-state.sh +61 -0
  69. package/scripts/lib/kit-status-test.sh +233 -0
  70. package/scripts/lib/kit-status.sh +415 -0
  71. package/scripts/lib/kit-task-ops-test.sh +1 -0
  72. package/scripts/lib/kit-task-ops.sh +1 -0
  73. package/scripts/lib/next.sh +1 -0
  74. package/scripts/lib/plan-machine-test.sh +54 -0
  75. package/scripts/lib/plan-machine.sh +86 -25
  76. package/scripts/lib/plan-next-test.sh +1 -0
  77. package/scripts/lib/plan-next.sh +1 -0
  78. package/scripts/lib/pr-evidence-test.sh +259 -0
  79. package/scripts/lib/pr-evidence.sh +220 -35
  80. package/scripts/lib/project-scan.sh +1 -0
  81. package/scripts/lib/react-detect.sh +1 -0
  82. package/scripts/lib/render-test.sh +1 -0
  83. package/scripts/lib/render.sh +1 -0
  84. package/scripts/lib/role-identity.sh +1 -0
  85. package/scripts/lib/secret-guard.sh +21 -1
  86. package/scripts/lib/toon.sh +1 -0
  87. package/scripts/lib/ui.sh +1 -0
  88. package/scripts/lib/version-bump-test.sh +1 -0
  89. package/scripts/lib/version-bump.sh +1 -0
  90. package/scripts/lib/worktree-bootstrap-test.sh +220 -0
  91. package/scripts/lib/worktree-issue-test.sh +15 -1
  92. package/scripts/lib/worktree-issue.sh +23 -8
  93. package/scripts/lib/worktree-start.sh +191 -7
  94. package/scripts/lib/zsh-safety-test.sh +10 -0
  95. package/scripts/portable-test.sh +13 -2
  96. package/scripts/self-install-test.sh +282 -0
  97. package/scripts/setup-labels.sh +1 -0
  98. package/scripts/status.sh +25 -10
  99. package/skills/kit-cleanup/SKILL.md +83 -0
  100. package/skills/kit-effort-close/SKILL.md +3 -0
  101. package/skills/kit-effort-new/SKILL.md +7 -0
  102. package/skills/kit-effort-start/SKILL.md +39 -4
  103. package/skills/kit-gc/SKILL.md +19 -0
  104. package/skills/kit-next/SKILL.md +5 -0
  105. package/skills/kit-status/SKILL.md +92 -0
  106. package/skills/kit-task-start/SKILL.md +7 -1
  107. package/templates/rules/branch-naming.md +20 -1
  108. package/templates/rules/communication-style.md +8 -0
  109. package/templates/rules/delegation-brief.md +38 -4
  110. package/templates/rules/effort-model.md +47 -4
  111. package/templates/rules/naming-and-ids.md +199 -0
  112. package/templates/rules/task-management.md +1 -1
  113. package/templates/skills/concrete/SKILL.md +117 -0
  114. package/templates/skills/karpathy-guidelines/SKILL.md +1 -0
@@ -0,0 +1,415 @@
1
+ #!/usr/bin/env bash
2
+ # shellcheck shell=bash
3
+ # kit-status.sh — "where are we?" as three buckets, from real state (#229).
4
+ # errors: mixed — the classifiers are pure; the fetchers degrade to empty, kit_status propagates nothing
5
+ #
6
+ # The question a session actually opens with is not "what does git say" but three things in order:
7
+ #
8
+ # 1. LOCAL UNDONE work that exists only on this machine — a dirty worktree, a branch with
9
+ # commits nobody else can see, an effort sub not merged into its effort branch.
10
+ # 2. PRS TO ATTEND open PRs that are waiting on a human: no approval, no AI-reviewer pass,
11
+ # unresolved review threads, red checks, a conflicting merge state.
12
+ # 3. CLEANUP branches and worktrees that can go, local AND remote.
13
+ #
14
+ # `git status` answers none of them, and answering them by hand takes a dozen commands whose output
15
+ # has to be cross-referenced against the board. Each bucket here is a pure classifier over data a
16
+ # thin fetcher collected, so the verdicts are unit-tested against fixtures rather than the network.
17
+ #
18
+ # Source it: source scripts/lib/kit-status.sh
19
+ # Depends on: git; gh + jq for the PR bucket (absent → the bucket says so); kit-gc.sh for cleanup.
20
+
21
+ # ── bucket 1: local undone work ────────────────────────────────────────────────────────────────
22
+
23
+ # status_local_rows [base] — one TSV row per piece of local-only work: `kind<TAB>name<TAB>detail`.
24
+ #
25
+ # dirty a worktree with uncommitted changes name = path
26
+ # unpushed a branch whose commits are on no remote name = branch
27
+ # unmerged a sub/<N> branch not yet in its effort/<N> name = branch
28
+ #
29
+ # A branch counts as `unpushed` when it holds commits reachable from NO remote ref — the honest test
30
+ # for "only this machine has this". Comparing against the branch's own upstream is not enough: an
31
+ # effort sub whose commits were merged into a pushed effort branch has no upstream of its own, yet
32
+ # its work is safely on the remote and is not undone. A branch that merely trails its upstream is
33
+ # not undone work either, and is deliberately absent. best-effort: without git, no rows.
34
+ status_local_rows() {
35
+ local base="${1:-${KIT_BASE_BRANCH:-main}}" wtpath ref b up ahead n effort
36
+ command -v git >/dev/null 2>&1 || return 0
37
+
38
+ # dirty worktrees (the main checkout included — it is a worktree too)
39
+ # `substr($0, 10)`, not `$2`: a worktree path may contain spaces, and `$2` silently truncates it
40
+ # at the first one — the row then names a directory that does not exist. ("worktree " is 9 chars.)
41
+ git worktree list --porcelain 2>/dev/null | awk '/^worktree /{print substr($0, 10)}' \
42
+ | while IFS= read -r wtpath; do
43
+ [ -d "$wtpath" ] || continue
44
+ n="$(git -C "$wtpath" status --porcelain 2>/dev/null | grep -c . || true)"
45
+ [ "${n:-0}" -gt 0 ] && printf 'dirty\t%s\t%s uncommitted file(s)\n' "$wtpath" "$n"
46
+ done
47
+
48
+ # branches carrying commits no remote has
49
+ git for-each-ref --format='%(refname:short)' refs/heads 2>/dev/null \
50
+ | while IFS= read -r b; do
51
+ [ -n "$b" ] || continue
52
+ case "$b" in "$base"|main|master|develop) continue ;; esac
53
+ # `--not --remotes`: commits on NO remote-tracking ref at all. This is what makes an effort
54
+ # sub already merged into a pushed effort branch correctly absent from the bucket.
55
+ ahead="$(git rev-list --count "$b" --not --remotes 2>/dev/null || echo 0)"
56
+ [ "${ahead:-0}" -gt 0 ] || continue
57
+ up="$(git rev-parse --abbrev-ref "$b@{u}" 2>/dev/null || true)"
58
+ if [ -n "$up" ]; then
59
+ printf 'unpushed\t%s\t%s commit(s) on no remote (upstream %s)\n' "$b" "$ahead" "$up"
60
+ else
61
+ printf 'unpushed\t%s\t%s commit(s) on no remote, no upstream branch\n' "$b" "$ahead"
62
+ fi
63
+ done
64
+
65
+ # effort subs not yet merged into their effort branch — the state that looks finished in a
66
+ # worktree and is invisible in the effort PR.
67
+ git for-each-ref --format='%(refname:short)' refs/heads 2>/dev/null \
68
+ | while IFS= read -r b; do
69
+ case "$b" in sub/*) : ;; *) continue ;; esac
70
+ n="${b#sub/}"; n="${n%%[!0-9]*}"
71
+ [ -n "$n" ] || continue
72
+ # Check EVERY effort branch, not `head -1`: picking an arbitrary one reports a sub as
73
+ # unmerged because it is absent from an effort it never belonged to. A sub branch name
74
+ # carries its own issue number, not its parent's, so the mapping cannot be derived — but
75
+ # containment can be tested, and "in no effort branch at all" is the honest verdict.
76
+ local found_in="" e
77
+ while IFS= read -r e; do
78
+ [ -n "$e" ] || continue
79
+ if git merge-base --is-ancestor "$b" "$e" 2>/dev/null; then found_in="$e"; break; fi
80
+ done <<EOT
81
+ $(git for-each-ref --format='%(refname:short)' "refs/heads/effort/*" 2>/dev/null)
82
+ EOT
83
+ [ -n "$found_in" ] && continue
84
+ effort="$(git for-each-ref --format='%(refname:short)' "refs/heads/effort/*" 2>/dev/null | head -1)"
85
+ [ -n "$effort" ] || continue
86
+ printf 'unmerged\t%s\tin no effort branch\n' "$b"
87
+ done
88
+ }
89
+
90
+ # status_worktree_rows — one TSV row per checked-out worktree: `path<TAB>branch`. The inventory half
91
+ # of "where are we": a clean worktree on an issue branch is still work in progress, and a session
92
+ # that cannot see it re-creates it. best-effort: without git, no rows.
93
+ status_worktree_rows() {
94
+ command -v git >/dev/null 2>&1 || return 0
95
+ # Same space-safe extraction as status_local_rows: take everything after the key, never `$2`.
96
+ # Emit per RECORD, not per `branch` line: a DETACHED worktree has a `HEAD` but no `branch`, so
97
+ # printing on `branch` alone silently drops it from the inventory — exactly the "in progress" work
98
+ # a session must not re-create. Flush on the next `worktree` and once more at EOF. ("branch " is
99
+ # 7 chars, "HEAD " is 5.)
100
+ git worktree list --porcelain 2>/dev/null \
101
+ | awk 'function emit() { if (seen) print w "\t" (b != "" ? b : "detached@" substr(head, 1, 12)) }
102
+ /^worktree /{ emit(); w=substr($0, 10); b=""; head=""; seen=1; next }
103
+ /^HEAD / { head=substr($0, 6); next }
104
+ /^branch / { b=substr($0, 8); sub(/^refs\/heads\//, "", b) }
105
+ END { emit() }'
106
+ }
107
+
108
+ # ── bucket 2: open PRs waiting on a human ──────────────────────────────────────────────────────
109
+
110
+ # status_prs_classify [ai_expected] — stdin is a JSON array of shaped PR objects; echo one TSV row
111
+ # per PR: `verdict<TAB>number<TAB>title<TAB>detail`. PURE (jq only, no gh), so every verdict below
112
+ # is unit-tested against fixtures.
113
+ #
114
+ # Each object: {number, title, draft, mergeable, checks, approvals, ai_review, unresolved}
115
+ # checks PASS | FAIL | PENDING | NONE (already collapsed by status_prs_fetch)
116
+ # approvals count of APPROVED reviews from non-bot authors
117
+ # ai_review true when an AI reviewer has reviewed this PR at all
118
+ # unresolved count of unresolved review threads
119
+ #
120
+ # The verdict is the ONE next action, most-blocking first: a conflict cannot be reviewed around, red
121
+ # checks make a review premature, and unresolved threads outrank a missing approval because the
122
+ # reviewer already spoke. `ai_expected` (1 when the repo evidently uses an AI reviewer) is what
123
+ # keeps `ai-review` from firing on every PR in a repo that has none.
124
+ status_prs_classify() {
125
+ local ai_expected="${1:-0}"
126
+ command -v jq >/dev/null 2>&1 || return 0
127
+ jq -r --argjson ai "${ai_expected:-0}" '
128
+ .[] |
129
+ . as $p |
130
+ (if ($p.mergeable // "") == "CONFLICTING" then "conflict"
131
+ elif ($p.checks // "NONE") == "FAIL" then "checks"
132
+ elif ($p.draft // false) then "draft"
133
+ elif ($p.checks // "NONE") == "PENDING" then "wait"
134
+ elif ($p.mergeable // "") == "UNKNOWN" then "wait"
135
+ elif (($p.unresolved // 0) > 0) then "threads"
136
+ elif ($ai == 1 and (($p.ai_review // false) | not)) then "ai-review"
137
+ elif (($p.approvals // 0) == 0) then "review"
138
+ else "ready" end) as $v |
139
+ (if $v == "conflict" then "merge state is CONFLICTING — rebase onto the base"
140
+ elif $v == "checks" then "a required check is failing"
141
+ elif $v == "draft" then "still a draft"
142
+ elif $v == "wait" then (if ($p.mergeable // "") == "UNKNOWN" and ($p.checks // "NONE") != "PENDING"
143
+ then "GitHub is still computing mergeability — re-check before merging"
144
+ else "checks still running" end)
145
+ elif $v == "threads" then "\($p.unresolved) unresolved review thread(s)"
146
+ elif $v == "ai-review" then "no AI-reviewer pass yet"
147
+ elif $v == "review" then "no human approval yet"
148
+ else "green and approved — mergeable" end) as $d |
149
+ # Escape `|`: the row is rendered into a markdown table, and an unescaped pipe in a PR title
150
+ # silently splits the cell — the title is attacker-adjacent text, not a controlled string.
151
+ [$v, ($p.number|tostring), ($p.title // "" | .[0:58] | gsub("\\|"; "\\|")), $d] | @tsv
152
+ ' 2>/dev/null || true
153
+ }
154
+
155
+ # status_prs_fetch — echo the shaped JSON array status_prs_classify expects, for the repo in
156
+ # $KIT_REPO. ONE `gh api graphql` call: open PRs with their reviews, review threads and the head
157
+ # commit's check rollup, collapsed to the four scalars the classifier reads.
158
+ #
159
+ # It always PRINTS a valid JSON array, but the rc distinguishes the two cases a caller must not
160
+ # conflate: rc 0 means the query ran (`[]` = genuinely no open PRs), rc 1 means it could not run
161
+ # (no gh, no jq, no auth, no network) and `[]` means "unknown", not "none". Reporting an empty
162
+ # bucket for an unreachable API is the failure this whole report exists to avoid.
163
+ status_prs_fetch() {
164
+ local repo="${1:-${KIT_REPO:-}}" owner name raw
165
+ command -v gh >/dev/null 2>&1 || { echo '[]'; return 1; }
166
+ command -v jq >/dev/null 2>&1 || { echo '[]'; return 1; }
167
+ case "$repo" in */*) owner="${repo%%/*}"; name="${repo##*/}" ;; *) echo '[]'; return 1 ;; esac
168
+
169
+ raw="$(gh api graphql -f owner="$owner" -f name="$name" -f query='
170
+ query($owner:String!,$name:String!){
171
+ repository(owner:$owner,name:$name){
172
+ pullRequests(states:OPEN, first:30, orderBy:{field:UPDATED_AT,direction:DESC}){
173
+ nodes{
174
+ number title isDraft mergeable
175
+ reviews(first:60){ nodes{ state author{ login } } }
176
+ reviewThreads(first:60){ nodes{ isResolved } }
177
+ commits(last:1){ nodes{ commit{ statusCheckRollup{
178
+ contexts(first:30){ nodes{
179
+ __typename
180
+ ... on CheckRun{ name conclusion startedAt }
181
+ ... on StatusContext{ context state createdAt }
182
+ } }
183
+ } } } }
184
+ }
185
+ }
186
+ }
187
+ }' 2>/dev/null)" || raw=""
188
+ [ -n "$raw" ] || { echo '[]'; return 1; }
189
+
190
+ printf '%s' "$raw" | jq -c '
191
+ def is_bot: test("(?i)(coderabbit|copilot|\\[bot\\]|-bot$|dependabot|renovate|sonar|codex)");
192
+ # Latest run per check name only. A re-run (or a PR retitle re-firing a title gate) leaves the
193
+ # superseded run in the rollup; counting every context then reports a PR as failing on a check
194
+ # that has since passed. Group by name, keep the newest timestamp, read the verdict of that one.
195
+ def rollup:
196
+ [ (.commits.nodes[0].commit.statusCheckRollup.contexts.nodes // [])[]
197
+ | { name: (.name // .context // ""),
198
+ at: (.startedAt // .createdAt // ""),
199
+ verdict: (.conclusion // .state // "") } ]
200
+ | group_by(.name)
201
+ | map(sort_by(.at) | last | .verdict);
202
+ [ (.data.repository.pullRequests.nodes // [])[]
203
+ | { number, title,
204
+ draft: .isDraft,
205
+ mergeable: .mergeable,
206
+ checks: ( rollup as $r
207
+ | if ($r | length) == 0 then "NONE"
208
+ elif ($r | map(select(. == "FAILURE" or . == "TIMED_OUT" or . == "CANCELLED" or . == "ERROR" or . == "ACTION_REQUIRED")) | length) > 0 then "FAIL"
209
+ elif ($r | map(select(. == "PENDING" or . == "IN_PROGRESS" or . == "QUEUED" or . == "EXPECTED" or . == "")) | length) > 0 then "PENDING"
210
+ else "PASS" end ),
211
+ approvals: ( [ (.reviews.nodes // [])[]
212
+ | select(.state == "APPROVED")
213
+ | select((.author.login // "") | is_bot | not) ] | length ),
214
+ ai_review: ( [ (.reviews.nodes // [])[]
215
+ | select((.author.login // "") | is_bot) ] | length > 0 ),
216
+ unresolved: ( [ (.reviewThreads.nodes // [])[] | select(.isResolved == false) ] | length )
217
+ } ]
218
+ ' 2>/dev/null || echo '[]'
219
+ }
220
+
221
+ # status_ai_expected [root] [prs-json] — rc 0 (and echo 1) when this repo evidently uses an AI
222
+ # reviewer, else echo 0. Two signals, both observable: a reviewer config file in the repo, or an AI
223
+ # review already present on one of the open PRs. Without this, `ai-review` would fire on every PR in
224
+ # a repo that has no AI reviewer, which is noise, not a finding. Pure given its inputs.
225
+ status_ai_expected() {
226
+ local root="${1:-.}" prs="${2:-[]}" f
227
+ for f in .coderabbit.yaml .coderabbit.yml .github/coderabbit.yaml .codex/config.toml; do
228
+ [ -f "$root/$f" ] && { printf '1'; return 0; }
229
+ done
230
+ if command -v jq >/dev/null 2>&1; then
231
+ case "$(printf '%s' "$prs" | jq -r 'map(select(.ai_review == true)) | length' 2>/dev/null)" in
232
+ ''|0) : ;;
233
+ *) printf '1'; return 0 ;;
234
+ esac
235
+ fi
236
+ printf '0'
237
+ }
238
+
239
+ # ── bucket 3: cleanup available ────────────────────────────────────────────────────────────────
240
+
241
+ # status_cleanup_counts — echo `safe<TAB>orphan<TAB>protected<TAB>remote_stale` for the current repo.
242
+ # The local three come from kit_gc_analyze (the ONE classifier, so status and gc can never disagree);
243
+ # `remote_stale` counts remote branches whose PR is merged and which are therefore deletable — the
244
+ # half `gc --prune` does not touch and a plain `git branch` view never shows.
245
+ # best-effort: an unavailable classifier yields zeros, never a broken bucket.
246
+ status_cleanup_counts() {
247
+ local out safe=0 orphan=0 prot=0 rstale=0 r b st
248
+ if command -v kit_gc_analyze >/dev/null 2>&1; then
249
+ out="$(kit_gc_analyze 2>/dev/null || true)"
250
+ safe="$(printf '%s\n' "$out" | grep -c -- '> SAFE ' || true)"
251
+ orphan="$(printf '%s\n' "$out" | grep -c -- '> ORPHAN' || true)"
252
+ prot="$(printf '%s\n' "$out" | grep -c -- '> PROTECTED:' || true)"
253
+ fi
254
+ if command -v git >/dev/null 2>&1 && command -v gh >/dev/null 2>&1; then
255
+ local base="${KIT_BASE_BRANCH:-main}" idx
256
+ # ONE PR query, reusing gc's index (#124) instead of a `gh pr list --head` per branch — an N+1
257
+ # that scales badly exactly when this count matters, i.e. with many stale branches. And
258
+ # `while IFS= read -r`, not `for … in $(…)`: an ambient IFS carrying a NUL breaks word
259
+ # splitting on a bare `for` (a bug this repo has already been bitten by).
260
+ if command -v _kit_gc_pr_index >/dev/null 2>&1; then
261
+ idx="$(_kit_gc_pr_index "${KIT_GC_REPO:-${KIT_REPO:-}}")"
262
+ else
263
+ idx="$(gh pr list --repo "${KIT_REPO:-}" --state all --limit 200 \
264
+ --json number,state,headRefName \
265
+ --jq '.[] | "\(.headRefName)\tPR#\(.number) \(.state)"' 2>/dev/null || true)"
266
+ fi
267
+ while IFS= read -r r; do
268
+ [ -n "$r" ] || continue
269
+ b="${r#origin/}"
270
+ case "$b" in "$base"|main|master|develop) continue ;; esac
271
+ st="$(printf '%s\n' "$idx" | awk -F'\t' -v want="$b" '$1==want{print $2; exit}')"
272
+ case "$st" in *MERGED*) rstale=$((rstale + 1)) ;; *) : ;; esac
273
+ done <<EOT
274
+ $(git branch -r --format='%(refname:short)' 2>/dev/null | grep -v HEAD || true)
275
+ EOT
276
+ fi
277
+ printf '%s\t%s\t%s\t%s\n' "${safe:-0}" "${orphan:-0}" "${prot:-0}" "${rstale:-0}"
278
+ }
279
+
280
+ # ── the three-bucket report ────────────────────────────────────────────────────────────────────
281
+
282
+ # status_buckets_md [root] — the three buckets as markdown on stdout. Each bucket states its own
283
+ # emptiness explicitly ("nothing local-only", "no open PRs"), because a silently missing bucket is
284
+ # indistinguishable from a clean one and this report is read to decide what to do next.
285
+ status_buckets_md() {
286
+ local root="${1:-.}" base="${KIT_BASE_BRANCH:-main}" rows prs ai prrows counts safe orphan prot rstale
287
+ local kind name detail verdict num title n_local
288
+
289
+ echo "## 1 · Local undone work"
290
+ echo ""
291
+ rows="$(status_local_rows "$base")"
292
+ n_local="$(printf '%s' "$rows" | grep -c . || true)"
293
+ if [ "${n_local:-0}" -gt 0 ]; then
294
+ while IFS="$(printf '\t')" read -r kind name detail; do
295
+ [ -n "$kind" ] || continue
296
+ case "$kind" in
297
+ dirty) printf -- '- **dirty** `%s` — %s\n' "$name" "$detail" ;;
298
+ unpushed) printf -- '- **unpushed** `%s` — %s\n' "$name" "$detail" ;;
299
+ unmerged) printf -- '- **unmerged sub** `%s` — %s\n' "$name" "$detail" ;;
300
+ *) printf -- '- %s `%s` — %s\n' "$kind" "$name" "$detail" ;;
301
+ esac
302
+ done <<EOF
303
+ $rows
304
+ EOF
305
+ else
306
+ echo "_Nothing local-only: every worktree is clean and every branch's commits are pushed._"
307
+ fi
308
+
309
+ local wt_rows n_wt
310
+ wt_rows="$(status_worktree_rows)"
311
+ n_wt="$(printf '%s' "$wt_rows" | grep -c . || true)"
312
+ if [ "${n_wt:-0}" -gt 0 ]; then
313
+ echo ""
314
+ printf -- '**In progress** — %s worktree(s) checked out:\n\n' "${n_wt:-0}"
315
+ while IFS="$(printf '\t')" read -r name detail; do
316
+ [ -n "$name" ] || continue
317
+ printf -- '- `%s` — `%s`\n' "${name##*/}" "$detail"
318
+ done <<EOF
319
+ $wt_rows
320
+ EOF
321
+ fi
322
+
323
+ echo ""
324
+ echo "## 2 · PRs waiting on a human"
325
+ echo ""
326
+ if command -v gh >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then
327
+ local pr_rc=0
328
+ prs="$(status_prs_fetch)" || pr_rc=$?
329
+ ai="$(status_ai_expected "$root" "$prs")"
330
+ prrows="$(printf '%s' "$prs" | status_prs_classify "$ai")"
331
+ if [ "$pr_rc" -ne 0 ]; then
332
+ echo "_Could not read the open PRs (gh unavailable, unauthenticated, or offline). This is NOT"
333
+ echo "the same as having none — re-run once \`gh auth status\` is clean._"
334
+ elif [ -n "$prrows" ]; then
335
+ echo "| PR | what it needs | title |"
336
+ echo "| --- | --- | --- |"
337
+ while IFS="$(printf '\t')" read -r verdict num title detail; do
338
+ [ -n "$num" ] || continue
339
+ printf '| #%s | **%s** — %s | %s |\n' "$num" "$verdict" "$detail" "$title"
340
+ done <<EOF
341
+ $prrows
342
+ EOF
343
+ [ "$ai" = "1" ] || echo ""
344
+ [ "$ai" = "1" ] || echo "_This repo shows no AI reviewer, so a missing AI pass is not reported._"
345
+ else
346
+ echo "_No open PRs._"
347
+ fi
348
+ else
349
+ echo "_gh or jq absent — this bucket needs both._"
350
+ fi
351
+
352
+ echo ""
353
+ echo "## 3 · Cleanup available"
354
+ echo ""
355
+ counts="$(status_cleanup_counts)"
356
+ safe="${counts%% *}"; counts="${counts#* }"
357
+ orphan="${counts%% *}"; counts="${counts#* }"
358
+ prot="${counts%% *}"; rstale="${counts##* }"
359
+ if [ "${safe:-0}" -gt 0 ] || [ "${rstale:-0}" -gt 0 ]; then
360
+ printf -- '- **%s** local branch(es) SAFE to delete — merged PR, issue closed\n' "${safe:-0}"
361
+ printf -- '- **%s** remote branch(es) whose PR merged\n' "${rstale:-0}"
362
+ printf -- '- kept: %s orphan (commits not on the base remote), %s protected (issue still open)\n' \
363
+ "${orphan:-0}" "${prot:-0}"
364
+ echo ""
365
+ echo "_\`cckit cleanup\` shows the plan; \`--yes\` acts on it._"
366
+ else
367
+ printf -- '_Nothing to clean. %s orphan / %s protected branch(es) are kept by design._\n' \
368
+ "${orphan:-0}" "${prot:-0}"
369
+ fi
370
+ }
371
+
372
+ # status_buckets_json [root] — the same three buckets as one JSON object, for an agent. Same
373
+ # classifiers as the markdown path, so the two can never disagree about a verdict.
374
+ status_buckets_json() {
375
+ local root="${1:-.}" base="${KIT_BASE_BRANCH:-main}" rows prs ai prrows counts safe orphan prot rstale
376
+ # No jq means no JSON at all. Emitting `{}` with rc 0 would hand an agent an empty report that
377
+ # reads as "nothing to do" — the exact confusion the markdown path is careful to avoid.
378
+ command -v jq >/dev/null 2>&1 || {
379
+ printf '%s\n' '{"error":"jq is required for --llm output","deps":{"jq":false}}'; return 1; }
380
+ local pr_rc=0 has_gh=false has_git=false
381
+ command -v gh >/dev/null 2>&1 && has_gh=true
382
+ command -v git >/dev/null 2>&1 && has_git=true
383
+ rows="$(status_local_rows "$base")"
384
+ local wt_rows; wt_rows="$(status_worktree_rows)"
385
+ prs="$(status_prs_fetch)" || pr_rc=$?
386
+ ai="$(status_ai_expected "$root" "$prs")"
387
+ prrows="$(printf '%s' "$prs" | status_prs_classify "$ai")"
388
+ counts="$(status_cleanup_counts)"
389
+ safe="${counts%% *}"; counts="${counts#* }"
390
+ orphan="${counts%% *}"; counts="${counts#* }"
391
+ prot="${counts%% *}"; rstale="${counts##* }"
392
+
393
+ jq -n \
394
+ --arg local_rows "$rows" \
395
+ --arg wt_rows "$wt_rows" \
396
+ --arg pr_rows "$prrows" \
397
+ --argjson safe "${safe:-0}" --argjson orphan "${orphan:-0}" \
398
+ --argjson protected "${prot:-0}" --argjson remote_stale "${rstale:-0}" \
399
+ --argjson ai_expected "${ai:-0}" \
400
+ --argjson prs_read "$([ "$pr_rc" -eq 0 ] && echo true || echo false)" \
401
+ --argjson has_gh "$has_gh" --argjson has_git "$has_git" '
402
+ def rows($s): if ($s | length) == 0 then [] else ($s | rtrimstr("\n") | split("\n") | map(select(length > 0) | split("\t"))) end;
403
+ { local_undone: (rows($local_rows) | map({kind: .[0], name: .[1], detail: .[2]})),
404
+ worktrees: (rows($wt_rows) | map({path: .[0], branch: .[1]})),
405
+ prs: (rows($pr_rows) | map({verdict: .[0], number: (.[1]|tonumber?), title: .[2], detail: .[3]})),
406
+ cleanup: { safe: $safe, orphan: $orphan, protected: $protected, remote_stale: $remote_stale },
407
+ ai_review_expected: ($ai_expected == 1),
408
+ # `prs_read: false` means the PR bucket is UNKNOWN, not empty — never treat its `[]` as "none".
409
+ prs_read: $prs_read,
410
+ deps: { git: $has_git, gh: $has_gh, jq: true } }
411
+ ' 2>/dev/null || { printf '%s\n' '{"error":"could not compose the status report"}'; return 1; }
412
+ # A report that could not read the PR bucket is not a clean report: signal it in the exit status
413
+ # too, so a caller that only checks rc does not act on a half-known state.
414
+ [ "$pr_rc" -eq 0 ]
415
+ }
@@ -2,6 +2,7 @@
2
2
  # kit-task-ops-test.sh — self-test for kit-task-ops.sh pure helpers under bash AND zsh.
3
3
  # Network-free: covers the parsers + body composers only (the gh-calling ops are not exercised).
4
4
  # Run: bash scripts/lib/kit-task-ops-test.sh
5
+ # errors: strict — a test runner: rc 1 on any failed assertion
5
6
 
6
7
  dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
7
8
 
@@ -23,6 +23,7 @@
23
23
  # kto_task_pr_merge [pr-num] squash-merge + close issues + switch develop + GC
24
24
  # kto_task_new <title> <role> <kind> <prio> <ms> [plan] [blocked] <body> create issue + board fields
25
25
  # kto_task_close <num> <summary> [pr-num] close issue + board → Done
26
+ # errors: mixed — git/gh ops propagate; board + label side effects are best-effort
26
27
 
27
28
  # --- repo resolution -----------------------------------------------------------------------------
28
29
  # Resolve the repo slug from KIT_REPO (kit-config) when available, else the kit's home repo. A
@@ -10,6 +10,7 @@
10
10
  # cckit next --llm the unblocked set as TOON rows {number,ctx,title}
11
11
  #
12
12
  # Requires gh + jq (via the plan machine). bash 3.2 / zsh compatible.
13
+ # errors: strict — refuses to recommend an issue without gh + jq
13
14
 
14
15
  NEXT_REPO="${NEXT_REPO:-${KIT_REPO:-}}"
15
16
 
@@ -3,6 +3,7 @@
3
3
  # Network-free: covers the wave layering, session/file packer, and file-hint parser only
4
4
  # (the gh-calling plan_machine orchestration is not exercised).
5
5
  # Run: bash scripts/lib/plan-machine-test.sh
6
+ # errors: strict — a test runner: rc 1 on any failed assertion
6
7
 
7
8
  dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
8
9
  TAB=$(printf '\t')
@@ -52,6 +53,59 @@ if [ -n "${PM_TEST_INNER:-}" ]; then
52
53
  dj="$(printf '1\tS\ta.sh\n2\tS\tb.sh\n' | pm_batches 8)"
53
54
  eq "disjoint same batch" "$(printf '%s\n' "$dj" | awk -F"$TAB" '$1==2{print $2}')" "0"
54
55
 
56
+ # ---- pm_prio_rank: p0..p3 map to 0..3; anything else/absent ranks last (9). ----
57
+ eq "rank p0" "$(pm_prio_rank p0)" "0"
58
+ eq "rank p1" "$(pm_prio_rank p1)" "1"
59
+ eq "rank p2" "$(pm_prio_rank p2)" "2"
60
+ eq "rank p3" "$(pm_prio_rank p3)" "3"
61
+ eq "rank unlabeled" "$(pm_prio_rank '')" "9"
62
+ eq "rank junk" "$(pm_prio_rank 'p9')" "9"
63
+
64
+ # ---- pm_prio_sort: stable priority order within ONE wave ----
65
+ # helper: emit just the number column, space-joined, so order is one comparable string.
66
+ order() { awk -F"$TAB" '{printf "%s%s", sep, $1; sep=" "} END{print ""}'; }
67
+
68
+ # p0 sorts ahead of p3 even when p3 arrived first.
69
+ eq "p0 before p3" \
70
+ "$(printf '1\tp3\tM\t\n2\tp0\tM\t\n' | pm_prio_sort | order)" "2 1"
71
+
72
+ # full ladder, input deliberately shuffled -> p0,p1,p2,p3.
73
+ eq "full ladder p0<p1<p2<p3" \
74
+ "$(printf '4\tp3\tM\t\n2\tp1\tM\t\n3\tp2\tM\t\n1\tp0\tM\t\n' | pm_prio_sort | order)" "1 2 3 4"
75
+
76
+ # STABILITY: equal priorities keep the incoming (dependency-derived) order, not numeric order.
77
+ eq "equal priority keeps input order" \
78
+ "$(printf '9\tp1\tM\t\n3\tp1\tM\t\n7\tp1\tM\t\n' | pm_prio_sort | order)" "9 3 7"
79
+
80
+ # unlabeled issues sort AFTER every labeled priority, and keep their own relative order.
81
+ eq "unlabeled sorts last, order kept" \
82
+ "$(printf '5\t\tM\t\n6\t\tM\t\n7\tp3\tM\t\n' | pm_prio_sort | order)" "7 5 6"
83
+
84
+ # pass-through: the trailing columns survive the sort untouched (they feed pm_batches).
85
+ eq "sort preserves payload columns" \
86
+ "$(printf '1\tp2\tL\ta.sh\n2\tp0\tS\tb.sh\n' | pm_prio_sort | head -1)" \
87
+ "2${TAB}p0${TAB}S${TAB}b.sh"
88
+
89
+ # ---- the safety property: a LOW-priority blocker still runs before its HIGH-priority dependent. ----
90
+ # #1 (p3) blocks #2 (p0). pm_waves puts them in different waves, so the priority sort — which only
91
+ # ever runs inside a single wave — can never see them together and can never invert them.
92
+ prio_dep="$(printf '1\t\n2\t1\n' | pm_waves)"
93
+ eq "p3 blocker lands in an earlier wave" \
94
+ "$(printf '%s\n' "$prio_dep" | awk -F"$TAB" '$1==1{print $2}')" "0"
95
+ eq "p0 dependent lands in a later wave" \
96
+ "$(printf '%s\n' "$prio_dep" | awk -F"$TAB" '$1==2{print $2}')" "1"
97
+ # and sorting each wave in isolation leaves each a single row -> the blocker still emits first.
98
+ eq "wave 0 sorted = the p3 blocker" \
99
+ "$(printf '1\tp3\tM\t\n' | pm_prio_sort | order)" "1"
100
+ eq "wave 1 sorted = the p0 dependent" \
101
+ "$(printf '2\tp0\tM\t\n' | pm_prio_sort | order)" "2"
102
+
103
+ # ---- priority order drives batch packing (p0 work packs into batch 0). ----
104
+ # budget 2 with three M(=2) issues -> one per batch; the p0 issue must own batch 0.
105
+ pb="$(printf '8\tp3\tM\t\n9\tp0\tM\t\n' | pm_prio_sort | cut -f1,3- | pm_batches 2)"
106
+ eq "p0 takes batch 0" "$(printf '%s\n' "$pb" | awk -F"$TAB" '$1==9{print $2}')" "0"
107
+ eq "p3 pushed to batch 1" "$(printf '%s\n' "$pb" | awk -F"$TAB" '$1==8{print $2}')" "1"
108
+
55
109
  # _pm_files: pulls a Files:/Touches: line, normalizes separators.
56
110
  eq "files hint comma" "$(_pm_files 'intro
57
111
  Files: a.sh, b.sh