@nolto/cli 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // src/index.ts
4
4
  import { createRequire as createRequire3 } from "module";
5
5
  import { fileURLToPath as fileURLToPath4 } from "url";
6
- import path19 from "path";
6
+ import path20 from "path";
7
7
  import { CommanderError } from "commander";
8
8
 
9
9
  // src/config.ts
@@ -60,6 +60,23 @@ function mapHttpStatusToCliError(status, opts = {}) {
60
60
  status
61
61
  );
62
62
  }
63
+ if (status === 409 && opts.serverError === "roadmap_conflict") {
64
+ const stored = opts.storedUpdatedAt ? ` (server updatedAt: ${opts.storedUpdatedAt})` : "";
65
+ return new CliError(
66
+ (opts.serverMessage ?? "The roadmap on the server is newer than this checkout.") + stored,
67
+ 2,
68
+ "Run `nolto diff` to see what differs. To take the server version: `nolto pull`. To keep this checkout as the source of truth: set `updatedAt` in the roadmap JSON to the current time and run `nolto sync` again.",
69
+ status
70
+ );
71
+ }
72
+ if (status === 409 && opts.serverError === "project_archived") {
73
+ return new CliError(
74
+ opts.serverMessage ?? "This project is archived.",
75
+ 2,
76
+ "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u304C\u30A2\u30FC\u30AB\u30A4\u30D6\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u89E3\u9664\u3059\u308B\u306B\u306F Web \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u8A2D\u5B9A\u3067\u300C\u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u89E3\u9664\u300D\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
77
+ status
78
+ );
79
+ }
63
80
  if (status === 429 && opts.serverError === "rebind_cooldown") {
64
81
  return new CliError(
65
82
  opts.serverMessage ?? "Rebind cooldown active.",
@@ -77,6 +94,21 @@ function mapHttpStatusToCliError(status, opts = {}) {
77
94
  status
78
95
  );
79
96
  }
97
+ if (status === 404 && opts.serverError) {
98
+ return new CliError(opts.serverError, 2, void 0, status);
99
+ }
100
+ if (status === 422) {
101
+ const details = Array.isArray(opts.details) ? opts.details.map((detail) => typeof detail === "string" ? detail : JSON.stringify(detail)).join("\n") : "";
102
+ return new CliError([opts.serverError ?? opts.serverMessage ?? "Validation failed", details].filter(Boolean).join("\n"), 2, void 0, status);
103
+ }
104
+ if (status === 403 && (opts.serverError === "token_scope" || opts.serverError === "token_project")) {
105
+ return new CliError(
106
+ opts.serverMessage ?? opts.serverError,
107
+ 3,
108
+ `Issue a token with the required scope at ${opts.baseUrl ?? "https://nolto.app"}/settings/tokens (nolto whoami shows the current scopes).`,
109
+ status
110
+ );
111
+ }
80
112
  if (status === 403) {
81
113
  return new CliError(
82
114
  opts.serverMessage ?? opts.serverError ?? "Forbidden",
@@ -87,9 +119,10 @@ function mapHttpStatusToCliError(status, opts = {}) {
87
119
  }
88
120
  if (status === 429) {
89
121
  const waitMsg = opts.retryAfter ? ` Retry-After: ${opts.retryAfter}s` : "";
90
- return new CliError(`Rate limit exceeded.${waitMsg}`, 4, void 0, status);
122
+ return new CliError(`${opts.serverMessage ?? "Rate limit exceeded."}${waitMsg}`, 4, void 0, status);
91
123
  }
92
- return new CliError(`Server returned HTTP ${status}`, 5, void 0, status);
124
+ const reason = opts.serverMessage ?? opts.serverError;
125
+ return new CliError(reason ? `Server returned HTTP ${status}: ${reason}` : `Server returned HTTP ${status}`, 5, void 0, status);
93
126
  }
94
127
  function isNetworkError(err) {
95
128
  if (!(err instanceof Error)) {
@@ -314,11 +347,11 @@ function maskToken(token) {
314
347
  function createHttpClient(opts) {
315
348
  const { baseUrl, version, token } = opts;
316
349
  const base = baseUrl.replace(/\/+$/, "");
317
- async function request(method, path20, body) {
318
- if (!path20.startsWith("/api/")) {
319
- throw new CliError(`HTTP client path must start with /api/, got: ${path20}`, 2);
350
+ async function request(method, path21, body) {
351
+ if (!path21.startsWith("/api/")) {
352
+ throw new CliError(`HTTP client path must start with /api/, got: ${path21}`, 2);
320
353
  }
321
- const url = `${base}${path20}`;
354
+ const url = `${base}${path21}`;
322
355
  const headers = {
323
356
  "Content-Type": "application/json",
324
357
  "User-Agent": `${CLI_USER_AGENT_NAME}/${version}`
@@ -354,18 +387,24 @@ function createHttpClient(opts) {
354
387
  } catch {
355
388
  }
356
389
  throw mapHttpStatusToCliError(response.status, {
390
+ baseUrl: base,
391
+ details: errorBody?.["details"],
357
392
  retryAfter,
358
393
  wwwAuthenticate,
359
394
  serverError: typeof errorBody?.["error"] === "string" ? errorBody["error"] : void 0,
360
395
  serverMessage: typeof errorBody?.["message"] === "string" ? errorBody["message"] : void 0,
396
+ storedUpdatedAt: typeof errorBody?.["storedUpdatedAt"] === "string" ? errorBody["storedUpdatedAt"] : void 0,
361
397
  upgradeUrl: typeof errorBody?.["upgradeUrl"] === "string" ? errorBody["upgradeUrl"] : void 0
362
398
  });
363
399
  }
400
+ if (response.status === 204) return void 0;
364
401
  return response.json();
365
402
  }
366
403
  return {
367
404
  get: (p) => request("GET", p),
368
405
  post: (p, b) => request("POST", p, b),
406
+ patch: (p, b) => request("PATCH", p, b),
407
+ delete: (p) => request("DELETE", p),
369
408
  put: (p, b) => request("PUT", p, b)
370
409
  };
371
410
  }
@@ -373,19 +412,10 @@ function createHttpClient(opts) {
373
412
  // src/program.ts
374
413
  import { Command } from "commander";
375
414
 
376
- // src/commands/init.ts
377
- import readline2 from "readline/promises";
378
- import { createRequire } from "module";
379
- import { fileURLToPath as fileURLToPath2 } from "url";
380
- import os3 from "os";
381
- import path9 from "path";
382
- import fs from "fs";
383
-
384
- // src/commands/link.ts
385
- import readline from "readline/promises";
386
- import os2 from "os";
387
- import path5 from "path";
388
- import { statSync as statSync2 } from "fs";
415
+ // src/commands/issue.ts
416
+ import { readFile as readFile2, readdir, writeFile as writeFile2, rename, rm } from "fs/promises";
417
+ import path2 from "path";
418
+ import { randomUUID } from "crypto";
389
419
 
390
420
  // src/output.ts
391
421
  function printResult(value, mode2, opts = {}) {
@@ -416,6 +446,11 @@ function printError(err, mode2) {
416
446
  }
417
447
  }
418
448
  }
449
+ function formatRecord(record) {
450
+ const keys = Object.keys(record);
451
+ const maxKeyLen = keys.reduce((m, k) => Math.max(m, k.length), 0);
452
+ return keys.map((k) => `${k.padEnd(maxKeyLen)}: ${record[k] ?? ""}`).join("\n");
453
+ }
419
454
  function formatValue(value) {
420
455
  if (value === null || value === void 0) {
421
456
  return "";
@@ -438,69 +473,6 @@ function formatValue(value) {
438
473
  return JSON.stringify(value, null, 2);
439
474
  }
440
475
 
441
- // src/registry.ts
442
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, rename, unlink } from "fs/promises";
443
- import { randomUUID } from "crypto";
444
- import path2 from "path";
445
- import { z as z2 } from "zod";
446
- var registrySchema = z2.object({
447
- schemaVersion: z2.literal(1),
448
- repos: z2.array(z2.object({ root: z2.string().min(1) }).passthrough())
449
- }).passthrough();
450
- function getRegistryPath(env) {
451
- return path2.join(getConfigDir(env), "registry.json");
452
- }
453
- async function loadRegistry(filePath) {
454
- let raw;
455
- try {
456
- raw = await readFile2(filePath, "utf8");
457
- } catch (err) {
458
- const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
459
- if (code === "ENOENT") {
460
- return { schemaVersion: 1, repos: [] };
461
- }
462
- throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
463
- }
464
- let parsed;
465
- try {
466
- parsed = JSON.parse(raw);
467
- } catch {
468
- throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
469
- }
470
- const result = registrySchema.safeParse(parsed);
471
- if (!result.success) {
472
- const issue = result.error.issues[0];
473
- const fieldPath = issue?.path.join(".") ?? "";
474
- throw new CliError(
475
- `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
476
- 2
477
- );
478
- }
479
- return result.data;
480
- }
481
- async function addRepoToRegistry(filePath, repoRoot) {
482
- const registry = await loadRegistry(filePath);
483
- if (registry.repos.some((repo) => repo.root === repoRoot)) {
484
- return { added: false, registry };
485
- }
486
- const updated = { ...registry, repos: [...registry.repos, { root: repoRoot }] };
487
- await mkdir2(path2.dirname(filePath), { recursive: true, mode: 448 });
488
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID()}`;
489
- try {
490
- await writeFile2(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
491
- await rename(tempPath, filePath);
492
- } catch (err) {
493
- await unlink(tempPath).catch(() => void 0);
494
- throw err;
495
- }
496
- return { added: true, registry: updated };
497
- }
498
-
499
- // src/repo-identity.ts
500
- import { execFile } from "child_process";
501
- import { realpathSync } from "fs";
502
- import path4 from "path";
503
-
504
476
  // ../roadmap-schema/src/repo-identity.ts
505
477
  var HOSTED_LOWERCASE_PATH = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
506
478
  function normalizeRemote(raw) {
@@ -520,23 +492,24 @@ function normalizeRemote(raw) {
520
492
  const firstSlash = s.indexOf("/");
521
493
  if (firstSlash <= 0) return null;
522
494
  let host = s.slice(0, firstSlash).toLowerCase();
523
- let path20 = s.slice(firstSlash + 1);
495
+ let path21 = s.slice(firstSlash + 1);
524
496
  if (hadScheme) host = host.replace(/:\d+$/, "");
525
- path20 = path20.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
526
- if (path20.length === 0) return null;
527
- if (HOSTED_LOWERCASE_PATH.has(host)) path20 = path20.toLowerCase();
528
- return `${host}/${path20}`;
497
+ path21 = path21.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
498
+ if (path21.length === 0) return null;
499
+ if (HOSTED_LOWERCASE_PATH.has(host)) path21 = path21.toLowerCase();
500
+ return `${host}/${path21}`;
529
501
  }
530
502
 
531
503
  // ../roadmap-schema/src/index.ts
532
504
  var STATUSES = /* @__PURE__ */ new Set(["todo", "in-progress", "done", "blocked"]);
533
505
  var ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
534
506
  var DATE_TIME_PATTERN = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
507
+ var ISSUE_KEY_REF_PATTERN = /^[A-Z][A-Z0-9]{1,9}-[1-9][0-9]{0,8}$/;
535
508
  var ALLOWED_KEYS = {
536
509
  roadmap: /* @__PURE__ */ new Set(["schemaVersion", "project", "updatedAt", "currentTaskId", "summary", "phases"]),
537
510
  project: /* @__PURE__ */ new Set(["id", "name", "repository"]),
538
511
  phase: /* @__PURE__ */ new Set(["id", "title", "status", "plan", "tasks"]),
539
- task: /* @__PURE__ */ new Set(["id", "title", "status", "startedAt", "completedAt", "note", "dependsOn", "plan"])
512
+ task: /* @__PURE__ */ new Set(["id", "title", "status", "startedAt", "completedAt", "note", "dependsOn", "plan", "issues"])
540
513
  };
541
514
  function isRecord(value) {
542
515
  return value != null && typeof value === "object" && !Array.isArray(value);
@@ -668,6 +641,23 @@ function validateRoadmap(value) {
668
641
  }
669
642
  if (task["status"] === "done" && task["completedAt"] == null) warnings.push(`${taskId} is done without completedAt.`);
670
643
  if (task["status"] === "in-progress" && task["startedAt"] == null) warnings.push(`${taskId} is in-progress without startedAt.`);
644
+ if (task["issues"] !== void 0 && !Array.isArray(task["issues"])) {
645
+ errors.push(`${taskAt}.issues must be an array.`);
646
+ } else if (Array.isArray(task["issues"])) {
647
+ const seenIssues = /* @__PURE__ */ new Set();
648
+ for (const [i, key] of task["issues"].entries()) {
649
+ if (typeof key !== "string") {
650
+ errors.push(`${taskAt}.issues[${i}] must be a string.`);
651
+ continue;
652
+ }
653
+ if (!ISSUE_KEY_REF_PATTERN.test(key)) {
654
+ errors.push(`${taskAt}.issues[${i}] is not an issue key (e.g. NOLTO-12).`);
655
+ continue;
656
+ }
657
+ if (seenIssues.has(key)) errors.push(`${taskAt}.issues contains duplicate key "${key}".`);
658
+ seenIssues.add(key);
659
+ }
660
+ }
671
661
  if (task["dependsOn"] !== void 0 && !Array.isArray(task["dependsOn"])) {
672
662
  errors.push(`${taskAt}.dependsOn must be an array.`);
673
663
  } else if (Array.isArray(task["dependsOn"])) {
@@ -734,10 +724,341 @@ function deriveTaskStats(roadmap) {
734
724
  };
735
725
  }
736
726
 
737
- // src/machine-id.ts
738
- import { chmod, mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
727
+ // src/issue-core.ts
728
+ var isUuid = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
729
+ function parseIssueRef(input) {
730
+ const match = /^(?:[A-Z][A-Z0-9]{1,9}-)?([1-9][0-9]{0,8})$/i.exec(input);
731
+ if (!match) throw new CliError(`Invalid issue reference: ${input}. Use KEY-12 or 12.`, 2);
732
+ return Number(match[1]);
733
+ }
734
+ function resolveMaster(kind, input, settings) {
735
+ const rows = kind === "status" ? settings.statuses : kind === "type" ? settings.types : settings.categories;
736
+ const normalized = input.toLowerCase();
737
+ const matches = rows.filter((row) => (isUuid(input) ? row.id : row.name).toLowerCase() === normalized);
738
+ if (matches.length !== 1) throw new CliError(`Unknown or ambiguous ${kind}: ${input}. Candidates: ${rows.map((row) => row.name).join(", ") || "(none)"}`, 2);
739
+ return { id: matches[0].id };
740
+ }
741
+ function pickClosedStatus(settings, override) {
742
+ const id = override === void 0 ? void 0 : resolveMaster("status", override, settings).id;
743
+ const selected = [...settings.statuses].filter((row) => row.isClosed && (id === void 0 || row.id === id)).sort((a, b) => a.sortOrder - b.sortOrder)[0];
744
+ if (!selected) throw new CliError("No matching closed status. Choose a closed status with --status.", 2);
745
+ return { id: selected.id, name: selected.name };
746
+ }
747
+ function buildListQuery(flags, settings) {
748
+ const params = new URLSearchParams();
749
+ for (const status of flags.status ?? []) params.append("status", resolveMaster("status", status, settings).id);
750
+ for (const kind of ["type", "category"]) {
751
+ const value = flags[kind];
752
+ if (value !== void 0) params.set(kind, resolveMaster(kind, value, settings).id);
753
+ }
754
+ const choices = {
755
+ closed: ["exclude", "include", "only"],
756
+ priority: ["high", "normal", "low"],
757
+ sort: ["updated", "due", "priority", "number", "created", "assignee", "status", "type", "subject"],
758
+ order: ["asc", "desc"]
759
+ };
760
+ for (const field of ["assignee", "closed", "q", "sort", "order", "page", "priority", "parent"]) {
761
+ const value = flags[field];
762
+ if (value === void 0) continue;
763
+ if (choices[field] && !choices[field].includes(value)) throw new CliError(`Invalid --${field}: ${value}. Choose ${choices[field].join(", ")}.`, 2);
764
+ if (field === "page" && (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(Number(value)))) throw new CliError("--page must be a positive integer.", 2);
765
+ if (field === "assignee" && !["me", "none"].includes(value) && !isUuid(value)) throw new CliError("--assignee must be me, none or a UUID.", 2);
766
+ params.set(field, field === "parent" && value !== "none" ? String(parseIssueRef(value)) : value);
767
+ }
768
+ return params;
769
+ }
770
+ var personLabel = (person) => person?.name ?? person?.email ?? "\u2014";
771
+ var singleLine = (value) => value.replace(/[\r\n\t]/g, " ");
772
+ var formatTimestamp = (value) => value.replace("T", " ").replace(/\.\d+/, "").replace(/([+-]\d{2})$/, "$1:00").replace(/Z$/, "+00:00");
773
+ function formatIssueList(rows, meta) {
774
+ const values = rows.map((row) => {
775
+ const subject = Array.from(singleLine(row.subject));
776
+ return [row.key, row.status.name, row.priority, personLabel(row.assignee), subject.length > 60 ? `${subject.slice(0, 59).join("")}\u2026` : subject.join("")].map(singleLine);
777
+ });
778
+ const widths = [0, 1, 2, 3].map((index) => Math.max(0, ...values.map((row) => row[index].length)));
779
+ const lines = values.map((row) => row.map((value, index) => index < 4 ? value.padEnd(widths[index]) : value).join(" "));
780
+ return [...lines, `${rows.length} / ${meta.total} (page ${meta.page})`].join("\n");
781
+ }
782
+ function formatIssueView(bundle) {
783
+ const issue = bundle.issue;
784
+ const attributes = formatRecord({
785
+ key: issue.key,
786
+ subject: issue.subject,
787
+ status: issue.status.name,
788
+ type: issue.type.name,
789
+ priority: issue.priority,
790
+ assignee: personLabel(issue.assignee),
791
+ due: issue.dueDate ?? "\u2014",
792
+ categories: issue.categories.map((row) => row.name).join(", "),
793
+ parent: issue.parent?.key ?? "\u2014"
794
+ });
795
+ const comments = bundle.comments.map((comment) => `${personLabel(comment.author)} / ${formatTimestamp(comment.createdAt)}${!comment.deletedAt && comment.via ? ` [API \u7D4C\u7531: ${comment.via.tokenName}]` : ""}
796
+ ${comment.deletedAt ? "\u30B3\u30E1\u30F3\u30C8\u306F\u524A\u9664\u3055\u308C\u3066\u3044\u307E\u3059\u3002" : comment.body}`);
797
+ return [attributes, issue.body, ...comments].join("\n\n");
798
+ }
799
+ function addIssueToRoadmapTask(roadmapJson, taskId, key, now) {
800
+ const validation = validateRoadmap(roadmapJson);
801
+ if (validation.errors.length) return { error: `Invalid roadmap: ${validation.errors.join("; ")}` };
802
+ const input = roadmapJson;
803
+ const target = input.phases.flatMap((phase) => phase.tasks).find((task) => task.id === taskId);
804
+ if (!target) return { error: `roadmap task ${taskId} was not found` };
805
+ if (target.issues?.includes(key)) return { roadmap: input, changed: false };
806
+ const roadmap = { ...input, schemaVersion: 2, updatedAt: now, phases: input.phases.map((phase) => ({
807
+ ...phase,
808
+ tasks: phase.tasks.map((task) => task.id === taskId ? { ...task, issues: [...task.issues ?? [], key] } : task)
809
+ })) };
810
+ const result = validateRoadmap(roadmap);
811
+ return result.errors.length ? { error: `Invalid roadmap: ${result.errors.join("; ")}` } : { roadmap, changed: true };
812
+ }
813
+ function issueUrl(baseUrl, projectId, number) {
814
+ return `${baseUrl.replace(/\/+$/, "")}/projects/${encodeURIComponent(projectId)}/issues/${number}`;
815
+ }
816
+
817
+ // src/commands/issue.ts
818
+ var emptySettings = { types: [], statuses: [], categories: [] };
819
+ function context(deps, command) {
820
+ if (!deps.settings.token) throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
821
+ const globals = command.optsWithGlobals();
822
+ const projectId = globals.project ?? deps.settings.defaultProjectId;
823
+ if (!projectId) throw new CliError("No project. Pass --project <id> or run nolto link.", 2);
824
+ return {
825
+ projectId,
826
+ root: `/api/projects/${encodeURIComponent(projectId)}`,
827
+ mode: globals.json ? "json" : deps.output.mode
828
+ };
829
+ }
830
+ async function bodyText(body, file) {
831
+ if (body !== void 0 && file !== void 0) throw new CliError("Use either --body/-m or --body-file, not both.", 2);
832
+ if (file === void 0) return body;
833
+ try {
834
+ if (file !== "-") return await readFile2(file, "utf8");
835
+ const chunks = [];
836
+ for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
837
+ return Buffer.concat(chunks).toString("utf8");
838
+ } catch (error) {
839
+ throw new CliError(`Cannot read body from ${file}: ${String(error)}`, 2);
840
+ }
841
+ }
842
+ async function writeInput(deps, root, flags, create) {
843
+ const body = await bodyText(flags.body, flags.bodyFile);
844
+ const settings = flags.type || flags.status || flags.category ? await deps.http.get(`${root}/issue-settings`) : emptySettings;
845
+ const typeId = flags.type === void 0 ? void 0 : resolveMaster("type", flags.type, settings).id;
846
+ const template = create && body === void 0 && typeId !== void 0 ? settings.types.find((type) => type.id === typeId)?.bodyTemplate : void 0;
847
+ let assigneeId;
848
+ if (flags.assignee !== void 0) {
849
+ if (flags.assignee === "none") assigneeId = null;
850
+ else if (flags.assignee === "me") assigneeId = (await deps.http.get("/api/me/profile")).profile.id;
851
+ else if (isUuid(flags.assignee)) assigneeId = flags.assignee;
852
+ else throw new CliError("--assignee must be me, none or a UUID.", 2);
853
+ }
854
+ let parentId;
855
+ if (flags.parent === false) parentId = null;
856
+ else if (flags.parent !== void 0) parentId = (await deps.http.get(`${root}/issues/${parseIssueRef(flags.parent)}`)).issue.id;
857
+ if (typeof flags.due === "string" && (!/^\d{4}-\d{2}-\d{2}$/.test(flags.due) || !Number.isFinite(Date.parse(flags.due)) || new Date(flags.due).toISOString().slice(0, 10) !== flags.due)) {
858
+ throw new CliError("--due must be a valid YYYY-MM-DD date.", 2);
859
+ }
860
+ if (flags.priority !== void 0 && !["high", "normal", "low"].includes(flags.priority)) throw new CliError("--priority must be high, normal or low.", 2);
861
+ const input = {
862
+ ...flags.subject !== void 0 ? { subject: flags.subject } : {},
863
+ ...body !== void 0 ? { body } : template != null ? { body: template } : {},
864
+ ...typeId !== void 0 ? { typeId } : {},
865
+ ...flags.status !== void 0 ? { statusId: resolveMaster("status", flags.status, settings).id } : {},
866
+ ...flags.priority !== void 0 ? { priority: flags.priority } : {},
867
+ ...assigneeId !== void 0 ? { assigneeId } : {},
868
+ ...flags.due !== void 0 ? { dueDate: flags.due === false ? null : flags.due } : {},
869
+ ...flags.category !== void 0 ? { categoryIds: flags.category.map((name) => resolveMaster("category", name, settings).id) } : {},
870
+ ...parentId !== void 0 ? { parentId } : {},
871
+ ...flags.comment !== void 0 ? { comment: flags.comment } : {}
872
+ };
873
+ if (Object.keys(input).length === 0) throw new CliError("No changes. Pass a field option or --comment.", 2);
874
+ return { input, fromTemplate: template != null };
875
+ }
876
+ function localTimestamp() {
877
+ const date = /* @__PURE__ */ new Date();
878
+ const minutes = -date.getTimezoneOffset();
879
+ const pad = (value) => String(Math.abs(value)).padStart(2, "0");
880
+ return `${new Date(date.getTime() + minutes * 6e4).toISOString().slice(0, -1)}${minutes >= 0 ? "+" : "-"}${pad(Math.trunc(minutes / 60))}:${pad(minutes % 60)}`;
881
+ }
882
+ async function attachRoadmap(deps, taskId, slug, key) {
883
+ let directory = path2.dirname(deps.repoBinding?.path ?? deps.projectBindingPath ?? path2.join(process.cwd(), "nolto.json"));
884
+ let file = "";
885
+ try {
886
+ if (slug !== void 0 && !/^[a-z0-9][a-z0-9._-]*$/.test(slug)) throw new Error("Invalid --roadmap slug.");
887
+ let entries;
888
+ for (; ; ) {
889
+ try {
890
+ entries = await readdir(path2.join(directory, ".nolto", "roadmaps"));
891
+ break;
892
+ } catch (error) {
893
+ if (error.code !== "ENOENT" || path2.dirname(directory) === directory) throw error;
894
+ directory = path2.dirname(directory);
895
+ }
896
+ }
897
+ const names = entries.filter((name) => name.endsWith(".json")).sort();
898
+ if (slug === void 0 && names.length !== 1) throw new Error(`Choose --roadmap <slug>. Candidates: ${names.map((name) => name.slice(0, -5)).join(", ") || "(none)"}`);
899
+ file = path2.join(directory, ".nolto", "roadmaps", slug === void 0 ? names[0] : `${slug}.json`);
900
+ const result = addIssueToRoadmapTask(JSON.parse(await readFile2(file, "utf8")), taskId, key, localTimestamp());
901
+ if ("error" in result) throw new Error(`${result.error} in ${file}`);
902
+ if (result.changed) {
903
+ const temp = `${file}.${randomUUID()}.tmp`;
904
+ try {
905
+ await writeFile2(temp, JSON.stringify(result.roadmap, null, 2) + "\n", { flag: "wx" });
906
+ await rename(temp, file);
907
+ } finally {
908
+ await rm(temp, { force: true });
909
+ }
910
+ }
911
+ process.stderr.write("Run `nolto sync` to link it on Nolto.\n");
912
+ return { file, taskId };
913
+ } catch (error) {
914
+ throw new CliError(
915
+ `Issue ${key} was created, but ${error instanceof Error ? error.message : String(error)}`,
916
+ 2,
917
+ "Do not create it again. Add the existing issue key to the roadmap task, then run `nolto sync`."
918
+ );
919
+ }
920
+ }
921
+ function writeOptions(command, create) {
922
+ if (create) command.requiredOption("--subject <text>", "Issue subject");
923
+ else command.option("--subject <text>", "Issue subject");
924
+ command.option("--body <text>", "Issue body").option("--body-file <path>", "Read body from file (- for stdin)").option("--type <name-or-id>", "Issue type").option("--status <name-or-id>", "Issue status").option("--priority <priority>", "high, normal or low").option("--assignee <assignee>", "me, none or UUID").option("--due <YYYY-MM-DD>", "Due date").option("--category <names...>", "Category names or UUIDs").option("--parent <ref>", "Parent issue key or number");
925
+ if (create) command.option("--phase <task-id>", "Attach the created key to a local roadmap task").option("--roadmap <slug>", "Roadmap filename slug (with --phase)");
926
+ else command.option("--no-due", "Clear due date").option("--no-parent", "Clear parent").option("-m, --comment <text>", "Comment in the same update");
927
+ return command;
928
+ }
929
+ function register(program, deps) {
930
+ const group = program.command("issue").description("List, view and manage project issues.");
931
+ group.command("list").description("List or search issues.").option("--status <names...>", "Status names or UUIDs").option("--assignee <assignee>", "me, none or UUID").option("--closed <mode>", "exclude, include or only").option("--q <text>", "Search text").option("--sort <field>", "updated, due, priority, number, created, assignee, status, type or subject").option("--order <order>", "asc or desc").option("--page <number>", "Page number").option("--type <name-or-id>", "Issue type").option("--priority <priority>", "high, normal or low").option("--category <name-or-id>", "Category").option("--parent <ref>", "Parent issue or none").action(async (flags, command) => {
932
+ const ctx = context(deps, command);
933
+ const settings = flags.status || flags.type || flags.category ? await deps.http.get(`${ctx.root}/issue-settings`) : emptySettings;
934
+ const query = buildListQuery(flags, settings).toString();
935
+ const result = await deps.http.get(`${ctx.root}/issues${query ? `?${query}` : ""}`);
936
+ printResult(ctx.mode === "json" ? result : formatIssueList(result.issues, result), ctx.mode);
937
+ });
938
+ group.command("view <ref>").description("Show issue details and comments.").action(async (ref, _flags, command) => {
939
+ const ctx = context(deps, command);
940
+ const result = await deps.http.get(`${ctx.root}/issues/${parseIssueRef(ref)}`);
941
+ printResult(ctx.mode === "json" ? result : formatIssueView(result), ctx.mode);
942
+ });
943
+ writeOptions(group.command("create").description("Create an issue."), true).action(async (flags, command) => {
944
+ const ctx = context(deps, command);
945
+ if (flags.roadmap !== void 0 && flags.phase === void 0) throw new CliError("--roadmap requires --phase.", 2);
946
+ const { input, fromTemplate } = await writeInput(deps, ctx.root, flags, true);
947
+ const result = await deps.http.post(`${ctx.root}/issues`, input);
948
+ const roadmap = flags.phase === void 0 ? void 0 : await attachRoadmap(deps, flags.phase, flags.roadmap, result.issue.key);
949
+ printResult(ctx.mode === "json" ? { ...result, ...roadmap ? { roadmap } : {} } : `${result.issue.key} created
950
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${fromTemplate ? "\nbody: from template" : ""}`, ctx.mode);
951
+ });
952
+ writeOptions(group.command("update <ref>").description("Update issue fields."), false).action(async (ref, flags, command) => {
953
+ const ctx = context(deps, command);
954
+ const number = parseIssueRef(ref);
955
+ const { input } = await writeInput(deps, ctx.root, flags, false);
956
+ const result = await deps.http.patch(`${ctx.root}/issues/${number}`, input);
957
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} updated
958
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
959
+ });
960
+ group.command("comment <ref>").description("Post a comment.").option("-m, --comment <text>", "Comment text").option("--body-file <path>", "Read comment from file (- for stdin)").action(async (ref, flags, command) => {
961
+ const ctx = context(deps, command);
962
+ const number = parseIssueRef(ref);
963
+ const body = await bodyText(flags.comment, flags.bodyFile);
964
+ if (!body?.trim()) throw new CliError("A comment is required. Use -m or --body-file.", 2);
965
+ const issue = ctx.mode === "human" ? (await deps.http.get(`${ctx.root}/issues/${number}`)).issue : void 0;
966
+ const result = await deps.http.post(`${ctx.root}/issues/${number}/comments`, { body });
967
+ printResult(ctx.mode === "json" ? result : `${issue.key} commented
968
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
969
+ });
970
+ group.command("close <ref>").description("Move an issue to a closed status.").option("--status <name-or-id>", "Closed status (defaults to first by sort order)").option("-m, --comment <text>", "Comment in the same update").action(async (ref, flags, command) => {
971
+ const ctx = context(deps, command);
972
+ const number = parseIssueRef(ref);
973
+ const settings = await deps.http.get(`${ctx.root}/issue-settings`);
974
+ const status = pickClosedStatus(settings, flags.status);
975
+ const result = await deps.http.patch(`${ctx.root}/issues/${number}`, { statusId: status.id, ...flags.comment !== void 0 ? { comment: flags.comment } : {} });
976
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} closed
977
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
978
+ });
979
+ }
980
+
981
+ // src/commands/init.ts
982
+ import readline2 from "readline/promises";
983
+ import { createRequire } from "module";
984
+ import { fileURLToPath as fileURLToPath2 } from "url";
985
+ import os3 from "os";
986
+ import path10 from "path";
987
+ import fs from "fs";
988
+
989
+ // src/commands/link.ts
990
+ import readline from "readline/promises";
991
+ import os2 from "os";
992
+ import path6 from "path";
993
+ import { statSync as statSync2 } from "fs";
994
+
995
+ // src/registry.ts
996
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir2, rename as rename2, unlink } from "fs/promises";
739
997
  import { randomUUID as randomUUID2 } from "crypto";
740
998
  import path3 from "path";
999
+ import { z as z2 } from "zod";
1000
+ var registrySchema = z2.object({
1001
+ schemaVersion: z2.literal(1),
1002
+ repos: z2.array(z2.object({ root: z2.string().min(1) }).passthrough())
1003
+ }).passthrough();
1004
+ function getRegistryPath(env) {
1005
+ return path3.join(getConfigDir(env), "registry.json");
1006
+ }
1007
+ async function loadRegistry(filePath) {
1008
+ let raw;
1009
+ try {
1010
+ raw = await readFile3(filePath, "utf8");
1011
+ } catch (err) {
1012
+ const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1013
+ if (code === "ENOENT") {
1014
+ return { schemaVersion: 1, repos: [] };
1015
+ }
1016
+ throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
1017
+ }
1018
+ let parsed;
1019
+ try {
1020
+ parsed = JSON.parse(raw);
1021
+ } catch {
1022
+ throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
1023
+ }
1024
+ const result = registrySchema.safeParse(parsed);
1025
+ if (!result.success) {
1026
+ const issue = result.error.issues[0];
1027
+ const fieldPath = issue?.path.join(".") ?? "";
1028
+ throw new CliError(
1029
+ `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
1030
+ 2
1031
+ );
1032
+ }
1033
+ return result.data;
1034
+ }
1035
+ async function addRepoToRegistry(filePath, repoRoot) {
1036
+ const registry = await loadRegistry(filePath);
1037
+ if (registry.repos.some((repo) => repo.root === repoRoot)) {
1038
+ return { added: false, registry };
1039
+ }
1040
+ const updated = { ...registry, repos: [...registry.repos, { root: repoRoot }] };
1041
+ await mkdir2(path3.dirname(filePath), { recursive: true, mode: 448 });
1042
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1043
+ try {
1044
+ await writeFile3(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1045
+ await rename2(tempPath, filePath);
1046
+ } catch (err) {
1047
+ await unlink(tempPath).catch(() => void 0);
1048
+ throw err;
1049
+ }
1050
+ return { added: true, registry: updated };
1051
+ }
1052
+
1053
+ // src/repo-identity.ts
1054
+ import { execFile } from "child_process";
1055
+ import { realpathSync } from "fs";
1056
+ import path5 from "path";
1057
+
1058
+ // src/machine-id.ts
1059
+ import { chmod, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
1060
+ import { randomUUID as randomUUID3 } from "crypto";
1061
+ import path4 from "path";
741
1062
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
742
1063
  function parseMachineId(raw, file) {
743
1064
  let parsed;
@@ -753,10 +1074,10 @@ function parseMachineId(raw, file) {
753
1074
  return id;
754
1075
  }
755
1076
  async function loadOrCreate(configDir) {
756
- const file = path3.join(configDir, "machine.json");
1077
+ const file = path4.join(configDir, "machine.json");
757
1078
  let raw = null;
758
1079
  try {
759
- raw = await readFile3(file, "utf8");
1080
+ raw = await readFile4(file, "utf8");
760
1081
  } catch (err) {
761
1082
  const code = err.code;
762
1083
  if (code !== "ENOENT") {
@@ -766,17 +1087,17 @@ async function loadOrCreate(configDir) {
766
1087
  if (raw !== null) {
767
1088
  return parseMachineId(raw, file);
768
1089
  }
769
- const machineId = randomUUID2();
1090
+ const machineId = randomUUID3();
770
1091
  await mkdir3(configDir, { recursive: true, mode: 448 });
771
1092
  try {
772
- await writeFile3(file, `${JSON.stringify({ machineId }, null, 2)}
1093
+ await writeFile4(file, `${JSON.stringify({ machineId }, null, 2)}
773
1094
  `, {
774
1095
  flag: "wx",
775
1096
  mode: 384
776
1097
  });
777
1098
  } catch (err) {
778
1099
  if (err.code === "EEXIST") {
779
- return parseMachineId(await readFile3(file, "utf8"), file);
1100
+ return parseMachineId(await readFile4(file, "utf8"), file);
780
1101
  }
781
1102
  throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
782
1103
  }
@@ -784,7 +1105,7 @@ async function loadOrCreate(configDir) {
784
1105
  return machineId;
785
1106
  }
786
1107
  function loadOrCreateMachineId(configDir) {
787
- const key = path3.resolve(configDir);
1108
+ const key = path4.resolve(configDir);
788
1109
  const existing = inFlightByConfigDir.get(key);
789
1110
  if (existing !== void 0) return existing;
790
1111
  const pending = loadOrCreate(key).finally(() => {
@@ -801,9 +1122,9 @@ function defaultGetRemoteUrl(root) {
801
1122
  "git",
802
1123
  ["-C", root, "remote", "get-url", "origin"],
803
1124
  { timeout: 5e3 },
804
- (err, stdout) => {
1125
+ (err, stdout2) => {
805
1126
  if (err) return resolve(null);
806
- const line = stdout.split(/\r?\n/)[0]?.trim() ?? "";
1127
+ const line = stdout2.split(/\r?\n/)[0]?.trim() ?? "";
807
1128
  resolve(line.length > 0 ? line : null);
808
1129
  }
809
1130
  );
@@ -818,7 +1139,7 @@ async function resolveRepoIdentity(root, deps) {
818
1139
  try {
819
1140
  canonicalRoot = realpathSync(root);
820
1141
  } catch {
821
- canonicalRoot = path4.resolve(root);
1142
+ canonicalRoot = path5.resolve(root);
822
1143
  }
823
1144
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
824
1145
  }
@@ -837,7 +1158,7 @@ function resolveStartDir(env, cwd) {
837
1158
  }
838
1159
  function dirHasGit(dir) {
839
1160
  try {
840
- statSync2(path5.join(dir, ".git"));
1161
+ statSync2(path6.join(dir, ".git"));
841
1162
  return true;
842
1163
  } catch {
843
1164
  return false;
@@ -849,14 +1170,14 @@ function findRepoRoot(startDir, hasGit = dirHasGit) {
849
1170
  if (hasGit(current)) {
850
1171
  return { root: current, foundGit: true };
851
1172
  }
852
- const parent = path5.dirname(current);
1173
+ const parent = path6.dirname(current);
853
1174
  if (parent === current) break;
854
1175
  current = parent;
855
1176
  }
856
1177
  return { root: startDir, foundGit: false };
857
1178
  }
858
1179
  function isHomeDirectory(dir, home = os2.homedir()) {
859
- return path5.resolve(dir) === path5.resolve(home);
1180
+ return path6.resolve(dir) === path6.resolve(home);
860
1181
  }
861
1182
  async function handleShow(deps, projectBindingPath, mode2) {
862
1183
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -955,10 +1276,10 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
955
1276
  }
956
1277
  }
957
1278
  async function handleUnlink(projectBindingPath, mode2) {
958
- const { readFile: readFile12, writeFile: writeFile10, chmod: chmod2 } = await import("fs/promises");
1279
+ const { readFile: readFile13, writeFile: writeFile11, chmod: chmod2 } = await import("fs/promises");
959
1280
  let existing = {};
960
1281
  try {
961
- const raw = await readFile12(projectBindingPath, "utf8");
1282
+ const raw = await readFile13(projectBindingPath, "utf8");
962
1283
  const parsed = JSON.parse(raw);
963
1284
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
964
1285
  throw new CliError(
@@ -973,7 +1294,7 @@ async function handleUnlink(projectBindingPath, mode2) {
973
1294
  }
974
1295
  const { projectId: _removed, ...rest } = existing;
975
1296
  void _removed;
976
- await writeFile10(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1297
+ await writeFile11(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
977
1298
  await chmod2(projectBindingPath, 420);
978
1299
  if (mode2 === "json") {
979
1300
  printResult({ unlinked: true, projectBindingPath }, mode2);
@@ -1028,7 +1349,7 @@ Proceeding anyway \u2014 verify the ID is correct.
1028
1349
  );
1029
1350
  }
1030
1351
  await writeRepoBinding(root, projectId);
1031
- const writtenPath = path5.join(root, "nolto.json");
1352
+ const writtenPath = path6.join(root, "nolto.json");
1032
1353
  let registryAdded = false;
1033
1354
  if (isHomeDirectory(root)) {
1034
1355
  process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
@@ -1061,7 +1382,7 @@ Commit nolto.json to share the binding with your team.
1061
1382
  }
1062
1383
  }
1063
1384
  }
1064
- function register(program, deps) {
1385
+ function register2(program, deps) {
1065
1386
  const cmd = program.command("link [projectId]").description(
1066
1387
  "Bind this repository to a Nolto project.\nWrites nolto.json at the repo root. Commit it to share the binding with your team.\n\nExamples:\n nolto link <uuid> Write / update nolto.json\n nolto link --show Show the current binding\n nolto link --rebind Rebind the project to this repository\n nolto link --unlink Remove the projectId from nolto.json"
1067
1388
  ).option("--show", "Show the current repo binding (path + projectId + source)").option("--rebind", "Rebind the project to this repository (owner only, once per 7 days)").option("-y, --yes", "Skip the rebind confirmation prompt").option("--unlink", "Remove the projectId key from nolto.json");
@@ -1115,35 +1436,35 @@ function invalidBindingError(projectBindingPath, error) {
1115
1436
  }
1116
1437
 
1117
1438
  // src/skill-install.ts
1118
- import { cp, mkdir as mkdir4, readFile as readFile4, writeFile as writeFile4, rm } from "fs/promises";
1439
+ import { cp, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile5, rm as rm2 } from "fs/promises";
1119
1440
  import { existsSync } from "fs";
1120
- import path6 from "path";
1441
+ import path7 from "path";
1121
1442
  import { fileURLToPath } from "url";
1122
- var __dirname = path6.dirname(fileURLToPath(import.meta.url));
1443
+ var __dirname = path7.dirname(fileURLToPath(import.meta.url));
1123
1444
  function resolveSkillSourceDir() {
1124
1445
  const candidates = [
1125
- path6.resolve(__dirname, "skill/roadmap-progress"),
1446
+ path7.resolve(__dirname, "skill/roadmap-progress"),
1126
1447
  // bundled: dist/skill/...
1127
- path6.resolve(__dirname, "../../../skills/roadmap-progress")
1448
+ path7.resolve(__dirname, "../../../skills/roadmap-progress")
1128
1449
  // source: <repo>/skills/...
1129
1450
  ];
1130
1451
  for (const candidate of candidates) {
1131
- if (existsSync(path6.join(candidate, "SKILL.md"))) return candidate;
1452
+ if (existsSync(path7.join(candidate, "SKILL.md"))) return candidate;
1132
1453
  }
1133
1454
  throw new Error("Bundled roadmap-progress skill not found. Reinstall @nolto/cli.");
1134
1455
  }
1135
1456
  var VERSION_MARKER = ".nolto-skill-version";
1136
1457
  async function checkSkillVersionDrift(repoRoot, cliVersion) {
1137
1458
  const skillDirs = [
1138
- path6.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1139
- path6.join(repoRoot, ".agents", "skills", "roadmap-progress")
1459
+ path7.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1460
+ path7.join(repoRoot, ".agents", "skills", "roadmap-progress")
1140
1461
  ];
1141
1462
  const drifted = [];
1142
1463
  for (const dir of skillDirs) {
1143
1464
  if (!existsSync(dir)) continue;
1144
1465
  let installed;
1145
1466
  try {
1146
- const marker = (await readFile4(path6.join(dir, VERSION_MARKER), "utf8")).trim();
1467
+ const marker = (await readFile5(path7.join(dir, VERSION_MARKER), "utf8")).trim();
1147
1468
  installed = marker.length > 0 ? marker : null;
1148
1469
  } catch {
1149
1470
  installed = null;
@@ -1153,18 +1474,18 @@ async function checkSkillVersionDrift(repoRoot, cliVersion) {
1153
1474
  return drifted;
1154
1475
  }
1155
1476
  function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
1156
- const dirs = drifted.map(({ dir }) => path6.relative(repoRoot, dir).split(path6.sep).join("/")).join(", ");
1477
+ const dirs = drifted.map(({ dir }) => path7.relative(repoRoot, dir).split(path7.sep).join("/")).join(", ");
1157
1478
  const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
1158
1479
  return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
1159
1480
  }
1160
1481
  async function installSkill(args) {
1161
- const targetDir = path6.join(args.skillsParentDir, "roadmap-progress");
1162
- const markerPath = path6.join(targetDir, VERSION_MARKER);
1482
+ const targetDir = path7.join(args.skillsParentDir, "roadmap-progress");
1483
+ const markerPath = path7.join(targetDir, VERSION_MARKER);
1163
1484
  const dirExists = existsSync(targetDir);
1164
1485
  let installedVersion = null;
1165
1486
  if (dirExists) {
1166
1487
  try {
1167
- installedVersion = (await readFile4(markerPath, "utf8")).trim();
1488
+ installedVersion = (await readFile5(markerPath, "utf8")).trim();
1168
1489
  } catch {
1169
1490
  installedVersion = null;
1170
1491
  }
@@ -1172,30 +1493,30 @@ async function installSkill(args) {
1172
1493
  if (dirExists && installedVersion === args.version && args.force !== true) {
1173
1494
  return { action: "skipped", targetDir };
1174
1495
  }
1175
- await rm(targetDir, { recursive: true, force: true });
1496
+ await rm2(targetDir, { recursive: true, force: true });
1176
1497
  await mkdir4(args.skillsParentDir, { recursive: true });
1177
1498
  await cp(args.sourceDir, targetDir, { recursive: true });
1178
- await writeFile4(markerPath, args.version + "\n", "utf8");
1499
+ await writeFile5(markerPath, args.version + "\n", "utf8");
1179
1500
  return { action: dirExists ? "updated" : "installed", targetDir };
1180
1501
  }
1181
1502
 
1182
1503
  // src/roadmap-scaffold.ts
1183
- import { mkdir as mkdir5, readdir, writeFile as writeFile5 } from "fs/promises";
1504
+ import { mkdir as mkdir5, readdir as readdir2, writeFile as writeFile6 } from "fs/promises";
1184
1505
  import { existsSync as existsSync2 } from "fs";
1185
- import path7 from "path";
1506
+ import path8 from "path";
1186
1507
  function slugifyProjectId(name) {
1187
1508
  const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1188
1509
  return slug.length > 0 ? slug : "project";
1189
1510
  }
1190
1511
  async function scaffoldRoadmap(args) {
1191
- const repoBasename = path7.basename(args.repoRoot);
1192
- const dir = path7.join(args.repoRoot, ".nolto", "roadmaps");
1193
- const filePath = path7.join(dir, `${slugifyProjectId(repoBasename)}.json`);
1194
- const legacyPath = path7.join(args.repoRoot, ".roadmap", "roadmap.json");
1512
+ const repoBasename = path8.basename(args.repoRoot);
1513
+ const dir = path8.join(args.repoRoot, ".nolto", "roadmaps");
1514
+ const filePath = path8.join(dir, `${slugifyProjectId(repoBasename)}.json`);
1515
+ const legacyPath = path8.join(args.repoRoot, ".roadmap", "roadmap.json");
1195
1516
  try {
1196
- const existing = (await readdir(dir)).sort();
1517
+ const existing = (await readdir2(dir)).sort();
1197
1518
  if (existing.length > 0) {
1198
- return { created: false, path: path7.join(dir, existing[0]) };
1519
+ return { created: false, path: path8.join(dir, existing[0]) };
1199
1520
  }
1200
1521
  } catch (err) {
1201
1522
  if (err == null || typeof err !== "object" || !("code" in err) || err.code !== "ENOENT") {
@@ -1218,28 +1539,28 @@ async function scaffoldRoadmap(args) {
1218
1539
  phases: []
1219
1540
  };
1220
1541
  await mkdir5(dir, { recursive: true });
1221
- await writeFile5(filePath, JSON.stringify(roadmap, null, 2) + "\n", "utf8");
1542
+ await writeFile6(filePath, JSON.stringify(roadmap, null, 2) + "\n", "utf8");
1222
1543
  return { created: true, path: filePath };
1223
1544
  }
1224
1545
 
1225
1546
  // src/git-merge-driver.ts
1226
1547
  import { execFile as execFile2 } from "child_process";
1227
- import { readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
1228
- import path8 from "path";
1548
+ import { readFile as readFile6, writeFile as writeFile7 } from "fs/promises";
1549
+ import path9 from "path";
1229
1550
  import { promisify } from "util";
1230
1551
  var ATTRIBUTE_LINE = ".nolto/roadmaps/*.json merge=nolto-roadmap";
1231
1552
  var DRIVER_COMMAND = "nolto merge-file %A %B --base %O";
1232
1553
  async function ensureGitAttributes(root) {
1233
- const filePath = path8.join(root, ".gitattributes");
1554
+ const filePath = path9.join(root, ".gitattributes");
1234
1555
  let content = "";
1235
1556
  try {
1236
- content = await readFile5(filePath, "utf8");
1557
+ content = await readFile6(filePath, "utf8");
1237
1558
  } catch (err) {
1238
1559
  if (err.code !== "ENOENT") throw err;
1239
1560
  }
1240
1561
  if (content.split(/\r?\n/).includes(ATTRIBUTE_LINE)) return "exists";
1241
1562
  const separator = content.length > 0 && !content.endsWith("\n") ? "\n" : "";
1242
- await writeFile6(filePath, content + separator + ATTRIBUTE_LINE + "\n", "utf8");
1563
+ await writeFile7(filePath, content + separator + ATTRIBUTE_LINE + "\n", "utf8");
1243
1564
  return "added";
1244
1565
  }
1245
1566
  async function configureMergeDriver(root, exec = async (file, args, options) => {
@@ -1264,13 +1585,13 @@ async function configureMergeDriver(root, exec = async (file, args, options) =>
1264
1585
  }
1265
1586
 
1266
1587
  // src/commands/init.ts
1267
- var __dirname2 = path9.dirname(fileURLToPath2(import.meta.url));
1588
+ var __dirname2 = path10.dirname(fileURLToPath2(import.meta.url));
1268
1589
  var _require = createRequire(import.meta.url);
1269
1590
  function getCliVersion() {
1270
1591
  const candidates = [
1271
- path9.resolve(__dirname2, "../package.json"),
1592
+ path10.resolve(__dirname2, "../package.json"),
1272
1593
  // bundled: dist/../package.json
1273
- path9.resolve(__dirname2, "../../package.json")
1594
+ path10.resolve(__dirname2, "../../package.json")
1274
1595
  // source: src/commands/../../package.json
1275
1596
  ];
1276
1597
  for (const pkgPath of candidates) {
@@ -1339,7 +1660,7 @@ async function selectRepoProject(rl, http, projects, defaultProjectId) {
1339
1660
  "Project number for this repository, 'c' to create new (or Enter to skip): "
1340
1661
  );
1341
1662
  }
1342
- function register2(program, deps) {
1663
+ function register3(program, deps) {
1343
1664
  program.command("init").description("Interactive setup: configure token, base URL, and default project.").option("--force", "Overwrite existing config without prompting").action(async (opts) => {
1344
1665
  const configPath = deps.configPath;
1345
1666
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
@@ -1431,7 +1752,7 @@ Saved ${configPath}
1431
1752
  }
1432
1753
  if (isHomeDirectory(root)) {
1433
1754
  process.stderr.write(
1434
- `Refusing to set up your home directory as a repository root (found ${path9.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
1755
+ `Refusing to set up your home directory as a repository root (found ${path10.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
1435
1756
  `
1436
1757
  );
1437
1758
  return;
@@ -1463,7 +1784,7 @@ Saved ${configPath}
1463
1784
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
1464
1785
  );
1465
1786
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
1466
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path9.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1787
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path10.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1467
1788
  } else {
1468
1789
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1469
1790
  }
@@ -1477,7 +1798,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1477
1798
  process.stdout.write("Skipped repo setup.\n");
1478
1799
  return;
1479
1800
  }
1480
- const bindingPath = deps.repoBinding?.path ?? path9.join(root, "nolto.json");
1801
+ const bindingPath = deps.repoBinding?.path ?? path10.join(root, "nolto.json");
1481
1802
  if (keepExistingBinding) {
1482
1803
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
1483
1804
  `);
@@ -1489,22 +1810,22 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1489
1810
  );
1490
1811
  }
1491
1812
  await writeRepoBinding(root, repoProject.id);
1492
- process.stdout.write(`binding: wrote ${path9.join(root, "nolto.json")}
1813
+ process.stdout.write(`binding: wrote ${path10.join(root, "nolto.json")}
1493
1814
  `);
1494
1815
  }
1495
1816
  const sourceDir = resolveSkillSourceDir();
1496
1817
  const version = getCliVersion();
1497
1818
  const claudeInstall = await installSkill({
1498
- skillsParentDir: path9.join(root, ".claude", "skills"),
1819
+ skillsParentDir: path10.join(root, ".claude", "skills"),
1499
1820
  sourceDir,
1500
1821
  version
1501
1822
  });
1502
1823
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
1503
1824
  `);
1504
- const usesAgentsTooling = fs.existsSync(path9.join(root, ".agents")) || fs.existsSync(path9.join(root, ".codex")) || fs.existsSync(path9.join(root, "AGENTS.md"));
1825
+ const usesAgentsTooling = fs.existsSync(path10.join(root, ".agents")) || fs.existsSync(path10.join(root, ".codex")) || fs.existsSync(path10.join(root, "AGENTS.md"));
1505
1826
  if (usesAgentsTooling) {
1506
1827
  const agentsInstall = await installSkill({
1507
- skillsParentDir: path9.join(root, ".agents", "skills"),
1828
+ skillsParentDir: path10.join(root, ".agents", "skills"),
1508
1829
  sourceDir,
1509
1830
  version
1510
1831
  });
@@ -1617,7 +1938,7 @@ function sleep(ms) {
1617
1938
  }
1618
1939
 
1619
1940
  // src/commands/login.ts
1620
- function register3(program, deps) {
1941
+ function register4(program, deps) {
1621
1942
  program.command("login").description("Authenticate via browser and save an API token to the config file.").option("--force", "Overwrite existing token without prompting").action(
1622
1943
  async (opts) => {
1623
1944
  const { configPath, settings, output } = deps;
@@ -1699,10 +2020,11 @@ function register3(program, deps) {
1699
2020
  }
1700
2021
 
1701
2022
  // src/commands/whoami.ts
1702
- function register4(program, deps) {
2023
+ function register5(program, deps) {
1703
2024
  program.command("whoami").description("Show the current authentication and configuration state.").action(async () => {
1704
2025
  const { settings, output, configPath } = deps;
1705
2026
  const mode2 = output.mode;
2027
+ let tokenInfo;
1706
2028
  let projectCount;
1707
2029
  if (settings.token != null) {
1708
2030
  try {
@@ -1716,6 +2038,13 @@ function register4(program, deps) {
1716
2038
  } catch {
1717
2039
  }
1718
2040
  }
2041
+ if (settings.token != null) {
2042
+ try {
2043
+ const result = await deps.http.get("/api/me/token");
2044
+ tokenInfo = result.token;
2045
+ } catch {
2046
+ }
2047
+ }
1719
2048
  const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
1720
2049
  if (mode2 === "json") {
1721
2050
  printResult(
@@ -1728,7 +2057,8 @@ function register4(program, deps) {
1728
2057
  defaultProject: settings.defaultProjectId ?? null,
1729
2058
  defaultProjectSource: settings.source.project,
1730
2059
  projectBindingPath: projectBindingPath ?? null,
1731
- projects: projectCount ?? null
2060
+ projects: projectCount ?? null,
2061
+ ...tokenInfo ? { tokenScopes: tokenInfo.scopes, tokenProject: tokenInfo.projectId } : {}
1732
2062
  },
1733
2063
  mode2
1734
2064
  );
@@ -1742,6 +2072,9 @@ function register4(program, deps) {
1742
2072
  ["defaultProject", bindingDisplay],
1743
2073
  ["projects", projectCount != null ? String(projectCount) : settings.token != null ? "(unavailable)" : "(no token)"]
1744
2074
  ];
2075
+ if (tokenInfo) {
2076
+ lines.push(["scopes", tokenInfo.scopes === null ? "full" : tokenInfo.scopes.join(", ")], ["project", tokenInfo.projectId ?? "all"]);
2077
+ }
1745
2078
  const maxKey = lines.reduce((m, [k]) => Math.max(m, k.length), 0);
1746
2079
  for (const [key, val] of lines) {
1747
2080
  process.stdout.write(`${key.padEnd(maxKey)}: ${val}
@@ -1752,15 +2085,64 @@ function register4(program, deps) {
1752
2085
  }
1753
2086
 
1754
2087
  // src/commands/sync.ts
1755
- import { copyFile, mkdir as mkdir6, readFile as readFile6, readdir as readdir2, realpath, rename as rename2, rmdir, unlink as unlink2 } from "fs/promises";
2088
+ import { execFile as execFile3 } from "child_process";
2089
+ import { promisify as promisify2 } from "util";
2090
+ import { copyFile, mkdir as mkdir6, readFile as readFile7, readdir as readdir3, realpath, rename as rename3, rmdir, unlink as unlink2 } from "fs/promises";
1756
2091
  import { existsSync as existsSync3 } from "fs";
1757
2092
 
2093
+ // src/git-links.ts
2094
+ function parseGitLog(raw) {
2095
+ return raw.split("\n").filter((line) => line.length > 0).map((line) => {
2096
+ const fields = line.replace(/\r$/, "").split("");
2097
+ const [ref, subject, author, committedAt] = fields;
2098
+ if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
2099
+ throw new Error("Malformed git log entry");
2100
+ }
2101
+ return { ref, subject, author, committedAt: new Date(committedAt).toISOString() };
2102
+ });
2103
+ }
2104
+ function extractIssueKeys(subject) {
2105
+ return [...new Set([...subject.matchAll(/\b([A-Z][A-Z0-9]{1,9})-([1-9][0-9]{0,8})\b/g)].map((match) => match[0]))];
2106
+ }
2107
+ function extractPrNumber(subject) {
2108
+ return /\(#([1-9][0-9]{0,8})\)$/.exec(subject)?.[1] ?? /^Merge pull request #([1-9][0-9]{0,8})\b/.exec(subject)?.[1] ?? null;
2109
+ }
2110
+ function buildGitLinksPayload(entries) {
2111
+ return { links: entries.flatMap((entry) => {
2112
+ const keys = extractIssueKeys(entry.subject);
2113
+ const pr = extractPrNumber(entry.subject);
2114
+ const refs = [{ kind: "commit", ref: entry.ref }, ...pr ? [{ kind: "pr", ref: pr }] : []];
2115
+ return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
2116
+ ...ref,
2117
+ title: entry.subject.slice(0, 500),
2118
+ author: entry.author.slice(0, 500),
2119
+ committedAt: entry.committedAt,
2120
+ issueKeys: keys.slice(index * 20, (index + 1) * 20)
2121
+ })));
2122
+ }) };
2123
+ }
2124
+ function stdout(result) {
2125
+ if (typeof result === "object" && result !== null && "stdout" in result && typeof result.stdout === "string") return result.stdout;
2126
+ throw new Error("Git command returned no text output");
2127
+ }
2128
+ async function collectGitLinks(root, exec) {
2129
+ let probe;
2130
+ try {
2131
+ probe = await exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root });
2132
+ } catch {
2133
+ return null;
2134
+ }
2135
+ if (stdout(probe).trim() !== "true") return null;
2136
+ const result = await exec("git", ["log", "--no-color", "--format=%H%x1f%s%x1f%an%x1f%cI", "-n", "300"], { cwd: root });
2137
+ return buildGitLinksPayload(parseGitLog(stdout(result)));
2138
+ }
2139
+
1758
2140
  // src/sync-repo.ts
1759
- import path11 from "path";
2141
+ import path12 from "path";
1760
2142
 
1761
2143
  // src/sync-core.ts
1762
2144
  import { createHash } from "crypto";
1763
- import path10 from "path";
2145
+ import path11 from "path";
1764
2146
  function sha256Hex(content) {
1765
2147
  return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1766
2148
  }
@@ -1781,10 +2163,10 @@ function collectPlanRefs(roadmap) {
1781
2163
  }
1782
2164
  return refs;
1783
2165
  }
1784
- async function loadValidRoadmap(filePath, readFile12) {
2166
+ async function loadValidRoadmap(filePath, readFile13) {
1785
2167
  let raw;
1786
2168
  try {
1787
- raw = await readFile12(filePath);
2169
+ raw = await readFile13(filePath);
1788
2170
  } catch {
1789
2171
  throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1790
2172
  }
@@ -1807,9 +2189,9 @@ async function loadValidRoadmap(filePath, readFile12) {
1807
2189
  async function buildSyncBody(args) {
1808
2190
  const planDocuments = [];
1809
2191
  for (const ref of collectPlanRefs(args.roadmap)) {
1810
- const root = path10.resolve(args.repoRoot);
1811
- const absolute = path10.resolve(root, ref.path);
1812
- if (absolute !== root && !absolute.startsWith(root + path10.sep)) {
2192
+ const root = path11.resolve(args.repoRoot);
2193
+ const absolute = path11.resolve(root, ref.path);
2194
+ if (absolute !== root && !absolute.startsWith(root + path11.sep)) {
1813
2195
  args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1814
2196
  continue;
1815
2197
  }
@@ -1827,7 +2209,7 @@ async function buildSyncBody(args) {
1827
2209
  args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1828
2210
  continue;
1829
2211
  }
1830
- if (real !== realRoot && !real.startsWith(realRoot + path10.sep)) {
2212
+ if (real !== realRoot && !real.startsWith(realRoot + path11.sep)) {
1831
2213
  args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1832
2214
  continue;
1833
2215
  }
@@ -1853,9 +2235,10 @@ async function runSync(args, deps) {
1853
2235
  `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1854
2236
  body
1855
2237
  );
2238
+ for (const warning of response.warnings ?? []) deps.warn(warning);
1856
2239
  const stats = deriveTaskStats(args.roadmap);
1857
2240
  deps.log(
1858
- `Synced ${args.slug}: ${stats.done}/${stats.total} done \u2014 docs upserted ${response.documents.upserted}, unchanged ${response.documents.unchanged}, deleted ${response.documents.deleted}`
2241
+ `Synced ${args.slug}: ${stats.done}/${stats.total} done \u2014 docs upserted ${response.documents.upserted}, unchanged ${response.documents.unchanged}, deleted ${response.documents.deleted}${response.issues ? `, issues linked ${response.issues.linked} (skipped ${response.issues.skipped})` : ""}`
1859
2242
  );
1860
2243
  return response;
1861
2244
  }
@@ -1864,11 +2247,11 @@ async function runSync(args, deps) {
1864
2247
  var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1865
2248
  function collectContainedPlanAbsPaths(roadmaps, root, warn) {
1866
2249
  const planAbsPaths = /* @__PURE__ */ new Set();
1867
- const resolvedRoot = path11.resolve(root);
2250
+ const resolvedRoot = path12.resolve(root);
1868
2251
  for (const roadmap of roadmaps) {
1869
2252
  for (const ref of collectPlanRefs(roadmap)) {
1870
- const absolute = path11.resolve(resolvedRoot, ref.path);
1871
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path11.sep)) {
2253
+ const absolute = path12.resolve(resolvedRoot, ref.path);
2254
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path12.sep)) {
1872
2255
  warn(`chokidar target outside repo, skipping: ${ref.path}`);
1873
2256
  continue;
1874
2257
  }
@@ -1889,7 +2272,7 @@ async function listRoadmapFiles(roadmapsDir, io) {
1889
2272
  }
1890
2273
  }
1891
2274
  async function migrateLegacyRoadmap(args) {
1892
- const targetPath = path11.join(args.roadmapsDir, `${args.slug}.json`);
2275
+ const targetPath = path12.join(args.roadmapsDir, `${args.slug}.json`);
1893
2276
  await args.io.mkdir(args.roadmapsDir);
1894
2277
  try {
1895
2278
  await args.io.rename(args.legacyPath, targetPath);
@@ -1898,7 +2281,7 @@ async function migrateLegacyRoadmap(args) {
1898
2281
  await args.io.unlink(args.legacyPath);
1899
2282
  }
1900
2283
  try {
1901
- await args.io.rmdir(path11.dirname(args.legacyPath));
2284
+ await args.io.rmdir(path12.dirname(args.legacyPath));
1902
2285
  } catch {
1903
2286
  }
1904
2287
  args.io.log(
@@ -1907,14 +2290,14 @@ async function migrateLegacyRoadmap(args) {
1907
2290
  return `${args.slug}.json`;
1908
2291
  }
1909
2292
  async function syncRepo(args, io) {
1910
- const bindingPath = path11.join(args.root, "nolto.json");
2293
+ const bindingPath = path12.join(args.root, "nolto.json");
1911
2294
  const binding = await loadRepoBinding(bindingPath);
1912
2295
  const projectId = binding?.projectId ?? args.defaultProjectId;
1913
2296
  if (projectId == null) {
1914
2297
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
1915
2298
  }
1916
- const roadmapsDir = path11.join(args.root, ".nolto", "roadmaps");
1917
- const legacyPath = path11.join(args.root, ".roadmap", "roadmap.json");
2299
+ const roadmapsDir = path12.join(args.root, ".nolto", "roadmaps");
2300
+ const legacyPath = path12.join(args.root, ".roadmap", "roadmap.json");
1918
2301
  let roadmapFiles = await listRoadmapFiles(roadmapsDir, io);
1919
2302
  if (roadmapFiles.length > 0) {
1920
2303
  if (io.fileExists(legacyPath)) {
@@ -1929,7 +2312,7 @@ async function syncRepo(args, io) {
1929
2312
  );
1930
2313
  return { results: [], planAbsPaths: [] };
1931
2314
  }
1932
- const migrationSlug = binding?.roadmapSlug ?? slugifyProjectId(path11.basename(args.root));
2315
+ const migrationSlug = binding?.roadmapSlug ?? slugifyProjectId(path12.basename(args.root));
1933
2316
  roadmapFiles = [
1934
2317
  await migrateLegacyRoadmap({
1935
2318
  slug: migrationSlug,
@@ -1953,7 +2336,7 @@ async function syncRepo(args, io) {
1953
2336
  2
1954
2337
  );
1955
2338
  }
1956
- const filePath = path11.join(roadmapsDir, fileName);
2339
+ const filePath = path12.join(roadmapsDir, fileName);
1957
2340
  return { slug, roadmap: await loadValidRoadmap(filePath, io.readFile) };
1958
2341
  })
1959
2342
  );
@@ -1979,12 +2362,34 @@ async function syncRepo(args, io) {
1979
2362
  )
1980
2363
  );
1981
2364
  }
1982
- return { results, planAbsPaths };
2365
+ let gitLinks = null;
2366
+ if (io.exec && io.gitLinks !== false) {
2367
+ try {
2368
+ const body = await collectGitLinks(args.root, io.exec);
2369
+ if (body && body.links.length > 0) {
2370
+ gitLinks = { linked: 0, existing: 0, skipped: 0 };
2371
+ for (let offset = 0; offset < body.links.length; offset += 500) {
2372
+ const response = await io.http.post(
2373
+ `/api/projects/${projectId}/git-links`,
2374
+ { links: body.links.slice(offset, offset + 500) }
2375
+ );
2376
+ if (!Number.isSafeInteger(response.linked) || response.linked < 0 || !Number.isSafeInteger(response.existing) || response.existing < 0 || !Number.isSafeInteger(response.skipped) || response.skipped < 0 || !Array.isArray(response.warnings) || response.warnings.some((warning) => typeof warning !== "string")) throw new Error("Invalid git links response");
2377
+ gitLinks = { linked: gitLinks.linked + response.linked, existing: gitLinks.existing + response.existing, skipped: gitLinks.skipped + response.skipped };
2378
+ for (const warning of response.warnings) io.warn(`git links: ${warning}`);
2379
+ }
2380
+ io.log(`git links: linked ${gitLinks.linked} (existing ${gitLinks.existing}, skipped ${gitLinks.skipped})`);
2381
+ }
2382
+ } catch (error) {
2383
+ gitLinks = null;
2384
+ io.warn(`git links: skipped \u2014 ${error instanceof Error ? error.message : String(error)}`);
2385
+ }
2386
+ }
2387
+ return { results, planAbsPaths, gitLinks };
1983
2388
  }
1984
2389
 
1985
2390
  // src/commands/sync.ts
1986
- function register5(program, deps) {
1987
- program.command("sync").description("Push .nolto/roadmaps/*.json and linked plan documents to Nolto (idempotent full upsert).").action(async () => {
2391
+ function register6(program, deps) {
2392
+ program.command("sync").description("Push .nolto/roadmaps/*.json and linked plan documents to Nolto (idempotent full upsert).").option("--no-git-links", "Skip commit / PR issue links").action(async (opts) => {
1988
2393
  if (deps.settings.token == null) {
1989
2394
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
1990
2395
  }
@@ -2000,18 +2405,22 @@ function register5(program, deps) {
2000
2405
  const response = await syncRepo(
2001
2406
  { root, defaultProjectId: deps.settings.defaultProjectId, migrateLegacy: true },
2002
2407
  {
2003
- readFile: (p) => readFile6(p, "utf8"),
2408
+ readFile: (p) => readFile7(p, "utf8"),
2004
2409
  realpath: (p) => realpath(p),
2005
2410
  fileExists: (p) => existsSync3(p),
2006
- listDir: (p) => readdir2(p),
2007
- rename: rename2,
2411
+ listDir: (p) => readdir3(p),
2412
+ rename: rename3,
2008
2413
  copyFile,
2009
2414
  mkdir: (p) => mkdir6(p, { recursive: true }).then(() => void 0),
2010
2415
  unlink: unlink2,
2011
2416
  rmdir,
2012
2417
  repoIdentity: makeRepoIdentityResolver(deps),
2418
+ exec: promisify2(execFile3),
2419
+ gitLinks: opts.gitLinks && process.env.NOLTO_GIT_LINKS !== "0",
2013
2420
  http,
2014
- log: (line) => process.stdout.write(line + "\n"),
2421
+ log: (line) => {
2422
+ if (deps.output.mode !== "json") process.stdout.write(line + "\n");
2423
+ },
2015
2424
  warn
2016
2425
  }
2017
2426
  );
@@ -2046,8 +2455,8 @@ function register5(program, deps) {
2046
2455
  }
2047
2456
 
2048
2457
  // src/commands/diff.ts
2049
- import { readFile as readFile7 } from "fs/promises";
2050
- import path13 from "path";
2458
+ import { readFile as readFile8 } from "fs/promises";
2459
+ import path14 from "path";
2051
2460
 
2052
2461
  // src/roadmap-diff.ts
2053
2462
  function diffRoadmaps(local, server) {
@@ -2126,8 +2535,8 @@ function diffRoadmaps(local, server) {
2126
2535
  }
2127
2536
  function truncate(value) {
2128
2537
  if (value == null) return "none";
2129
- const singleLine = value.replace(/\s+/g, " ");
2130
- return singleLine.length <= 60 ? singleLine : singleLine.slice(0, 57) + "...";
2538
+ const singleLine2 = value.replace(/\s+/g, " ");
2539
+ return singleLine2.length <= 60 ? singleLine2 : singleLine2.slice(0, 57) + "...";
2131
2540
  }
2132
2541
  function formatRoadmapDiff(slug, entries) {
2133
2542
  if (entries.length === 0) return [];
@@ -2151,8 +2560,8 @@ function formatRoadmapDiff(slug, entries) {
2151
2560
  }
2152
2561
 
2153
2562
  // src/roadmap-read.ts
2154
- import { readdir as readdir3 } from "fs/promises";
2155
- import path12 from "path";
2563
+ import { readdir as readdir4 } from "fs/promises";
2564
+ import path13 from "path";
2156
2565
  async function resolveRoadmapReadContext(deps) {
2157
2566
  if (deps.settings.token == null) {
2158
2567
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
@@ -2162,7 +2571,7 @@ async function resolveRoadmapReadContext(deps) {
2162
2571
  if (!foundGit) {
2163
2572
  throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2164
2573
  }
2165
- const binding = await loadRepoBinding(path12.join(root, "nolto.json"));
2574
+ const binding = await loadRepoBinding(path13.join(root, "nolto.json"));
2166
2575
  const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2167
2576
  if (projectId == null) {
2168
2577
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
@@ -2171,7 +2580,7 @@ async function resolveRoadmapReadContext(deps) {
2171
2580
  }
2172
2581
  async function listLocalRoadmapSlugs(root) {
2173
2582
  try {
2174
- const entries = await readdir3(path12.join(root, ".nolto", "roadmaps"));
2583
+ const entries = await readdir4(path13.join(root, ".nolto", "roadmaps"));
2175
2584
  return entries.filter((entry) => entry.endsWith(".json")).map((entry) => entry.slice(0, -".json".length)).sort();
2176
2585
  } catch (err) {
2177
2586
  if (err != null && typeof err === "object" && "code" in err && err.code === "ENOENT") {
@@ -2182,7 +2591,7 @@ async function listLocalRoadmapSlugs(root) {
2182
2591
  }
2183
2592
 
2184
2593
  // src/commands/diff.ts
2185
- function register6(program, deps) {
2594
+ function register7(program, deps) {
2186
2595
  program.command("diff [slug]").description("Compare local roadmaps with the server without changing either side.").action(async (requestedSlug) => {
2187
2596
  const { root, projectId } = await resolveRoadmapReadContext(deps);
2188
2597
  const list = await deps.http.get(
@@ -2203,9 +2612,9 @@ function register6(program, deps) {
2203
2612
  for (const slug of targetSlugs) {
2204
2613
  let local = null;
2205
2614
  if (localSlugSet.has(slug)) {
2206
- const localPath = path13.join(root, ".nolto", "roadmaps", `${slug}.json`);
2615
+ const localPath = path14.join(root, ".nolto", "roadmaps", `${slug}.json`);
2207
2616
  try {
2208
- local = await loadValidRoadmap(localPath, (filePath) => readFile7(filePath, "utf8"));
2617
+ local = await loadValidRoadmap(localPath, (filePath) => readFile8(filePath, "utf8"));
2209
2618
  } catch (err) {
2210
2619
  const message = err instanceof Error ? err.message : String(err);
2211
2620
  process.stderr.write(`Warning: could not diff ${slug}.json: ${message}
@@ -2248,8 +2657,8 @@ function register6(program, deps) {
2248
2657
  }
2249
2658
 
2250
2659
  // src/commands/pull.ts
2251
- import { mkdir as mkdir7, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
2252
- import path14 from "path";
2660
+ import { mkdir as mkdir7, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
2661
+ import path15 from "path";
2253
2662
 
2254
2663
  // src/roadmap-merge.ts
2255
2664
  import { isDeepStrictEqual } from "util";
@@ -2294,6 +2703,7 @@ function assignOptional(target, key, value) {
2294
2703
  function cloneSingleTask(task) {
2295
2704
  const cloned = { ...task };
2296
2705
  if (task.dependsOn !== void 0) cloned.dependsOn = [...task.dependsOn];
2706
+ if (task.issues !== void 0) cloned.issues = [...task.issues];
2297
2707
  if (cloned.status !== "done") delete cloned.completedAt;
2298
2708
  return cloned;
2299
2709
  }
@@ -2342,6 +2752,8 @@ function mergeTask(args) {
2342
2752
  ...args.theirs.dependsOn ?? []
2343
2753
  ].filter((id, index, values) => values.indexOf(id) === index);
2344
2754
  if (dependsOn.length > 0) merged.dependsOn = dependsOn;
2755
+ const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
2756
+ if (issues.length > 0) merged.issues = issues;
2345
2757
  return merged;
2346
2758
  }
2347
2759
  function shouldKeep(base, ours, theirs) {
@@ -2485,7 +2897,7 @@ function mergeRoadmaps(args) {
2485
2897
  // src/commands/pull.ts
2486
2898
  async function readExisting(filePath) {
2487
2899
  try {
2488
- return await readFile8(filePath, "utf8");
2900
+ return await readFile9(filePath, "utf8");
2489
2901
  } catch (err) {
2490
2902
  if (err != null && typeof err === "object" && "code" in err && err.code === "ENOENT") {
2491
2903
  return null;
@@ -2493,7 +2905,7 @@ async function readExisting(filePath) {
2493
2905
  throw err;
2494
2906
  }
2495
2907
  }
2496
- function register7(program, deps) {
2908
+ function register8(program, deps) {
2497
2909
  program.command("pull [slug]").description(
2498
2910
  "Pull server roadmaps, optionally merging them with valid local copies."
2499
2911
  ).option("--merge", "Structurally merge server and local roadmap changes").action(async (requestedSlug, opts) => {
@@ -2506,7 +2918,7 @@ function register7(program, deps) {
2506
2918
  throw new CliError(`Roadmap "${requestedSlug}" was not found on the server.`, 2);
2507
2919
  }
2508
2920
  const targets = requestedSlug == null ? [...serverBySlug.values()] : [serverBySlug.get(requestedSlug)];
2509
- const roadmapsDir = path14.join(root, ".nolto", "roadmaps");
2921
+ const roadmapsDir = path15.join(root, ".nolto", "roadmaps");
2510
2922
  for (const summary of targets) {
2511
2923
  const response = await deps.http.get(
2512
2924
  `/api/projects/${projectId}/roadmaps/${encodeURIComponent(summary.slug)}`
@@ -2518,7 +2930,7 @@ function register7(program, deps) {
2518
2930
  5
2519
2931
  );
2520
2932
  }
2521
- const filePath = path14.join(roadmapsDir, `${summary.slug}.json`);
2933
+ const filePath = path15.join(roadmapsDir, `${summary.slug}.json`);
2522
2934
  const existing = await readExisting(filePath);
2523
2935
  let roadmap = response.roadmap;
2524
2936
  let outputVerb = "pulled";
@@ -2555,7 +2967,7 @@ function register7(program, deps) {
2555
2967
  continue;
2556
2968
  }
2557
2969
  await mkdir7(roadmapsDir, { recursive: true });
2558
- await writeFile7(filePath, serialized, "utf8");
2970
+ await writeFile8(filePath, serialized, "utf8");
2559
2971
  process.stdout.write(
2560
2972
  outputVerb === "merged" ? `merged ${summary.slug}.json
2561
2973
  ` : `pulled ${summary.slug}.json (${summary.taskDone}/${summary.taskTotal} done)
@@ -2567,9 +2979,11 @@ function register7(program, deps) {
2567
2979
  }
2568
2980
 
2569
2981
  // src/commands/watch.ts
2570
- import { copyFile as copyFile2, mkdir as mkdir8, readFile as readFile9, readdir as readdir4, realpath as realpath2, rename as rename3, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
2982
+ import { execFile as execFile4 } from "child_process";
2983
+ import { promisify as promisify3 } from "util";
2984
+ import { copyFile as copyFile2, mkdir as mkdir8, readFile as readFile10, readdir as readdir5, realpath as realpath2, rename as rename4, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
2571
2985
  import { existsSync as existsSync4 } from "fs";
2572
- import path16 from "path";
2986
+ import path17 from "path";
2573
2987
  import chokidar from "chokidar";
2574
2988
 
2575
2989
  // src/watch-core.ts
@@ -2675,7 +3089,7 @@ var RepoWatch = class {
2675
3089
  };
2676
3090
 
2677
3091
  // src/service-install.ts
2678
- import path15 from "path";
3092
+ import path16 from "path";
2679
3093
  import os4 from "os";
2680
3094
  function buildUnitFile(args) {
2681
3095
  return [
@@ -2695,8 +3109,8 @@ function buildUnitFile(args) {
2695
3109
  }
2696
3110
  function getUnitPath(env) {
2697
3111
  const xdg = env["XDG_CONFIG_HOME"];
2698
- const base = xdg != null && xdg.length > 0 ? xdg : path15.join(os4.homedir(), ".config");
2699
- return path15.join(base, "systemd", "user", "nolto-watch.service");
3112
+ const base = xdg != null && xdg.length > 0 ? xdg : path16.join(os4.homedir(), ".config");
3113
+ return path16.join(base, "systemd", "user", "nolto-watch.service");
2700
3114
  }
2701
3115
  async function installServiceWith(deps) {
2702
3116
  if (deps.platform !== "linux") {
@@ -2707,7 +3121,7 @@ async function installServiceWith(deps) {
2707
3121
  );
2708
3122
  }
2709
3123
  const unitPath = getUnitPath(deps.env);
2710
- await deps.mkdir(path15.dirname(unitPath));
3124
+ await deps.mkdir(path16.dirname(unitPath));
2711
3125
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
2712
3126
  deps.log(`Wrote ${unitPath}`);
2713
3127
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -2721,16 +3135,16 @@ async function installServiceWith(deps) {
2721
3135
  deps.log("Service nolto-watch enabled and started. Logs: journalctl --user -u nolto-watch -f");
2722
3136
  }
2723
3137
  async function installService() {
2724
- const { writeFile: writeFile10, mkdir: mkdir10 } = await import("fs/promises");
2725
- const { execFile: execFile4 } = await import("child_process");
2726
- const { promisify: promisify3 } = await import("util");
2727
- const execFileAsync = promisify3(execFile4);
3138
+ const { writeFile: writeFile11, mkdir: mkdir10 } = await import("fs/promises");
3139
+ const { execFile: execFile6 } = await import("child_process");
3140
+ const { promisify: promisify5 } = await import("util");
3141
+ const execFileAsync = promisify5(execFile6);
2728
3142
  await installServiceWith({
2729
3143
  platform: process.platform,
2730
3144
  env: process.env,
2731
3145
  nodePath: process.execPath,
2732
- scriptPath: path15.resolve(process.argv[1] ?? ""),
2733
- writeFile: (p, content) => writeFile10(p, content, "utf8"),
3146
+ scriptPath: path16.resolve(process.argv[1] ?? ""),
3147
+ writeFile: (p, content) => writeFile11(p, content, "utf8"),
2734
3148
  mkdir: async (p) => {
2735
3149
  await mkdir10(p, { recursive: true });
2736
3150
  },
@@ -2787,9 +3201,9 @@ async function uninstallServiceWith(deps) {
2787
3201
  }
2788
3202
  async function uninstallService() {
2789
3203
  const { unlink: unlink4 } = await import("fs/promises");
2790
- const { execFile: execFile4 } = await import("child_process");
2791
- const { promisify: promisify3 } = await import("util");
2792
- const execFileAsync = promisify3(execFile4);
3204
+ const { execFile: execFile6 } = await import("child_process");
3205
+ const { promisify: promisify5 } = await import("util");
3206
+ const execFileAsync = promisify5(execFile6);
2793
3207
  await uninstallServiceWith({
2794
3208
  platform: process.platform,
2795
3209
  env: process.env,
@@ -2809,7 +3223,7 @@ async function uninstallService() {
2809
3223
  }
2810
3224
 
2811
3225
  // src/commands/watch.ts
2812
- function register8(program, deps) {
3226
+ function register9(program, deps) {
2813
3227
  program.command("watch").description("Watch every registered repository's roadmap + plan files and sync on change.").option("--debounce <ms>", "Debounce window in milliseconds", "2000").option("--install-service", "Install and enable a systemd user unit (nolto-watch) instead of watching").option("--uninstall-service", "Stop and remove the systemd user unit (nolto-watch) instead of watching").action(async (opts) => {
2814
3228
  if (opts.installService && opts.uninstallService) {
2815
3229
  throw new CliError("--install-service and --uninstall-service cannot be used together.", 2);
@@ -2846,10 +3260,10 @@ function register8(program, deps) {
2846
3260
  token: deps.settings.token
2847
3261
  });
2848
3262
  const startRepo = (root) => {
2849
- const roadmapsPath = path16.join(root, ".nolto", "roadmaps");
2850
- const legacyRoadmapPath = path16.join(root, ".roadmap", "roadmap.json");
3263
+ const roadmapsPath = path17.join(root, ".nolto", "roadmaps");
3264
+ const legacyRoadmapPath = path17.join(root, ".roadmap", "roadmap.json");
2851
3265
  const warn = (line) => {
2852
- process.stderr.write(`Warning: [${path16.basename(root)}] ${line}
3266
+ process.stderr.write(`Warning: [${path17.basename(root)}] ${line}
2853
3267
  `);
2854
3268
  };
2855
3269
  const watcher = chokidar.watch([roadmapsPath, legacyRoadmapPath], { ignoreInitial: true });
@@ -2858,18 +3272,20 @@ function register8(program, deps) {
2858
3272
  // #316: watch must warn about legacy roadmaps without migrating them.
2859
3273
  { root, defaultProjectId: deps.settings.defaultProjectId, migrateLegacy: false },
2860
3274
  {
2861
- readFile: (p) => readFile9(p, "utf8"),
3275
+ readFile: (p) => readFile10(p, "utf8"),
2862
3276
  realpath: (p) => realpath2(p),
2863
3277
  fileExists: (p) => existsSync4(p),
2864
- listDir: (p) => readdir4(p),
2865
- rename: rename3,
3278
+ listDir: (p) => readdir5(p),
3279
+ rename: rename4,
2866
3280
  copyFile: copyFile2,
2867
3281
  mkdir: (p) => mkdir8(p, { recursive: true }).then(() => void 0),
2868
3282
  unlink: unlink3,
2869
3283
  rmdir: rmdir2,
2870
3284
  repoIdentity: makeRepoIdentityResolver(deps),
3285
+ exec: promisify3(execFile4),
3286
+ gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
2871
3287
  http,
2872
- log: (line) => process.stdout.write(`[${path16.basename(root)}] ${line}
3288
+ log: (line) => process.stdout.write(`[${path17.basename(root)}] ${line}
2873
3289
  `),
2874
3290
  warn
2875
3291
  }
@@ -2932,18 +3348,18 @@ function register8(program, deps) {
2932
3348
  }
2933
3349
 
2934
3350
  // src/update-cli.ts
2935
- import { execFile as execFile3 } from "child_process";
3351
+ import { execFile as execFile5 } from "child_process";
2936
3352
  import { existsSync as existsSync5 } from "fs";
2937
3353
  import { realpath as realpath3 } from "fs/promises";
2938
3354
  import { createRequire as createRequire2 } from "module";
2939
- import path18 from "path";
3355
+ import path19 from "path";
2940
3356
  import { fileURLToPath as fileURLToPath3 } from "url";
2941
- import { promisify as promisify2 } from "util";
3357
+ import { promisify as promisify4 } from "util";
2942
3358
 
2943
3359
  // src/update-notifier.ts
2944
- import { readFile as readFile10, writeFile as writeFile8, mkdir as mkdir9 } from "fs/promises";
3360
+ import { readFile as readFile11, writeFile as writeFile9, mkdir as mkdir9 } from "fs/promises";
2945
3361
  import https from "https";
2946
- import path17 from "path";
3362
+ import path18 from "path";
2947
3363
  var PACKAGE = "@nolto/cli";
2948
3364
  var CACHE_FILE = "update-check.json";
2949
3365
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -3001,9 +3417,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3001
3417
  });
3002
3418
  }
3003
3419
  async function writeUpdateCache(cachePath, now, latest2) {
3004
- await mkdir9(path17.dirname(cachePath), { recursive: true });
3420
+ await mkdir9(path18.dirname(cachePath), { recursive: true });
3005
3421
  const payload = { checkedAt: now, latest: latest2 };
3006
- await writeFile8(cachePath, JSON.stringify(payload), { mode: 384 });
3422
+ await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
3007
3423
  }
3008
3424
  async function refreshCache(cachePath, now, fetchLatest) {
3009
3425
  const latest2 = await fetchLatest();
@@ -3012,10 +3428,10 @@ async function refreshCache(cachePath, now, fetchLatest) {
3012
3428
  }
3013
3429
  async function checkForUpdate(opts) {
3014
3430
  if (isDisabled(opts.env)) return null;
3015
- const cachePath = path17.join(opts.configDir, CACHE_FILE);
3431
+ const cachePath = path18.join(opts.configDir, CACHE_FILE);
3016
3432
  let cache = {};
3017
3433
  try {
3018
- cache = JSON.parse(await readFile10(cachePath, "utf8"));
3434
+ cache = JSON.parse(await readFile11(cachePath, "utf8"));
3019
3435
  } catch {
3020
3436
  }
3021
3437
  if (typeof cache.checkedAt !== "number" || opts.now - cache.checkedAt > CACHE_TTL_MS) {
@@ -3120,7 +3536,7 @@ async function updateCliWith(deps) {
3120
3536
  }
3121
3537
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
3122
3538
  await deps.writeCache(
3123
- path18.join(deps.configDir, UPDATE_CACHE_FILE),
3539
+ path19.join(deps.configDir, UPDATE_CACHE_FILE),
3124
3540
  deps.now,
3125
3541
  latest2
3126
3542
  ).catch(() => void 0);
@@ -3151,17 +3567,17 @@ async function updateCliWith(deps) {
3151
3567
  };
3152
3568
  }
3153
3569
  function getCurrentVersion() {
3154
- const dirname = path18.dirname(fileURLToPath3(import.meta.url));
3570
+ const dirname = path19.dirname(fileURLToPath3(import.meta.url));
3155
3571
  const require3 = createRequire2(import.meta.url);
3156
3572
  try {
3157
- const pkg = require3(path18.resolve(dirname, "../package.json"));
3573
+ const pkg = require3(path19.resolve(dirname, "../package.json"));
3158
3574
  return pkg.version ?? "0.0.0";
3159
3575
  } catch {
3160
3576
  return "0.0.0";
3161
3577
  }
3162
3578
  }
3163
3579
  async function updateCli(opts = {}) {
3164
- const execFileAsync = promisify2(execFile3);
3580
+ const execFileAsync = promisify4(execFile5);
3165
3581
  const scriptPath = await realpath3(process.argv[1] ?? "");
3166
3582
  return updateCliWith({
3167
3583
  currentVersion: getCurrentVersion(),
@@ -3193,7 +3609,7 @@ async function updateCli(opts = {}) {
3193
3609
  }
3194
3610
 
3195
3611
  // src/commands/update.ts
3196
- function register9(program, deps) {
3612
+ function register10(program, deps) {
3197
3613
  program.command("update").description("Update @nolto/cli to the latest version and restart the watch service if installed").action(async () => {
3198
3614
  const mode2 = deps.output.mode;
3199
3615
  const result = await updateCli({ quiet: mode2 === "json" });
@@ -3204,11 +3620,11 @@ function register9(program, deps) {
3204
3620
  }
3205
3621
 
3206
3622
  // src/commands/merge-file.ts
3207
- import { readFile as readFile11, writeFile as writeFile9 } from "fs/promises";
3623
+ import { readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
3208
3624
  async function readRoadmap(filePath) {
3209
3625
  let parsed;
3210
3626
  try {
3211
- parsed = JSON.parse(await readFile11(filePath, "utf8"));
3627
+ parsed = JSON.parse(await readFile12(filePath, "utf8"));
3212
3628
  } catch (err) {
3213
3629
  const message = err instanceof SyntaxError ? "malformed JSON" : String(err);
3214
3630
  throw new CliError(`${filePath}: ${message}`, 1);
@@ -3223,7 +3639,7 @@ async function readRoadmap(filePath) {
3223
3639
  }
3224
3640
  return parsed;
3225
3641
  }
3226
- function register10(program) {
3642
+ function register11(program) {
3227
3643
  program.command("merge-file <ours> <theirs>").description(
3228
3644
  'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
3229
3645
  ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
@@ -3231,7 +3647,7 @@ function register10(program) {
3231
3647
  const theirs = await readRoadmap(theirsPath);
3232
3648
  const base = opts.base == null ? null : await readRoadmap(opts.base);
3233
3649
  const merged = mergeRoadmaps({ base, ours, theirs });
3234
- await writeFile9(
3650
+ await writeFile10(
3235
3651
  opts.output ?? oursPath,
3236
3652
  JSON.stringify(merged, null, 2) + "\n",
3237
3653
  "utf8"
@@ -3251,20 +3667,21 @@ function buildProgram(deps) {
3251
3667
  const writeErr = (_msg) => {
3252
3668
  };
3253
3669
  const program = new Command("nolto").version(deps.version, "-V, --version", "Print version number").exitOverride().configureOutput({ writeErr }).description("Nolto CLI \u2014 sync repository roadmaps with Nolto.").option("--token <value>", "API token (overrides env/file)").option("--base-url <url>", "Nolto base URL (default: https://nolto.app)").option("--project <projectId>", "Default project ID").option("--json", "Output as JSON");
3254
- register2(program, deps);
3670
+ register(program, deps);
3255
3671
  register3(program, deps);
3256
3672
  register4(program, deps);
3257
- register(program, deps);
3258
3673
  register5(program, deps);
3674
+ register2(program, deps);
3259
3675
  register6(program, deps);
3260
3676
  register7(program, deps);
3261
3677
  register8(program, deps);
3262
3678
  register9(program, deps);
3263
- register10(program);
3679
+ register10(program, deps);
3680
+ register11(program);
3264
3681
  program.hook("preAction", (_thisCommand, actionCommand) => {
3265
3682
  const bindingError = deps.repoBinding?.error;
3266
3683
  const bindingExemptCommands = ["init", "link", "update", "merge-file"];
3267
- if (bindingError != null && !bindingExemptCommands.includes(actionCommand.name())) {
3684
+ if (bindingError != null && !(actionCommand.parent === program && bindingExemptCommands.includes(actionCommand.name()))) {
3268
3685
  throw bindingError;
3269
3686
  }
3270
3687
  });
@@ -3272,11 +3689,11 @@ function buildProgram(deps) {
3272
3689
  }
3273
3690
 
3274
3691
  // src/index.ts
3275
- var __dirname3 = path19.dirname(fileURLToPath4(import.meta.url));
3692
+ var __dirname3 = path20.dirname(fileURLToPath4(import.meta.url));
3276
3693
  var require2 = createRequire3(import.meta.url);
3277
3694
  function getVersion() {
3278
3695
  try {
3279
- const pkgPath = path19.resolve(__dirname3, "../package.json");
3696
+ const pkgPath = path20.resolve(__dirname3, "../package.json");
3280
3697
  const pkg = require2(pkgPath);
3281
3698
  return pkg.version ?? "0.0.0";
3282
3699
  } catch {