@coding-with-hassan/devkit 1.4.0 → 1.6.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.
@@ -0,0 +1,31 @@
1
+ import { requireConfig, TRANSITION_EVENTS } from '../core/config.js';
2
+ import { ticketKeyFromBranch, ticketPattern } from '../core/derive.js';
3
+ import { transitionTicket } from '../core/tracker/index.js';
4
+ import { exitOnFailure } from '../util/run.js';
5
+
6
+ /**
7
+ * `tracker:transition <ticket> <event>` — report a PR event for a ticket; the tracker
8
+ * adapter moves the ticket to the status `tracker.transitions` names for it. `ticket` is
9
+ * a ticket key or anything starting with one, so the branch name works too. Best effort:
10
+ * a ticket the tracker does not know, missing credentials or an unreachable tracker is a
11
+ * `note:` and exit 0. Only a wrong event name is an error — that is a typo in the caller
12
+ * (an invalid config block fails as it does for every command).
13
+ */
14
+ export async function cmdTransition({ tracker, ticket, event, log = console.log, note = (m) => console.error(`note: ${m}`) }) {
15
+ if (!TRANSITION_EVENTS.includes(event)) throw new Error(`usage: hassan-devkit tracker:transition <TICKET> <${TRANSITION_EVENTS.join('|')}>`);
16
+ const pattern = ticketPattern(tracker);
17
+ if (!pattern) return null; // tracker `none`: there are no tickets
18
+ const key = ticketKeyFromBranch(ticket, tracker);
19
+ if (!key) {
20
+ note(`"${ticket}" does not start with a ticket key (${pattern}) — nothing moved`);
21
+ return null;
22
+ }
23
+ await transitionTicket({ key, event, tracker, log, note });
24
+ return key;
25
+ }
26
+
27
+ export function registerTracker(cli) {
28
+ cli
29
+ .command('tracker:transition <ticket> <event>', `Move a ticket to its tracker.transitions status for a PR event (${TRANSITION_EVENTS.join(' | ')}); best effort, a no-op unless the tracker is jira`)
30
+ .action((ticket, event) => exitOnFailure(Promise.resolve().then(() => cmdTransition({ tracker: requireConfig().config.tracker, ticket, event }))));
31
+ }
@@ -1,5 +1,5 @@
1
1
  import { requireConfig } from '../core/config.js';
2
- import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, createContext } from '../core/worktrees.js';
2
+ import { cmdCreate, cmdEnv, cmdList, cmdProfiles, cmdPrune, cmdRemove, cmdStop, createContext } from '../core/worktrees.js';
3
3
  import { exitOnFailure } from '../util/run.js';
4
4
 
5
5
  // Config loading may throw synchronously; run every action through a promise so the
@@ -22,6 +22,11 @@ export function registerWorktree(cli) {
22
22
  .command('worktree:profiles [action] [...names]', 'list | add <names> | remove <names> — which compose profiles this stack runs')
23
23
  .action((action, names) => withCtx((ctx) => cmdProfiles(ctx, action ?? 'list', names ?? [])));
24
24
 
25
+ // No context here: unlike its siblings, `stop` succeeds where the `worktree` block is missing.
26
+ cli
27
+ .command('worktree:stop', "Stop this checkout's stack; containers, volumes, slot and .env are kept (docker:up starts it again)")
28
+ .action(() => exitOnFailure(Promise.resolve().then(() => cmdStop(requireConfig()))));
29
+
25
30
  cli
26
31
  .command('worktree:remove <name>', 'Stack down (volumes deleted unless --keep-data) and remove the worktree; the branch is kept')
27
32
  .option('--keep-data', 'Keep the database and other volumes')
@@ -32,9 +32,19 @@ token and commit subjects need none.
32
32
  );
33
33
  }
34
34
 
