sdtk-code-kit 0.5.0 → 0.6.1

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 (24) hide show
  1. package/README.md +1 -1
  2. package/assets/manifest/toolkit-bundle.manifest.json +69 -14
  3. package/assets/manifest/toolkit-bundle.sha256.txt +19 -8
  4. package/assets/toolkit/toolkit/AGENTS.md +2 -1
  5. package/assets/toolkit/toolkit/SDTKCODE_TOOLKIT.md +2 -2
  6. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +4 -4
  7. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +4 -4
  8. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +2 -2
  9. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +2 -2
  10. package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +4 -1
  11. package/assets/toolkit/toolkit/skills/code-issue/SKILL.md +75 -0
  12. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_FIX.md +31 -0
  13. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PICK.md +19 -0
  14. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PLAN.md +23 -0
  15. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_REVIEW.md +21 -0
  16. package/assets/toolkit/toolkit/skills/code-issue/references/PROFILE_TEMPLATE.md +53 -0
  17. package/assets/toolkit/toolkit/skills/code-issue/references/RECORDS.md +39 -0
  18. package/assets/toolkit/toolkit/skills/code-issue/scripts/test_tracker.py +300 -0
  19. package/assets/toolkit/toolkit/skills/code-issue/scripts/tracker.py +470 -0
  20. package/assets/toolkit/toolkit/skills/code-review/SKILL.md +2 -1
  21. package/assets/toolkit/toolkit/skills/code-review/references/lead-review-lessons.md +30 -0
  22. package/assets/toolkit/toolkit/skills/code-review/references/lead-review.md +120 -0
  23. package/package.json +1 -1
  24. package/src/lib/scope.js +1 -0
