@nolto/cli 0.15.1 → 0.16.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.
Files changed (3) hide show
  1. package/README.md +25 -0
  2. package/dist/index.js +373 -116
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -43,6 +43,16 @@ nolto whoami # Show resolved auth/config state and project count
43
43
 
44
44
  ### Repository Binding
45
45
 
46
+ To add a second repository to an existing project, run `nolto init` or
47
+ `nolto link <projectId>`. The CLI asks before adding an unrecognized repository;
48
+ press Enter to accept, or use `link --yes` to skip the prompt. JSON mode requires
49
+ `--yes` when addition is needed. Only the project owner can add repositories.
50
+ Declining keeps the local binding (and init's skill), but skips roadmap cache
51
+ initialization and watch registration. Run `nolto link --add` later before syncing.
52
+ If addition hits a plan limit (HTTP 402), the CLI exits with code 4 and an upgrade
53
+ URL. The binding and skill remain; upgrade and retry. `link --json` includes
54
+ `repoAdded` to indicate whether this command added the repository.
55
+
46
56
  ```bash
47
57
  nolto link <projectId> # Write or update nolto.json at the repository root
48
58
  nolto link --show # Show the current binding, source, and repository identity
@@ -71,6 +81,10 @@ nolto diff [slug] # Compare local and server roadmaps without c
71
81
  nolto pull [slug] [--all] # Pull server roadmaps into the cache
72
82
  nolto pull [slug] --force # Overwrite unsynced local changes
73
83
  nolto watch [--debounce <ms>] # Watch registered repositories and auto-sync
84
+ nolto watch status # Show pid, version, start time, and service status
85
+ nolto watch stop # Stop watch (leaves the service installed)
86
+ nolto watch list # List registered repositories, including missing roots
87
+ nolto watch remove [root] # Unregister a repository (defaults to the current repo)
74
88
  nolto watch --install-service # Install the Linux systemd user service
75
89
  ```
76
90
 
@@ -97,6 +111,17 @@ Timestamp fields (`updatedAt`, `startedAt`, and `completedAt`) must be RFC 3339
97
111
  The shared proxy rejects a sync request body over 10 MB with HTTP `413`. Free
98
112
  plan documents are already limited to 2 MB per roadmap before that shared cap.
99
113
 
114
+ `watch` records its PID, CLI version, and start time in `<config dir>/watch.json`
115
+ (mode 0600). `watch status` reports version drift; these four subcommands support
116
+ `--json`. `watch stop` leaves the systemd unit enabled for the next login; use
117
+ `watch --uninstall-service` to remove it permanently. Removing a registry entry
118
+ stops watching that repository without restarting watch and does not delete its files.
119
+
120
+ When init, link, sync, or roadmap migrate adds a registry entry, it warns if a
121
+ running watch uses a different CLI version. Watch from 0.15.x and earlier does
122
+ not write `watch.json` and cannot be detected. `nolto update` restarts the systemd
123
+ watch service so the updated watcher can report its version.
124
+
100
125
  `watch` uses `{ root, projectId }` entries in the registry maintained by init, link,
101
126
  and sync. Older entries resolve their project from `nolto.json`; missing repositories
102
127
  or bindings are skipped with a warning. It watches the project cache (excluding
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 path20 from "path";
6
+ import path21 from "path";
7
7
  import { CommanderError } from "commander";
8
8
 
9
9
  // src/config.ts
@@ -372,11 +372,11 @@ function maskToken(token) {
372
372
  function createHttpClient(opts) {
373
373
  const { baseUrl, version, token } = opts;
374
374
  const base = baseUrl.replace(/\/+$/, "");
375
- async function request(method, path21, body) {
376
- if (!path21.startsWith("/api/")) {
377
- throw new CliError(`HTTP client path must start with /api/, got: ${path21}`, 2);
375
+ async function request(method, path22, body) {
376
+ if (!path22.startsWith("/api/")) {
377
+ throw new CliError(`HTTP client path must start with /api/, got: ${path22}`, 2);
378
378
  }
379
- const url = `${base}${path21}`;
379
+ const url = `${base}${path22}`;
380
380
  const headers = {
381
381
  "Content-Type": "application/json",
382
382
  "User-Agent": `${CLI_USER_AGENT_NAME}/${version}`
@@ -518,12 +518,12 @@ function normalizeRemote(raw) {
518
518
  const firstSlash = s.indexOf("/");
519
519
  if (firstSlash <= 0) return null;
520
520
  let host = s.slice(0, firstSlash).toLowerCase();
521
- let path21 = s.slice(firstSlash + 1);
521
+ let path22 = s.slice(firstSlash + 1);
522
522
  if (hadScheme) host = host.replace(/:\d+$/, "");
523
- path21 = path21.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
524
- if (path21.length === 0) return null;
525
- if (HOSTED_LOWERCASE_PATH.has(host)) path21 = path21.toLowerCase();
526
- return `${host}/${path21}`;
523
+ path22 = path22.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
524
+ if (path22.length === 0) return null;
525
+ if (HOSTED_LOWERCASE_PATH.has(host)) path22 = path22.toLowerCase();
526
+ return `${host}/${path22}`;
527
527
  }
528
528
  function repoIdentityToString(id) {
529
529
  return `${id.kind}:${id.value}`;
@@ -1036,27 +1036,80 @@ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1036
1036
  });
1037
1037
  }
1038
1038
 
1039
+ // src/watch-state.ts
1040
+ import * as fs from "fs/promises";
1041
+ import { randomUUID as randomUUID2 } from "crypto";
1042
+ import path3 from "path";
1043
+ import { z as z2 } from "zod";
1044
+ var watchStateSchema = z2.object({
1045
+ pid: z2.number().int().positive(),
1046
+ version: z2.string().min(1),
1047
+ startedAt: z2.string().datetime()
1048
+ });
1049
+ function getWatchStatePath(env) {
1050
+ return path3.join(getConfigDir(env), "watch.json");
1051
+ }
1052
+ async function readWatchState(filePath, io = fs) {
1053
+ try {
1054
+ const result = watchStateSchema.safeParse(JSON.parse(await io.readFile(filePath, "utf8")));
1055
+ return result.success ? result.data : null;
1056
+ } catch {
1057
+ return null;
1058
+ }
1059
+ }
1060
+ async function writeWatchState(filePath, state, io = fs) {
1061
+ await io.mkdir(path3.dirname(filePath), { recursive: true, mode: 448 });
1062
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1063
+ try {
1064
+ await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
1065
+ await io.rename(tempPath, filePath);
1066
+ } catch (error) {
1067
+ await io.unlink(tempPath).catch(() => void 0);
1068
+ throw error;
1069
+ }
1070
+ }
1071
+ async function removeWatchState(filePath, pid, io = fs) {
1072
+ if ((await readWatchState(filePath, io))?.pid === pid) {
1073
+ await io.unlink(filePath).catch(() => void 0);
1074
+ }
1075
+ }
1076
+ function isAlive(pid, kill = process.kill) {
1077
+ try {
1078
+ kill(pid, 0);
1079
+ return true;
1080
+ } catch (error) {
1081
+ if (error.code === "ESRCH") return false;
1082
+ if (error.code === "EPERM") return true;
1083
+ throw error;
1084
+ }
1085
+ }
1086
+ async function staleWatchWarning(env, currentVersion, kill = process.kill) {
1087
+ const state = await readWatchState(getWatchStatePath(env));
1088
+ if (!state || state.version === currentVersion || !isAlive(state.pid, kill)) return null;
1089
+ return `Warning: nolto watch (pid ${state.pid}) is running CLI v${state.version}, this CLI is v${currentVersion}. Restart it: nolto watch stop, then start it again (or nolto update).`;
1090
+ }
1091
+
1039
1092
  // src/commands/init.ts
1040
1093
  import readline2 from "readline/promises";
1041
1094
  import { createRequire } from "module";
1042
1095
  import { fileURLToPath as fileURLToPath2 } from "url";
1043
1096
  import os3 from "os";
1044
- import path11 from "path";
1045
- import fs from "fs";
1097
+ import path12 from "path";
1098
+ import fs2 from "fs";
1046
1099
 
1047
1100
  // src/roadmap-bootstrap.ts
1048
1101
  import { existsSync } from "fs";
1049
1102
  import { readFile as readFile4, realpath } from "fs/promises";
1050
- import path5 from "path";
1103
+ import path6 from "path";
1051
1104
 
1052
1105
  // src/roadmap-cache.ts
1053
1106
  import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, writeFile as writeFile3, rename as rename2, unlink } from "fs/promises";
1054
- import { randomUUID as randomUUID2 } from "crypto";
1055
- import path4 from "path";
1107
+ import { randomUUID as randomUUID3 } from "crypto";
1108
+ import path5 from "path";
1056
1109
 
1057
1110
  // src/sync-core.ts
1058
1111
  import { createHash } from "crypto";
1059
- import path3 from "path";
1112
+ import path4 from "path";
1060
1113
  function sha256Hex(content) {
1061
1114
  return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1062
1115
  }
@@ -1114,9 +1167,9 @@ async function buildSyncBody(args) {
1114
1167
  }
1115
1168
  } catch {
1116
1169
  }
1117
- const root = path3.resolve(args.repoRoot);
1118
- const absolute = path3.resolve(root, ref.path);
1119
- if (absolute !== root && !absolute.startsWith(root + path3.sep)) {
1170
+ const root = path4.resolve(args.repoRoot);
1171
+ const absolute = path4.resolve(root, ref.path);
1172
+ if (absolute !== root && !absolute.startsWith(root + path4.sep)) {
1120
1173
  args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1121
1174
  continue;
1122
1175
  }
@@ -1134,11 +1187,11 @@ async function buildSyncBody(args) {
1134
1187
  args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1135
1188
  continue;
1136
1189
  }
1137
- if (real !== realRoot && !real.startsWith(realRoot + path3.sep)) {
1190
+ if (real !== realRoot && !real.startsWith(realRoot + path4.sep)) {
1138
1191
  args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1139
1192
  continue;
1140
1193
  }
1141
- if (!isValidPlanPath(path3.relative(realRoot, real).split(path3.sep).join("/"))) {
1194
+ if (!isValidPlanPath(path4.relative(realRoot, real).split(path4.sep).join("/"))) {
1142
1195
  args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1143
1196
  continue;
1144
1197
  }
@@ -1177,12 +1230,12 @@ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1177
1230
  var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1178
1231
  function cacheDir(env, projectId) {
1179
1232
  if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1180
- return path4.join(getConfigDir(env), "projects", projectId, "roadmaps");
1233
+ return path5.join(getConfigDir(env), "projects", projectId, "roadmaps");
1181
1234
  }
1182
1235
  function cachePaths(env, projectId, slug) {
1183
1236
  if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1184
1237
  const dir = cacheDir(env, projectId);
1185
- return { json: path4.join(dir, `${slug}.json`), meta: path4.join(dir, `${slug}.meta.json`) };
1238
+ return { json: path5.join(dir, `${slug}.json`), meta: path5.join(dir, `${slug}.meta.json`) };
1186
1239
  }
1187
1240
  async function listCachedSlugs(env, projectId) {
1188
1241
  try {
@@ -1236,7 +1289,7 @@ async function writeCache(env, projectId, slug, roadmap, meta) {
1236
1289
  const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
1237
1290
  await mkdir2(cacheDir(env, projectId), { recursive: true, mode: 448 });
1238
1291
  for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1239
- const temp = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1292
+ const temp = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1240
1293
  try {
1241
1294
  await writeFile3(temp, content, { mode: 384 });
1242
1295
  await rename2(temp, filePath);
@@ -1308,7 +1361,7 @@ async function ensureRoadmapCache(args) {
1308
1361
  if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1309
1362
  if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1310
1363
  }
1311
- const basename = path5.basename(args.repoRoot);
1364
+ const basename = path6.basename(args.repoRoot);
1312
1365
  const slug = args.slug ?? slugifyProjectId(basename);
1313
1366
  const collision = list.roadmaps.find((row) => row.slug === slug);
1314
1367
  if (collision) throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
@@ -1336,24 +1389,58 @@ async function ensureRoadmapCache(args) {
1336
1389
  await writeCache(env, projectId, slug, response.roadmap ?? roadmap, { repoIdentity: identity, revision: response.revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : existing?.meta?.currentTaskId });
1337
1390
  log(`created ${slug} on server (rev ${response.revision})`);
1338
1391
  }
1392
+ async function ensureProjectRepo(args) {
1393
+ let repos;
1394
+ try {
1395
+ const project = await args.http.get(`/api/projects/${args.projectId}`);
1396
+ repos = Array.isArray(project.repos) ? project.repos : [];
1397
+ } catch (error) {
1398
+ if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
1399
+ process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
1400
+ `);
1401
+ return "unbound";
1402
+ }
1403
+ if (repos.length === 0) return "unbound";
1404
+ const identity = repoIdentityToString(args.repoIdentity);
1405
+ if (repos.some((repo) => repo.identity === identity)) return "bound";
1406
+ if (!await args.confirm(`Project is bound to ${repos.map((repo) => repo.identity).join(", ")}. Add this repository (${identity}) to the project? [Y/n] `)) return "declined";
1407
+ try {
1408
+ await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
1409
+ } catch (error) {
1410
+ if (error instanceof CliError) {
1411
+ if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
1412
+ if (error.status === 403) {
1413
+ throw new CliError(
1414
+ "Only the project owner can add a repository.",
1415
+ 2,
1416
+ "Ask the owner to run `nolto link --add` in this repository."
1417
+ );
1418
+ }
1419
+ if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
1420
+ }
1421
+ throw error;
1422
+ }
1423
+ args.log(`Added ${identity} to project.`);
1424
+ return "added";
1425
+ }
1339
1426
 
1340
1427
  // src/commands/link.ts
1341
1428
  import readline from "readline/promises";
1342
1429
  import os2 from "os";
1343
- import path9 from "path";
1430
+ import path10 from "path";
1344
1431
  import { statSync as statSync2 } from "fs";
1345
1432
 
1346
1433
  // src/registry.ts
1347
1434
  import { readFile as readFile5, writeFile as writeFile4, mkdir as mkdir3, rename as rename3, unlink as unlink2 } from "fs/promises";
1348
- import { randomUUID as randomUUID3 } from "crypto";
1349
- import path6 from "path";
1350
- import { z as z2 } from "zod";
1351
- var registrySchema = z2.object({
1352
- schemaVersion: z2.literal(1),
1353
- repos: z2.array(z2.object({ root: z2.string().min(1), projectId: z2.string().uuid().optional() }).passthrough())
1435
+ import { randomUUID as randomUUID4 } from "crypto";
1436
+ import path7 from "path";
1437
+ import { z as z3 } from "zod";
1438
+ var registrySchema = z3.object({
1439
+ schemaVersion: z3.literal(1),
1440
+ repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
1354
1441
  }).passthrough();
1355
1442
  function getRegistryPath(env) {
1356
- return path6.join(getConfigDir(env), "registry.json");
1443
+ return path7.join(getConfigDir(env), "registry.json");
1357
1444
  }
1358
1445
  async function loadRegistry(filePath) {
1359
1446
  let raw;
@@ -1393,27 +1480,38 @@ async function addRepoToRegistry(filePath, entry) {
1393
1480
  ...registry,
1394
1481
  repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
1395
1482
  };
1396
- await mkdir3(path6.dirname(filePath), { recursive: true, mode: 448 });
1397
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1483
+ await writeRegistry(filePath, updated);
1484
+ return { added: !existing, updated: !!existing, registry: updated };
1485
+ }
1486
+ async function writeRegistry(filePath, registry) {
1487
+ await mkdir3(path7.dirname(filePath), { recursive: true, mode: 448 });
1488
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID4()}`;
1398
1489
  try {
1399
- await writeFile4(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1490
+ await writeFile4(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
1400
1491
  await rename3(tempPath, filePath);
1401
1492
  } catch (err) {
1402
1493
  await unlink2(tempPath).catch(() => void 0);
1403
1494
  throw err;
1404
1495
  }
1405
- return { added: !existing, updated: !!existing, registry: updated };
1496
+ }
1497
+ async function removeRepoFromRegistry(filePath, root) {
1498
+ const registry = await loadRegistry(filePath);
1499
+ const repos = registry.repos.filter((repo) => repo.root !== root);
1500
+ if (repos.length === registry.repos.length) return { removed: false, registry };
1501
+ const updated = { ...registry, repos };
1502
+ await writeRegistry(filePath, updated);
1503
+ return { removed: true, registry: updated };
1406
1504
  }
1407
1505
 
1408
1506
  // src/repo-identity.ts
1409
1507
  import { execFile } from "child_process";
1410
1508
  import { realpathSync } from "fs";
1411
- import path8 from "path";
1509
+ import path9 from "path";
1412
1510
 
1413
1511
  // src/machine-id.ts
1414
1512
  import { chmod, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5 } from "fs/promises";
1415
- import { randomUUID as randomUUID4 } from "crypto";
1416
- import path7 from "path";
1513
+ import { randomUUID as randomUUID5 } from "crypto";
1514
+ import path8 from "path";
1417
1515
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
1418
1516
  function parseMachineId(raw, file) {
1419
1517
  let parsed;
@@ -1429,7 +1527,7 @@ function parseMachineId(raw, file) {
1429
1527
  return id;
1430
1528
  }
1431
1529
  async function loadOrCreate(configDir) {
1432
- const file = path7.join(configDir, "machine.json");
1530
+ const file = path8.join(configDir, "machine.json");
1433
1531
  let raw = null;
1434
1532
  try {
1435
1533
  raw = await readFile6(file, "utf8");
@@ -1442,7 +1540,7 @@ async function loadOrCreate(configDir) {
1442
1540
  if (raw !== null) {
1443
1541
  return parseMachineId(raw, file);
1444
1542
  }
1445
- const machineId = randomUUID4();
1543
+ const machineId = randomUUID5();
1446
1544
  await mkdir4(configDir, { recursive: true, mode: 448 });
1447
1545
  try {
1448
1546
  await writeFile5(file, `${JSON.stringify({ machineId }, null, 2)}
@@ -1460,7 +1558,7 @@ async function loadOrCreate(configDir) {
1460
1558
  return machineId;
1461
1559
  }
1462
1560
  function loadOrCreateMachineId(configDir) {
1463
- const key = path7.resolve(configDir);
1561
+ const key = path8.resolve(configDir);
1464
1562
  const existing = inFlightByConfigDir.get(key);
1465
1563
  if (existing !== void 0) return existing;
1466
1564
  const pending = loadOrCreate(key).finally(() => {
@@ -1494,7 +1592,7 @@ async function resolveRepoIdentity(root, deps) {
1494
1592
  try {
1495
1593
  canonicalRoot = realpathSync(root);
1496
1594
  } catch {
1497
- canonicalRoot = path8.resolve(root);
1595
+ canonicalRoot = path9.resolve(root);
1498
1596
  }
1499
1597
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1500
1598
  }
@@ -1513,7 +1611,7 @@ function resolveStartDir(env, cwd) {
1513
1611
  }
1514
1612
  function dirHasGit(dir) {
1515
1613
  try {
1516
- statSync2(path9.join(dir, ".git"));
1614
+ statSync2(path10.join(dir, ".git"));
1517
1615
  return true;
1518
1616
  } catch {
1519
1617
  return false;
@@ -1525,14 +1623,14 @@ function findRepoRoot(startDir, hasGit = dirHasGit) {
1525
1623
  if (hasGit(current)) {
1526
1624
  return { root: current, foundGit: true };
1527
1625
  }
1528
- const parent = path9.dirname(current);
1626
+ const parent = path10.dirname(current);
1529
1627
  if (parent === current) break;
1530
1628
  current = parent;
1531
1629
  }
1532
1630
  return { root: startDir, foundGit: false };
1533
1631
  }
1534
1632
  function isHomeDirectory(dir, home = os2.homedir()) {
1535
- return path9.resolve(dir) === path9.resolve(home);
1633
+ return path10.resolve(dir) === path10.resolve(home);
1536
1634
  }
1537
1635
  async function handleShow(deps, projectBindingPath, mode2) {
1538
1636
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1658,7 +1756,7 @@ async function handleUnlink(projectBindingPath, mode2) {
1658
1756
  `);
1659
1757
  }
1660
1758
  }
1661
- async function performLink(deps, projectId, mode2, slug) {
1759
+ async function performLink(deps, projectId, mode2, slug, yes = false) {
1662
1760
  if (!UUID_RE2.test(projectId)) {
1663
1761
  throw new CliError(
1664
1762
  `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
@@ -1678,7 +1776,7 @@ async function performLink(deps, projectId, mode2, slug) {
1678
1776
  token: deps.settings.token,
1679
1777
  version: deps.version
1680
1778
  });
1681
- let projectName = path9.basename(root);
1779
+ let projectName = path10.basename(root);
1682
1780
  if (deps.settings.token != null) {
1683
1781
  try {
1684
1782
  const result = await http.get(
@@ -1706,10 +1804,36 @@ Proceeding anyway \u2014 verify the ID is correct.
1706
1804
  );
1707
1805
  }
1708
1806
  await writeRepoBinding(root, projectId);
1709
- const writtenPath = path9.join(root, "nolto.json");
1807
+ const writtenPath = path10.join(root, "nolto.json");
1808
+ let repoAdded = false;
1710
1809
  if (deps.settings.token == null) {
1711
1810
  process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
1712
1811
  } else {
1812
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1813
+ const result = await ensureProjectRepo({
1814
+ http,
1815
+ projectId,
1816
+ repoIdentity,
1817
+ confirm: async (question) => {
1818
+ if (yes) return true;
1819
+ if (mode2 === "json") throw new CliError("Adding this repository requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
1820
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1821
+ try {
1822
+ const answer = (await rl.question(question)).trim().toLowerCase();
1823
+ return answer === "" || answer === "y" || answer === "yes";
1824
+ } finally {
1825
+ rl.close();
1826
+ }
1827
+ },
1828
+ log: (line) => {
1829
+ if (mode2 !== "json") process.stdout.write(line + "\n");
1830
+ }
1831
+ });
1832
+ if (result === "declined") {
1833
+ process.stdout.write("Skipped adding this repository. Run `nolto link --add` later; roadmap sync will fail until then.\n");
1834
+ return;
1835
+ }
1836
+ repoAdded = result === "added";
1713
1837
  await ensureRoadmapCache({
1714
1838
  env: process.env,
1715
1839
  http,
@@ -1717,7 +1841,7 @@ Proceeding anyway \u2014 verify the ID is correct.
1717
1841
  projectName,
1718
1842
  repoRoot: root,
1719
1843
  slug,
1720
- repoIdentity: await makeRepoIdentityResolver(deps)(root),
1844
+ repoIdentity,
1721
1845
  log: (line) => {
1722
1846
  if (mode2 !== "json") process.stdout.write(line + "\n");
1723
1847
  }
@@ -1730,6 +1854,10 @@ Proceeding anyway \u2014 verify the ID is correct.
1730
1854
  } else {
1731
1855
  try {
1732
1856
  registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
1857
+ if (registryAdded) {
1858
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
1859
+ if (warning) process.stderr.write(warning + "\n");
1860
+ }
1733
1861
  } catch (err) {
1734
1862
  const message = err instanceof Error ? err.message : String(err);
1735
1863
  process.stderr.write(`Warning: could not update watch registry: ${message}
@@ -1741,7 +1869,8 @@ Proceeding anyway \u2014 verify the ID is correct.
1741
1869
  linked: true,
1742
1870
  projectId,
1743
1871
  projectBindingPath: writtenPath,
1744
- registryAdded
1872
+ registryAdded,
1873
+ repoAdded
1745
1874
  }, mode2);
1746
1875
  } else {
1747
1876
  process.stdout.write(
@@ -1758,7 +1887,7 @@ Commit nolto.json to share the binding with your team.
1758
1887
  function register2(program, deps) {
1759
1888
  const cmd = program.command("link [projectId]").description(
1760
1889
  "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 --list List project repositories\n nolto link --add Add this repository to the project\n nolto link --remove <identity-or-id> Remove a project repository\n nolto link --unlink Remove the projectId from nolto.json"
1761
- ).option("--slug <slug>", "Name this repository's roadmap").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").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");
1890
+ ).option("--slug <slug>", "Name this repository's roadmap").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").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 repository addition, rebind, and removal confirmation prompts").option("--unlink", "Remove the projectId key from nolto.json");
1762
1891
  cmd.action(async (projectId) => {
1763
1892
  const { output } = deps;
1764
1893
  const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
@@ -1848,7 +1977,7 @@ function register2(program, deps) {
1848
1977
  2
1849
1978
  );
1850
1979
  }
1851
- await performLink(deps, projectId, mode2, opts["slug"]);
1980
+ await performLink(deps, projectId, mode2, opts["slug"], opts["yes"] === true);
1852
1981
  });
1853
1982
  }
1854
1983
  function invalidBindingError(projectBindingPath, error) {
@@ -1861,33 +1990,33 @@ function invalidBindingError(projectBindingPath, error) {
1861
1990
  // src/skill-install.ts
1862
1991
  import { cp, mkdir as mkdir5, readFile as readFile7, writeFile as writeFile6, rm as rm2 } from "fs/promises";
1863
1992
  import { existsSync as existsSync2 } from "fs";
1864
- import path10 from "path";
1993
+ import path11 from "path";
1865
1994
  import { fileURLToPath } from "url";
1866
- var __dirname = path10.dirname(fileURLToPath(import.meta.url));
1995
+ var __dirname = path11.dirname(fileURLToPath(import.meta.url));
1867
1996
  function resolveSkillSourceDir() {
1868
1997
  const candidates = [
1869
- path10.resolve(__dirname, "skill/roadmap-progress"),
1998
+ path11.resolve(__dirname, "skill/roadmap-progress"),
1870
1999
  // bundled: dist/skill/...
1871
- path10.resolve(__dirname, "../../../skills/roadmap-progress")
2000
+ path11.resolve(__dirname, "../../../skills/roadmap-progress")
1872
2001
  // source: <repo>/skills/...
1873
2002
  ];
1874
2003
  for (const candidate of candidates) {
1875
- if (existsSync2(path10.join(candidate, "SKILL.md"))) return candidate;
2004
+ if (existsSync2(path11.join(candidate, "SKILL.md"))) return candidate;
1876
2005
  }
1877
2006
  throw new Error("Bundled roadmap-progress skill not found. Reinstall @nolto/cli.");
1878
2007
  }
1879
2008
  var VERSION_MARKER = ".nolto-skill-version";
1880
2009
  async function checkSkillVersionDrift(repoRoot, cliVersion) {
1881
2010
  const skillDirs = [
1882
- path10.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1883
- path10.join(repoRoot, ".agents", "skills", "roadmap-progress")
2011
+ path11.join(repoRoot, ".claude", "skills", "roadmap-progress"),
2012
+ path11.join(repoRoot, ".agents", "skills", "roadmap-progress")
1884
2013
  ];
1885
2014
  const drifted = [];
1886
2015
  for (const dir of skillDirs) {
1887
2016
  if (!existsSync2(dir)) continue;
1888
2017
  let installed;
1889
2018
  try {
1890
- const marker = (await readFile7(path10.join(dir, VERSION_MARKER), "utf8")).trim();
2019
+ const marker = (await readFile7(path11.join(dir, VERSION_MARKER), "utf8")).trim();
1891
2020
  installed = marker.length > 0 ? marker : null;
1892
2021
  } catch {
1893
2022
  installed = null;
@@ -1897,13 +2026,13 @@ async function checkSkillVersionDrift(repoRoot, cliVersion) {
1897
2026
  return drifted;
1898
2027
  }
1899
2028
  function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
1900
- const dirs = drifted.map(({ dir }) => path10.relative(repoRoot, dir).split(path10.sep).join("/")).join(", ");
2029
+ const dirs = drifted.map(({ dir }) => path11.relative(repoRoot, dir).split(path11.sep).join("/")).join(", ");
1901
2030
  const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
1902
2031
  return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
1903
2032
  }
1904
2033
  async function installSkill(args) {
1905
- const targetDir = path10.join(args.skillsParentDir, "roadmap-progress");
1906
- const markerPath = path10.join(targetDir, VERSION_MARKER);
2034
+ const targetDir = path11.join(args.skillsParentDir, "roadmap-progress");
2035
+ const markerPath = path11.join(targetDir, VERSION_MARKER);
1907
2036
  const dirExists = existsSync2(targetDir);
1908
2037
  let installedVersion = null;
1909
2038
  if (dirExists) {
@@ -1924,17 +2053,17 @@ async function installSkill(args) {
1924
2053
  }
1925
2054
 
1926
2055
  // src/commands/init.ts
1927
- var __dirname2 = path11.dirname(fileURLToPath2(import.meta.url));
2056
+ var __dirname2 = path12.dirname(fileURLToPath2(import.meta.url));
1928
2057
  var _require = createRequire(import.meta.url);
1929
2058
  function getCliVersion() {
1930
2059
  const candidates = [
1931
- path11.resolve(__dirname2, "../package.json"),
2060
+ path12.resolve(__dirname2, "../package.json"),
1932
2061
  // bundled: dist/../package.json
1933
- path11.resolve(__dirname2, "../../package.json")
2062
+ path12.resolve(__dirname2, "../../package.json")
1934
2063
  // source: src/commands/../../package.json
1935
2064
  ];
1936
2065
  for (const pkgPath of candidates) {
1937
- if (fs.existsSync(pkgPath)) {
2066
+ if (fs2.existsSync(pkgPath)) {
1938
2067
  try {
1939
2068
  const pkg = _require(pkgPath);
1940
2069
  return pkg.version ?? "0.0.0";
@@ -2091,7 +2220,7 @@ Saved ${configPath}
2091
2220
  }
2092
2221
  if (isHomeDirectory(root)) {
2093
2222
  process.stderr.write(
2094
- `Refusing to set up your home directory as a repository root (found ${path11.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
2223
+ `Refusing to set up your home directory as a repository root (found ${path12.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
2095
2224
  `
2096
2225
  );
2097
2226
  return;
@@ -2123,7 +2252,7 @@ Saved ${configPath}
2123
2252
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
2124
2253
  );
2125
2254
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
2126
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path11.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
2255
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path12.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
2127
2256
  } else {
2128
2257
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
2129
2258
  }
@@ -2137,7 +2266,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2137
2266
  process.stdout.write("Skipped repo setup.\n");
2138
2267
  return;
2139
2268
  }
2140
- const bindingPath = deps.repoBinding?.path ?? path11.join(root, "nolto.json");
2269
+ const bindingPath = deps.repoBinding?.path ?? path12.join(root, "nolto.json");
2141
2270
  if (keepExistingBinding) {
2142
2271
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
2143
2272
  `);
@@ -2149,40 +2278,61 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2149
2278
  );
2150
2279
  }
2151
2280
  await writeRepoBinding(root, repoProject.id);
2152
- process.stdout.write(`binding: wrote ${path11.join(root, "nolto.json")}
2281
+ process.stdout.write(`binding: wrote ${path12.join(root, "nolto.json")}
2153
2282
  `);
2154
2283
  }
2155
2284
  const sourceDir = resolveSkillSourceDir();
2156
2285
  const version = getCliVersion();
2157
2286
  const claudeInstall = await installSkill({
2158
- skillsParentDir: path11.join(root, ".claude", "skills"),
2287
+ skillsParentDir: path12.join(root, ".claude", "skills"),
2159
2288
  sourceDir,
2160
2289
  version
2161
2290
  });
2162
2291
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
2163
2292
  `);
2164
- const usesAgentsTooling = fs.existsSync(path11.join(root, ".agents")) || fs.existsSync(path11.join(root, ".codex")) || fs.existsSync(path11.join(root, "AGENTS.md"));
2293
+ const usesAgentsTooling = fs2.existsSync(path12.join(root, ".agents")) || fs2.existsSync(path12.join(root, ".codex")) || fs2.existsSync(path12.join(root, "AGENTS.md"));
2165
2294
  if (usesAgentsTooling) {
2166
2295
  const agentsInstall = await installSkill({
2167
- skillsParentDir: path11.join(root, ".agents", "skills"),
2296
+ skillsParentDir: path12.join(root, ".agents", "skills"),
2168
2297
  sourceDir,
2169
2298
  version
2170
2299
  });
2171
2300
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
2172
2301
  `);
2173
2302
  }
2303
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2304
+ const repoResult = await ensureProjectRepo({
2305
+ http: repoHttp,
2306
+ projectId: repoProject.id,
2307
+ repoIdentity,
2308
+ confirm: async (question) => {
2309
+ const answer = (await rl.question(question)).trim().toLowerCase();
2310
+ return answer === "" || answer === "y" || answer === "yes";
2311
+ },
2312
+ log: (line) => {
2313
+ process.stdout.write(line + "\n");
2314
+ }
2315
+ });
2316
+ if (repoResult === "declined") {
2317
+ process.stdout.write("Skipped adding this repository. Run `nolto link --add` later; roadmap sync will fail until then.\n");
2318
+ return;
2319
+ }
2174
2320
  await ensureRoadmapCache({
2175
2321
  env: process.env,
2176
2322
  http: repoHttp,
2177
2323
  projectId: repoProject.id,
2178
2324
  projectName: repoProject.name,
2179
2325
  repoRoot: root,
2180
- repoIdentity: await makeRepoIdentityResolver(deps)(root),
2326
+ repoIdentity,
2181
2327
  log: (line) => {
2182
2328
  process.stdout.write(line + "\n");
2183
2329
  }
2184
2330
  });
2185
2331
  const registryResult = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId: repoProject.id });
2332
+ if (registryResult.added) {
2333
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
2334
+ if (warning) process.stderr.write(warning + "\n");
2335
+ }
2186
2336
  process.stdout.write(
2187
2337
  registryResult.added ? `watch registry: added ${root}
2188
2338
  ` : `watch registry: already registered
@@ -2425,7 +2575,7 @@ import { readFile as readFile8, realpath as realpath2 } from "fs/promises";
2425
2575
  import { existsSync as existsSync3 } from "fs";
2426
2576
 
2427
2577
  // src/roadmap-read.ts
2428
- import path12 from "path";
2578
+ import path13 from "path";
2429
2579
  async function resolveRoadmapReadContext(deps) {
2430
2580
  if (deps.settings.token == null) {
2431
2581
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
@@ -2435,7 +2585,7 @@ async function resolveRoadmapReadContext(deps) {
2435
2585
  if (!foundGit) {
2436
2586
  throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2437
2587
  }
2438
- const binding = await loadRepoBinding(path12.join(root, "nolto.json"));
2588
+ const binding = await loadRepoBinding(path13.join(root, "nolto.json"));
2439
2589
  const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2440
2590
  if (projectId == null) {
2441
2591
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
@@ -2491,15 +2641,15 @@ async function collectGitLinks(root, exec) {
2491
2641
  }
2492
2642
 
2493
2643
  // src/sync-repo.ts
2494
- import path13 from "path";
2644
+ import path14 from "path";
2495
2645
  import { readdir as readdir3 } from "fs/promises";
2496
2646
  function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2497
2647
  const planAbsPaths = /* @__PURE__ */ new Set();
2498
- const resolvedRoot = path13.resolve(root);
2648
+ const resolvedRoot = path14.resolve(root);
2499
2649
  for (const roadmap of roadmaps) {
2500
2650
  for (const ref of collectPlanRefs(roadmap)) {
2501
- const absolute = path13.resolve(resolvedRoot, ref.path);
2502
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path13.sep)) {
2651
+ const absolute = path14.resolve(resolvedRoot, ref.path);
2652
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path14.sep)) {
2503
2653
  warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2504
2654
  continue;
2505
2655
  }
@@ -2520,7 +2670,7 @@ async function syncRepo(args, io) {
2520
2670
  if (slugs.length === 0) {
2521
2671
  let legacyFiles = [];
2522
2672
  try {
2523
- legacyFiles = await readdir3(path13.join(args.root, ".nolto", "roadmaps"));
2673
+ legacyFiles = await readdir3(path14.join(args.root, ".nolto", "roadmaps"));
2524
2674
  } catch (err) {
2525
2675
  if (err.code !== "ENOENT") throw err;
2526
2676
  }
@@ -2654,6 +2804,10 @@ async function runSyncCommand(deps, opts = {}) {
2654
2804
  } else {
2655
2805
  try {
2656
2806
  registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
2807
+ if (registryAdded) {
2808
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
2809
+ if (warning) process.stderr.write(warning + "\n");
2810
+ }
2657
2811
  } catch (err) {
2658
2812
  const message = err instanceof Error ? err.message : String(err);
2659
2813
  process.stderr.write(`Warning: could not update watch registry: ${message}
@@ -2837,10 +2991,10 @@ function register7(program, deps) {
2837
2991
  }
2838
2992
 
2839
2993
  // src/roadmap-commands.ts
2840
- import path14 from "path";
2994
+ import path15 from "path";
2841
2995
  import { existsSync as existsSync4 } from "fs";
2842
2996
  import { readFile as readFile9, readdir as readdir4, writeFile as writeFile7, rename as rename4, unlink as unlink3, realpath as realpath3 } from "fs/promises";
2843
- import { randomUUID as randomUUID5 } from "crypto";
2997
+ import { randomUUID as randomUUID6 } from "crypto";
2844
2998
  import readline4 from "readline/promises";
2845
2999
 
2846
3000
  // src/commands/pull.ts
@@ -2908,7 +3062,7 @@ async function selectRoadmap(deps, requestedSlug) {
2908
3062
  }
2909
3063
  async function roadmapPath(deps, slug) {
2910
3064
  const { paths } = await selectRoadmap(deps, slug);
2911
- printResult(path14.resolve(paths.json), deps.output.mode);
3065
+ printResult(path15.resolve(paths.json), deps.output.mode);
2912
3066
  }
2913
3067
  async function roadmapStatus(deps, slug, fresh = false) {
2914
3068
  const selected = await selectRoadmap(deps, slug);
@@ -2953,7 +3107,7 @@ async function roadmapSummary(deps, slug, text) {
2953
3107
  const selected = await selectRoadmap(deps, slug);
2954
3108
  const entry = await readCache(process.env, selected.projectId, selected.slug);
2955
3109
  entry.roadmap.summary = text;
2956
- const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
3110
+ const temp = `${selected.paths.json}.tmp-${randomUUID6()}`;
2957
3111
  try {
2958
3112
  await writeFile7(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
2959
3113
  await rename4(temp, selected.paths.json);
@@ -2987,8 +3141,8 @@ async function roadmapTask(deps, taskId, slug, body) {
2987
3141
  const selected = await selectRoadmap(deps, slug);
2988
3142
  if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
2989
3143
  if (body.plan !== void 0) {
2990
- const absolute = path14.resolve(selected.root, body.plan);
2991
- if (!isValidPlanPath(body.plan) || !absolute.startsWith(path14.resolve(selected.root) + path14.sep)) {
3144
+ const absolute = path15.resolve(selected.root, body.plan);
3145
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path15.resolve(selected.root) + path15.sep)) {
2992
3146
  throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
2993
3147
  }
2994
3148
  if (!existsSync4(absolute)) warn(`WARN plan file not found at ${absolute}`);
@@ -3010,7 +3164,7 @@ async function roadmapEvents(deps, slug, opts) {
3010
3164
  }
3011
3165
  async function roadmapMigrate(deps, yes = false) {
3012
3166
  const { root, projectId } = await resolveRoadmapReadContext(deps);
3013
- const dir = path14.join(root, ".nolto", "roadmaps");
3167
+ const dir = path15.join(root, ".nolto", "roadmaps");
3014
3168
  let files;
3015
3169
  try {
3016
3170
  files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
@@ -3026,7 +3180,7 @@ async function roadmapMigrate(deps, yes = false) {
3026
3180
  for (const file of files) {
3027
3181
  const slug = file.slice(0, -5);
3028
3182
  cachePaths(process.env, projectId, slug);
3029
- const roadmap = await loadValidRoadmap(path14.join(dir, file), (p) => readFile9(p, "utf8"));
3183
+ const roadmap = await loadValidRoadmap(path15.join(dir, file), (p) => readFile9(p, "utf8"));
3030
3184
  roadmap.schemaVersion = 3;
3031
3185
  delete roadmap.updatedAt;
3032
3186
  delete roadmap.currentTaskId;
@@ -3076,7 +3230,7 @@ async function roadmapMigrate(deps, yes = false) {
3076
3230
  const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3077
3231
  let attributes = "";
3078
3232
  try {
3079
- attributes = await readFile9(path14.join(root, ".gitattributes"), "utf8");
3233
+ attributes = await readFile9(path15.join(root, ".gitattributes"), "utf8");
3080
3234
  } catch (error) {
3081
3235
  if (error.code !== "ENOENT") throw error;
3082
3236
  }
@@ -3084,7 +3238,11 @@ async function roadmapMigrate(deps, yes = false) {
3084
3238
  nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
3085
3239
  }
3086
3240
  nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
3087
- await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
3241
+ const { added } = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
3242
+ if (added) {
3243
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
3244
+ if (warning) process.stderr.write(warning + "\n");
3245
+ }
3088
3246
  printResult(deps.output.mode === "json" ? { results, nextSteps } : nextSteps.join("\n"), deps.output.mode);
3089
3247
  }
3090
3248
 
@@ -3122,11 +3280,11 @@ import { execFile as execFile3 } from "child_process";
3122
3280
  import { promisify as promisify2 } from "util";
3123
3281
  import { readFile as readFile10, realpath as realpath4 } from "fs/promises";
3124
3282
  import { existsSync as existsSync5, mkdirSync } from "fs";
3125
- import path17 from "path";
3283
+ import path18 from "path";
3126
3284
  import chokidar from "chokidar";
3127
3285
 
3128
3286
  // src/watch-core.ts
3129
- import path15 from "path";
3287
+ import path16 from "path";
3130
3288
  var WatchSet = class {
3131
3289
  constructor(deps) {
3132
3290
  this.deps = deps;
@@ -3175,7 +3333,7 @@ async function reloadRoots(deps) {
3175
3333
  continue;
3176
3334
  }
3177
3335
  try {
3178
- const projectId = repo.projectId ?? (await loadRepoBinding(path15.join(repo.root, "nolto.json")))?.projectId;
3336
+ const projectId = repo.projectId ?? (await loadRepoBinding(path16.join(repo.root, "nolto.json")))?.projectId;
3179
3337
  if (projectId) repos.push({ root: repo.root, projectId });
3180
3338
  else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3181
3339
  } catch (err) {
@@ -3246,7 +3404,7 @@ var RepoWatch = class {
3246
3404
  };
3247
3405
 
3248
3406
  // src/service-install.ts
3249
- import path16 from "path";
3407
+ import path17 from "path";
3250
3408
  import os4 from "os";
3251
3409
  function buildUnitFile(args) {
3252
3410
  return [
@@ -3266,8 +3424,8 @@ function buildUnitFile(args) {
3266
3424
  }
3267
3425
  function getUnitPath(env) {
3268
3426
  const xdg = env["XDG_CONFIG_HOME"];
3269
- const base = xdg != null && xdg.length > 0 ? xdg : path16.join(os4.homedir(), ".config");
3270
- return path16.join(base, "systemd", "user", "nolto-watch.service");
3427
+ const base = xdg != null && xdg.length > 0 ? xdg : path17.join(os4.homedir(), ".config");
3428
+ return path17.join(base, "systemd", "user", "nolto-watch.service");
3271
3429
  }
3272
3430
  async function installServiceWith(deps) {
3273
3431
  if (deps.platform !== "linux") {
@@ -3278,7 +3436,7 @@ async function installServiceWith(deps) {
3278
3436
  );
3279
3437
  }
3280
3438
  const unitPath = getUnitPath(deps.env);
3281
- await deps.mkdir(path16.dirname(unitPath));
3439
+ await deps.mkdir(path17.dirname(unitPath));
3282
3440
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
3283
3441
  deps.log(`Wrote ${unitPath}`);
3284
3442
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -3300,7 +3458,7 @@ async function installService() {
3300
3458
  platform: process.platform,
3301
3459
  env: process.env,
3302
3460
  nodePath: process.execPath,
3303
- scriptPath: path16.resolve(process.argv[1] ?? ""),
3461
+ scriptPath: path17.resolve(process.argv[1] ?? ""),
3304
3462
  writeFile: (p, content) => writeFile10(p, content, "utf8"),
3305
3463
  mkdir: async (p) => {
3306
3464
  await mkdir7(p, { recursive: true });
@@ -3378,10 +3536,23 @@ async function uninstallService() {
3378
3536
  warn: (line) => process.stderr.write("Warning: " + line + "\n")
3379
3537
  });
3380
3538
  }
3539
+ async function stopServiceWith(deps) {
3540
+ if (deps.platform !== "linux") {
3541
+ throw new CliError("Stopping the watch service requires systemd and is only supported on Linux.", 2);
3542
+ }
3543
+ const result = await deps.exec(["systemctl", "--user", "stop", "nolto-watch"]);
3544
+ if (result.code !== 0) {
3545
+ throw new CliError(
3546
+ `Could not stop the watch service: ${result.stderr}`,
3547
+ 2,
3548
+ "Run `systemctl --user stop nolto-watch` manually."
3549
+ );
3550
+ }
3551
+ }
3381
3552
 
3382
3553
  // src/commands/watch.ts
3383
3554
  function register10(program, deps) {
3384
- 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) => {
3555
+ const watch = 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) => {
3385
3556
  if (opts.installService && opts.uninstallService) {
3386
3557
  throw new CliError("--install-service and --uninstall-service cannot be used together.", 2);
3387
3558
  }
@@ -3400,6 +3571,15 @@ function register10(program, deps) {
3400
3571
  if (Number.isNaN(debounceMs) || debounceMs < 0) {
3401
3572
  throw new CliError("--debounce must be a non-negative integer.", 2);
3402
3573
  }
3574
+ const statePath = getWatchStatePath(process.env);
3575
+ const previous = await readWatchState(statePath);
3576
+ if (previous && previous.pid !== process.pid && isAlive(previous.pid)) {
3577
+ throw new CliError(
3578
+ `nolto watch is already running (pid ${previous.pid}, v${previous.version}).`,
3579
+ 2,
3580
+ "Run `nolto watch stop` first."
3581
+ );
3582
+ }
3403
3583
  const registryPath = getRegistryPath(process.env);
3404
3584
  const roots = await reloadRoots({
3405
3585
  load: () => loadRegistry(registryPath),
@@ -3420,7 +3600,7 @@ function register10(program, deps) {
3420
3600
  const startRepo = ({ root, projectId }) => {
3421
3601
  const roadmapsPath = cacheDir(process.env, projectId);
3422
3602
  const warn2 = (line) => {
3423
- process.stderr.write(line.startsWith(" ") ? line + "\n" : `Warning: [${path17.basename(root)}] ${line}
3603
+ process.stderr.write(line.startsWith(" ") ? line + "\n" : `Warning: [${path18.basename(root)}] ${line}
3424
3604
  `);
3425
3605
  };
3426
3606
  mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
@@ -3437,7 +3617,7 @@ function register10(program, deps) {
3437
3617
  exec: promisify2(execFile3),
3438
3618
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3439
3619
  http,
3440
- log: (line) => process.stdout.write(`[${path17.basename(root)}] ${line}
3620
+ log: (line) => process.stdout.write(`[${path18.basename(root)}] ${line}
3441
3621
  `),
3442
3622
  warn: warn2
3443
3623
  }
@@ -3450,7 +3630,7 @@ function register10(program, deps) {
3450
3630
  warn: (line) => process.stderr.write(line + "\n")
3451
3631
  });
3452
3632
  watcher.on("all", (_event, filePath) => {
3453
- if (path17.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3633
+ if (path18.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3454
3634
  repoWatch.handleEvent(filePath);
3455
3635
  });
3456
3636
  void checkSkillVersionDrift(root, deps.version).then((drifted) => {
@@ -3467,6 +3647,12 @@ function register10(program, deps) {
3467
3647
  log: (line) => process.stdout.write(line + "\n")
3468
3648
  });
3469
3649
  await watchSet.reconcile(roots);
3650
+ try {
3651
+ await writeWatchState(statePath, { pid: process.pid, version: deps.version, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
3652
+ } catch (error) {
3653
+ await watchSet.stopAll();
3654
+ throw error;
3655
+ }
3470
3656
  const registryWatcher = chokidar.watch(registryPath, { ignoreInitial: true });
3471
3657
  let registryReloadTimer = null;
3472
3658
  registryWatcher.on("all", () => {
@@ -3493,13 +3679,84 @@ function register10(program, deps) {
3493
3679
  `);
3494
3680
  await new Promise((resolve) => {
3495
3681
  const stop = () => {
3682
+ process.removeListener("SIGINT", stop);
3683
+ process.removeListener("SIGTERM", stop);
3496
3684
  if (registryReloadTimer != null) clearTimeout(registryReloadTimer);
3497
- void Promise.all([registryWatcher.close(), watchSet.stopAll()]).then(() => resolve());
3685
+ void Promise.all([registryWatcher.close(), watchSet.stopAll()]).finally(() => removeWatchState(statePath, process.pid)).finally(resolve);
3498
3686
  };
3499
3687
  process.once("SIGINT", stop);
3500
3688
  process.once("SIGTERM", stop);
3501
3689
  });
3502
3690
  });
3691
+ watch.addHelpText("after", "\nstop leaves the service installed for the next login; use --uninstall-service to remove it permanently.");
3692
+ watch.command("status").description("Show watch process and service status.").action(async () => {
3693
+ const state = await readWatchState(getWatchStatePath(process.env));
3694
+ const running = state !== null && isAlive(state.pid);
3695
+ const result = {
3696
+ running,
3697
+ pid: running ? state.pid : null,
3698
+ version: running ? state.version : null,
3699
+ startedAt: running ? state.startedAt : null,
3700
+ stale: running && state.version !== deps.version,
3701
+ service: existsSync5(getUnitPath(process.env)) ? "installed" : "not-installed"
3702
+ };
3703
+ printResult(deps.output.mode === "json" ? result : `${running ? "running" : "not running"}
3704
+ service: ${result.service}
3705
+ pid: ${result.pid ?? "\u2014"}
3706
+ version: ${result.version ?? "\u2014"}
3707
+ startedAt: ${result.startedAt ?? "\u2014"}
3708
+ stale: ${result.stale}`, deps.output.mode);
3709
+ });
3710
+ watch.command("stop").description("Stop watch without disabling the installed service.").action(async () => {
3711
+ const statePath = getWatchStatePath(process.env);
3712
+ const state = await readWatchState(statePath);
3713
+ const service = existsSync5(getUnitPath(process.env));
3714
+ let via = null;
3715
+ if (service) {
3716
+ await stopServiceWith({
3717
+ platform: process.platform,
3718
+ exec: async (cmd) => {
3719
+ try {
3720
+ await promisify2(execFile3)(cmd[0], cmd.slice(1));
3721
+ return { code: 0, stderr: "" };
3722
+ } catch (error) {
3723
+ const e = error;
3724
+ return { code: e.code ?? 1, stderr: e.stderr ?? String(error) };
3725
+ }
3726
+ }
3727
+ });
3728
+ via = "systemd";
3729
+ }
3730
+ if (state && isAlive(state.pid)) {
3731
+ try {
3732
+ process.kill(state.pid, "SIGTERM");
3733
+ } catch (error) {
3734
+ if (error.code !== "ESRCH") {
3735
+ throw new CliError(`Could not stop nolto watch (pid ${state.pid}): ${String(error)}`, 2);
3736
+ }
3737
+ }
3738
+ via ??= "signal";
3739
+ }
3740
+ if (state) {
3741
+ for (let attempt = 0; attempt < 50 && isAlive(state.pid); attempt++) {
3742
+ await new Promise((resolve) => setTimeout(resolve, 100));
3743
+ }
3744
+ if (isAlive(state.pid)) throw new CliError(`nolto watch (pid ${state.pid}) did not stop within 5 seconds.`, 2);
3745
+ await removeWatchState(statePath, state.pid);
3746
+ }
3747
+ printResult(deps.output.mode === "json" ? { stopped: via !== null, via } : via === null ? "not running" : `Stopped nolto watch via ${via}.`, deps.output.mode);
3748
+ });
3749
+ watch.command("list").description("List repositories in the watch registry.").action(async () => {
3750
+ const registry = await loadRegistry(getRegistryPath(process.env));
3751
+ const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync5(repo.root) }));
3752
+ printResult(deps.output.mode === "json" ? { repos } : repos.map((repo) => `${repo.root} ${repo.projectId ?? "\u2014"}${repo.exists ? "" : " (missing)"}`).join("\n"), deps.output.mode);
3753
+ });
3754
+ watch.command("remove [root]").description("Remove a repository from the watch registry.").action(async (arg) => {
3755
+ const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path18.resolve(arg);
3756
+ const { removed } = await removeRepoFromRegistry(getRegistryPath(process.env), root);
3757
+ if (!removed) throw new CliError(`${root} is not in the watch registry.`, 2, "Run `nolto watch list` to see registered repositories.");
3758
+ printResult(deps.output.mode === "json" ? { removed: true, root } : `Removed ${root} from the watch registry.`, deps.output.mode);
3759
+ });
3503
3760
  }
3504
3761
 
3505
3762
  // src/update-cli.ts
@@ -3507,14 +3764,14 @@ import { execFile as execFile4 } from "child_process";
3507
3764
  import { existsSync as existsSync6 } from "fs";
3508
3765
  import { realpath as realpath5 } from "fs/promises";
3509
3766
  import { createRequire as createRequire2 } from "module";
3510
- import path19 from "path";
3767
+ import path20 from "path";
3511
3768
  import { fileURLToPath as fileURLToPath3 } from "url";
3512
3769
  import { promisify as promisify3 } from "util";
3513
3770
 
3514
3771
  // src/update-notifier.ts
3515
3772
  import { readFile as readFile11, writeFile as writeFile8, mkdir as mkdir6 } from "fs/promises";
3516
3773
  import https from "https";
3517
- import path18 from "path";
3774
+ import path19 from "path";
3518
3775
  var PACKAGE = "@nolto/cli";
3519
3776
  var CACHE_FILE = "update-check.json";
3520
3777
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -3572,7 +3829,7 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3572
3829
  });
3573
3830
  }
3574
3831
  async function writeUpdateCache(cachePath, now, latest2) {
3575
- await mkdir6(path18.dirname(cachePath), { recursive: true });
3832
+ await mkdir6(path19.dirname(cachePath), { recursive: true });
3576
3833
  const payload = { checkedAt: now, latest: latest2 };
3577
3834
  await writeFile8(cachePath, JSON.stringify(payload), { mode: 384 });
3578
3835
  }
@@ -3583,7 +3840,7 @@ async function refreshCache(cachePath, now, fetchLatest) {
3583
3840
  }
3584
3841
  async function checkForUpdate(opts) {
3585
3842
  if (isDisabled(opts.env)) return null;
3586
- const cachePath = path18.join(opts.configDir, CACHE_FILE);
3843
+ const cachePath = path19.join(opts.configDir, CACHE_FILE);
3587
3844
  let cache = {};
3588
3845
  try {
3589
3846
  cache = JSON.parse(await readFile11(cachePath, "utf8"));
@@ -3691,7 +3948,7 @@ async function updateCliWith(deps) {
3691
3948
  }
3692
3949
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
3693
3950
  await deps.writeCache(
3694
- path19.join(deps.configDir, UPDATE_CACHE_FILE),
3951
+ path20.join(deps.configDir, UPDATE_CACHE_FILE),
3695
3952
  deps.now,
3696
3953
  latest2
3697
3954
  ).catch(() => void 0);
@@ -3722,10 +3979,10 @@ async function updateCliWith(deps) {
3722
3979
  };
3723
3980
  }
3724
3981
  function getCurrentVersion() {
3725
- const dirname = path19.dirname(fileURLToPath3(import.meta.url));
3982
+ const dirname = path20.dirname(fileURLToPath3(import.meta.url));
3726
3983
  const require3 = createRequire2(import.meta.url);
3727
3984
  try {
3728
- const pkg = require3(path19.resolve(dirname, "../package.json"));
3985
+ const pkg = require3(path20.resolve(dirname, "../package.json"));
3729
3986
  return pkg.version ?? "0.0.0";
3730
3987
  } catch {
3731
3988
  return "0.0.0";
@@ -4085,11 +4342,11 @@ function buildProgram(deps) {
4085
4342
  }
4086
4343
 
4087
4344
  // src/index.ts
4088
- var __dirname3 = path20.dirname(fileURLToPath4(import.meta.url));
4345
+ var __dirname3 = path21.dirname(fileURLToPath4(import.meta.url));
4089
4346
  var require2 = createRequire3(import.meta.url);
4090
4347
  function getVersion() {
4091
4348
  try {
4092
- const pkgPath = path20.resolve(__dirname3, "../package.json");
4349
+ const pkgPath = path21.resolve(__dirname3, "../package.json");
4093
4350
  const pkg = require2(pkgPath);
4094
4351
  return pkg.version ?? "0.0.0";
4095
4352
  } catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nolto/cli",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "description": "CLI for syncing repository roadmaps with Nolto.",
5
5
  "license": "MIT",
6
6
  "type": "module",