35
- function jiraDoc({ project, baseUrl }) {
35
+ function jiraDoc({ project, baseUrl, transitions }) {
36
36
  const site = baseUrl ?? 'the Jira site from `JIRA_URL` in `~/.config/jira/env`';
37
37
  const k = `${project}-<n>`;
38
+ const off = (event) => `off (\`tracker.transitions.${event}\` is \`null\`) — the devkit moves nothing, follow the team's workflow by hand.`;
39
+ const prOpened = transitions.prOpened
40
+ ? `**PR opened** → \`${transitions.prOpened}\`: run \`hassan-devkit tracker:transition ${k} prOpened\` right after
41
+ \`gh pr create\`.`
42
+ : `**PR opened**: ${off('prOpened')}`;
43
+ const merged = transitions.merged
44
+ ? `**PR merged** → \`${transitions.merged}\`: \`hassan-devkit worktree:prune\` (run by every \`worktree:create\`) does it for
45
+ the ticket of each worktree it removes; for a ticket without a worktree, run
46
+ \`hassan-devkit tracker:transition ${k} merged\`.`
47
+ : `**PR merged**: ${off('merged')}`;
38
48
  return `# Issue tracker: Jira (${project})
39
49
 
40
50
  Issues and specs for this repo live in the Jira project **${project}** at ${site}. Use the
@@ -68,6 +78,14 @@ Pick the type by this rule, not by gut feel.
68
78
  \`GET /rest/api/3/myself\` for your \`accountId\` and \`PUT /rest/api/3/issue/${k}/assignee\`
69
79
  with \`{"accountId": "<id>"}\`. Never leave a ticket you are working on unassigned or
70
80
  assigned to someone else.
81
+ - **Status — the ticket follows its PR**: \`worktree:create\` moves a \`To Do\` ticket to
82
+ \`In Progress\`; after that:
83
+ - ${prOpened}
84
+ - ${merged}
85
+
86
+ A ticket already in or past the target status is left alone, and every failure is a
87
+ \`note:\` — move the ticket by hand then. The target statuses come from
88
+ \`hassan-devkit.tracker.transitions\` in \`package.json\` (\`null\` turns one off).
71
89
  - **Labels**: set via \`editJiraIssue\` on the \`labels\` field (add/remove by updating the array).
72
90
  - **Close**: MCP \`transitionJiraIssue\` — fetch available transitions first with
73
91
  \`getTransitionsForJiraIssue\`; the workflow decides valid target states.
@@ -3,6 +3,7 @@ import { join, posix } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { formatJson, planFile, upsertMarkedBlock } from './scaffold.js';
5
5
  import { mergeSettingsHooks } from './claude-hooks.js';
6
+ import { TICKETS_GRAPH_FILE } from './tickets/graph.js';
6
7
 
7
8
  /**
8
9
  * The Claude Code layer. Nothing here is copied content: the project's `CLAUDE.md` imports the
@@ -21,7 +22,12 @@ import { mergeSettingsHooks } from './claude-hooks.js';
21
22
  * and listed by its plugin manifest. Renovate bumps the tag, so an upstream release reaches
22
23
  * every project without a devkit release.
23
24
  * The stubs are derived on every install (`prepare` → `claude:install`) and gitignored through a
24
- * managed block, so a version bump never leaves anything to commit.
25
+ * managed block, so a version bump never leaves anything to commit. The same block ignores the
26
+ * other file the devkit generates into a checkout: the `tickets:graph` chart.
27
+ *
28
+ * One exception to "every skill gets a stub": a `SKILL.md` the project wrote itself at a stub
29
+ * path (a hand-made skill that predates the shipped one of the same name) is left alone and
30
+ * stays out of the gitignore block, until the project deletes it (`partitionSkills`).
25
31
  */
26
32
 
27
33
  const PACKAGE_ROOT = fileURLToPath(new URL('../../', import.meta.url));
@@ -151,11 +157,49 @@ stub never needs to change.${siblings}
151
157
  `;
152
158
  }
153
159
 
154
- export const stubPath = (name) => `.claude/skills/${name}/SKILL.md`;
160
+ const stubDir = (name) => `.claude/skills/${name}`;
161
+ export const stubPath = (name) => `${stubDir(name)}/SKILL.md`;
162
+
163
+ /** A stub's whole body, whitespace collapsed: the pointer into `node_modules` and nothing after it. */
164
+ const STUB_BODY = /^Read `node_modules\/[^` ]+\/SKILL\.md` \(relative to the repo root\) and follow it exactly\. That file is the skill's body; it ships with [^.]+ so this stub never needs to change\.( Relative links in that file point at files in the same folder\.)?$/;
165
+
166
+ /**
167
+ * Pure: is this text a stub some devkit version wrote? Every version has the same body modulo
168
+ * line wrapping, so line endings, a BOM and a formatter's reflow are ignored. Anything else at
169
+ * a stub path — a hand-written skill, a stub the project added a line to — is the project's
170
+ * own, which errs on the side of keeping a file.
171
+ */
172
+ export function isSkillStub(text) {
173
+ const normalised = text.replace(/^\uFEFF/, '').replaceAll('\r\n', '\n');
174
+ if (!normalised.startsWith('---\n')) return false;
175
+ const fence = normalised.indexOf('\n---\n', 3);
176
+ if (fence === -1) return false;
177
+ return STUB_BODY.test(normalised.slice(fence + 5).replace(/\s+/g, ' ').trim());
178
+ }
179
+
180
+ /**
181
+ * Split the skills into the ones that get a stub and the ones the project keeps its own copy
182
+ * of: a `SKILL.md` at the stub path that is not a stub (a skill the project wrote by hand
183
+ * before the devkit shipped one of that name). The copy wins until the project deletes it.
184
+ */
185
+ export function partitionSkills(root, skills) {
186
+ const stubbed = [];
187
+ const owned = [];
188
+ for (const skill of skills) {
189
+ const file = join(root, stubPath(skill.name));
190
+ const isOwn = existsSync(file) && !isSkillStub(readFileSync(file, 'utf8'));
191
+ (isOwn ? owned : stubbed).push(skill);
192
+ }
193
+ return { stubbed, owned };
194
+ }
155
195
 
156
- /** Pure: the `.gitignore` text with the managed block listing every generated stub folder. */
157
- export function withSkillStubsIgnored(text, skillNames) {
158
- const lines = [...skillNames].sort().map((name) => `.claude/skills/${name}/`);
196
+ /**
197
+ * Pure: the `.gitignore` text with the managed block listing what the devkit generates and a
198
+ * project never commits — every skill stub folder, then the `tickets:graph` chart. The begin
199
+ * marker still names only the stubs: it is matched as an exact line in every consumer's file.
200
+ */
201
+ export function withGeneratedIgnored(text, skillNames) {
202
+ const lines = [...[...skillNames].sort().map((name) => `${stubDir(name)}/`), TICKETS_GRAPH_FILE];
159
203
  return upsertMarkedBlock(text ?? '', GITIGNORE_BEGIN, GITIGNORE_END, lines);
160
204
  }
161
205
 
@@ -170,11 +214,17 @@ export function claudePlans(root, { notes = [] } = {}) {
170
214
  if (!skills.some((s) => s.source === SKILLS_PACKAGE)) {
171
215
  notes.push(`${SKILLS_PACKAGE} is not installed — \`hassan-devkit init --only config\` adds it to devDependencies; then \`pnpm install\` writes the skill stubs`);