@@ -0,0 +1,470 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Issue tracker access for code-issue: one profile, three trackers (github, redmine, jira), stdlib only.
3
+
4
+ python tracker.py check # find + validate the profile, say which credential is missing
5
+ python tracker.py list [--all] [--json] # open issues (mine unless --all), normalized
6
+ python tracker.py pick [--json] [--limit N] # mine, blocked dropped, feature from the title, ranked
7
+ python tracker.py show <id> [--json] # issue + comments + attachments + links
8
+ python tracker.py comment <id> --body-file F [--apply]
9
+ python tracker.py transition <id> --to <status key> [--assign <user>] [--apply]
10
+
11
+ Reads are always safe. `comment` and `transition` print the request and send nothing unless `--apply` is given.
12
+ The profile is `issue_profile.json` (see references/PROFILE_TEMPLATE.md), found from the working directory upward
13
+ or given with --profile. Credentials come from environment variables named in the profile or from a `.env` beside it or
14
+ at the repository root; they are never printed. Every network call has a timeout, and `git` / `gh` run with prompts disabled.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import base64
20
+ import json
21
+ import os
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+
29
+ PROFILE_NAME = "issue_profile.json"
30
+ SEARCH_DIRS = ("", "docs", os.path.join("docs", "issues"), ".sdtk")
31
+ KINDS = ("github", "redmine", "jira")
32
+ NO_PROMPT_ENV = {"GIT_TERMINAL_PROMPT": "0", "GH_PROMPT_DISABLED": "1", "GCM_INTERACTIVE": "never"}
33
+
34
+
35
+ class TrackerError(Exception):
36
+ pass
37
+
38
+
39
+ # ---------------------------------------------------------------- profile + credentials
40
+ def find_profile(start: str | None = None) -> str | None:
41
+ cur = os.path.abspath(start or os.getcwd())
42
+ while True:
43
+ for sub in SEARCH_DIRS:
44
+ path = os.path.join(cur, sub, PROFILE_NAME)
45
+ if os.path.isfile(path):
46
+ return path
47
+ parent = os.path.dirname(cur)
48
+ if parent == cur:
49
+ return None
50
+ cur = parent
51
+
52
+
53
+ def read_dotenv(path: str) -> dict:
54
+ values = {}
55
+ if not os.path.isfile(path):
56
+ return values
57
+ with open(path, encoding="utf-8") as f:
58
+ for line in f:
59
+ line = line.strip()
60
+ if not line or line.startswith("#") or "=" not in line:
61
+ continue
62
+ key, _, value = line.partition("=")
63
+ values[key.strip().removeprefix("export ").strip()] = value.strip().strip('"').strip("'")
64
+ return values
65
+
66
+
67
+ def dotenv_dirs(profile_path: str) -> list:
68
+ """The profile's folder and its parents up to the repository root (the folder holding .git), nearest first."""
69
+ dirs, cur = [], os.path.dirname(os.path.abspath(profile_path))
70
+ while True:
71
+ dirs.append(cur)
72
+ parent = os.path.dirname(cur)
73
+ if os.path.exists(os.path.join(cur, ".git")) or parent == cur:
74
+ return dirs
75
+ cur = parent
76
+
77
+
78
+ def load_profile(path: str) -> dict:
79
+ with open(path, encoding="utf-8") as f:
80
+ prof = json.load(f)
81
+ prof["_path"] = path
82
+ problems = []
83
+ if prof.get("tracker") not in KINDS:
84
+ problems.append("tracker must be one of %s" % ", ".join(KINDS))
85
+ if not prof.get("project"):
86
+ problems.append("project is required (github: owner/repo, redmine: project identifier, jira: project key)")
87
+ if prof.get("tracker") in ("redmine", "jira") and not prof.get("base_url"):
88
+ problems.append("base_url is required for %s" % prof.get("tracker"))
89
+ if prof.get("title_pattern"):
90
+ try:
91
+ if "feature" not in re.compile(prof["title_pattern"]).groupindex:
92
+ problems.append("title_pattern needs a (?P<feature>...) group")
93
+ except re.error as exc:
94
+ problems.append("title_pattern is not a valid regular expression: %s" % exc)
95
+ if problems:
96
+ raise TrackerError("%s:\n - %s" % (path, "\n - ".join(problems)))
97
+ return prof
98
+
99
+
100
+ def credentials(prof: dict, environ=None) -> dict:
101
+ environ = os.environ if environ is None else environ
102
+ names = {"token": "ISSUE_TRACKER_TOKEN", "user": "ISSUE_TRACKER_USER"}
103
+ names.update(prof.get("credentials_env") or {})
104
+ dotenv = {}
105
+ for folder in dotenv_dirs(prof["_path"]): # nearest wins
106
+ dotenv = {**read_dotenv(os.path.join(folder, ".env")), **dotenv}
107
+ found = {}
108
+ for key, var in names.items():
109
+ value = environ.get(var) or dotenv.get(var)
110
+ if value:
111
+ found[key] = value
112
+ found["_names"] = names
113
+ return found
114
+
115
+
116
+ def gh_token(timeout: float) -> str | None:
117
+ """Fallback for GitHub: the token of a signed-in `gh`, never an interactive login."""
118
+ try:
119
+ r = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, timeout=timeout,
120
+ env={**os.environ, **NO_PROMPT_ENV}, check=False)
121
+ except (OSError, subprocess.TimeoutExpired):
122
+ return None
123
+ return r.stdout.strip() or None if r.returncode == 0 else None
124
+
125
+
126
+ # ---------------------------------------------------------------- HTTP
127
+ class Http:
128
+ def __init__(self, base: str, headers: dict, timeout: float):
129
+ self.base = base.rstrip("/")
130
+ self.headers = headers
131
+ self.timeout = timeout
132
+
133
+ def url(self, path: str, query: dict | None = None) -> str:
134
+ url = self.base + path
135
+ if query:
136
+ url += "?" + urllib.parse.urlencode(query)
137
+ return url
138
+
139
+ def call(self, method: str, path: str, query: dict | None = None, body=None):
140
+ data = None if body is None else json.dumps(body).encode("utf-8")
141
+ req = urllib.request.Request(self.url(path, query), data=data, method=method)
142
+ for k, v in self.headers.items():
143
+ req.add_header(k, v)
144
+ if data is not None:
145
+ req.add_header("Content-Type", "application/json")
146
+ try:
147
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
148
+ raw = resp.read()
149
+ except urllib.error.HTTPError as exc:
150
+ raise TrackerError("%s %s -> HTTP %s %s" % (method, path, exc.code, exc.read()[:300].decode("utf-8", "replace")))
151
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
152
+ raise TrackerError("%s %s -> %s (timeout %ss)" % (method, path, getattr(exc, "reason", exc), self.timeout))
153
+ return json.loads(raw.decode("utf-8")) if raw.strip() else {}
154
+
155
+
156
+ def issue(id_, title, status, assignee, priority, created, updated, url, blocked=False, labels=(), **extra):
157
+ return {"id": str(id_), "title": title or "", "status": status or "", "assignee": assignee or "",
158
+ "priority": priority or "", "created": created or "", "updated": updated or "", "url": url or "",
159
+ "blocked": bool(blocked), "labels": list(labels), **extra}
160
+
161
+
162
+ # ---------------------------------------------------------------- adapters
163
+ class Adapter:
164
+ """A write is a (method, path, body) tuple; `send` performs it. Reads go straight to the tracker."""
165
+
166
+ def __init__(self, prof: dict, creds: dict, timeout: float):
167
+ self.prof, self.creds, self.timeout = prof, creds, timeout
168
+ self.http = self.make_http()
169
+
170
+ def status_value(self, key: str):
171
+ statuses = self.prof.get("statuses") or {}
172
+ if key not in statuses:
173
+ raise TrackerError("status key %r is not in the profile's statuses (%s)" % (key, ", ".join(statuses) or "none"))
174
+ return statuses[key]
175
+
176
+ def send(self, write):
177
+ method, path, body = write
178
+ return self.http.call(method, path, body=body)
179
+
180
+
181
+ class GitHub(Adapter):
182
+ def make_http(self):
183
+ token = self.creds.get("token") or gh_token(self.timeout)
184
+ headers = {"Accept": "application/vnd.github+json", "User-Agent": "sdtk-code-issue"}
185
+ if token:
186
+ headers["Authorization"] = "Bearer " + token
187
+ return Http(self.prof.get("base_url") or "https://api.github.com", headers, self.timeout)
188
+
189
+ def _norm(self, d):
190
+ labels = [l["name"] for l in d.get("labels", [])]
191
+ blocked = bool(set(labels) & set(self.prof.get("blocked_labels") or []))
192
+ prio = next((l for l in self.prof.get("priority_labels") or [] if l in labels), "")
193
+ assignees = ",".join(a["login"] for a in d.get("assignees") or [])
194
+ return issue(d["number"], d["title"], d["state"], assignees, prio, d.get("created_at"), d.get("updated_at"),
195
+ d.get("html_url"), blocked, labels)
196
+
197
+ def list(self, mine: bool):
198
+ q = {"state": "open", "per_page": 100}
199
+ if mine:
200
+ q["assignee"] = self.prof.get("me") or "*"
201
+ data = self.http.call("GET", "/repos/%s/issues" % self.prof["project"], q)
202
+ return [self._norm(d) for d in data if "pull_request" not in d]
203
+
204
+ def show(self, id_):
205
+ d = self.http.call("GET", "/repos/%s/issues/%s" % (self.prof["project"], id_))
206
+ comments = self.http.call("GET", "/repos/%s/issues/%s/comments" % (self.prof["project"], id_))
207
+ out = self._norm(d)
208
+ out.update(description=d.get("body") or "", attachments=[],
209
+ comments=[{"author": c["user"]["login"], "at": c["created_at"], "body": c["body"]} for c in comments],
210
+ links=[])
211
+ return out
212
+
213
+ def comment(self, id_, body):
214
+ return [("POST", "/repos/%s/issues/%s/comments" % (self.prof["project"], id_), {"body": body})]
215
+
216
+ def transition(self, id_, key, assign):
217
+ value = self.status_value(key)
218
+ base = "/repos/%s/issues/%s" % (self.prof["project"], id_)
219
+ writes = []
220
+ if value in ("open", "closed"):
221
+ writes.append(("PATCH", base, {"state": value}))
222
+ else:
223
+ writes.append(("POST", base + "/labels", {"labels": [value]}))
224
+ if assign:
225
+ writes.append(("POST", base + "/assignees", {"assignees": [assign]}))
226
+ return writes
227
+
228
+
229
+ class Redmine(Adapter):
230
+ def make_http(self):
231
+ headers = {"Accept": "application/json"}
232
+ if self.creds.get("token"):
233
+ headers["X-Redmine-API-Key"] = self.creds["token"]
234
+ return Http(self.prof["base_url"], headers, self.timeout)
235
+
236
+ def _norm(self, d):
237
+ rels = d.get("relations") or []
238
+ blocked = any(r.get("relation_type") == "blocks" and str(r.get("issue_to_id")) == str(d["id"]) for r in rels)
239
+ return issue(d["id"], d.get("subject"), (d.get("status") or {}).get("name"),
240
+ (d.get("assigned_to") or {}).get("name"), (d.get("priority") or {}).get("name"),
241
+ d.get("created_on"), d.get("updated_on"), "%s/issues/%s" % (self.http.base, d["id"]), blocked,
242
+ priority_id=(d.get("priority") or {}).get("id"),
243
+ tracker=(d.get("tracker") or {}).get("name", ""))
244
+
245
+ def list(self, mine: bool):
246
+ q = {"project_id": self.prof["project"], "status_id": "open", "limit": 100, "include": "relations"}
247
+ if mine:
248
+ q["assigned_to_id"] = self.prof.get("me") or "me"
249
+ return [self._norm(d) for d in self.http.call("GET", "/issues.json", q).get("issues", [])]
250
+
251
+ def show(self, id_):
252
+ d = self.http.call("GET", "/issues/%s.json" % id_, {"include": "journals,attachments,relations"})["issue"]
253
+ out = self._norm(d)
254
+ out.update(description=d.get("description") or "",
255
+ comments=[{"author": (j.get("user") or {}).get("name", ""), "at": j.get("created_on", ""),
256
+ "body": j.get("notes", "")} for j in d.get("journals", []) if j.get("notes")],
257
+ attachments=[a.get("filename", "") for a in d.get("attachments", [])],
258
+ links=["%s %s -> %s" % (r.get("relation_type"), r.get("issue_id"), r.get("issue_to_id"))
259
+ for r in d.get("relations", [])])
260
+ return out
261
+
262
+ def comment(self, id_, body):
263
+ return [("PUT", "/issues/%s.json" % id_, {"issue": {"notes": body}})]
264
+
265
+ def transition(self, id_, key, assign):
266
+ fields = {"status_id": self.status_value(key)}
267
+ if assign:
268
+ fields["assigned_to_id"] = assign
269
+ return [("PUT", "/issues/%s.json" % id_, {"issue": fields})]
270
+
271
+
272
+ class Jira(Adapter):
273
+ FIELDS = "summary,status,assignee,priority,created,updated,issuelinks,labels"
274
+
275
+ def make_http(self):
276
+ headers = {"Accept": "application/json"}
277
+ user, token = self.creds.get("user"), self.creds.get("token")
278
+ if user and token:
279
+ headers["Authorization"] = "Basic " + base64.b64encode(("%s:%s" % (user, token)).encode()).decode()
280
+ elif token:
281
+ headers["Authorization"] = "Bearer " + token
282
+ return Http(self.prof["base_url"], headers, self.timeout)
283
+
284
+ def _norm(self, d):
285
+ f = d.get("fields") or {}
286
+ blocked = any(l.get("type", {}).get("name") == "Blocks" and "inwardIssue" in l
287
+ and ((l["inwardIssue"].get("fields") or {}).get("status") or {}).get("statusCategory", {}).get("key") != "done"
288
+ for l in f.get("issuelinks") or [])
289
+ return issue(d["key"], f.get("summary"), (f.get("status") or {}).get("name"),
290
+ (f.get("assignee") or {}).get("displayName"), (f.get("priority") or {}).get("name"),
291
+ f.get("created"), f.get("updated"), "%s/browse/%s" % (self.http.base, d["key"]), blocked,
292
+ f.get("labels") or [])
293
+
294
+ def list(self, mine: bool):
295
+ jql = 'project = "%s" AND statusCategory != Done' % self.prof["project"]
296
+ if mine:
297
+ jql += " AND assignee = currentUser()"
298
+ data = self.http.call("GET", "/rest/api/2/search", {"jql": jql + " ORDER BY created ASC", "maxResults": 100,
299
+ "fields": self.FIELDS})
300
+ return [self._norm(d) for d in data.get("issues", [])]
301
+
302
+ def show(self, id_):
303
+ d = self.http.call("GET", "/rest/api/2/issue/%s" % id_,
304
+ {"fields": self.FIELDS + ",description,comment,attachment"})
305
+ f = d.get("fields") or {}
306
+ out = self._norm(d)
307
+ out.update(description=f.get("description") or "",
308
+ comments=[{"author": (c.get("author") or {}).get("displayName", ""), "at": c.get("created", ""),
309
+ "body": c.get("body", "")} for c in (f.get("comment") or {}).get("comments", [])],
310
+ attachments=[a.get("filename", "") for a in f.get("attachment") or []],
311
+ links=["%s %s" % (l.get("type", {}).get("name"),
312
+ (l.get("inwardIssue") or l.get("outwardIssue") or {}).get("key"))
313
+ for l in f.get("issuelinks") or []])
314
+ return out
315
+
316
+ def comment(self, id_, body):
317
+ return [("POST", "/rest/api/2/issue/%s/comment" % id_, {"body": body})]
318
+
319
+ def transition(self, id_, key, assign):
320
+ wanted = self.status_value(key)
321
+ available = self.http.call("GET", "/rest/api/2/issue/%s/transitions" % id_).get("transitions", [])
322
+ match = [t for t in available if wanted in (t.get("id"), t.get("name"), (t.get("to") or {}).get("name"))]
323
+ if not match:
324
+ raise TrackerError("no transition to %r from the current status (available: %s)"
325
+ % (wanted, ", ".join(t.get("name", "") for t in available) or "none"))
326
+ writes = [("POST", "/rest/api/2/issue/%s/transitions" % id_, {"transition": {"id": match[0]["id"]}})]
327
+ if assign:
328
+ writes.append(("PUT", "/rest/api/2/issue/%s/assignee" % id_, {"accountId": assign}))
329
+ return writes
330
+
331
+
332
+ ADAPTERS = {"github": GitHub, "redmine": Redmine, "jira": Jira}
333
+
334
+
335
+ def adapter(prof: dict, timeout: float = 20.0, environ=None) -> Adapter:
336
+ return ADAPTERS[prof["tracker"]](prof, credentials(prof, environ), timeout)
337
+
338
+
339
+ # ---------------------------------------------------------------- pick
340
+ def feature_of(prof: dict, title: str) -> str | None:
341
+ pattern = prof.get("title_pattern")
342
+ if not pattern:
343
+ return None
344
+ m = re.search(pattern, title or "")
345
+ return m.group("feature") if m else None
346
+
347
+
348
+ def rank(prof: dict, issues: list) -> dict:
349
+ order = prof.get("priority_order") or prof.get("priority_labels") or []
350
+ lower = [p.lower() for p in order]
351
+
352
+ def prio(i):
353
+ p = (i.get("priority") or "").lower()
354
+ return lower.index(p) if p in lower else len(lower)
355
+
356
+ blocked = [i for i in issues if i["blocked"]]
357
+ ready = [i for i in issues if not i["blocked"]]
358
+ for i in ready:
359
+ i["feature"] = feature_of(prof, i["title"])
360
+ i["title_ok"] = i["feature"] is not None or not prof.get("title_pattern")
361
+ ready.sort(key=lambda i: (prio(i), i.get("created") or "", i["id"]))
362
+ return {"candidates": ready, "blocked": blocked}
363
+
364
+
365
+ def render_pick(prof: dict, picked: dict, limit: int) -> str:
366
+ features = prof.get("features") or {}
367
+ lines = ["# Next issue candidates — %s (%s)" % (prof["project"], prof["tracker"]), ""]
368
+ if not picked["candidates"]:
369
+ lines.append("No open issue assigned to you is ready.")
370
+ for n, i in enumerate(picked["candidates"][:limit], 1):
371
+ feat = i.get("feature")
372
+ where = "%s (%s)" % (feat, features[feat]) if feat in features else (feat or "? title does not follow the convention")
373
+ lines += ["%d. #%s %s" % (n, i["id"], i["title"]),
374
+ " priority: %s · status: %s · opened: %s" % (i["priority"] or "-", i["status"], i["created"][:10]),
375
+ " feature: %s" % where, " %s" % i["url"]]
376
+ if picked["blocked"]:
377
+ lines += ["", "Blocked (not candidates): " + ", ".join("#%s" % i["id"] for i in picked["blocked"])]
378
+ lines += ["", "Nothing was started. Say which issue to plan (`code-issue` plan mode)."]
379
+ return "\n".join(lines)
380
+
381
+
382
+ # ---------------------------------------------------------------- CLI
383
+ def describe_write(write, creds) -> str:
384
+ method, path, body = write
385
+ text = "%s %s\n%s" % (method, path, json.dumps(body, ensure_ascii=False, indent=2))
386
+ for key in ("token", "user"):
387
+ if creds.get(key):
388
+ text = text.replace(creds[key], "***")
389
+ return text
390
+
391
+
392
+ def main(argv=None) -> int:
393
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
394
+ ap.add_argument("--profile", help="path to issue_profile.json (default: search upward)")
395
+ ap.add_argument("--timeout", type=float, default=20.0, help="seconds per network call")
396
+ sub = ap.add_subparsers(dest="cmd", required=True)
397
+ sub.add_parser("check")
398
+ p = sub.add_parser("list"); p.add_argument("--all", action="store_true"); p.add_argument("--json", action="store_true")
399
+ p = sub.add_parser("pick"); p.add_argument("--json", action="store_true"); p.add_argument("--limit", type=int, default=5)
400
+ p = sub.add_parser("show"); p.add_argument("id"); p.add_argument("--json", action="store_true")
401
+ p = sub.add_parser("comment"); p.add_argument("id"); p.add_argument("--body-file", required=True)
402
+ p.add_argument("--apply", action="store_true")
403
+ p = sub.add_parser("transition"); p.add_argument("id"); p.add_argument("--to", required=True)
404
+ p.add_argument("--assign"); p.add_argument("--apply", action="store_true")
405
+ args = ap.parse_args(argv)
406
+
407
+ os.environ.update(NO_PROMPT_ENV) # anything this process starts (gh, git) must never prompt
408
+ try:
409
+ path = args.profile or find_profile()
410
+ if not path:
411
+ raise TrackerError("no %s found from %s upward; create one from references/PROFILE_TEMPLATE.md"
412
+ % (PROFILE_NAME, os.getcwd()))
413
+ prof = load_profile(path)
414
+ if args.cmd == "check":
415
+ creds = credentials(prof)
416
+ missing = [v for k, v in creds["_names"].items() if k not in creds
417
+ and not (k == "user" and prof["tracker"] != "jira")]
418
+ via = ""
419
+ if missing and prof["tracker"] == "github" and gh_token(args.timeout):
420
+ missing, via = [], " (via the signed-in gh)" # the same fallback every GitHub call uses
421
+ print("profile: %s (%s, project %s)" % (path, prof["tracker"], prof["project"]))
422
+ hint = " (environment, or .env beside the profile or at the repository root; never commit it)"
423
+ if prof["tracker"] == "github":
424
+ hint += " or sign in with `gh auth login`"
425
+ print("credentials: " + ("ok" + via if not missing else "missing " + ", ".join(missing) + hint))
426
+ return 0 if not missing else 2
427
+ ad = adapter(prof, args.timeout)
428
+ if args.cmd == "list":
429
+ data = ad.list(mine=not args.all)
430
+ print(json.dumps(data, ensure_ascii=False, indent=1) if args.json else
431
+ "\n".join("#%s [%s] %s%s" % (i["id"], i["status"], i["title"], " (blocked)" if i["blocked"] else "")
432
+ for i in data) or "no open issues")
433
+ elif args.cmd == "pick":
434
+ picked = rank(prof, ad.list(mine=True))
435
+ print(json.dumps(picked, ensure_ascii=False, indent=1) if args.json else render_pick(prof, picked, args.limit))
436
+ elif args.cmd == "show":
437
+ data = ad.show(args.id)
438
+ if args.json:
439
+ print(json.dumps(data, ensure_ascii=False, indent=1))
440
+ else:
441
+ print("#%s %s\nstatus: %s · assignee: %s · priority: %s\n%s\n\n%s" % (
442
+ data["id"], data["title"], data["status"], data["assignee"] or "-", data["priority"] or "-",
443
+ data["url"], data["description"]))
444
+ for c in data["comments"]:
445
+ print("\n--- %s %s\n%s" % (c["author"], c["at"], c["body"]))
446
+ if data["attachments"]:
447
+ print("\nattachments: " + ", ".join(data["attachments"]))
448
+ if data["links"]:
449
+ print("links: " + "; ".join(data["links"]))
450
+ else:
451
+ if args.cmd == "comment":
452
+ with open(args.body_file, encoding="utf-8") as f:
453
+ writes = ad.comment(args.id, f.read())
454
+ else:
455
+ writes = ad.transition(args.id, args.to, args.assign)
456
+ for w in writes:
457
+ print(describe_write(w, ad.creds))
458
+ if args.apply:
459
+ ad.send(w)
460
+ print("-> sent")
461
+ if not args.apply:
462
+ print("\nDry run: nothing was sent. Show this to the person; rerun with --apply once they agree.")
463
+ except TrackerError as exc:
464
+ print("error: %s" % exc, file=sys.stderr)
465
+ return 1
466
+ return 0
467
+
468
+
469
+ if __name__ == "__main__":
470
+ sys.exit(main())
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: code-review
3
- description: Code review -- requesting and receiving. Use when completing a feature, before merging, or when receiving review feedback.
3
+ description: Code review -- requesting and receiving. Use when completing a feature, before merging, when receiving review feedback, or when reviewing a developer's or an agent's pull request as the lead / PM against the task spec, decisions and smoke tests (including re-reviews and stacked PRs).
4
4
  ---
