@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.
@@ -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
  };
@@ -1,14 +1,14 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
3
  import { loadProfiles } from './compose.js';
4
- import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
5
- import { expandEnv, imageTag, imageTagInputs, sanitizeName } from './derive.js';
4
+ import { COMPOSE_FILE, CONFIG_KEY, ENV_DIST_FILE, ENV_FILE, requireConfig, resolveConfig } from './config.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
  /**
@@ -135,6 +135,59 @@ export function pruneDecision(states) {
135
135
  return 'closed';
136
136
  }
137
137
 
138
+ /**
139
+ * A compose call that reaches the containers of every profile, whatever `.env` lists. The
140
+ * shell env wins over --env-file, so `COMPOSE_PROFILES` always gets a value: a .env from
141
+ * before profiles were mandatory must not block its own stop or teardown on the compose guard.
142
+ */
143
+ export function everyProfile(args, { known, shellProfiles = process.env.COMPOSE_PROFILES }) {
144
+ return { args: ['--profile', '*', ...args], env: { COMPOSE_PROFILES: shellProfiles || known[0] || 'devkit' } };
145
+ }
146
+
147
+ /**
148
+ * Why `worktree:stop` leaves this checkout alone, or `null` when it has a stack to stop.
149
+ * Only a stack the devkit manages per checkout is stopped: without the managed `.env` the
150
+ * compose project is not this checkout's own, and a stop could hit another checkout's stack.
151
+ */
152
+ export function stopSkipReason({ hasStack, managed, hasEnv }) {
153
+ if (!hasStack) return `no ${COMPOSE_FILE}: this repo has no stack`;
154
+ if (!managed) return `"${CONFIG_KEY}.worktree" is not filled in: the stack is not managed per checkout`;
155
+ if (!hasEnv) return `no ${ENV_FILE}: this checkout has no stack of its own`;
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * The `worktree` block `worktree:create` sets a new worktree up with: the worktree's `own`
161
+ * block, because its commit decides what its stack is (ports, profiles, ready, seeds, env) and
162
+ * the invoking checkout may be behind it. Only where worktrees live and how many slots exist
163
+ * is shared by every checkout, so those two stay the invoking checkout's.
164
+ */
165
+ export function ownSettings(invoking, own) {
166
+ return { ...own, baseDir: invoking.baseDir, maxSlot: invoking.maxSlot };
167
+ }
168
+
169
+ /** Dotted keys on which two resolved `worktree` blocks differ, in the order the block lists them. */
170
+ export function settingsDrift(a, b) {
171
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
172
+ const walk = (x, y, path) => {
173
+ if (isRecord(x) && isRecord(y)) return [...new Set([...Object.keys(x), ...Object.keys(y)])].flatMap((k) => walk(x[k], y[k], path ? `${path}.${k}` : k));
174
+ return JSON.stringify(x) === JSON.stringify(y) ? [] : [path];
175
+ };
176
+ return walk(a, b, '');
177
+ }
178
+
179
+ /**
180
+ * The seed step of `worktree:create`: every entry has the `line` to print and the compose
181
+ * `exec` to run after it (`null`: nothing runs). Never empty, so the step is never silent: a
182
+ * stack that came up without its seed data looks the same as a seeded one until a login fails.
183
+ */
184
+ export function seedPlan(seeds, { hasStack, up }) {
185
+ if (seeds.scripts.length === 0) return [{ line: 'no seed scripts configured (worktree.seeds.scripts)', exec: null }];
186
+ const why = !hasStack ? `no ${COMPOSE_FILE}, so no stack` : !up ? 'the stack was not started (--no-up)' : null;
187
+ if (why) return [{ line: `not seeding: ${why}; skipped ${seeds.scripts.map((s) => `pnpm ${s}`).join(', ')} (service ${seeds.service})`, exec: null }];
188
+ return seeds.scripts.map((script) => ({ line: `seeding: pnpm ${script} (service ${seeds.service})`, exec: ['exec', seeds.service, 'pnpm', script] }));
189
+ }
190
+
138
191
  /** Dockerfiles of the buildable services, relative to `root` (extra image-tag inputs). */
139
192
  export function dockerfilesFromCompose(compose, root) {
140
193
  const files = new Set();
@@ -190,6 +243,20 @@ export function createContext(loaded, { log = console.log, note = (m) => console
190
243
  };
191
244
  }
192
245
 
246
+ /**
247
+ * The context `worktree:create` sets the new worktree at `dir` up with: its own `package.json`
248
+ * and compose file (see `ownSettings`). The tracker stays the invoking checkout's: it is asked
249
+ * about the branch, not about the stack.
250
+ */
251
+ function ownContext(ctx, dir) {
252
+ let loaded = requireConfig({ root: dir });
253
+ // A package.json without a name is named after its directory, here the branch: the defaults
254
+ // derived from the name would differ from the invoking checkout's for no reason.
255
+ if (!loaded.pkg.name) loaded = { ...loaded, rootName: ctx.rootName, config: resolveConfig(loaded.raw, { rootName: ctx.rootName }) };
256
+ const own = createContext(loaded, { log: ctx.log, note: ctx.note });
257
+ return { ...ctx, wt: ownSettings(ctx.wt, own.wt), hasStack: own.hasStack, compose: own.compose, known: own.known, drift: settingsDrift(ctx.wt, own.wt) };
258
+ }
259
+
193
260
  // ───────────────────────── .env bookkeeping ─────────────────────────
194
261
 
195
262
  export function envOf(dir) {
@@ -312,12 +379,8 @@ export function pruneImages(ctx) {
312
379
 
313
380
  /** `down` across every profile (nothing left behind); `wipe` also removes volumes. */
314
381
  export async function stackDown(ctx, dir, { wipe }) {
315
- const ok = await stack.compose(dir, ['--profile', '*', 'down', ...(wipe ? ['-v'] : []), '--remove-orphans'], {
316
- // The shell env wins over --env-file: a .env from before profiles were mandatory must
317
- // not block its own teardown on the compose guard.
318
- env: { COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || ctx.known[0] || 'devkit' },
319
- allowFailure: true,
320
- });
382
+ const call = everyProfile(['down', ...(wipe ? ['-v'] : []), '--remove-orphans'], { known: ctx.known });
383
+ const ok = await stack.compose(dir, call.args, { env: call.env, allowFailure: true });
321
384
  if (!ok) ctx.note(`compose down failed in ${dir} — check 'docker ps -a' for leftovers`);
322
385
  if (wipe) {
323
386
  const project = envOf(dir).COMPOSE_PROJECT_NAME;
@@ -385,7 +448,6 @@ export async function cmdEnv(ctx, { cwd = process.cwd(), slot: requestedSlot } =
385
448
  /** `worktree:create <branch>` */
386
449
  export async function cmdCreate(ctx, branch, { profiles: requested, up = true } = {}) {
387
450
  if (!branch) throw new Error('usage: hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]');
388
- const profiles = ctx.hasStack ? normalizeProfiles(requested ?? ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required }) : [];
389
451
  await cmdPrune(ctx, {}); // reclaim merged-PR stacks (and their slots) before spending resources on a new one
390
452
  const wtDir = join(ctx.baseDir, branch);
391
453
  if (existsSync(wtDir)) throw new Error(`${wtDir} already exists`);
@@ -396,26 +458,46 @@ export async function cmdCreate(ctx, branch, { profiles: requested, up = true }
396
458
  const fetched = await run('git', ['-C', ctx.mainRoot, 'fetch', remote, 'main'], { allowFailure: true });
397
459
  if (!fetched) throw new Error(`cannot fetch ${remote}/main — refusing to base new work on a possibly stale main`);
398
460
  const base = `refs/remotes/${remote}/main`;
399
- if (git.branchExists(ctx.mainRoot, branch)) {
461
+ const existing = git.branchExists(ctx.mainRoot, branch);
462
+ if (existing) {
400
463
  await git.worktreeAdd(ctx.mainRoot, wtDir, { branch });
401
464
  if (!git.isAncestor(ctx.mainRoot, base, branch)) ctx.note(`existing branch ${branch} is behind ${remote}/main — merge it before starting work`);
402
465
  } else {
403
466
  await git.worktreeAdd(ctx.mainRoot, wtDir, { newBranch: branch, startPoint: base });
404
467
  }
468
+
469
+ // From here on the worktree's own settings decide: the invoking checkout may be behind (or
470
+ // ahead of) the commit that was just checked out, and its stack settings belong to its commit.
471
+ let own;
472
+ let profiles;
473
+ try {
474
+ own = ownContext(ctx, wtDir);
475
+ profiles = own.hasStack ? normalizeProfiles(requested ?? own.wt.profiles.default, { known: own.known, required: own.wt.profiles.required }) : [];
476
+ } catch (e) {
477
+ // Nothing is spent yet (no slot, no ticket, no install): take the worktree back, so the
478
+ // retry is not refused because the directory already exists.
479
+ const removed = await git.worktreeRemove(ctx.mainRoot, wtDir, { force: true });
480
+ if (removed && !existing) await git.branchDelete(ctx.mainRoot, branch);
481
+ const left = removed ? 'the worktree was removed again' : `the worktree is still at ${wtDir} — remove it with: hassan-devkit worktree:remove ${branch} --force`;
482
+ throw new Error(`${e.message}\n(${branch} is set up from its own package.json and compose file; ${left})`, { cause: e });
483
+ }
484
+ if (own.drift.length) {
485
+ ctx.note(`"${CONFIG_KEY}.worktree" of this checkout differs from the new worktree's in ${own.drift.join(', ')} — the new worktree follows its own package.json, except for baseDir and maxSlot (this checkout's)`);
486
+ }
405
487
  if (git.branchExists(ctx.mainRoot, 'main') && !git.isAncestor(ctx.mainRoot, base, 'main')) {
406
488
  ctx.note(`local main is behind ${remote}/main — sync it with: git checkout main && git merge --ff-only ${remote}/main`);
407
489
  }
408
490
 
409
491
  let slot = null;
410
- if (ctx.hasStack) {
492
+ if (own.hasStack) {
411
493
  await withLock(
412
- ctx.baseDir,
494
+ own.baseDir,
413
495
  '.slot.lock',
414
496
  'assigning a slot',
415
497
  120,
416
498
  async () => {
417
- slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
418
- writeEnv(ctx, wtDir, slot, profiles);
499
+ slot = pickFreeSlot(usedSlots(own), own.wt.maxSlot);
500
+ writeEnv(own, wtDir, slot, profiles);
419
501
  },
420
502
  { log: ctx.log },
421
503
  );
@@ -432,19 +514,22 @@ export async function cmdCreate(ctx, branch, { profiles: requested, up = true }
432
514
  }
433
515
 
434
516
  let values = null;
435
- if (ctx.hasStack && up) {
436
- await ensureImages(ctx, wtDir);
517
+ if (own.hasStack && up) {
518
+ await ensureImages(own, wtDir);
437
519
  await stack.compose(wtDir, ['up', '-d', '--build']);
438
520
  values = envOf(wtDir);
439
- if (ctx.wt.ready) await stack.waitForUrl(expandEnv(ctx.wt.ready.url, values), ctx.wt.ready.timeoutSeconds, { log: ctx.log });
440
- for (const script of ctx.wt.seeds.scripts) await stack.compose(wtDir, ['exec', ctx.wt.seeds.service, 'pnpm', script]);
521
+ if (own.wt.ready) await stack.waitForUrl(expandEnv(own.wt.ready.url, values), own.wt.ready.timeoutSeconds, { log: ctx.log });
522
+ }
523
+ for (const step of seedPlan(own.wt.seeds, { hasStack: own.hasStack, up })) {
524
+ ctx.log(step.line);
525
+ if (step.exec) await stack.compose(wtDir, step.exec); // a failing seed fails the command
441
526
  }
442
527
 
443
528
  ctx.log('');
444
529
  ctx.log(`Worktree ready: ${wtDir}${slot !== null ? ` (slot ${slot}, profiles: ${profiles.join(',')})` : ''}`);
445
530
  if (values) {
446
531
  for (const [k, v] of Object.entries(values)) if (k.startsWith('DEVKIT_PORT_')) ctx.log(` ${k.slice('DEVKIT_PORT_'.length).toLowerCase().padEnd(14)} localhost:${v}`);
447
- const optional = ctx.known.filter((p) => !ctx.wt.profiles.required.includes(p) && !profiles.includes(p));
532
+ const optional = own.known.filter((p) => !own.wt.profiles.required.includes(p) && !profiles.includes(p));
448
533
  if (optional.length) ctx.log(` add a profile with: hassan-devkit worktree:profiles add ${optional.join('|')}`);
449
534
  }
450
535
  return { dir: wtDir, slot, profiles };
@@ -490,6 +575,29 @@ export async function cmdProfiles(ctx, action = 'list', names = [], { cwd = proc
490
575
  }
491
576
  }
492
577
 
578
+ /**
579
+ * `worktree:stop` — stop this checkout's stack across every profile. The containers stay, with
580
+ * their volumes, the slot and `.env`, so `docker:up` starts the same stack again. Takes the
581
+ * loaded config, not a context: where there is nothing to stop it says why and succeeds, also
582
+ * in a repo whose `worktree` block is missing. A stop that fails throws.
583
+ */
584
+ export async function cmdStop(loaded, { log = console.log } = {}) {
585
+ const dir = loaded.root;
586
+ const hasStack = stack.hasComposeFile(dir);
587
+ const skip = stopSkipReason({
588
+ hasStack,
589
+ managed: hasStack && worktreeActive(loaded.config.worktree, { hasStack }),
590
+ hasEnv: existsSync(join(dir, ENV_FILE)),
591
+ });
592
+ if (skip) {
593
+ log(`${skip} — nothing stopped`);
594
+ return;
595
+ }
596
+ const call = everyProfile(['stop'], { known: createContext(loaded, { log }).known });
597
+ await stack.compose(dir, call.args, { env: call.env });
598
+ log(`stopped the stack of ${dir} (containers and data kept) — start it again with: pnpm docker:dev:up`);
599
+ }
600
+
493
601
  /** `worktree:remove <name>` — stack down (volumes gone unless --keep-data), worktree removed, branch kept. */
494
602
  export async function cmdRemove(ctx, name, { keepData = false, force = false } = {}) {
495
603
  if (!name) throw new Error('usage: hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]');
@@ -502,7 +610,10 @@ export async function cmdRemove(ctx, name, { keepData = false, force = false } =
502
610
  ctx.log(`removed ${dir} (branch kept — delete it with: git branch -D ${basename(dir)})`);
503
611
  }
504
612
 
505
- /** `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle). */
613
+ /**
614
+ * `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle) and
615
+ * report the merge to the tracker for the ticket of each one it removed.
616
+ */
506
617
  export async function cmdPrune(ctx, { dryRun = false } = {}) {
507
618
  if (!commandExists('gh')) {
508
619
  ctx.note('gh not installed — cannot check PR states, skipping prune');
@@ -539,12 +650,16 @@ export async function cmdPrune(ctx, { dryRun = false } = {}) {
539
650
  continue;
540
651
  }
541
652
  ctx.log(`prune: ${entry.name}: PR merged — removing worktree, containers, volumes, and branch`);
653
+ const key = ticketKeyFromBranch(branch, ctx.tracker);
542
654
  if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: true });
543
655
  if (await git.worktreeRemove(ctx.mainRoot, dir)) {
544
656
  await git.branchDelete(ctx.mainRoot, branch);
545
657
  removed.push(entry.name);
658
+ await transitionTicket({ key, event: 'merged', tracker: ctx.tracker, log: ctx.log, note: ctx.note });
546
659
  } 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}`);
660
+ // The ticket only moves with the worktree prune removes; this one is left to the developer.
661
+ const move = key && ctx.tracker.transitions?.merged ? ` && hassan-devkit tracker:transition ${key} merged` : '';
662
+ 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
663
  }
549
664
  }
550
665
  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);