172
216
  }
217
+ // A skill the project wrote itself is neither overwritten nor gitignored: it stays committed.
218
+ const { stubbed, owned } = partitionSkills(root, skills);
219
+ for (const skill of owned) {
220
+ const dir = stubDir(skill.name);
221
+ notes.push(`${stubPath(skill.name)} is the project's own copy and wins over the \`${skill.name}\` skill shipped by ${skill.source} — delete ${dir}/ (\`git rm -r ${dir}\`) and re-run to switch to the shipped one`);
222
+ }
173
223
  // Derived on every install: managed, so a bumped description flows without --force.
174
- for (const skill of skills) plans.push(planFile(root, stubPath(skill.name), skillStub(skill), { managed: true }));
224
+ for (const skill of stubbed) plans.push(planFile(root, stubPath(skill.name), skillStub(skill), { managed: true }));
175
225
  const gitignoreFile = join(root, GITIGNORE_FILE);
176
226
  const gitignore = existsSync(gitignoreFile) ? readFileSync(gitignoreFile, 'utf8') : '';
177
- plans.push(planFile(root, GITIGNORE_FILE, withSkillStubsIgnored(gitignore, skills.map((s) => s.name)), { managed: true }));
227
+ plans.push(planFile(root, GITIGNORE_FILE, withGeneratedIgnored(gitignore, stubbed.map((s) => s.name)), { managed: true }));
178
228
  const settingsFile = join(root, '.claude/settings.json');