5
5
 
6
6
  # Code Review
@@ -75,5 +75,6 @@ Each issue should include:
75
75
  - Turning review into an unbounded refactor request.
76
76
 
77
77
  ## Integration
78
+ - Reviewing someone else's PR as the lead / PM (against spec, dated decisions, smoke-case ids; re-review; "can it merge?"; stacked PRs): follow `./references/lead-review.md` and read `./references/lead-review-lessons.md` first.
78
79
  - Use after `code-execute` or `code-parallel` finishes an implementation slice.
79
80
  - `code-ship` depends on this review gate being complete.
@@ -0,0 +1,30 @@
1
+ # Lead review — lessons from past reviews
2
+
3
+ Each lesson: what went wrong or was nearly missed → what to check. Project-specific decisions live in the project profile, not here. Read before every lead review (`lead-review.md`). Append a lesson after a review teaches something new; keep it generic.
4
+
5
+ ## Classifying findings
6
+ 1. **Open-question text is not the decision.** A review called a behaviour "a deviation from decision P" because the smoke file's open-question description mentioned the case — the decision itself covered only part of it. → Quote the decision row itself; if it does not cover the case, the spec is silent.
7
+ 2. **The person may ask "is this a dev error or a spec gap?"** → Put an "origin" line in every finding so the answer is already there.
8
+ 3. **"Decided with the lead on <date>" in a PR** happened three times; twice it contradicted the written docs. → Ask the person; then update the docs so the next review does not ask again.
9
+ 4. **A decision for one PR changes another PR.** A naming limit chosen for one task applied to the manual-input field of the next; a "no filter" decision for one search changed an earlier finding on a list screen. → After each decision, grep the other open reviews for the same rule and draft a follow-up comment.
10
+
11
+ ## What to check in code
12
+ 5. **Inherited hard-coded filters / constants** from the old logic (a fixed list of status values) silently drop data the new spec includes. → Compare every hard-coded list with the latest decision.
13
+ 6. **Limits against downstream constraints**: a 251-character folder name passed Windows' per-name limit but made the folder path exceed MAX_PATH (260) with the default base path. → Add base path + inner structure before accepting a length limit.
14
+ 7. **A check moved into shared code** (a "folder must be empty" rule placed in the core provision method) would have blocked another open branch's feature that merges into non-empty folders. → For every check added to shared code, list its callers on all open branches.
15
+ 8. **Removed or renamed functions** still called on `main` and other open branches → merge-time compile break. → `git grep <name>` on each open branch.
16
+ 9. **Whole-dataset reloads on paging/search** (fetching thousands of records per page click) → performance note; it is a decision only if the spec says nothing about it.
17
+ 10. **Button / flow semantics**: a first-run question's "Use" opened a settings tab with the switch still off; cancel left it off forever. → Check that each answer produces the state the spec names.
18
+ 11. **Reading code of the reviewed commit**, not the local checkout, and never checking out over the person's work.
19
+
20
+ ## Process
21
+ 12. **Ask before writing**, in one batch, with a recommendation each; the person often answers "record it, I decide later" — then write pending findings, not must-fix.
22
+ 13. **Drop what the person drops**: when told a finding needs no action, remove it from the report rather than keeping it as a note.
23
+ 14. **Keep the PR comment short**: action items + answers; the long reasoning stays in the report.
24
+ 15. **Merge chains**: stacked PRs merge in order with merge commits; each later PR merges `main` first. Write the order in every review of the chain.
25
+ 16. **Security issues found in other systems** (a server endpoint concatenating user input into SQL) → report to their owners as a separate item.
26
+ 17. **Pre-existing failing / flaky tests**: compare with the profile's list; new flaky tests in the PR's own area are findings, unrelated ones are a separate issue.
27
+ 18. **Before a re-review verdict**, confirm the head on the remote equals the commit the developer reported, and that the full suite ran on that head.
28
+ 19. **Test-only code in a product repository the team does not own** (UI Automation names, debug switches) was
29
+ pushed "only so CI can build it". → A finding in every review: hooks stay a private patch, the build comes from
30
+ `git archive` (`code-ui-e2e`), never a branch on the owner's remote.
@@ -0,0 +1,120 @@
1
+ # Reviewing a PR as the lead
2
+
3
+ For the person who owns the requirements (lead, PM) reviewing a developer's or an agent's pull request against the
4
+ task spec, the dated decisions, the mockups and the smoke tests; re-reviewing after fixes; or saying whether a PR —
5
+ possibly stacked on other open PRs — can merge.
6
+
7
+ ## Core rule
8
+
9
+ A finding is a defect only if it breaks a **written** rule: a task-spec section, a dated decision, a smoke case's
10
+ expected result. Name the rule and the code (`file:line` at the reviewed commit). A gap in the spec is a **decision
11
+ for the person**, never a developer error. You draft; the person posts, approves and merges.
12
+
13
+ **Before every review read:**
14
+ - the project profile `pr_review_profile.md` (search the working tree — it may be untracked; template below):
15
+ sources, output languages, known failing tests, merge rules, the project's past decisions;
16
+ - `lead-review-lessons.md` next to this file.
17
+
18
+ ## First review
19
+
20
+ 1. **Requirements.** The task-spec section (with its "decided at review of PR #…" notes); the decision rows (later
21
+ date wins); the mockups (open the images); the task's smoke file (`sdtk-smoke-test-spec`) — each case id's
22
+ expected result, and the open-points table (decided vs "developer fills in").
23
+ 2. **The PR.** `gh pr view` (base, stacked?, mergeable, size, body, commits). Collect: scope, "decided with the lead"
24
+ claims, questions to the lead, known issues, new user-facing strings, the commit the test results ran on.
25
+ 3. **Code, read-only.** `git fetch`; `git diff <base>...<head> --stat`; `git show <ref>:<path>`. Never check out
26
+ into the person's working tree. Read each path with real inputs before stating behaviour. Check the other open
27
+ PRs (`gh pr list`) for shared files and removed functions (`git grep <name> origin/<branch>`).
28
+ 4. **Requirement table** — one row per requirement / smoke case id: ✅ / ⚠️ / ❌ with `file:line`.
29
+ 5. **Classify each finding:**
30
+
31
+ | Situation | Class |
32
+ |---|---|
33
+ | Breaks a written rule | must fix |
34
+ | The spec is silent | decision for the person (read the legacy behaviour first; propose the narrowest option) |
35
+ | Developer's choice within the latitude the spec gives | accept / note |
36
+ | "Decided with the lead" claimed, not in the docs | confirm with the person |
37
+ | Existed before this PR | separate issue |
38
+ | Conflicts with another open branch | merge note |
39
+
40
+ Every finding carries an **origin** line (developer error / spec gap / pre-existing / cross-branch).
41
+ 6. **Ask the person** all decisions in **one batch**, each with a recommended option and its consequence. "Record
42
+ it, I decide later" → write it as a pending finding, not a must-fix.
43
+ 7. **Write the report** (folder, file name and languages from the profile):
44
+ 1. conclusion — can merge / can merge after fixes / cannot merge, and why in one line;
45
+ 2. requirement table;
46
+ 3. findings F1… — rule · code · impact · origin · fix + the test that proves it;
47
+ 4. merge notes — stacked order, other branches affected;
48
+ 5. paste-ready feedback for the developer (or a copy-paste prompt for an agent);
49
+ 6. a short PR comment in the profile's languages: action items and answers to the developer's questions only.
50
+ 8. **Record the person's decisions:** add "decided at review of PR #N (date)" to the task-spec section; bump the
51
+ smoke file's version and rewrite the affected cases / open-points rows; update earlier reviews whose findings the
52
+ decision changes and draft a follow-up comment for those PRs.
53
+
54
+ ## Stacked PRs
55
+
56
+ - Read the whole chain (`gh pr view` on each base until `main`). Review each PR's own diff
57
+ (`<its base>...<its head>`), not the accumulated diff.
58
+ - The chain merges in order with merge commits; each later PR merges `main` (or its new base) before its own merge.
59
+ Write the order in every review of the chain.
60
+ - A finding in a lower PR that a higher PR fixes is still a finding of the lower PR (it may merge alone).
61
+ - "Can B merge?" is never answered from B alone: its base must merge first, and B must be re-checked after
62
+ re-basing on `main`.
63
+
64
+ ## Product-repository rules for test code
65
+
66
+ Test-only code — UI Automation names, debug switches, fixture data — never reaches a repository the team does not
67
+ own, not even as a pushed branch for CI. It stays a private patch built through `git archive` (see `code-ui-e2e`).
68
+ A PR that adds it there is a must-fix whatever the spec says.
69
+
70
+ ## Re-review after fixes
71
+
72
+ 1. Confirm the remote head equals the commit the developer reported, and that the full test run used that head.
73
+ 2. Diff from the reviewed commit to the new head; map every finding to its commits; read each fix; read unrelated new
74
+ commits too.
75
+ 3. Verdict per finding: fixed / not fixed / changed (and why).
76
+ 4. What still blocks merge: open decisions, smoke results, the full test run on head, the stacked order.
77
+ 5. Append a "re-review <date>" section to the same report.
78
+
79
+ ## Red flags
80
+
81
+ | Thought | Reality |
82
+ |---|---|
83
+ | "The spec doesn't say it → the PR is wrong" | A decision question. Say "not a developer error". |
84
+ | "The PR says the lead approved it" | Ask the person; record who / when; update the docs. |
85
+ | "Same as what was decided for another PR" | Check the decision covers this case; propagate it to the other reviews. |
86
+ | "The value looks fine" | Check it against the real downstream limit. |
87
+ | "The check is correct for this feature" | It sits in shared code → check every caller, on every open branch. |
88
+ | "B looks fine, it can merge" | B is stacked: its base merges first. |
89
+ | "I'll post / approve it" | Draft only. The person posts. |
90
+
91
+ ## Project profile template (`pr_review_profile.md`)
92
+
93
+ ```markdown
94
+ # PR review profile: <project>
95
+
96
+ ## Sources
97
+ | What | Where |
98
+ |---|---|
99
+ | Task specs | <path / pattern> |
100
+ | Decision log | <path>; later date wins |
101
+ | Mockups | <path> |
102
+ | Smoke files | <path pattern> (sdtk-smoke-test-spec) |
103
+ | Legacy app / behaviour reference | <path or how to run> |
104
+
105
+ ## Output
106
+ - Report folder / file name: <path>/<PR-number>_review.md
107
+ - Report language: <lang>; PR comment languages: <lang, lang>
108
+
109
+ ## Merge rules
110
+ - Base branch: <main>; merge method: <merge commit / squash>; stacked PRs: <rule>
111
+ - Who merges: <role>
112
+
113
+ ## Known failing / flaky tests
114
+ | Test | Since | Tracked in |
115
+ |---|---|---|
116
+
117
+ ## Project decisions that recur in reviews
118
+ | Date | Decision | Source |
119
+ |---|---|---|
120
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdtk-code-kit",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Workflow-first coding process toolkit: start, plan, build, verify, ship, and runtime setup.",
5
5
  "bin": {
6
6
  "sdtk-code": "bin/sdtk-code.js"
package/src/lib/scope.js CHANGED
@@ -45,6 +45,7 @@ const MANAGED_CLAUDE_SKILLS = [
45
45
  "code-discover",
46
46
  "code-execute",
47
47
  "code-finish",
48
+ "code-issue",
48
49
  "code-parallel",
49
50
  "code-plan",
50
51
  "code-review",