@coding-with-hassan/devkit 1.4.0 → 1.5.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.
@@ -23,11 +23,17 @@ export function commitScopes(projects, extraScopes = []) {
23
23
  return [...new Set([...projects.map((p) => p.name), ...extraScopes])].sort();
24
24
  }
25
25
 
26
+ /** The token ticket keys start with: the Jira project, the GitHub prefix; `null` without a tracker. */
27
+ export function ticketToken(tracker) {
28
+ if (tracker?.kind === 'jira') return tracker.project;
29
+ if (tracker?.kind === 'github') return tracker.prefix;
30
+ return null;
31
+ }
32
+
26
33
  /** Regex source for the ticket token at the start of a branch name / commit subject. */
27
34
  export function ticketPattern(tracker) {
28
- if (tracker?.kind === 'jira') return `${tracker.project}-[0-9]+`;
29
- if (tracker?.kind === 'github') return `${tracker.prefix}-[0-9]+`;
30
- return null;
35
+ const token = ticketToken(tracker);
36
+ return token ? `${token}-[0-9]+` : null;
31
37
  }
32
38
 
33
39
  /** `DAZ-42-FE-Some-Feature` → `DAZ-42`; `null` when the branch carries no ticket. */
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The ticket dependency graph behind `tickets:graph`. Pure: a tracker adapter's read operation
3
+ * hands over `{ tickets, epics, edges }` and everything here is a function of that data.
4
+ *
5
+ * ticket { key, title, status: 'todo' | 'in-progress' | 'done', epic: <epic key> | null }
6
+ * epic { key, title, status } — an epic is a group in the chart, never a node
7
+ * edge { from: <blocker key>, to: <blocked key> }
8
+ */
9
+
10
+ /** Where `tickets:graph` writes the chart, relative to the repo root; gitignored by the managed block. */
11
+ export const TICKETS_GRAPH_FILE = 'docs/tickets/dependencies.md';
12
+
13
+ /** Keys of the **ready tickets**: not started, and every ticket that blocks them is done. */
14
+ export function readyKeys(tickets, edges) {
15
+ const status = new Map(tickets.map((t) => [t.key, t.status]));
16
+ const blocked = new Set(edges.filter((e) => status.get(e.from) !== 'done').map((e) => e.to));
17
+ return new Set(tickets.filter((t) => t.status === 'todo' && !blocked.has(t.key)).map((t) => t.key));
18
+ }
19
+
20
+ /**
21
+ * Transitive reduction: drop every edge a longer path already implies, so a project-wide chart
22
+ * stays readable. Edges go one at a time against what is left, which keeps reachability intact
23
+ * even when the links form a cycle (two tickets blocking each other never lose both edges).
24
+ * `passable` says which tickets a path may run through: `buildGraph` refuses done ones, since
25
+ * a path through finished work no longer holds anything back.
26
+ */
27
+ export function reduceEdges(edges, passable = () => true) {
28
+ const successors = new Map();
29
+ for (const e of edges) successors.set(e.from, (successors.get(e.from) ?? new Set()).add(e.to));
30
+ /** A path `from` → `to` over what is left that does not take the direct edge. */
31
+ const implied = (from, to) => {
32
+ const seen = new Set([from]);
33
+ const stack = [...successors.get(from)].filter((node) => node !== to);
34
+ while (stack.length > 0) {
35
+ const node = stack.pop();
36
+ if (node === to) return true;
37
+ if (seen.has(node) || !passable(node)) continue;
38
+ seen.add(node);
39
+ stack.push(...(successors.get(node) ?? []));
40
+ }
41
+ return false;
42
+ };
43
+ return edges.filter((e) => {
44
+ if (!implied(e.from, e.to)) return true;
45
+ successors.get(e.from).delete(e.to);
46
+ return false;
47
+ });
48
+ }
49
+
50
+ const naturalOrder = (a, b) => a.localeCompare(b, 'en', { numeric: true });
51
+ const byKey = (a, b) => naturalOrder(a.key, b.key);
52
+
53
+ /**
54
+ * The chart's content. Scope: every ticket that is not done (only those of `epic` when given)
55
+ * plus the tickets that block them directly — so a done blocker one hop away stays visible as
56
+ * the reason a ticket is ready, and a blocker from another epic as the reason one is not.
57
+ * Edges are those between tickets in scope, without self-links and duplicates, reduced.
58
+ * Each ticket carries `ready`, decided on every link the tracker reported: a blocker that is
59
+ * not a ticket here (an epic, an issue that could not be read) still blocks unless it is done.
60
+ */
61
+ export function buildGraph({ tickets, epics = [], edges }, { epic = null } = {}) {
62
+ const status = new Map(tickets.map((t) => [t.key, t.status]));
63
+ const seen = new Set();
64
+ const reported = edges.filter((e) => {
65
+ const id = `${e.from}\n${e.to}`;
66
+ if (e.from === e.to || seen.has(id)) return false;
67
+ seen.add(id);
68
+ return true;
69
+ });
70
+ const ready = readyKeys([...tickets, ...epics], reported);
71
+ const links = reported.filter((e) => status.has(e.from) && status.has(e.to));
72
+ const open = tickets.filter((t) => t.status !== 'done');
73
+ const core = epic === null ? open : open.filter((t) => t.epic === epic);
74
+ if (epic !== null && core.length === 0) {
75
+ const withOpen = [...new Set(open.map((t) => t.epic).filter(Boolean))].sort(naturalOrder);
76
+ throw new Error(`no open ticket under epic ${epic} — epics with open tickets: ${withOpen.join(', ') || 'none'}`);
77
+ }
78
+ const coreKeys = new Set(core.map((t) => t.key));
79
+ const scope = new Set(coreKeys);
80
+ for (const e of links) if (coreKeys.has(e.to)) scope.add(e.from);
81
+ const inScope = tickets.filter((t) => scope.has(t.key)).sort(byKey);
82
+ const titles = new Map(epics.map((e) => [e.key, e.title]));
83
+ const used = [...new Set(inScope.map((t) => t.epic).filter(Boolean))];
84
+ return {
85
+ tickets: inScope.map((t) => ({ ...t, ready: ready.has(t.key) })),
86
+ epics: used.map((key) => ({ key, title: titles.get(key) ?? '' })).sort(byKey),
87
+ edges: reduceEdges(
88
+ links.filter((e) => scope.has(e.from) && scope.has(e.to)),
89
+ (key) => status.get(key) !== 'done',
90
+ ),
91
+ };
92
+ }
93
+
94
+ const TITLE_LENGTH = 60;
95
+ const STATUS_CLASS = { todo: 'todo', 'in-progress': 'inProgress', done: 'done' };
96
+ /** Fill, border and text colour are all set, so a node reads the same on a light and a dark page. */
97
+ const CLASS_DEFS = [
98
+ 'classDef todo fill:#e5e7eb,stroke:#6b7280,color:#111827',
99
+ 'classDef inProgress fill:#dbeafe,stroke:#2563eb,color:#1e3a8a',
100
+ 'classDef done fill:#dcfce7,stroke:#16a34a,color:#14532d',
101
+ 'classDef ready fill:#fef3c7,stroke:#d97706,stroke-width:3px,color:#78350f',
102
+ ];
103
+
104
+ const nodeId = (key) => key.replace(/[^A-Za-z0-9]/g, '_');
105
+
106
+ const ENTITY_CODES = { '#': '#35;', '&': '#amp;', '"': '#quot;', '<': '#lt;', '>': '#gt;' };
107
+ /**
108
+ * Mermaid 11 reads a label as Markdown and prints "Unsupported markdown: …" in the node for a
109
+ * code span, a strikethrough or a link (written or auto-detected). Entity codes do not help —
110
+ * they are decoded first — so the characters that start those constructs are swapped for a
111
+ * look-alike or split by a zero-width space. Emphasis is left alone: it only styles the text.
112
+ */
113
+ const MARKDOWN_BREAKS = [
114
+ [/`/g, "'"],
115
+ [/~/g, '\u223c'],
116
+ [/\]\(/g, ']\u200b('],
117
+ [/:\/\//g, ':\u200b//'],
118
+ [/\b(www)\./gi, '$1\u200b.'],
119
+ [/@/g, '@\u200b'],
120
+ ];
121
+
122
+ /** Text for a quoted Mermaid label: one line, cut to length, never markup or Markdown. */
123
+ function labelText(text) {
124
+ const line = String(text ?? '').replace(/\s+/g, ' ').trim();
125
+ const cut = line.length > TITLE_LENGTH ? `${line.slice(0, TITLE_LENGTH - 1)}…` : line;
126
+ return MARKDOWN_BREAKS.reduce((s, [pattern, to]) => s.replace(pattern, to), cut).replace(/[#&"<>]/g, (c) => ENTITY_CODES[c]);
127
+ }
128
+
129
+ /** A subgraph title that wraps is drawn over the nodes below it: no place to break it. */
130
+ const titleText = (text) => labelText(text).replace(/ /g, '#160;').replace(/-/g, '#8209;');
131
+
132
+ const nodeLine = (t) => `${nodeId(t.key)}["${t.key}<br/>${labelText(t.title)}"]:::${t.ready ? 'ready' : STATUS_CLASS[t.status]}`;
133
+
134
+ /**
135
+ * The graph as a Mermaid flowchart: tickets without an epic first, then one subgraph per epic,
136
+ * then the edges (blocker → blocked) and the status classes. Ready tickets take the `ready`
137
+ * class instead of `todo`.
138
+ */
139
+ export function renderMermaid({ tickets, epics, edges }) {
140
+ const lines = ['flowchart LR'];
141
+ for (const t of tickets.filter((t) => t.epic === null)) lines.push(` ${nodeLine(t)}`);
142
+ for (const epic of epics) {
143
+ lines.push(` subgraph epic_${nodeId(epic.key)}["${titleText(`${epic.key} ${epic.title}`)}"]`);
144
+ for (const t of tickets.filter((t) => t.epic === epic.key)) lines.push(` ${nodeLine(t)}`);
145
+ lines.push(' end');
146
+ }
147
+ const order = new Map(tickets.map((t, i) => [t.key, i]));
148
+ const sorted = [...edges].sort((a, b) => order.get(a.from) - order.get(b.from) || order.get(a.to) - order.get(b.to));
149
+ for (const e of sorted) lines.push(` ${nodeId(e.from)} --> ${nodeId(e.to)}`);
150
+ for (const def of CLASS_DEFS) lines.push(` ${def}`);
151
+ return `${lines.join('\n')}\n`;
152
+ }
153
+
154
+ const DOCUMENT_HEADER = '<!-- Generated by `hassan-devkit tickets:graph` — never committed; re-run the command to refresh it. -->';
155
+
156
+ /** The chart as a Markdown page: the Mermaid block, the colour key and the ready tickets by name. */
157
+ export function renderDocument(graph, { epic = null } = {}) {
158
+ const head = `${DOCUMENT_HEADER}\n\n# Ticket dependencies\n\n`;
159
+ if (graph.tickets.length === 0) return `${head}No open tickets.\n`;
160
+ const ready = graph.tickets.filter((t) => t.ready);
161
+ const count = `${graph.tickets.length} ticket${graph.tickets.length === 1 ? '' : 's'}${epic ? ` under epic ${epic}` : ''}`;
162
+ const parts = [
163
+ `${count}, ${ready.length} ready to start. An arrow runs from a blocker to the ticket it blocks.`,
164
+ `\`\`\`mermaid\n${renderMermaid(graph)}\`\`\``,
165
+ 'Grey: to do. Blue: in progress. Green: done. Amber with a thick border: **ready** (not started, every blocker done).',
166
+ ];
167
+ if (ready.length > 0) parts.push(`## Ready to start\n\n${ready.map((t) => `- ${t.key} ${t.title}`).join('\n')}`);
168
+ return `${head}${parts.join('\n\n')}\n`;
169
+ }
@@ -8,9 +8,93 @@ import { remoteUrl } from '../git.js';
8
8
  * signal. Issues live on the base repo (fork model), so `upstream` wins over `origin`.
9
9
  */
10
10
 
11
+ const repoArgs = (repo) => (repo ? ['--repo', repo] : []);
12
+
11
13
  /** Pure: the `gh` argument list for assigning issue `number` (repo optional). */
12
14
  export function githubAssignArgs(number, repo) {
13
- return ['issue', 'edit', String(number), '--add-assignee', '@me', ...(repo ? ['--repo', repo] : [])];
15
+ return ['issue', 'edit', String(number), '--add-assignee', '@me', ...repoArgs(repo)];
16
+ }
17
+
18
+ const ISSUE_REF = /(?<![\w/])#(\d+)\b/g;
19
+ /** The references right after the phrase: `: #12, #13 and #14`, not a `#20` later in a sentence. */
20
+ const LEADING_REFS = /^[\s:*_]*((?:\s*(?:,|and|&)?\s*#\d+)+)/i;
21
+
22
+ /**
23
+ * Pure: the issue numbers a body attaches to a phrase — right after it on a line that starts
24
+ * with it (`Blocked by #12, #13`; list marker, checkbox and bold allowed) and anywhere on the
25
+ * lines under a heading that is it (`## Blocked by`, the upstream ticket template). A mention
26
+ * inside a sentence, a code fence and a reference into another repo (`owner/repo#12`) are not
27
+ * links.
28
+ */
29
+ function references(body, lineStart, heading) {
30
+ const found = [];
31
+ let inSection = false;
32
+ let inFence = false;
33
+ for (const line of String(body ?? '').split(/\r?\n/)) {
34
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
35
+ else if (inFence) continue;
36
+ else if (/^#{1,6}\s+\S/.test(line)) inSection = heading.test(line);
37
+ else {
38
+ const text = inSection ? line : LEADING_REFS.exec(lineStart.exec(line)?.[1] ?? '')?.[1];
39
+ for (const match of (text ?? '').matchAll(ISSUE_REF)) found.push(Number(match[1]));
40
+ }
41
+ }
42
+ return [...new Set(found)];
43
+ }
44
+
45
+ const lineStartsWith = (phrase) => new RegExp(`^\\s*(?:[-*+]\\s+)?(?:\\[[ xX]\\]\\s+)?(?:\\*\\*|__)?${phrase}\\b(.*)$`, 'i');
46
+ const headingIs = (phrase) => new RegExp(`^#{1,6}\\s+${phrase}\\s*:?\\s*$`, 'i');
47
+ const BLOCKED_BY = [lineStartsWith('blocked by'), headingIs('blocked by')];
48
+ const PARENT = [lineStartsWith('part of'), headingIs('parent')];
49
+
50
+ /** Pure: the issues that block this one, from its `Blocked by #<n>` lines. */
51
+ export const parseBlockedBy = (body) => references(body, ...BLOCKED_BY);
52
+
53
+ /** Pure: the issue this one is part of (its epic), from the `Part of #<n>` line; `null` when none. */
54
+ export const parseParent = (body) => references(body, ...PARENT)[0] ?? null;
55
+
56
+ const ISSUE_FIELDS = 'number,title,body,state,assignees';
57
+ /** `gh issue list` stops at its `--limit`; this many open issues is more than a chart can show anyway. */
58
+ const ISSUE_LIMIT = 1000;
59
+
60
+ /** Pure: the `gh` argument list for reading every open issue. */
61
+ export function githubListArgs(repo) {
62
+ return ['issue', 'list', '--state', 'open', '--limit', String(ISSUE_LIMIT), '--json', ISSUE_FIELDS, ...repoArgs(repo)];
63
+ }
64
+
65
+ /** Pure: the `gh` argument list for reading one issue (a closed blocker or epic). */
66
+ export function githubViewArgs(number, repo) {
67
+ return ['issue', 'view', String(number), '--json', ISSUE_FIELDS, ...repoArgs(repo)];
68
+ }
69
+
70
+ /** Pure: the issues `issues` reference as blocker or epic without being among them, ascending. */
71
+ export function githubMissingReferences(issues) {
72
+ const have = new Set(issues.map((i) => i.number));
73
+ const wanted = issues.flatMap((i) => [...parseBlockedBy(i.body), parseParent(i.body)]);
74
+ return [...new Set(wanted.filter((n) => n !== null && !have.has(n)))].sort((a, b) => a - b);
75
+ }
76
+
77
+ /** Closed is done, open with an assignee is in progress (starting a ticket assigns it), open without one is to do. */
78
+ const issueStatus = (issue) => (issue.state !== 'OPEN' ? 'done' : issue.assignees?.length ? 'in-progress' : 'todo');
79
+
80
+ /**
81
+ * Pure: `gh` issues as the ticket graph's input. An issue that others are part of is an epic
82
+ * and leaves the ticket list; one that was not read is not known to be done.
83
+ */
84
+ export function githubTicketData(issues, tracker) {
85
+ const key = (number) => `${tracker.prefix}-${number}`;
86
+ const byNumber = new Map(issues.map((i) => [i.number, i]));
87
+ const parents = new Map(issues.map((i) => [i.number, parseParent(i.body)]));
88
+ const epicNumbers = new Set([...parents.values()].filter((n) => n !== null));
89
+ return {
90
+ tickets: issues
91
+ .filter((i) => !epicNumbers.has(i.number))
92
+ .map((i) => ({ key: key(i.number), title: i.title, status: issueStatus(i), epic: parents.get(i.number) === null ? null : key(parents.get(i.number)) })),
93
+ epics: [...epicNumbers]
94
+ .sort((a, b) => a - b)
95
+ .map((n) => ({ key: key(n), title: byNumber.get(n)?.title ?? '', status: byNumber.has(n) ? issueStatus(byNumber.get(n)) : 'todo' })),
96
+ edges: issues.flatMap((i) => parseBlockedBy(i.body).map((blocker) => ({ from: key(blocker), to: key(i.number) }))),
97
+ };
14
98
  }
15
99
 
16
100
  export const githubAdapter = {
@@ -26,4 +110,19 @@ export const githubAdapter = {
26
110
  if (result === null) note(`assigning #${number} failed (does the issue exist and is gh authenticated?) — assign it to yourself on GitHub`);
27
111
  else log(`GitHub: #${number} assigned to you`);
28
112
  },
113
+
114
+ /** Open issues, plus the issues they name as blocker or epic — one `gh issue view` each. */
115
+ async readTickets({ tracker, cwd, note }) {
116
+ if (!commandExists('gh')) throw new Error('gh is not installed — the GitHub tracker is read through the gh CLI');
117
+ const repo = remoteUrl(cwd, 'upstream') ?? remoteUrl(cwd, 'origin');
118
+ const open = JSON.parse(capture('gh', githubListArgs(repo), { cwd }));
119
+ if (open.length >= ISSUE_LIMIT) note(`only the first ${ISSUE_LIMIT} open issues were read`);
120
+ const referenced = [];
121
+ for (const number of githubMissingReferences(open)) {
122
+ const issue = capture('gh', githubViewArgs(number, repo), { cwd, allowFailure: true });
123
+ if (issue === null) note(`#${number} is referenced by an open issue but could not be read — left out of the chart; what it blocks is not shown as ready`);
124
+ else referenced.push(JSON.parse(issue));
125
+ }
126
+ return githubTicketData([...open, ...referenced], tracker);
127
+ },
29
128
  };
@@ -3,11 +3,20 @@ import { githubAdapter } from './github.js';
3
3
  import { jiraAdapter } from './jira.js';
4
4
 
5
5
  /**
6
- * Tracker adapters: what `worktree:create` does with the branch's ticket. Every adapter
7
- * is best effort — a missing token or an unreachable tracker prints a `note:` and never
8
- * breaks worktree creation (creating the worktree IS the "work started" signal).
6
+ * Tracker adapters: what `worktree:create` does with the branch's ticket, and what happens
7
+ * to the ticket when its PR opens and when it merges. Every adapter is best effort — a
8
+ * missing token or an unreachable tracker prints a `note:` and never breaks worktree
9
+ * creation (creating the worktree IS the "work started" signal) or the command that
10
+ * reported the PR event.
9
11
  *
10
- * Adapter contract: `{ startTicket({ key, branch, tracker, cwd, log, note }) }`.
12
+ * Adapter contract: `{ startTicket({ key, branch, tracker, cwd, log, note }),
13
+ * transitionTicket?({ key, event, tracker, log, note }),
14
+ * readTickets?({ tracker, cwd, note }) }`. `transitionTicket` is optional: a tracker without
15
+ * a status to move (`github`, `none` — an open PR stays the progress signal there) leaves it
16
+ * out. `readTickets` is the read operation behind `tickets:graph`: it resolves to
17
+ * `{ tickets, epics, edges }` (shapes in ../tickets/graph.js) — every ticket that is not done
18
+ * plus the tickets blocking them; `none` leaves it out. It is the one operation that is not
19
+ * best effort: without the tracker there is no chart, so a failure is the command's failure.
11
20
  */
12
21
 
13
22
  const adapters = {
@@ -35,3 +44,21 @@ export async function startTicket({ branch, tracker, cwd, log = console.log, not
35
44
  }
36
45
  return key;
37
46
  }
47
+
48
+ /** Move ticket `key` for a PR event (`prOpened` | `merged`, see `TRANSITION_EVENTS`). */
49
+ export async function transitionTicket({ key, event, tracker, log = console.log, note = (m) => console.error(`note: ${m}`) }) {
50
+ const adapter = adapters[tracker.kind];
51
+ if (!key || !adapter?.transitionTicket) return;
52
+ try {
53
+ await adapter.transitionTicket({ key, event, tracker, log, note });
54
+ } catch (e) {
55
+ note(`${tracker.kind}: ${e.message} — move ${key} by hand`);
56
+ }
57
+ }
58
+
59
+ /** The tracker's tickets and blocking edges; `null` when the tracker kind has none to read. */
60
+ export async function readTickets({ tracker, cwd, note = (m) => console.error(`note: ${m}`) }) {
61
+ const adapter = adapters[tracker.kind];
62
+ if (!adapter?.readTickets) return null;
63
+ return adapter.readTickets({ tracker, cwd, note });
64
+ }
@@ -1,18 +1,22 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
+ import { TRANSITION_EVENTS } from '../config.js';
4
5
  import { parseEnv } from '../env-block.js';
5
6
 
6
7
  /**
7
8
  * Jira adapter. On `worktree:create`: whoever starts the work owns the ticket, so the
8
9
  * issue is assigned to the current user regardless of status, and a `To Do` issue moves
9
- * to `In Progress`. Best effort throughout — every failure is a `note:`.
10
+ * to `In Progress`. After that the ticket follows its PR: `transitionTicket` moves it to
11
+ * the status `tracker.transitions` names for the event (`prOpened`, `merged`), unless it
12
+ * is already there or further. Best effort throughout — every failure is a `note:`.
10
13
  *
11
14
  * Credentials: `JIRA_EMAIL`, `JIRA_API_TOKEN` and optionally `JIRA_URL` (or `JIRA_BASE_URL`)
12
15
  * from the environment, else from `~/.config/jira/env` (KEY=value lines).
13
16
  */
14
17
 
15
18
  export const JIRA_ENV_FILE = join(homedir(), '.config', 'jira', 'env');
19
+ const CREDENTIALS_HINT = `set JIRA_EMAIL/JIRA_API_TOKEN/JIRA_URL or ${JIRA_ENV_FILE}`;
16
20
 
17
21
  /** Pure: pick credentials from the process env, falling back to the env file's text. */
18
22
  export function resolveJiraCredentials(env, fileText, baseUrlFromConfig) {
@@ -29,11 +33,37 @@ function unquote(obj) {
29
33
  return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v.replace(/^(['"])(.*)\1$/, '$2')]));
30
34
  }
31
35
 
36
+ const sameStatus = (a, b) => typeof a === 'string' && typeof b === 'string' && a.trim().toLowerCase() === b.trim().toLowerCase();
37
+
38
+ /**
39
+ * Pure: the transition that lands on the status named `target`, out of the payload of
40
+ * `GET /issue/<key>/transitions` (the transitions available to the ticket right now).
41
+ * `null` when the workflow offers none from the ticket's current status.
42
+ */
43
+ export function pickTransition(payload, target) {
44
+ return (payload?.transitions ?? []).find((t) => sameStatus(t.to?.name, target)) ?? null;
45
+ }
46
+
47
+ /**
48
+ * Pure: where a ticket stands relative to the target status of `event` — `'before'`,
49
+ * `'at'` or `'past'`. Only `'before'` is moved. Past means a done status, or the target
50
+ * status of a later event: a workflow that allows every transition would otherwise let a
51
+ * late `prOpened` pull a ticket back out of `Acceptance`.
52
+ */
53
+ export function ticketStanding({ event, targets, status }) {
54
+ if (sameStatus(status.name, targets[event])) return 'at';
55
+ if (status.category === 'done') return 'past';
56
+ const later = TRANSITION_EVENTS.slice(TRANSITION_EVENTS.indexOf(event) + 1);
57
+ return later.some((e) => sameStatus(status.name, targets[e])) ? 'past' : 'before';
58
+ }
59
+
32
60
  export function loadJiraCredentials(tracker) {
33
61
  const text = existsSync(JIRA_ENV_FILE) ? readFileSync(JIRA_ENV_FILE, 'utf8') : null;
34
62
  return resolveJiraCredentials(process.env, text, tracker.baseUrl);
35
63
  }
36
64
 
65
+ const isComplete = (creds) => Boolean(creds.email && creds.token && creds.baseUrl);
66
+
37
67
  async function api(creds, method, path, body) {
38
68
  const res = await fetch(`${creds.baseUrl}/rest/api/3${path}`, {
39
69
  method,
@@ -50,11 +80,115 @@ async function api(creds, method, path, body) {
50
80
  return text ? JSON.parse(text) : null;
51
81
  }
52
82
 
83
+ const SEARCH_FIELDS = ['summary', 'status', 'issuetype', 'parent', 'issuelinks'];
84
+ const SEARCH_PAGE_SIZE = 100;
85
+ const STATUS_BY_CATEGORY = { new: 'todo', indeterminate: 'in-progress', done: 'done' };
86
+
87
+ /** Pure: every issue of the project that is not done. */
88
+ export const jiraOpenJql = (project) => `project = "${project}" AND statusCategory != Done ORDER BY key ASC`;
89
+
90
+ /** Pure: the issues with these keys, whatever their project or status. */
91
+ export const jiraKeysJql = (keys) => `key in (${keys.map((k) => `"${k}"`).join(', ')})`;
92
+
93
+ /** Pure: one page of `POST /search/jql`; the token of the previous page asks for the next. */
94
+ export function jiraSearchBody(jql, nextPageToken) {
95
+ return { jql, fields: SEARCH_FIELDS, maxResults: SEARCH_PAGE_SIZE, ...(nextPageToken ? { nextPageToken } : {}) };
96
+ }
97
+
98
+ /** Issue type level: 1 and up is an epic (or above), 0 a ticket, -1 a sub-task. */
99
+ const hierarchyLevel = (issue) => issue.fields?.issuetype?.hierarchyLevel ?? (issue.fields?.issuetype?.subtask ? -1 : 0);
100
+ const isBlocks = (link) => /^blocks$/i.test(link.type?.name ?? '');
101
+
102
+ /** The `Blocks` links of one issue as edges plus the linked issue as Jira embeds it (no parent). */
103
+ function blockingLinks(issue) {
104
+ return (issue.fields?.issuelinks ?? []).filter(isBlocks).flatMap((link) => {
105
+ if (link.inwardIssue) return [{ from: link.inwardIssue.key, to: issue.key, linked: link.inwardIssue }];
106
+ if (link.outwardIssue) return [{ from: issue.key, to: link.outwardIssue.key, linked: link.outwardIssue }];
107
+ return [];
108
+ });
109
+ }
110
+
111
+ /** Pure: the keys that block one of `issues` without being among them, in key order. */
112
+ export function jiraMissingReferences(issues) {
113
+ const have = new Set(issues.map((i) => i.key));
114
+ const blockers = issues.flatMap((i) => blockingLinks(i).filter((l) => l.to === i.key).map((l) => l.from));
115
+ return [...new Set(blockers.filter((key) => !have.has(key)))].sort();
116
+ }
117
+
118
+ /**
119
+ * Pure: the open issues plus their blockers — as the second search returned them, else as
120
+ * the link embeds them (status known, epic not).
121
+ */
122
+ export function jiraWithBlockers(open, fetched) {
123
+ const have = new Set([...open, ...fetched].map((issue) => issue.key));
124
+ const embedded = new Map(open.flatMap((issue) => blockingLinks(issue).map((link) => [link.linked.key, link.linked])));
125
+ return [...open, ...fetched, ...jiraMissingReferences(open).filter((key) => !have.has(key)).map((key) => embedded.get(key))];
126
+ }
127
+
128
+ const statusOf = (issue) => STATUS_BY_CATEGORY[issue.fields?.status?.statusCategory?.key] ?? 'todo';
129
+
130
+ /**
131
+ * Pure: Jira issues as the ticket graph's input. Status category comes from the status's own
132
+ * category, so a project's custom statuses need no mapping. Epics (and anything above) become
133
+ * the groups, known from their own issue or from a child naming them as parent; sub-tasks are
134
+ * left out — the chart is about tickets. A link is reported by both of its issues: one edge.
135
+ */
136
+ export function jiraTicketData(issues) {
137
+ const epics = new Map();
138
+ const tickets = [];
139
+ const edges = new Map();
140
+ for (const issue of issues) {
141
+ const level = hierarchyLevel(issue);
142
+ if (level >= 1) epics.set(issue.key, { key: issue.key, title: issue.fields.summary, status: statusOf(issue) });
143
+ if (level !== 0) continue;
144
+ const parent = issue.fields.parent ?? null;
145
+ if (parent && !epics.has(parent.key)) epics.set(parent.key, { key: parent.key, title: parent.fields?.summary ?? '', status: statusOf(parent) });
146
+ tickets.push({ key: issue.key, title: issue.fields.summary, status: statusOf(issue), epic: parent?.key ?? null });
147
+ for (const { from, to } of blockingLinks(issue)) edges.set(`${from}\n${to}`, { from, to });
148
+ }
149
+ return { tickets, epics: [...epics.values()], edges: [...edges.values()] };
150
+ }
151
+
152
+ /** Every issue a JQL query matches, page by page. */
153
+ async function search(creds, jql) {
154
+ const issues = [];
155
+ let token = null;
156
+ do {
157
+ const page = (await api(creds, 'POST', '/search/jql', jiraSearchBody(jql, token))) ?? {};
158
+ issues.push(...(page.issues ?? []));
159
+ token = page.nextPageToken ?? null;
160
+ } while (token);
161
+ return issues;
162
+ }
163
+
53
164
  export const jiraAdapter = {
165
+ /**
166
+ * The project's issues that are not done, plus the issues blocking them (done ones, other
167
+ * projects' ones) in a second search so they come with their epic. A blocker that search
168
+ * does not return is taken as the link embeds it: status known, epic not.
169
+ */
170
+ async readTickets({ tracker, note }) {
171
+ const creds = loadJiraCredentials(tracker);
172
+ if (!isComplete(creds)) {
173
+ throw new Error(`Jira credentials unavailable — ${CREDENTIALS_HINT}`);
174
+ }
175
+ const open = await search(creds, jiraOpenJql(tracker.project));
176
+ const missing = jiraMissingReferences(open);
177
+ const fetched = [];
178
+ for (let i = 0; i < missing.length; i += SEARCH_PAGE_SIZE) {
179
+ try {
180
+ fetched.push(...(await search(creds, jiraKeysJql(missing.slice(i, i + SEARCH_PAGE_SIZE)))));
181
+ } catch (e) {
182
+ note(`reading the blocking issues failed (${e.message}) — they are drawn without their epic`);
183
+ }
184
+ }
185
+ return jiraTicketData(jiraWithBlockers(open, fetched));
186
+ },
187
+
54
188
  async startTicket({ key, tracker, log, note }) {
55
189
  const creds = loadJiraCredentials(tracker);
56
- if (!creds.email || !creds.token || !creds.baseUrl) {
57
- note(`Jira credentials unavailable (set JIRA_EMAIL/JIRA_API_TOKEN/JIRA_URL or ${JIRA_ENV_FILE}) — assign ${key} to yourself and move it to In Progress`);
190
+ if (!isComplete(creds)) {
191
+ note(`Jira credentials unavailable (${CREDENTIALS_HINT}) — assign ${key} to yourself and move it to In Progress`);
58
192
  return;
59
193
  }
60
194
  let me = null;
@@ -82,8 +216,7 @@ export const jiraAdapter = {
82
216
  }
83
217
  let transitionId = null;
84
218
  try {
85
- const { transitions = [] } = (await api(creds, 'GET', `/issue/${key}/transitions`)) ?? {};
86
- transitionId = transitions.find((t) => t.to?.name === 'In Progress')?.id ?? null;
219
+ transitionId = pickTransition(await api(creds, 'GET', `/issue/${key}/transitions`), 'In Progress')?.id ?? null;
87
220
  } catch {
88
221
  transitionId = null;
89
222
  }
@@ -98,4 +231,48 @@ export const jiraAdapter = {
98
231
  note(`transitioning ${key} failed (${e.message}) — move it to In Progress yourself`);
99
232
  }
100
233
  },
234
+
235
+ async transitionTicket({ key, event, tracker, log, note }) {
236
+ const target = tracker.transitions?.[event] ?? null;
237
+ if (!target) {
238
+ log(`Jira: the '${event}' transition is off — leaving ${key} alone`);
239
+ return;
240
+ }
241
+ const byHand = `move ${key} to ${target} yourself`;
242
+ const creds = loadJiraCredentials(tracker);
243
+ if (!isComplete(creds)) {
244
+ note(`Jira credentials unavailable (${CREDENTIALS_HINT}) — ${byHand}`);
245
+ return;
246
+ }
247
+ let status = null;
248
+ try {
249
+ const current = (await api(creds, 'GET', `/issue/${key}?fields=status`))?.fields?.status;
250
+ status = { name: current?.name ?? null, category: current?.statusCategory?.key ?? null };
251
+ } catch (e) {
252
+ note(`reading the status of ${key} failed (${e.message}) — ${byHand}`);
253
+ return;
254
+ }
255
+ const standing = ticketStanding({ event, targets: tracker.transitions, status });
256
+ if (standing !== 'before') {
257
+ log(`Jira: ${key} is ${standing === 'at' ? `already '${status.name}'` : `'${status.name}', past ${target}`} — leaving its status alone`);
258
+ return;
259
+ }
260
+ let transition = null;
261
+ try {
262
+ transition = pickTransition(await api(creds, 'GET', `/issue/${key}/transitions`), target);
263
+ } catch (e) {
264
+ note(`reading the transitions of ${key} failed (${e.message}) — ${byHand}`);
265
+ return;
266
+ }
267
+ if (!transition) {
268
+ note(`${key} has no transition from '${status.name}' to ${target} — ${byHand}`);
269
+ return;
270
+ }
271
+ try {
272
+ await api(creds, 'POST', `/issue/${key}/transitions`, { transition: { id: transition.id } });
273
+ log(`Jira: ${key} → ${target}`);
274
+ } catch (e) {
275
+ note(`transitioning ${key} failed (${e.message}) — ${byHand}`);
276
+ }
277
+ },
101
278
  };
@@ -2,13 +2,13 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFile
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
3
  import { loadProfiles } from './compose.js';
4
4
  import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
5
- import { expandEnv, imageTag, imageTagInputs, sanitizeName } from './derive.js';
5
+ import { expandEnv, imageTag, imageTagInputs, sanitizeName, ticketKeyFromBranch } from './derive.js';
6
6
  import { managedValues, parseEnv, writeManagedBlock } from './env-block.js';
7
7
  import { commandExists, run } from './exec.js';
8
8
  import * as git from './git.js';
9
9
  import { withLock } from './locks.js';
10
10
  import * as stack from './stack.js';
11
- import { startTicket } from './tracker/index.js';
11
+ import { startTicket, transitionTicket } from './tracker/index.js';
12
12
  import { listProjects } from './workspace.js';
13
13
 
14
14
  /**
@@ -502,7 +502,10 @@ export async function cmdRemove(ctx, name, { keepData = false, force = false } =
502
502
  ctx.log(`removed ${dir} (branch kept — delete it with: git branch -D ${basename(dir)})`);
503
503
  }
504
504
 
505
- /** `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle). */
505
+ /**
506
+ * `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle) and
507
+ * report the merge to the tracker for the ticket of each one it removed.
508
+ */
506
509
  export async function cmdPrune(ctx, { dryRun = false } = {}) {
507
510
  if (!commandExists('gh')) {
508
511
  ctx.note('gh not installed — cannot check PR states, skipping prune');
@@ -539,12 +542,16 @@ export async function cmdPrune(ctx, { dryRun = false } = {}) {
539
542
  continue;
540
543
  }
541
544
  ctx.log(`prune: ${entry.name}: PR merged — removing worktree, containers, volumes, and branch`);
545
+ const key = ticketKeyFromBranch(branch, ctx.tracker);
542
546
  if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: true });
543
547
  if (await git.worktreeRemove(ctx.mainRoot, dir)) {
544
548
  await git.branchDelete(ctx.mainRoot, branch);
545
549
  removed.push(entry.name);
550
+ await transitionTicket({ key, event: 'merged', tracker: ctx.tracker, log: ctx.log, note: ctx.note });
546
551
  } else {
547
- ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}`);
552
+ // The ticket only moves with the worktree prune removes; this one is left to the developer.
553
+ const move = key && ctx.tracker.transitions?.merged ? ` && hassan-devkit tracker:transition ${key} merged` : '';
554
+ ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}${move}`);
548
555
  }
549
556
  }
550
557
  if (!dryRun) pruneImages(ctx);
package/src/index.js CHANGED
@@ -6,10 +6,12 @@ import { registerI18n } from './commands/i18n.js';
6
6
  import { registerInit } from './commands/init.js';
7
7
  import { registerConfig } from './commands/config.js';
8
8
  import { registerWorktree } from './commands/worktree.js';
9
+ import { registerTracker } from './commands/tracker.js';
9
10
  import { registerCi } from './commands/ci.js';
10
11
  import { registerClaude } from './commands/claude.js';
11
12
  import { registerFormat } from './commands/format.js';
12
13
  import { registerTestCases } from './commands/test-cases.js';
14
+ import { registerTickets } from './commands/tickets.js';
13
15
 
14
16
  export function run(argv) {
15
17
  const cli = cac('hassan-devkit');
@@ -17,10 +19,12 @@ export function run(argv) {
17
19
  registerInit(cli);
18
20
  registerConfig(cli);
19
21
  registerWorktree(cli);
22
+ registerTracker(cli);
20
23
  registerCi(cli);
21
24
  registerClaude(cli);
22
25
  registerFormat(cli);
23
26
  registerTestCases(cli);
27
+ registerTickets(cli);
24
28
  registerDocker(cli);
25
29
  registerDb(cli);
26
30
  registerHooks(cli);