179
229
  let settings = {};
180
230
  if (existsSync(settingsFile)) {
@@ -22,7 +22,8 @@ import { sanitizeName } from './derive.js';
22
22
  * "ready": { "url": "http://localhost:${DEVKIT_PORT_API}/api-json", "timeoutSeconds": 600 },
23
23
  * "env": { "API_PROXY_TARGET": "http://localhost:${DEVKIT_PORT_API}" }
24
24
  * },
25
- * "tracker": { "kind": "jira", "project": "DAZ", "baseUrl": "https://x.atlassian.net" }
25
+ * "tracker": { "kind": "jira", "project": "DAZ", "baseUrl": "https://x.atlassian.net",
26
+ * "transitions": { "prOpened": "In Review", "merged": "Acceptance" } } // target status per event; null = off
26
27
  * | { "kind": "github", "prefix": "GH" }
27
28
  * | { "kind": "none" },
28
29
  * "commits": { "types": [...], "extraScopes": [...], "requireSigned": true,
@@ -33,7 +34,8 @@ import { sanitizeName } from './derive.js';
33
34
  * "testCases": { "dir": "docs/testing", "languages": ["en", "nl"], "title": "My Project" },
34
35
  * "db": { "service": "db", "user": "postgres", "name": "app" },
35
36
  * "docker": { "preUp": "..." },
36
- * "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
37
+ * "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] },
38
+ * "design": { "url": "https://claude.ai/artifact/…" } // the design system the `sync-theme` skill reads; it stores the link here
37
39
  * }
38
40
  */
39
41
 
@@ -50,11 +52,19 @@ export const DEFAULT_GITHUB_PREFIX = 'GH';
50
52
  export const DEFAULT_NODE_VERSION = '24';
51
53
  export const DEFAULT_BASE_BRANCH = 'main';
52
54
  export const TRACKER_KINDS = ['jira', 'github', 'none'];
55
+ /**
56
+ * The ticket events after "work started", in lifecycle order, each with the status the
57
+ * jira tracker moves the ticket to by default. The order matters: a ticket sitting in a
58
+ * later event's status is past the earlier one.
59
+ */
60
+ export const DEFAULT_TRANSITIONS = { prOpened: 'In Review', merged: 'Acceptance' };
61
+ export const TRANSITION_EVENTS = Object.keys(DEFAULT_TRANSITIONS);
53
62
 
54
63
  const isString = (v) => typeof v === 'string';
55
64
  const isNonEmptyString = (v) => isString(v) && v.trim().length > 0;
56
65
  const isBoolean = (v) => typeof v === 'boolean';
57
66
  const isInteger = (v) => Number.isInteger(v);
67
+ const isHttpUrl = (v) => isNonEmptyString(v) && /^https?:\/\//.test(v);
58
68
  const isPort = (v) => isInteger(v) && v > 0 && v < 65536;
59
69
  const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
60
70
  const isStringArray = (v) => Array.isArray(v) && v.every(isNonEmptyString);
@@ -69,7 +79,7 @@ export function validateConfig(raw) {
69
79
  if (raw === undefined) return errors;
70
80
  if (!isPlainObject(raw)) return [`${CONFIG_KEY}: expected an object`];
71
81
 
72
- const known = ['worktree', 'tracker', 'commits', 'ci', 'testCases', 'db', 'docker', 'i18n'];
82
+ const known = ['worktree', 'tracker', 'commits', 'ci', 'testCases', 'db', 'docker', 'i18n', 'design'];
73
83
  for (const key of Object.keys(raw)) {
74
84
  if (!known.includes(key)) errors.push(`${CONFIG_KEY}.${key}: unknown key (known: ${known.join(', ')})`);
75
85
  }
@@ -129,7 +139,17 @@ export function validateConfig(raw) {
129
139
  if (!isNonEmptyString(tr.project) || !/^[A-Z][A-Z0-9_]*$/.test(tr.project)) {
130
140
  errors.push(`${CONFIG_KEY}.tracker.project: expected a Jira project key like "DAZ"`);
131
141
  }
132
- expect(`${CONFIG_KEY}.tracker.baseUrl`, tr.baseUrl, (v) => isNonEmptyString(v) && /^https?:\/\//.test(v), 'an http(s) URL');
142
+ expect(`${CONFIG_KEY}.tracker.baseUrl`, tr.baseUrl, isHttpUrl, 'an http(s) URL');
143
+ if (tr.transitions !== undefined) {
144
+ const p = `${CONFIG_KEY}.tracker.transitions`;
145
+ if (!isPlainObject(tr.transitions)) errors.push(`${p}: expected an object`);
146
+ else {
147
+ for (const [event, status] of Object.entries(tr.transitions)) {
148
+ if (!TRANSITION_EVENTS.includes(event)) errors.push(`${p}.${event}: unknown key (known: ${TRANSITION_EVENTS.join(', ')})`);
149
+ else if (status !== null && !isNonEmptyString(status)) errors.push(`${p}.${event}: expected a status name or null (null turns the transition off)`);
150
+ }
151
+ }
152
+ }
133
153
  } else if (tr.kind === 'github') {
134
154
  expect(`${CONFIG_KEY}.tracker.prefix`, tr.prefix, (v) => isNonEmptyString(v) && /^[A-Z][A-Z0-9]*$/.test(v), 'an upper-case token like "GH"');
135
155
  }
@@ -221,6 +241,19 @@ export function validateConfig(raw) {
221
241
  }
222
242
  }
223
243
 
244
+ const design = raw.design;
245
+ if (design !== undefined) {
246
+ const p = `${CONFIG_KEY}.design`;
247
+ if (!isPlainObject(design)) errors.push(`${p}: expected an object`);
248
+ else {
249
+ // Only the link is declared: everything else is read from the design system itself.
250
+ for (const key of Object.keys(design)) {
251
+ if (key !== 'url') errors.push(`${p}.${key}: unknown key (known: url)`);
252
+ }
253
+ expect(`${p}.url`, design.url, isHttpUrl, 'an http(s) URL (the link of the design system)');
254
+ }
255
+ }
256
+
224
257
  return errors;
225
258
  }
226
259
 
@@ -252,7 +285,7 @@ export function resolveConfig(raw = {}, { rootName }) {
252
285
  const tr = raw.tracker ?? { kind: 'none' };
253
286
  const tracker =
254
287
  tr.kind === 'jira'
255
- ? { kind: 'jira', project: tr.project, baseUrl: tr.baseUrl ?? null }
288
+ ? { kind: 'jira', project: tr.project, baseUrl: tr.baseUrl ?? null, transitions: { ...DEFAULT_TRANSITIONS, ...(tr.transitions ?? {}) } }
256
289
  : tr.kind === 'github'
257
290
  ? { kind: 'github', prefix: tr.prefix ?? DEFAULT_GITHUB_PREFIX }
258
291
  : { kind: 'none' };
@@ -282,8 +315,9 @@ export function resolveConfig(raw = {}, { rootName }) {
282
315
  const db = raw.db ? { service: raw.db.service, user: raw.db.user, name: raw.db.name } : null;
283
316
  const docker = { preUp: typeof raw.docker?.preUp === 'string' && raw.docker.preUp.trim() ? raw.docker.preUp.trim() : null };
284
317
  const i18n = { dir: raw.i18n?.dir ?? 'public/assets/i18n', languages: [...(raw.i18n?.languages ?? ['en', 'nl'])] };
318
+ const design = { url: raw.design?.url ?? null };
285
319
 
286
- return { worktree, tracker, commits, ci, testCases, db, docker, i18n };
320
+ return { worktree, tracker, commits, ci, testCases, db, docker, i18n, design };
287
321
  }
288
322
 
289
323
  /**
@@ -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
+ }