@nolto/cli 0.13.2 → 0.15.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.
package/dist/index.js CHANGED
@@ -15,16 +15,20 @@ import { z } from "zod";
15
15
 
16
16
  // src/errors.ts
17
17
  var CliError = class extends Error {
18
- constructor(message, exitCode, hint, status) {
18
+ constructor(message, exitCode, hint, status, serverError, body) {
19
19
  super(message);
20
20
  this.exitCode = exitCode;
21
21
  this.hint = hint;
22
22
  this.status = status;
23
+ this.serverError = serverError;
24
+ this.body = body;
23
25
  this.name = "CliError";
24
26
  }
25
27
  exitCode;
26
28
  hint;
27
29
  status;
30
+ serverError;
31
+ body;
28
32
  };
29
33
  function mapHttpStatusToCliError(status, opts = {}) {
30
34
  if (status === 401) {
@@ -33,7 +37,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
33
37
  `Unauthorized${detail}`,
34
38
  3,
35
39
  "Run `nolto init` to configure a token, or set the NOLTO_TOKEN environment variable.",
36
- status
40
+ status,
41
+ opts.serverError,
42
+ opts.body
37
43
  );
38
44
  }
39
45
  if (status === 426) {
@@ -41,7 +47,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
41
47
  opts.serverMessage ?? "Nolto CLI is outdated.",
42
48
  2,
43
49
  "Run `nolto update`, then retry.",
44
- status
50
+ status,
51
+ opts.serverError,
52
+ opts.body
45
53
  );
46
54
  }
47
55
  if (status === 409 && opts.serverError === "repo_unbound") {
@@ -49,7 +57,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
49
57
  opts.serverMessage ?? "This project is not bound to a repository.",
50
58
  2,
51
59
  "Ask the project owner to run nolto sync in the correct repository first.",
52
- status
60
+ status,
61
+ opts.serverError,
62
+ opts.body
53
63
  );
54
64
  }
55
65
  if (status === 409 && opts.serverError === "repo_mismatch") {
@@ -57,7 +67,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
57
67
  opts.serverMessage ?? "This project is bound to a different repository.",
58
68
  2,
59
69
  "Check that nolto.json points to the project for this repository (nolto link --show). Owner: run `nolto link --rebind` inside the repository that should own this project.",
60
- status
70
+ status,
71
+ opts.serverError,
72
+ opts.body
61
73
  );
62
74
  }
63
75
  if (status === 409 && opts.serverError === "roadmap_conflict") {
@@ -66,7 +78,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
66
78
  (opts.serverMessage ?? "The roadmap on the server is newer than this checkout.") + stored,
67
79
  2,
68
80
  "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
81
+ status,
82
+ opts.serverError,
83
+ opts.body
70
84
  );
71
85
  }
72
86
  if (status === 409 && opts.serverError === "project_archived") {
@@ -74,7 +88,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
74
88
  opts.serverMessage ?? "This project is archived.",
75
89
  2,
76
90
  "\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
91
+ status,
92
+ opts.serverError,
93
+ opts.body
78
94
  );
79
95
  }
80
96
  if (status === 429 && opts.serverError === "rebind_cooldown") {
@@ -82,7 +98,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
82
98
  opts.serverMessage ?? "Rebind cooldown active.",
83
99
  4,
84
100
  void 0,
85
- status
101
+ status,
102
+ opts.serverError,
103
+ opts.body
86
104
  );
87
105
  }
88
106
  if (status === 402) {
@@ -91,22 +109,26 @@ function mapHttpStatusToCliError(status, opts = {}) {
91
109
  opts.serverMessage ?? opts.serverError ?? "Payment Required",
92
110
  4,
93
111
  hint,
94
- status
112
+ status,
113
+ opts.serverError,
114
+ opts.body
95
115
  );
96
116
  }
97
117
  if (status === 404 && opts.serverError) {
98
- return new CliError(opts.serverError, 2, void 0, status);
118
+ return new CliError(opts.serverError, 2, void 0, status, opts.serverError, opts.body);
99
119
  }
100
120
  if (status === 422) {
101
121
  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);
122
+ return new CliError([opts.serverError ?? opts.serverMessage ?? "Validation failed", details].filter(Boolean).join("\n"), 2, void 0, status, opts.serverError, opts.body);
103
123
  }
104
124
  if (status === 403 && (opts.serverError === "token_scope" || opts.serverError === "token_project")) {
105
125
  return new CliError(
106
126
  opts.serverMessage ?? opts.serverError,
107
127
  3,
108
128
  `Issue a token with the required scope at ${opts.baseUrl ?? "https://nolto.app"}/settings/tokens (nolto whoami shows the current scopes).`,
109
- status
129
+ status,
130
+ opts.serverError,
131
+ opts.body
110
132
  );
111
133
  }
112
134
  if (status === 403) {
@@ -114,15 +136,17 @@ function mapHttpStatusToCliError(status, opts = {}) {
114
136
  opts.serverMessage ?? opts.serverError ?? "Forbidden",
115
137
  3,
116
138
  "Check that your token belongs to a member of this project (`nolto whoami`).",
117
- status
139
+ status,
140
+ opts.serverError,
141
+ opts.body
118
142
  );
119
143
  }
120
144
  if (status === 429) {
121
145
  const waitMsg = opts.retryAfter ? ` Retry-After: ${opts.retryAfter}s` : "";
122
- return new CliError(`${opts.serverMessage ?? "Rate limit exceeded."}${waitMsg}`, 4, void 0, status);
146
+ return new CliError(`${opts.serverMessage ?? "Rate limit exceeded."}${waitMsg}`, 4, void 0, status, opts.serverError, opts.body);
123
147
  }
124
148
  const reason = opts.serverMessage ?? opts.serverError;
125
- return new CliError(reason ? `Server returned HTTP ${status}: ${reason}` : `Server returned HTTP ${status}`, 5, void 0, status);
149
+ return new CliError(reason ? `Server returned HTTP ${status}: ${reason}` : `Server returned HTTP ${status}`, 5, void 0, status, opts.serverError, opts.body);
126
150
  }
127
151
  function isNetworkError(err) {
128
152
  if (!(err instanceof Error)) {
@@ -230,6 +254,7 @@ async function writeRepoBinding(root, projectId) {
230
254
  await mergeJsonFile(path.join(root, "nolto.json"), { projectId });
231
255
  }
232
256
  function getConfigDir(env) {
257
+ if (env["NOLTO_HOME"]) return env["NOLTO_HOME"];
233
258
  const xdg = env["XDG_CONFIG_HOME"];
234
259
  const base = xdg != null && xdg.length > 0 ? xdg : path.join(os.homedir(), ".config");
235
260
  return path.join(base, "nolto");
@@ -388,6 +413,7 @@ function createHttpClient(opts) {
388
413
  }
389
414
  throw mapHttpStatusToCliError(response.status, {
390
415
  baseUrl: base,
416
+ body: errorBody,
391
417
  details: errorBody?.["details"],
392
418
  retryAfter,
393
419
  wwwAuthenticate,
@@ -499,6 +525,9 @@ function normalizeRemote(raw) {
499
525
  if (HOSTED_LOWERCASE_PATH.has(host)) path21 = path21.toLowerCase();
500
526
  return `${host}/${path21}`;
501
527
  }
528
+ function repoIdentityToString(id) {
529
+ return `${id.kind}:${id.value}`;
530
+ }
502
531
 
503
532
  // ../roadmap-schema/src/index.ts
504
533
  var STATUSES = /* @__PURE__ */ new Set(["todo", "in-progress", "done", "blocked"]);
@@ -585,10 +614,10 @@ function validateRoadmap(value) {
585
614
  const warnings = [];
586
615
  if (!isRecord(value)) return { errors: ["Root must be an object."], warnings };
587
616
  checkKeys(value, ALLOWED_KEYS.roadmap, "roadmap", errors);
588
- if (value["schemaVersion"] !== 1 && value["schemaVersion"] !== 2) {
589
- errors.push("schemaVersion must be 1 or 2.");
617
+ if (value["schemaVersion"] !== 1 && value["schemaVersion"] !== 2 && value["schemaVersion"] !== 3) {
618
+ errors.push("schemaVersion must be 1, 2 or 3.");
590
619
  } else if (value["schemaVersion"] === 1) {
591
- warnings.push("schemaVersion 1 is legacy; the next roadmap-progress mutation migrates this file to 2.");
620
+ warnings.push("schemaVersion 1 is legacy; the next roadmap-progress mutation migrates this file to 3.");
592
621
  }
593
622
  const project = value["project"];
594
623
  checkKeys(project, ALLOWED_KEYS.project, "project", errors);
@@ -596,7 +625,9 @@ function validateRoadmap(value) {
596
625
  if (typeof projectRecord["id"] !== "string" || !ID_PATTERN.test(projectRecord["id"])) errors.push("project.id is invalid.");
597
626
  if (typeof projectRecord["name"] !== "string" || projectRecord["name"].length === 0) errors.push("project.name must be a non-empty string.");
598
627
  if (typeof projectRecord["repository"] !== "string" || projectRecord["repository"].length === 0) errors.push("project.repository must be a non-empty string.");
599
- errors.push(...validateDateTime(value["updatedAt"], "updatedAt"));
628
+ if (value["schemaVersion"] !== 3 || value["updatedAt"] !== void 0) {
629
+ errors.push(...validateDateTime(value["updatedAt"], "updatedAt"));
630
+ }
600
631
  if (typeof value["summary"] !== "string") errors.push("summary must be a string.");
601
632
  if (!Array.isArray(value["phases"])) errors.push("phases must be an array.");
602
633
  const allIds = /* @__PURE__ */ new Set();
@@ -723,6 +754,33 @@ function deriveTaskStats(roadmap) {
723
754
  progressPct: total > 0 ? Math.round(done / total * 100) : 0
724
755
  };
725
756
  }
757
+ function serializeRoadmap(roadmap) {
758
+ const ordered = {
759
+ schemaVersion: roadmap.schemaVersion,
760
+ project: { id: roadmap.project.id, name: roadmap.project.name, repository: roadmap.project.repository },
761
+ updatedAt: roadmap.updatedAt,
762
+ currentTaskId: roadmap.currentTaskId,
763
+ summary: roadmap.summary,
764
+ phases: roadmap.phases.map((phase) => ({
765
+ id: phase.id,
766
+ title: phase.title,
767
+ status: phase.status,
768
+ plan: phase.plan,
769
+ tasks: phase.tasks.map((task) => ({
770
+ id: task.id,
771
+ title: task.title,
772
+ status: task.status,
773
+ startedAt: task.startedAt,
774
+ completedAt: task.completedAt,
775
+ note: task.note,
776
+ plan: task.plan,
777
+ dependsOn: task.dependsOn,
778
+ issues: task.issues
779
+ }))
780
+ }))
781
+ };
782
+ return JSON.stringify(ordered, null, 2) + "\n";
783
+ }
726
784
 
727
785
  // src/issue-core.ts
728
786
  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);
@@ -983,31 +1041,309 @@ import readline2 from "readline/promises";
983
1041
  import { createRequire } from "module";
984
1042
  import { fileURLToPath as fileURLToPath2 } from "url";
985
1043
  import os3 from "os";
986
- import path10 from "path";
1044
+ import path11 from "path";
987
1045
  import fs from "fs";
988
1046
 
1047
+ // src/roadmap-bootstrap.ts
1048
+ import { existsSync } from "fs";
1049
+ import { readFile as readFile4, realpath } from "fs/promises";
1050
+ import path5 from "path";
1051
+
1052
+ // src/roadmap-cache.ts
1053
+ 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";
1056
+
1057
+ // src/sync-core.ts
1058
+ import { createHash } from "crypto";
1059
+ import path3 from "path";
1060
+ function sha256Hex(content) {
1061
+ return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1062
+ }
1063
+ function collectPlanRefs(roadmap) {
1064
+ const seen = /* @__PURE__ */ new Set();
1065
+ const refs = [];
1066
+ for (const phase of roadmap.phases) {
1067
+ if (phase.plan != null && !seen.has(phase.plan)) {
1068
+ seen.add(phase.plan);
1069
+ refs.push({ path: phase.plan, ownerId: phase.id });
1070
+ }
1071
+ for (const task of phase.tasks) {
1072
+ if (task.plan != null && !seen.has(task.plan)) {
1073
+ seen.add(task.plan);
1074
+ refs.push({ path: task.plan, ownerId: task.id });
1075
+ }
1076
+ }
1077
+ }
1078
+ return refs;
1079
+ }
1080
+ async function loadValidRoadmap(filePath, readFile13) {
1081
+ let raw;
1082
+ try {
1083
+ raw = await readFile13(filePath);
1084
+ } catch {
1085
+ throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1086
+ }
1087
+ let parsed;
1088
+ try {
1089
+ parsed = JSON.parse(raw);
1090
+ } catch {
1091
+ throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1092
+ }
1093
+ const { errors } = validateRoadmap(parsed);
1094
+ if (errors.length > 0) {
1095
+ throw new CliError(
1096
+ `${filePath} failed validation \u2014 not syncing:
1097
+ ${errors.join("\n ")}`,
1098
+ 2
1099
+ );
1100
+ }
1101
+ return parsed;
1102
+ }
1103
+ async function buildSyncBody(args) {
1104
+ const planDocuments = [];
1105
+ for (const ref of collectPlanRefs(args.roadmap)) {
1106
+ const root = path3.resolve(args.repoRoot);
1107
+ const absolute = path3.resolve(root, ref.path);
1108
+ if (absolute !== root && !absolute.startsWith(root + path3.sep)) {
1109
+ args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1110
+ continue;
1111
+ }
1112
+ if (!args.deps.fileExists(absolute)) {
1113
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1114
+ continue;
1115
+ }
1116
+ if (args.deps.realpath !== void 0) {
1117
+ let real;
1118
+ let realRoot;
1119
+ try {
1120
+ real = await args.deps.realpath(absolute);
1121
+ realRoot = await args.deps.realpath(root);
1122
+ } catch {
1123
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1124
+ continue;
1125
+ }
1126
+ if (real !== realRoot && !real.startsWith(realRoot + path3.sep)) {
1127
+ args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1128
+ continue;
1129
+ }
1130
+ }
1131
+ const content = await args.deps.readFile(absolute);
1132
+ planDocuments.push({
1133
+ path: ref.path,
1134
+ taskId: ref.ownerId,
1135
+ content,
1136
+ contentHash: sha256Hex(content)
1137
+ });
1138
+ }
1139
+ return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1140
+ }
1141
+ async function runSync(args, deps) {
1142
+ const body = await buildSyncBody({
1143
+ roadmap: args.roadmap,
1144
+ repoRoot: args.repoRoot,
1145
+ repoIdentity: args.repoIdentity,
1146
+ deps
1147
+ });
1148
+ const response = await deps.http.put(
1149
+ `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1150
+ { ...body, baseRevision: args.baseRevision }
1151
+ );
1152
+ for (const warning of response.warnings ?? []) deps.warn(warning);
1153
+ const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1154
+ deps.log(
1155
+ `Synced ${args.slug}${response.merged ? " (merged with server changes)" : ""}: ${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})` : ""}`
1156
+ );
1157
+ return response;
1158
+ }
1159
+
1160
+ // src/roadmap-cache.ts
1161
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1162
+ var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1163
+ function cacheDir(env, projectId) {
1164
+ if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1165
+ return path4.join(getConfigDir(env), "projects", projectId, "roadmaps");
1166
+ }
1167
+ function cachePaths(env, projectId, slug) {
1168
+ if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1169
+ const dir = cacheDir(env, projectId);
1170
+ return { json: path4.join(dir, `${slug}.json`), meta: path4.join(dir, `${slug}.meta.json`) };
1171
+ }
1172
+ async function listCachedSlugs(env, projectId) {
1173
+ try {
1174
+ const entries = await readdir2(cacheDir(env, projectId), { withFileTypes: true });
1175
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
1176
+ } catch (err) {
1177
+ if (err.code === "ENOENT") return [];
1178
+ throw err;
1179
+ }
1180
+ }
1181
+ async function readCache(env, projectId, slug) {
1182
+ const paths = cachePaths(env, projectId, slug);
1183
+ let raw;
1184
+ try {
1185
+ raw = await readFile3(paths.json, "utf8");
1186
+ } catch (err) {
1187
+ if (err.code === "ENOENT") return null;
1188
+ throw err;
1189
+ }
1190
+ let roadmap;
1191
+ try {
1192
+ roadmap = JSON.parse(raw);
1193
+ } catch {
1194
+ throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
1195
+ }
1196
+ const { errors } = validateRoadmap(roadmap);
1197
+ if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1198
+ let meta = null;
1199
+ try {
1200
+ const parsed = JSON.parse(await readFile3(paths.meta, "utf8"));
1201
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !("revision" in parsed) || !Number.isSafeInteger(parsed.revision) || Number(parsed.revision) < 0 || !("pulledAt" in parsed) || typeof parsed.pulledAt !== "string" || !("contentHash" in parsed) || typeof parsed.contentHash !== "string") {
1202
+ throw new Error("Invalid cache metadata");
1203
+ }
1204
+ if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
1205
+ throw new Error("Invalid currentTaskId");
1206
+ }
1207
+ if ("repoIdentity" in parsed && parsed.repoIdentity !== null && typeof parsed.repoIdentity !== "string") {
1208
+ throw new Error("Invalid repoIdentity");
1209
+ }
1210
+ meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null, repoIdentity: parsed.repoIdentity ?? null };
1211
+ } catch (err) {
1212
+ if (err.code !== "ENOENT") {
1213
+ throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
1214
+ }
1215
+ }
1216
+ return { roadmap, meta, raw };
1217
+ }
1218
+ async function writeCache(env, projectId, slug, roadmap, meta) {
1219
+ const paths = cachePaths(env, projectId, slug);
1220
+ const raw = serializeRoadmap(roadmap);
1221
+ const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
1222
+ await mkdir2(cacheDir(env, projectId), { recursive: true, mode: 448 });
1223
+ for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1224
+ const temp = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1225
+ try {
1226
+ await writeFile3(temp, content, { mode: 384 });
1227
+ await rename2(temp, filePath);
1228
+ } finally {
1229
+ await unlink(temp).catch(() => void 0);
1230
+ }
1231
+ }
1232
+ }
1233
+ function isDirty(entry) {
1234
+ return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
1235
+ }
1236
+
1237
+ // src/roadmap-scaffold.ts
1238
+ function slugifyProjectId(name) {
1239
+ const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1240
+ return slug.length > 0 ? slug : "project";
1241
+ }
1242
+ function buildScaffold(projectName, repoBasename) {
1243
+ return {
1244
+ schemaVersion: 3,
1245
+ project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
1246
+ summary: "",
1247
+ phases: []
1248
+ };
1249
+ }
1250
+
1251
+ // src/roadmap-bootstrap.ts
1252
+ async function pullRoadmapCache(args) {
1253
+ const { env, projectId, slug } = args;
1254
+ const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
1255
+ const validation = validateRoadmap(response.roadmap);
1256
+ if (validation.errors.length > 0) {
1257
+ throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
1258
+ }
1259
+ let existing;
1260
+ try {
1261
+ existing = await readCache(env, projectId, slug);
1262
+ } catch (err) {
1263
+ if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
1264
+ existing = null;
1265
+ }
1266
+ if (existing && isDirty(existing) && !args.force) {
1267
+ args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1268
+ return false;
1269
+ }
1270
+ const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
1271
+ await writeCache(env, projectId, slug, response.roadmap, {
1272
+ revision: response.revision,
1273
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
1274
+ currentTaskId: response.currentTaskId,
1275
+ repoIdentity: response.repoIdentity ?? null
1276
+ });
1277
+ args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
1278
+ return true;
1279
+ }
1280
+ async function ensureRoadmapCache(args) {
1281
+ const { env, projectId } = args;
1282
+ const identity = repoIdentityToString(args.repoIdentity);
1283
+ const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1284
+ const warn2 = (line) => {
1285
+ process.stderr.write(line + "\n");
1286
+ };
1287
+ const log = (line) => args.log(`roadmap: ${line}`);
1288
+ if (list.roadmaps.length > 0) {
1289
+ let skipped = false;
1290
+ for (const { slug: slug2 } of list.roadmaps) {
1291
+ if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
1292
+ }
1293
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1294
+ if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1295
+ }
1296
+ const basename = path5.basename(args.repoRoot);
1297
+ const slug = args.slug ?? slugifyProjectId(basename);
1298
+ const collision = list.roadmaps.find((row) => row.slug === slug);
1299
+ 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);
1300
+ let existing;
1301
+ try {
1302
+ existing = await readCache(env, projectId, slug);
1303
+ } catch (err) {
1304
+ if (!(err instanceof CliError)) throw err;
1305
+ existing = null;
1306
+ }
1307
+ if (existing && isDirty(existing)) {
1308
+ warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1309
+ throw new CliError("Roadmap has local changes that are not synced.", 4);
1310
+ }
1311
+ const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
1312
+ await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1313
+ const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1314
+ http: args.http,
1315
+ readFile: (p) => readFile4(p, "utf8"),
1316
+ realpath,
1317
+ fileExists: existsSync,
1318
+ log: () => void 0,
1319
+ warn: warn2
1320
+ });
1321
+ 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 });
1322
+ log(`created ${slug} on server (rev ${response.revision})`);
1323
+ }
1324
+
989
1325
  // src/commands/link.ts
990
1326
  import readline from "readline/promises";
991
1327
  import os2 from "os";
992
- import path6 from "path";
1328
+ import path9 from "path";
993
1329
  import { statSync as statSync2 } from "fs";
994
1330
 
995
1331
  // src/registry.ts
996
- import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir2, rename as rename2, unlink } from "fs/promises";
997
- import { randomUUID as randomUUID2 } from "crypto";
998
- import path3 from "path";
1332
+ import { readFile as readFile5, writeFile as writeFile4, mkdir as mkdir3, rename as rename3, unlink as unlink2 } from "fs/promises";
1333
+ import { randomUUID as randomUUID3 } from "crypto";
1334
+ import path6 from "path";
999
1335
  import { z as z2 } from "zod";
1000
1336
  var registrySchema = z2.object({
1001
1337
  schemaVersion: z2.literal(1),
1002
- repos: z2.array(z2.object({ root: z2.string().min(1) }).passthrough())
1338
+ repos: z2.array(z2.object({ root: z2.string().min(1), projectId: z2.string().uuid().optional() }).passthrough())
1003
1339
  }).passthrough();
1004
1340
  function getRegistryPath(env) {
1005
- return path3.join(getConfigDir(env), "registry.json");
1341
+ return path6.join(getConfigDir(env), "registry.json");
1006
1342
  }
1007
1343
  async function loadRegistry(filePath) {
1008
1344
  let raw;
1009
1345
  try {
1010
- raw = await readFile3(filePath, "utf8");
1346
+ raw = await readFile5(filePath, "utf8");
1011
1347
  } catch (err) {
1012
1348
  const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1013
1349
  if (code === "ENOENT") {
@@ -1032,33 +1368,37 @@ async function loadRegistry(filePath) {
1032
1368
  }
1033
1369
  return result.data;
1034
1370
  }
1035
- async function addRepoToRegistry(filePath, repoRoot) {
1371
+ async function addRepoToRegistry(filePath, entry) {
1036
1372
  const registry = await loadRegistry(filePath);
1037
- if (registry.repos.some((repo) => repo.root === repoRoot)) {
1038
- return { added: false, registry };
1373
+ const existing = registry.repos.find((repo) => repo.root === entry.root);
1374
+ if (existing?.projectId === entry.projectId) {
1375
+ return { added: false, updated: false, registry };
1039
1376
  }
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()}`;
1377
+ const updated = {
1378
+ ...registry,
1379
+ repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
1380
+ };
1381
+ await mkdir3(path6.dirname(filePath), { recursive: true, mode: 448 });
1382
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1043
1383
  try {
1044
- await writeFile3(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1045
- await rename2(tempPath, filePath);
1384
+ await writeFile4(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1385
+ await rename3(tempPath, filePath);
1046
1386
  } catch (err) {
1047
- await unlink(tempPath).catch(() => void 0);
1387
+ await unlink2(tempPath).catch(() => void 0);
1048
1388
  throw err;
1049
1389
  }
1050
- return { added: true, registry: updated };
1390
+ return { added: !existing, updated: !!existing, registry: updated };
1051
1391
  }
1052
1392
 
1053
1393
  // src/repo-identity.ts
1054
1394
  import { execFile } from "child_process";
1055
1395
  import { realpathSync } from "fs";
1056
- import path5 from "path";
1396
+ import path8 from "path";
1057
1397
 
1058
1398
  // 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";
1399
+ import { chmod, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5 } from "fs/promises";
1400
+ import { randomUUID as randomUUID4 } from "crypto";
1401
+ import path7 from "path";
1062
1402
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
1063
1403
  function parseMachineId(raw, file) {
1064
1404
  let parsed;
@@ -1074,10 +1414,10 @@ function parseMachineId(raw, file) {
1074
1414
  return id;
1075
1415
  }
1076
1416
  async function loadOrCreate(configDir) {
1077
- const file = path4.join(configDir, "machine.json");
1417
+ const file = path7.join(configDir, "machine.json");
1078
1418
  let raw = null;
1079
1419
  try {
1080
- raw = await readFile4(file, "utf8");
1420
+ raw = await readFile6(file, "utf8");
1081
1421
  } catch (err) {
1082
1422
  const code = err.code;
1083
1423
  if (code !== "ENOENT") {
@@ -1087,17 +1427,17 @@ async function loadOrCreate(configDir) {
1087
1427
  if (raw !== null) {
1088
1428
  return parseMachineId(raw, file);
1089
1429
  }
1090
- const machineId = randomUUID3();
1091
- await mkdir3(configDir, { recursive: true, mode: 448 });
1430
+ const machineId = randomUUID4();
1431
+ await mkdir4(configDir, { recursive: true, mode: 448 });
1092
1432
  try {
1093
- await writeFile4(file, `${JSON.stringify({ machineId }, null, 2)}
1433
+ await writeFile5(file, `${JSON.stringify({ machineId }, null, 2)}
1094
1434
  `, {
1095
1435
  flag: "wx",
1096
1436
  mode: 384
1097
1437
  });
1098
1438
  } catch (err) {
1099
1439
  if (err.code === "EEXIST") {
1100
- return parseMachineId(await readFile4(file, "utf8"), file);
1440
+ return parseMachineId(await readFile6(file, "utf8"), file);
1101
1441
  }
1102
1442
  throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1103
1443
  }
@@ -1105,7 +1445,7 @@ async function loadOrCreate(configDir) {
1105
1445
  return machineId;
1106
1446
  }
1107
1447
  function loadOrCreateMachineId(configDir) {
1108
- const key = path4.resolve(configDir);
1448
+ const key = path7.resolve(configDir);
1109
1449
  const existing = inFlightByConfigDir.get(key);
1110
1450
  if (existing !== void 0) return existing;
1111
1451
  const pending = loadOrCreate(key).finally(() => {
@@ -1139,7 +1479,7 @@ async function resolveRepoIdentity(root, deps) {
1139
1479
  try {
1140
1480
  canonicalRoot = realpathSync(root);
1141
1481
  } catch {
1142
- canonicalRoot = path5.resolve(root);
1482
+ canonicalRoot = path8.resolve(root);
1143
1483
  }
1144
1484
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1145
1485
  }
@@ -1151,14 +1491,14 @@ function makeRepoIdentityResolver(deps) {
1151
1491
  }
1152
1492
 
1153
1493
  // src/commands/link.ts
1154
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1494
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1155
1495
  function resolveStartDir(env, cwd) {
1156
1496
  const cpd = env["CLAUDE_PROJECT_DIR"];
1157
1497
  return cpd != null && cpd.length > 0 ? cpd : cwd;
1158
1498
  }
1159
1499
  function dirHasGit(dir) {
1160
1500
  try {
1161
- statSync2(path6.join(dir, ".git"));
1501
+ statSync2(path9.join(dir, ".git"));
1162
1502
  return true;
1163
1503
  } catch {
1164
1504
  return false;
@@ -1170,14 +1510,14 @@ function findRepoRoot(startDir, hasGit = dirHasGit) {
1170
1510
  if (hasGit(current)) {
1171
1511
  return { root: current, foundGit: true };
1172
1512
  }
1173
- const parent = path6.dirname(current);
1513
+ const parent = path9.dirname(current);
1174
1514
  if (parent === current) break;
1175
1515
  current = parent;
1176
1516
  }
1177
1517
  return { root: startDir, foundGit: false };
1178
1518
  }
1179
1519
  function isHomeDirectory(dir, home = os2.homedir()) {
1180
- return path6.resolve(dir) === path6.resolve(home);
1520
+ return path9.resolve(dir) === path9.resolve(home);
1181
1521
  }
1182
1522
  async function handleShow(deps, projectBindingPath, mode2) {
1183
1523
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1223,7 +1563,7 @@ async function handleShow(deps, projectBindingPath, mode2) {
1223
1563
  }
1224
1564
  }
1225
1565
  async function handleRebind(deps, projectId, root, mode2, yes) {
1226
- if (!UUID_RE.test(projectId)) {
1566
+ if (!UUID_RE2.test(projectId)) {
1227
1567
  throw new CliError(
1228
1568
  `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1229
1569
  2
@@ -1276,7 +1616,7 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1276
1616
  }
1277
1617
  }
1278
1618
  async function handleUnlink(projectBindingPath, mode2) {
1279
- const { readFile: readFile13, writeFile: writeFile11, chmod: chmod2 } = await import("fs/promises");
1619
+ const { readFile: readFile13, writeFile: writeFile10, chmod: chmod2 } = await import("fs/promises");
1280
1620
  let existing = {};
1281
1621
  try {
1282
1622
  const raw = await readFile13(projectBindingPath, "utf8");
@@ -1294,7 +1634,7 @@ async function handleUnlink(projectBindingPath, mode2) {
1294
1634
  }
1295
1635
  const { projectId: _removed, ...rest } = existing;
1296
1636
  void _removed;
1297
- await writeFile11(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1637
+ await writeFile10(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1298
1638
  await chmod2(projectBindingPath, 420);
1299
1639
  if (mode2 === "json") {
1300
1640
  printResult({ unlinked: true, projectBindingPath }, mode2);
@@ -1303,8 +1643,8 @@ async function handleUnlink(projectBindingPath, mode2) {
1303
1643
  `);
1304
1644
  }
1305
1645
  }
1306
- async function performLink(deps, projectId, mode2) {
1307
- if (!UUID_RE.test(projectId)) {
1646
+ async function performLink(deps, projectId, mode2, slug) {
1647
+ if (!UUID_RE2.test(projectId)) {
1308
1648
  throw new CliError(
1309
1649
  `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1310
1650
  2
@@ -1318,17 +1658,19 @@ async function performLink(deps, projectId, mode2) {
1318
1658
  `
1319
1659
  );
1320
1660
  }
1661
+ const http = deps.http ?? createHttpClient({
1662
+ baseUrl: deps.settings.baseUrl,
1663
+ token: deps.settings.token,
1664
+ version: deps.version
1665
+ });
1666
+ let projectName = path9.basename(root);
1321
1667
  if (deps.settings.token != null) {
1322
1668
  try {
1323
- const http = deps.http ?? createHttpClient({
1324
- baseUrl: deps.settings.baseUrl,
1325
- token: deps.settings.token,
1326
- version: deps.version
1327
- });
1328
1669
  const result = await http.get(
1329
1670
  "/api/projects"
1330
1671
  );
1331
1672
  const projects = Array.isArray(result.projects) ? result.projects : [];
1673
+ projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
1332
1674
  if (!projects.some((p) => p.id === projectId)) {
1333
1675
  process.stderr.write(
1334
1676
  `Warning: project ${projectId} was not found in GET /api/projects.
@@ -1349,14 +1691,30 @@ Proceeding anyway \u2014 verify the ID is correct.
1349
1691
  );
1350
1692
  }
1351
1693
  await writeRepoBinding(root, projectId);
1352
- const writtenPath = path6.join(root, "nolto.json");
1694
+ const writtenPath = path9.join(root, "nolto.json");
1695
+ if (deps.settings.token == null) {
1696
+ process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
1697
+ } else {
1698
+ await ensureRoadmapCache({
1699
+ env: process.env,
1700
+ http,
1701
+ projectId,
1702
+ projectName,
1703
+ repoRoot: root,
1704
+ slug,
1705
+ repoIdentity: await makeRepoIdentityResolver(deps)(root),
1706
+ log: (line) => {
1707
+ if (mode2 !== "json") process.stdout.write(line + "\n");
1708
+ }
1709
+ });
1710
+ }
1353
1711
  let registryAdded = false;
1354
1712
  if (isHomeDirectory(root)) {
1355
1713
  process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
1356
1714
  `);
1357
1715
  } else {
1358
1716
  try {
1359
- registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), root)).added;
1717
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
1360
1718
  } catch (err) {
1361
1719
  const message = err instanceof Error ? err.message : String(err);
1362
1720
  process.stderr.write(`Warning: could not update watch registry: ${message}
@@ -1384,8 +1742,8 @@ Commit nolto.json to share the binding with your team.
1384
1742
  }
1385
1743
  function register2(program, deps) {
1386
1744
  const cmd = program.command("link [projectId]").description(
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"
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");
1745
+ "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"
1746
+ ).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");
1389
1747
  cmd.action(async (projectId) => {
1390
1748
  const { output } = deps;
1391
1749
  const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
@@ -1405,6 +1763,56 @@ function register2(program, deps) {
1405
1763
  await handleUnlink(projectBindingPath, mode2);
1406
1764
  return;
1407
1765
  }
1766
+ const opts = cmd.opts();
1767
+ if (opts["list"] || opts["add"] || opts["remove"] !== void 0 || opts["slug"] !== void 0) {
1768
+ if (projectId == null) {
1769
+ if (bindingError != null) throw invalidBindingError(projectBindingPath, bindingError);
1770
+ const binding = deps.repoBinding?.binding ?? (projectBindingPath ? await loadRepoBinding(projectBindingPath) : null);
1771
+ projectId = binding?.projectId;
1772
+ }
1773
+ if (projectId == null) throw new CliError("No project binding. Run `nolto link <projectId>` first.", 2);
1774
+ if (!UUID_RE2.test(projectId)) throw new CliError(`Invalid project ID: "${projectId}". Must be a UUID.`, 2);
1775
+ if (opts["add"]) {
1776
+ const root = findRepoRoot(resolveStartDir(process.env, process.cwd())).root;
1777
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1778
+ const repo = await deps.http.post(`/api/projects/${projectId}/repos`, {
1779
+ repoIdentity,
1780
+ ...opts["label"] !== void 0 ? { label: opts["label"] } : {}
1781
+ });
1782
+ printResult(mode2 === "json" ? { added: true, projectId, repo } : `Added ${repoIdentity.kind}:${repoIdentity.value} to project ${projectId}.`, mode2);
1783
+ return;
1784
+ }
1785
+ if (opts["list"] || opts["remove"] !== void 0) {
1786
+ const { repos } = await deps.http.get(`/api/projects/${projectId}`);
1787
+ if (opts["list"]) {
1788
+ if (mode2 === "json") printResult({ repos }, mode2);
1789
+ else for (const repo2 of repos) printResult(`${repo2.identity}${repo2.label ? ` (${repo2.label})` : ""} ${repo2.boundAt} ${repo2.id}`, mode2);
1790
+ return;
1791
+ }
1792
+ const input = opts["remove"];
1793
+ const identity = /^(remote|local):/.test(input) ? input : `remote:${input}`;
1794
+ const repo = repos.find((row) => row.id === input || row.identity === identity);
1795
+ if (!repo) throw new CliError(`Repository ${input} is not bound to this project.`, 2);
1796
+ if (!opts["yes"]) {
1797
+ if (mode2 === "json") throw new CliError("--remove requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
1798
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1799
+ let confirmed = false;
1800
+ try {
1801
+ const answer = await rl.question(`Remove "${repo.identity}" from project ${projectId}? [y/N] `);
1802
+ confirmed = answer.trim().toLowerCase() === "y";
1803
+ } finally {
1804
+ rl.close();
1805
+ }
1806
+ if (!confirmed) {
1807
+ process.stdout.write("Aborted.\n");
1808
+ return;
1809
+ }
1810
+ }
1811
+ await deps.http.delete(`/api/projects/${projectId}/repos/${repo.id}`);
1812
+ printResult(mode2 === "json" ? { removed: true, projectId, repoId: repo.id } : `Removed ${repo.identity} from project ${projectId}.`, mode2);
1813
+ return;
1814
+ }
1815
+ }
1408
1816
  if (cmd.opts()["rebind"]) {
1409
1817
  const boundProjectId = deps.repoBinding?.binding?.projectId;
1410
1818
  const effectiveProjectId = projectId ?? boundProjectId;
@@ -1425,7 +1833,7 @@ function register2(program, deps) {
1425
1833
  2
1426
1834
  );
1427
1835
  }
1428
- await performLink(deps, projectId, mode2);
1836
+ await performLink(deps, projectId, mode2, opts["slug"]);
1429
1837
  });
1430
1838
  }
1431
1839
  function invalidBindingError(projectBindingPath, error) {
@@ -1436,35 +1844,35 @@ function invalidBindingError(projectBindingPath, error) {
1436
1844
  }
1437
1845
 
1438
1846
  // src/skill-install.ts
1439
- import { cp, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile5, rm as rm2 } from "fs/promises";
1440
- import { existsSync } from "fs";
1441
- import path7 from "path";
1847
+ import { cp, mkdir as mkdir5, readFile as readFile7, writeFile as writeFile6, rm as rm2 } from "fs/promises";
1848
+ import { existsSync as existsSync2 } from "fs";
1849
+ import path10 from "path";
1442
1850
  import { fileURLToPath } from "url";
1443
- var __dirname = path7.dirname(fileURLToPath(import.meta.url));
1851
+ var __dirname = path10.dirname(fileURLToPath(import.meta.url));
1444
1852
  function resolveSkillSourceDir() {
1445
1853
  const candidates = [
1446
- path7.resolve(__dirname, "skill/roadmap-progress"),
1854
+ path10.resolve(__dirname, "skill/roadmap-progress"),
1447
1855
  // bundled: dist/skill/...
1448
- path7.resolve(__dirname, "../../../skills/roadmap-progress")
1856
+ path10.resolve(__dirname, "../../../skills/roadmap-progress")
1449
1857
  // source: <repo>/skills/...
1450
1858
  ];
1451
1859
  for (const candidate of candidates) {
1452
- if (existsSync(path7.join(candidate, "SKILL.md"))) return candidate;
1860
+ if (existsSync2(path10.join(candidate, "SKILL.md"))) return candidate;
1453
1861
  }
1454
1862
  throw new Error("Bundled roadmap-progress skill not found. Reinstall @nolto/cli.");
1455
1863
  }
1456
1864
  var VERSION_MARKER = ".nolto-skill-version";
1457
1865
  async function checkSkillVersionDrift(repoRoot, cliVersion) {
1458
1866
  const skillDirs = [
1459
- path7.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1460
- path7.join(repoRoot, ".agents", "skills", "roadmap-progress")
1867
+ path10.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1868
+ path10.join(repoRoot, ".agents", "skills", "roadmap-progress")
1461
1869
  ];
1462
1870
  const drifted = [];
1463
1871
  for (const dir of skillDirs) {
1464
- if (!existsSync(dir)) continue;
1872
+ if (!existsSync2(dir)) continue;
1465
1873
  let installed;
1466
1874
  try {
1467
- const marker = (await readFile5(path7.join(dir, VERSION_MARKER), "utf8")).trim();
1875
+ const marker = (await readFile7(path10.join(dir, VERSION_MARKER), "utf8")).trim();
1468
1876
  installed = marker.length > 0 ? marker : null;
1469
1877
  } catch {
1470
1878
  installed = null;
@@ -1474,18 +1882,18 @@ async function checkSkillVersionDrift(repoRoot, cliVersion) {
1474
1882
  return drifted;
1475
1883
  }
1476
1884
  function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
1477
- const dirs = drifted.map(({ dir }) => path7.relative(repoRoot, dir).split(path7.sep).join("/")).join(", ");
1885
+ const dirs = drifted.map(({ dir }) => path10.relative(repoRoot, dir).split(path10.sep).join("/")).join(", ");
1478
1886
  const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
1479
1887
  return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
1480
1888
  }
1481
1889
  async function installSkill(args) {
1482
- const targetDir = path7.join(args.skillsParentDir, "roadmap-progress");
1483
- const markerPath = path7.join(targetDir, VERSION_MARKER);
1484
- const dirExists = existsSync(targetDir);
1890
+ const targetDir = path10.join(args.skillsParentDir, "roadmap-progress");
1891
+ const markerPath = path10.join(targetDir, VERSION_MARKER);
1892
+ const dirExists = existsSync2(targetDir);
1485
1893
  let installedVersion = null;
1486
1894
  if (dirExists) {
1487
1895
  try {
1488
- installedVersion = (await readFile5(markerPath, "utf8")).trim();
1896
+ installedVersion = (await readFile7(markerPath, "utf8")).trim();
1489
1897
  } catch {
1490
1898
  installedVersion = null;
1491
1899
  }
@@ -1494,104 +1902,20 @@ async function installSkill(args) {
1494
1902
  return { action: "skipped", targetDir };
1495
1903
  }
1496
1904
  await rm2(targetDir, { recursive: true, force: true });
1497
- await mkdir4(args.skillsParentDir, { recursive: true });
1905
+ await mkdir5(args.skillsParentDir, { recursive: true });
1498
1906
  await cp(args.sourceDir, targetDir, { recursive: true });
1499
- await writeFile5(markerPath, args.version + "\n", "utf8");
1907
+ await writeFile6(markerPath, args.version + "\n", "utf8");
1500
1908
  return { action: dirExists ? "updated" : "installed", targetDir };
1501
1909
  }
1502
1910
 
1503
- // src/roadmap-scaffold.ts
1504
- import { mkdir as mkdir5, readdir as readdir2, writeFile as writeFile6 } from "fs/promises";
1505
- import { existsSync as existsSync2 } from "fs";
1506
- import path8 from "path";
1507
- function slugifyProjectId(name) {
1508
- const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1509
- return slug.length > 0 ? slug : "project";
1510
- }
1511
- async function scaffoldRoadmap(args) {
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");
1516
- try {
1517
- const existing = (await readdir2(dir)).sort();
1518
- if (existing.length > 0) {
1519
- return { created: false, path: path8.join(dir, existing[0]) };
1520
- }
1521
- } catch (err) {
1522
- if (err == null || typeof err !== "object" || !("code" in err) || err.code !== "ENOENT") {
1523
- throw err;
1524
- }
1525
- }
1526
- if (existsSync2(legacyPath)) {
1527
- return { created: false, path: legacyPath };
1528
- }
1529
- const roadmap = {
1530
- schemaVersion: 2,
1531
- project: {
1532
- id: slugifyProjectId(repoBasename),
1533
- name: args.projectName,
1534
- repository: repoBasename
1535
- },
1536
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1537
- currentTaskId: null,
1538
- summary: "",
1539
- phases: []
1540
- };
1541
- await mkdir5(dir, { recursive: true });
1542
- await writeFile6(filePath, JSON.stringify(roadmap, null, 2) + "\n", "utf8");
1543
- return { created: true, path: filePath };
1544
- }
1545
-
1546
- // src/git-merge-driver.ts
1547
- import { execFile as execFile2 } from "child_process";
1548
- import { readFile as readFile6, writeFile as writeFile7 } from "fs/promises";
1549
- import path9 from "path";
1550
- import { promisify } from "util";
1551
- var ATTRIBUTE_LINE = ".nolto/roadmaps/*.json merge=nolto-roadmap";
1552
- var DRIVER_COMMAND = "nolto merge-file %A %B --base %O";
1553
- async function ensureGitAttributes(root) {
1554
- const filePath = path9.join(root, ".gitattributes");
1555
- let content = "";
1556
- try {
1557
- content = await readFile6(filePath, "utf8");
1558
- } catch (err) {
1559
- if (err.code !== "ENOENT") throw err;
1560
- }
1561
- if (content.split(/\r?\n/).includes(ATTRIBUTE_LINE)) return "exists";
1562
- const separator = content.length > 0 && !content.endsWith("\n") ? "\n" : "";
1563
- await writeFile7(filePath, content + separator + ATTRIBUTE_LINE + "\n", "utf8");
1564
- return "added";
1565
- }
1566
- async function configureMergeDriver(root, exec = async (file, args, options) => {
1567
- const execFileAsync = promisify(execFile2);
1568
- await execFileAsync(file, args, options);
1569
- }) {
1570
- try {
1571
- await exec(
1572
- "git",
1573
- ["config", "--local", "merge.nolto-roadmap.name", "Nolto roadmap merge"],
1574
- { cwd: root }
1575
- );
1576
- await exec(
1577
- "git",
1578
- ["config", "--local", "merge.nolto-roadmap.driver", DRIVER_COMMAND],
1579
- { cwd: root }
1580
- );
1581
- return "configured";
1582
- } catch {
1583
- return "skipped";
1584
- }
1585
- }
1586
-
1587
1911
  // src/commands/init.ts
1588
- var __dirname2 = path10.dirname(fileURLToPath2(import.meta.url));
1912
+ var __dirname2 = path11.dirname(fileURLToPath2(import.meta.url));
1589
1913
  var _require = createRequire(import.meta.url);
1590
1914
  function getCliVersion() {
1591
1915
  const candidates = [
1592
- path10.resolve(__dirname2, "../package.json"),
1916
+ path11.resolve(__dirname2, "../package.json"),
1593
1917
  // bundled: dist/../package.json
1594
- path10.resolve(__dirname2, "../../package.json")
1918
+ path11.resolve(__dirname2, "../../package.json")
1595
1919
  // source: src/commands/../../package.json
1596
1920
  ];
1597
1921
  for (const pkgPath of candidates) {
@@ -1752,7 +2076,7 @@ Saved ${configPath}
1752
2076
  }
1753
2077
  if (isHomeDirectory(root)) {
1754
2078
  process.stderr.write(
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.
2079
+ `Refusing to set up your home directory as a repository root (found ${path11.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
1756
2080
  `
1757
2081
  );
1758
2082
  return;
@@ -1784,7 +2108,7 @@ Saved ${configPath}
1784
2108
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
1785
2109
  );
1786
2110
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
1787
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path10.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
2111
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path11.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1788
2112
  } else {
1789
2113
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1790
2114
  }
@@ -1798,7 +2122,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1798
2122
  process.stdout.write("Skipped repo setup.\n");
1799
2123
  return;
1800
2124
  }
1801
- const bindingPath = deps.repoBinding?.path ?? path10.join(root, "nolto.json");
2125
+ const bindingPath = deps.repoBinding?.path ?? path11.join(root, "nolto.json");
1802
2126
  if (keepExistingBinding) {
1803
2127
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
1804
2128
  `);
@@ -1810,50 +2134,45 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1810
2134
  );
1811
2135
  }
1812
2136
  await writeRepoBinding(root, repoProject.id);
1813
- process.stdout.write(`binding: wrote ${path10.join(root, "nolto.json")}
2137
+ process.stdout.write(`binding: wrote ${path11.join(root, "nolto.json")}
1814
2138
  `);
1815
2139
  }
1816
2140
  const sourceDir = resolveSkillSourceDir();
1817
2141
  const version = getCliVersion();
1818
2142
  const claudeInstall = await installSkill({
1819
- skillsParentDir: path10.join(root, ".claude", "skills"),
2143
+ skillsParentDir: path11.join(root, ".claude", "skills"),
1820
2144
  sourceDir,
1821
2145
  version
1822
2146
  });
1823
2147
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
1824
2148
  `);
1825
- const usesAgentsTooling = fs.existsSync(path10.join(root, ".agents")) || fs.existsSync(path10.join(root, ".codex")) || fs.existsSync(path10.join(root, "AGENTS.md"));
2149
+ const usesAgentsTooling = fs.existsSync(path11.join(root, ".agents")) || fs.existsSync(path11.join(root, ".codex")) || fs.existsSync(path11.join(root, "AGENTS.md"));
1826
2150
  if (usesAgentsTooling) {
1827
2151
  const agentsInstall = await installSkill({
1828
- skillsParentDir: path10.join(root, ".agents", "skills"),
2152
+ skillsParentDir: path11.join(root, ".agents", "skills"),
1829
2153
  sourceDir,
1830
2154
  version
1831
2155
  });
1832
2156
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
1833
2157
  `);
1834
2158
  }
1835
- const scaffold = await scaffoldRoadmap({
2159
+ await ensureRoadmapCache({
2160
+ env: process.env,
2161
+ http: repoHttp,
2162
+ projectId: repoProject.id,
2163
+ projectName: repoProject.name,
1836
2164
  repoRoot: root,
1837
- projectName: repoProject.name
2165
+ repoIdentity: await makeRepoIdentityResolver(deps)(root),
2166
+ log: (line) => {
2167
+ process.stdout.write(line + "\n");
2168
+ }
1838
2169
  });
1839
- process.stdout.write(
1840
- scaffold.created ? `roadmap: created ${scaffold.path}
1841
- ` : `roadmap: exists ${scaffold.path}
1842
- `
1843
- );
1844
- const registryResult = await addRepoToRegistry(getRegistryPath(process.env), root);
2170
+ const registryResult = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId: repoProject.id });
1845
2171
  process.stdout.write(
1846
2172
  registryResult.added ? `watch registry: added ${root}
1847
2173
  ` : `watch registry: already registered
1848
2174
  `
1849
2175
  );
1850
- const attributesResult = await ensureGitAttributes(root);
1851
- process.stdout.write(`gitattributes: ${attributesResult} .gitattributes
1852
- `);
1853
- const mergeDriverResult = await configureMergeDriver(root, deps.gitMergeExec);
1854
- process.stdout.write(
1855
- mergeDriverResult === "configured" ? "merge driver: configured\n" : "merge driver: skipped (git unavailable)\n"
1856
- );
1857
2176
  } finally {
1858
2177
  rl.close();
1859
2178
  }
@@ -2085,10 +2404,29 @@ function register5(program, deps) {
2085
2404
  }
2086
2405
 
2087
2406
  // src/commands/sync.ts
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";
2091
- import { existsSync as existsSync3 } from "fs";
2407
+ import { execFile as execFile2 } from "child_process";
2408
+ import { promisify } from "util";
2409
+ import { readFile as readFile8, realpath as realpath2 } from "fs/promises";
2410
+ import { existsSync as existsSync3 } from "fs";
2411
+
2412
+ // src/roadmap-read.ts
2413
+ import path12 from "path";
2414
+ async function resolveRoadmapReadContext(deps) {
2415
+ if (deps.settings.token == null) {
2416
+ throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2417
+ }
2418
+ const startDir = resolveStartDir(process.env, process.cwd());
2419
+ const { root, foundGit } = findRepoRoot(startDir);
2420
+ if (!foundGit) {
2421
+ throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2422
+ }
2423
+ const binding = await loadRepoBinding(path12.join(root, "nolto.json"));
2424
+ const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2425
+ if (projectId == null) {
2426
+ throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
2427
+ }
2428
+ return { root, projectId };
2429
+ }
2092
2430
 
2093
2431
  // src/git-links.ts
2094
2432
  function parseGitLog(raw) {
@@ -2138,121 +2476,16 @@ async function collectGitLinks(root, exec) {
2138
2476
  }
2139
2477
 
2140
2478
  // src/sync-repo.ts
2141
- import path12 from "path";
2142
-
2143
- // src/sync-core.ts
2144
- import { createHash } from "crypto";
2145
- import path11 from "path";
2146
- function sha256Hex(content) {
2147
- return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
2148
- }
2149
- function collectPlanRefs(roadmap) {
2150
- const seen = /* @__PURE__ */ new Set();
2151
- const refs = [];
2152
- for (const phase of roadmap.phases) {
2153
- if (phase.plan != null && !seen.has(phase.plan)) {
2154
- seen.add(phase.plan);
2155
- refs.push({ path: phase.plan, ownerId: phase.id });
2156
- }
2157
- for (const task of phase.tasks) {
2158
- if (task.plan != null && !seen.has(task.plan)) {
2159
- seen.add(task.plan);
2160
- refs.push({ path: task.plan, ownerId: task.id });
2161
- }
2162
- }
2163
- }
2164
- return refs;
2165
- }
2166
- async function loadValidRoadmap(filePath, readFile13) {
2167
- let raw;
2168
- try {
2169
- raw = await readFile13(filePath);
2170
- } catch {
2171
- throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
2172
- }
2173
- let parsed;
2174
- try {
2175
- parsed = JSON.parse(raw);
2176
- } catch {
2177
- throw new CliError(`Malformed JSON in ${filePath}.`, 2);
2178
- }
2179
- const { errors } = validateRoadmap(parsed);
2180
- if (errors.length > 0) {
2181
- throw new CliError(
2182
- `${filePath} failed validation \u2014 not syncing:
2183
- ${errors.join("\n ")}`,
2184
- 2
2185
- );
2186
- }
2187
- return parsed;
2188
- }
2189
- async function buildSyncBody(args) {
2190
- const planDocuments = [];
2191
- for (const ref of collectPlanRefs(args.roadmap)) {
2192
- const root = path11.resolve(args.repoRoot);
2193
- const absolute = path11.resolve(root, ref.path);
2194
- if (absolute !== root && !absolute.startsWith(root + path11.sep)) {
2195
- args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
2196
- continue;
2197
- }
2198
- if (!args.deps.fileExists(absolute)) {
2199
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
2200
- continue;
2201
- }
2202
- if (args.deps.realpath !== void 0) {
2203
- let real;
2204
- let realRoot;
2205
- try {
2206
- real = await args.deps.realpath(absolute);
2207
- realRoot = await args.deps.realpath(root);
2208
- } catch {
2209
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
2210
- continue;
2211
- }
2212
- if (real !== realRoot && !real.startsWith(realRoot + path11.sep)) {
2213
- args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
2214
- continue;
2215
- }
2216
- }
2217
- const content = await args.deps.readFile(absolute);
2218
- planDocuments.push({
2219
- path: ref.path,
2220
- taskId: ref.ownerId,
2221
- content,
2222
- contentHash: sha256Hex(content)
2223
- });
2224
- }
2225
- return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
2226
- }
2227
- async function runSync(args, deps) {
2228
- const body = await buildSyncBody({
2229
- roadmap: args.roadmap,
2230
- repoRoot: args.repoRoot,
2231
- repoIdentity: args.repoIdentity,
2232
- deps
2233
- });
2234
- const response = await deps.http.put(
2235
- `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
2236
- body
2237
- );
2238
- for (const warning of response.warnings ?? []) deps.warn(warning);
2239
- const stats = deriveTaskStats(args.roadmap);
2240
- deps.log(
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})` : ""}`
2242
- );
2243
- return response;
2244
- }
2245
-
2246
- // src/sync-repo.ts
2247
- var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
2248
- function collectContainedPlanAbsPaths(roadmaps, root, warn) {
2479
+ import path13 from "path";
2480
+ import { readdir as readdir3 } from "fs/promises";
2481
+ function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2249
2482
  const planAbsPaths = /* @__PURE__ */ new Set();
2250
- const resolvedRoot = path12.resolve(root);
2483
+ const resolvedRoot = path13.resolve(root);
2251
2484
  for (const roadmap of roadmaps) {
2252
2485
  for (const ref of collectPlanRefs(roadmap)) {
2253
- const absolute = path12.resolve(resolvedRoot, ref.path);
2254
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path12.sep)) {
2255
- warn(`chokidar target outside repo, skipping: ${ref.path}`);
2486
+ const absolute = path13.resolve(resolvedRoot, ref.path);
2487
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path13.sep)) {
2488
+ warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2256
2489
  continue;
2257
2490
  }
2258
2491
  planAbsPaths.add(absolute);
@@ -2260,107 +2493,70 @@ function collectContainedPlanAbsPaths(roadmaps, root, warn) {
2260
2493
  }
2261
2494
  return [...planAbsPaths];
2262
2495
  }
2263
- async function listRoadmapFiles(roadmapsDir, io) {
2264
- try {
2265
- const entries = await io.listDir(roadmapsDir);
2266
- return entries.filter((entry) => entry.endsWith(".json")).sort();
2267
- } catch (err) {
2268
- if (err != null && typeof err === "object" && "code" in err && err.code === "ENOENT") {
2269
- return [];
2270
- }
2271
- throw err;
2272
- }
2273
- }
2274
- async function migrateLegacyRoadmap(args) {
2275
- const targetPath = path12.join(args.roadmapsDir, `${args.slug}.json`);
2276
- await args.io.mkdir(args.roadmapsDir);
2277
- try {
2278
- await args.io.rename(args.legacyPath, targetPath);
2279
- } catch {
2280
- await args.io.copyFile(args.legacyPath, targetPath);
2281
- await args.io.unlink(args.legacyPath);
2282
- }
2283
- try {
2284
- await args.io.rmdir(path12.dirname(args.legacyPath));
2285
- } catch {
2286
- }
2287
- args.io.log(
2288
- `migrated .roadmap/roadmap.json \u2192 .nolto/roadmaps/${args.slug}.json \u2014 commit this change (ensure .nolto/ is not gitignored)`
2289
- );
2290
- return `${args.slug}.json`;
2291
- }
2292
2496
  async function syncRepo(args, io) {
2293
- const bindingPath = path12.join(args.root, "nolto.json");
2294
- const binding = await loadRepoBinding(bindingPath);
2295
- const projectId = binding?.projectId ?? args.defaultProjectId;
2296
- if (projectId == null) {
2297
- throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
2298
- }
2299
- const roadmapsDir = path12.join(args.root, ".nolto", "roadmaps");
2300
- const legacyPath = path12.join(args.root, ".roadmap", "roadmap.json");
2301
- let roadmapFiles = await listRoadmapFiles(roadmapsDir, io);
2302
- if (roadmapFiles.length > 0) {
2303
- if (io.fileExists(legacyPath)) {
2304
- io.warn(
2305
- "legacy .roadmap/roadmap.json is ignored because .nolto/roadmaps/ already contains roadmap files"
2306
- );
2497
+ const { projectId } = args;
2498
+ const repoIdentity = await io.repoIdentity(args.root);
2499
+ const identity = repoIdentityToString(repoIdentity);
2500
+ const slugs = args.slugs ?? await listCachedSlugs(io.env, projectId);
2501
+ if (slugs.length === 0) {
2502
+ let legacyFiles = [];
2503
+ try {
2504
+ legacyFiles = await readdir3(path13.join(args.root, ".nolto", "roadmaps"));
2505
+ } catch (err) {
2506
+ if (err.code !== "ENOENT") throw err;
2307
2507
  }
2308
- } else if (io.fileExists(legacyPath)) {
2309
- if (args.migrateLegacy !== true) {
2310
- io.warn(
2311
- "legacy .roadmap/roadmap.json found \u2014 run `nolto sync` once to migrate it to .nolto/roadmaps/ (watch does not migrate automatically)"
2312
- );
2313
- return { results: [], planAbsPaths: [] };
2314
- }
2315
- const migrationSlug = binding?.roadmapSlug ?? slugifyProjectId(path12.basename(args.root));
2316
- roadmapFiles = [
2317
- await migrateLegacyRoadmap({
2318
- slug: migrationSlug,
2319
- legacyPath,
2320
- roadmapsDir,
2321
- io
2322
- })
2323
- ];
2324
- } else {
2325
- throw new CliError(
2326
- `No roadmap found in ${roadmapsDir}. Run \`nolto init\` to create one.`,
2327
- 2
2328
- );
2508
+ if (legacyFiles.some((file) => file.endsWith(".json"))) {
2509
+ throw new CliError("Roadmaps are still in .nolto/roadmaps. Run `nolto roadmap migrate`.", 2);
2510
+ }
2511
+ throw new CliError("No cached roadmap for this project. Run `nolto pull` or `nolto init`.", 2);
2512
+ }
2513
+ const roadmaps = [];
2514
+ for (const slug of slugs) {
2515
+ const entry = await readCache(io.env, projectId, slug);
2516
+ if (!entry) throw new CliError(`No cached roadmap "${slug}". Run \`nolto roadmap pull ${slug}\`.`, 2);
2517
+ if (args.slugs === void 0 && entry.meta?.repoIdentity != null && entry.meta.repoIdentity !== identity) {
2518
+ io.log(`skipped ${slug} (belongs to ${entry.meta.repoIdentity})`);
2519
+ continue;
2520
+ }
2521
+ roadmaps.push({ slug, ...entry });
2329
2522
  }
2330
- const roadmaps = await Promise.all(
2331
- roadmapFiles.map(async (fileName) => {
2332
- const slug = fileName.slice(0, -".json".length);
2333
- if (!ROADMAP_SLUG_PATTERN.test(slug)) {
2334
- throw new CliError(
2335
- `Invalid roadmap filename "${fileName}": slug must match ^[a-z0-9][a-z0-9._-]*$.`,
2336
- 2
2337
- );
2338
- }
2339
- const filePath = path12.join(roadmapsDir, fileName);
2340
- return { slug, roadmap: await loadValidRoadmap(filePath, io.readFile) };
2341
- })
2342
- );
2343
- const planAbsPaths = collectContainedPlanAbsPaths(
2344
- roadmaps.map(({ roadmap }) => roadmap),
2345
- args.root,
2346
- io.warn
2347
- );
2523
+ if (roadmaps.length === 0) throw new CliError("No cached roadmap belongs to this repository. Run `nolto link --slug <slug>` to create one, or `nolto pull`.", 2);
2348
2524
  const results = [];
2349
- const repoIdentity = await io.repoIdentity(args.root);
2350
- for (const { slug, roadmap } of roadmaps) {
2351
- results.push(
2352
- await runSync(
2353
- { repoRoot: args.root, projectId, slug, roadmap, repoIdentity },
2354
- {
2355
- http: io.http,
2356
- readFile: io.readFile,
2357
- fileExists: io.fileExists,
2358
- realpath: io.realpath,
2359
- log: io.log,
2360
- warn: io.warn
2525
+ for (const entry of roadmaps) {
2526
+ const { slug, roadmap, meta } = entry;
2527
+ if (args.onlyDirty && !isDirty(entry)) continue;
2528
+ try {
2529
+ const response = await runSync(
2530
+ { repoRoot: args.root, projectId, slug, roadmap, repoIdentity, baseRevision: meta?.revision ?? 0 },
2531
+ { http: io.http, readFile: io.readFile, fileExists: io.fileExists, realpath: io.realpath, log: io.log, warn: io.warn }
2532
+ );
2533
+ await writeCache(io.env, projectId, slug, response.roadmap ?? roadmap, {
2534
+ repoIdentity: identity,
2535
+ revision: response.revision,
2536
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2537
+ currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : meta?.currentTaskId
2538
+ });
2539
+ results.push(response);
2540
+ entry.roadmap = response.roadmap ?? roadmap;
2541
+ } catch (err) {
2542
+ if (err instanceof CliError && err.status === 409) {
2543
+ if (err.serverError === "task_conflict") {
2544
+ const conflicts = err.body?.["conflicts"];
2545
+ if (Array.isArray(conflicts)) {
2546
+ for (const conflict of conflicts) {
2547
+ if (conflict !== null && typeof conflict === "object") {
2548
+ io.warn(` ${conflict.level} ${conflict.id} ${conflict.field}: ours=${JSON.stringify(conflict.ours)} theirs=${JSON.stringify(conflict.theirs)}`);
2549
+ }
2550
+ }
2551
+ }
2552
+ throw new CliError(`Roadmap ${slug} conflicts with the server. Run \`nolto pull\` and resolve, then sync again.`, 4);
2361
2553
  }
2362
- )
2363
- );
2554
+ if (err.serverError === "base_revision_expired") {
2555
+ throw new CliError(`Roadmap ${slug} is based on an expired revision. Run \`nolto pull\` and reapply your changes.`, 4);
2556
+ }
2557
+ }
2558
+ throw err;
2559
+ }
2364
2560
  }
2365
2561
  let gitLinks = null;
2366
2562
  if (io.exec && io.gitLinks !== false) {
@@ -2371,7 +2567,7 @@ async function syncRepo(args, io) {
2371
2567
  for (let offset = 0; offset < body.links.length; offset += 500) {
2372
2568
  const response = await io.http.post(
2373
2569
  `/api/projects/${projectId}/git-links`,
2374
- { links: body.links.slice(offset, offset + 500) }
2570
+ { links: body.links.slice(offset, offset + 500), repoIdentity }
2375
2571
  );
2376
2572
  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
2573
  gitLinks = { linked: gitLinks.linked + response.linked, existing: gitLinks.existing + response.existing, skipped: gitLinks.skipped + response.skipped };
@@ -2384,80 +2580,68 @@ async function syncRepo(args, io) {
2384
2580
  io.warn(`git links: skipped \u2014 ${error instanceof Error ? error.message : String(error)}`);
2385
2581
  }
2386
2582
  }
2387
- return { results, planAbsPaths, gitLinks };
2583
+ return { results, planAbsPaths: collectContainedPlanAbsPaths(roadmaps.map((entry) => entry.roadmap), args.root, io.warn), gitLinks };
2388
2584
  }
2389
2585
 
2390
2586
  // src/commands/sync.ts
2391
2587
  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) => {
2393
- if (deps.settings.token == null) {
2394
- throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2395
- }
2396
- const startDir = resolveStartDir(process.env, process.cwd());
2397
- const { root, foundGit } = findRepoRoot(startDir);
2398
- if (!foundGit) {
2399
- throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2588
+ program.command("sync").description("Push cached roadmaps and linked plan documents to Nolto (baseRevision-aware)").option("--no-git-links", "Skip commit / PR issue links").action(async (opts) => {
2589
+ await runSyncCommand(deps, opts);
2590
+ });
2591
+ }
2592
+ async function runSyncCommand(deps, opts = {}) {
2593
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2594
+ const http = deps.http;
2595
+ const warn2 = (line) => {
2596
+ process.stderr.write((line.startsWith(" ") ? "" : "Warning: ") + line + "\n");
2597
+ };
2598
+ const response = await syncRepo(
2599
+ { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2600
+ {
2601
+ env: process.env,
2602
+ readFile: (p) => readFile8(p, "utf8"),
2603
+ realpath: (p) => realpath2(p),
2604
+ fileExists: (p) => existsSync3(p),
2605
+ repoIdentity: makeRepoIdentityResolver(deps),
2606
+ exec: promisify(execFile2),
2607
+ gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2608
+ http,
2609
+ log: (line) => {
2610
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
2611
+ },
2612
+ warn: warn2
2400
2613
  }
2401
- const http = deps.http;
2402
- const warn = (line) => {
2403
- process.stderr.write("Warning: " + line + "\n");
2404
- };
2405
- const response = await syncRepo(
2406
- { root, defaultProjectId: deps.settings.defaultProjectId, migrateLegacy: true },
2407
- {
2408
- readFile: (p) => readFile7(p, "utf8"),
2409
- realpath: (p) => realpath(p),
2410
- fileExists: (p) => existsSync3(p),
2411
- listDir: (p) => readdir3(p),
2412
- rename: rename3,
2413
- copyFile,
2414
- mkdir: (p) => mkdir6(p, { recursive: true }).then(() => void 0),
2415
- unlink: unlink2,
2416
- rmdir,
2417
- repoIdentity: makeRepoIdentityResolver(deps),
2418
- exec: promisify2(execFile3),
2419
- gitLinks: opts.gitLinks && process.env.NOLTO_GIT_LINKS !== "0",
2420
- http,
2421
- log: (line) => {
2422
- if (deps.output.mode !== "json") process.stdout.write(line + "\n");
2423
- },
2424
- warn
2425
- }
2426
- );
2427
- try {
2428
- const drifted = await checkSkillVersionDrift(root, deps.version);
2429
- if (drifted.length > 0) {
2430
- warn(formatSkillVersionDriftWarning(root, deps.version, drifted));
2431
- }
2432
- } catch {
2614
+ );
2615
+ try {
2616
+ const drifted = await checkSkillVersionDrift(root, deps.version);
2617
+ if (drifted.length > 0) {
2618
+ warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
2433
2619
  }
2434
- let registryAdded = false;
2435
- if (isHomeDirectory(root)) {
2436
- process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2620
+ } catch {
2621
+ }
2622
+ let registryAdded = false;
2623
+ if (isHomeDirectory(root)) {
2624
+ process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2437
2625
  `);
2438
- } else {
2439
- try {
2440
- registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), root)).added;
2441
- } catch (err) {
2442
- const message = err instanceof Error ? err.message : String(err);
2443
- process.stderr.write(`Warning: could not update watch registry: ${message}
2626
+ } else {
2627
+ try {
2628
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
2629
+ } catch (err) {
2630
+ const message = err instanceof Error ? err.message : String(err);
2631
+ process.stderr.write(`Warning: could not update watch registry: ${message}
2444
2632
  `);
2445
- }
2446
2633
  }
2447
- if (deps.output.mode === "json") {
2448
- const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
2449
- printResult({ ...publicResponse, registryAdded }, "json");
2450
- } else if (registryAdded) {
2451
- process.stdout.write(`watch registry: added ${root}
2634
+ }
2635
+ if (!opts.quiet && deps.output.mode === "json") {
2636
+ const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
2637
+ printResult({ ...publicResponse, registryAdded }, "json");
2638
+ } else if (!opts.quiet && registryAdded) {
2639
+ process.stdout.write(`watch registry: added ${root}
2452
2640
  `);
2453
- }
2454
- });
2641
+ }
2642
+ return response;
2455
2643
  }
2456
2644
 
2457
- // src/commands/diff.ts
2458
- import { readFile as readFile8 } from "fs/promises";
2459
- import path14 from "path";
2460
-
2461
2645
  // src/roadmap-diff.ts
2462
2646
  function diffRoadmaps(local, server) {
2463
2647
  if (local === null && server === null) return [];
@@ -2520,7 +2704,7 @@ function diffRoadmaps(local, server) {
2520
2704
  }
2521
2705
  }
2522
2706
  const meta = [
2523
- { field: "updatedAt", local: local.updatedAt, server: server.updatedAt },
2707
+ { field: "updatedAt", local: local.updatedAt ?? null, server: server.updatedAt ?? null },
2524
2708
  {
2525
2709
  field: "currentTaskId",
2526
2710
  local: local.currentTaskId ?? null,
@@ -2559,46 +2743,15 @@ function formatRoadmapDiff(slug, entries) {
2559
2743
  return lines;
2560
2744
  }
2561
2745
 
2562
- // src/roadmap-read.ts
2563
- import { readdir as readdir4 } from "fs/promises";
2564
- import path13 from "path";
2565
- async function resolveRoadmapReadContext(deps) {
2566
- if (deps.settings.token == null) {
2567
- throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2568
- }
2569
- const startDir = resolveStartDir(process.env, process.cwd());
2570
- const { root, foundGit } = findRepoRoot(startDir);
2571
- if (!foundGit) {
2572
- throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2573
- }
2574
- const binding = await loadRepoBinding(path13.join(root, "nolto.json"));
2575
- const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2576
- if (projectId == null) {
2577
- throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
2578
- }
2579
- return { root, projectId };
2580
- }
2581
- async function listLocalRoadmapSlugs(root) {
2582
- try {
2583
- const entries = await readdir4(path13.join(root, ".nolto", "roadmaps"));
2584
- return entries.filter((entry) => entry.endsWith(".json")).map((entry) => entry.slice(0, -".json".length)).sort();
2585
- } catch (err) {
2586
- if (err != null && typeof err === "object" && "code" in err && err.code === "ENOENT") {
2587
- return [];
2588
- }
2589
- throw err;
2590
- }
2591
- }
2592
-
2593
2746
  // src/commands/diff.ts
2594
2747
  function register7(program, deps) {
2595
2748
  program.command("diff [slug]").description("Compare local roadmaps with the server without changing either side.").action(async (requestedSlug) => {
2596
- const { root, projectId } = await resolveRoadmapReadContext(deps);
2749
+ const { projectId } = await resolveRoadmapReadContext(deps);
2597
2750
  const list = await deps.http.get(
2598
2751
  `/api/projects/${projectId}/roadmaps`
2599
2752
  );
2600
2753
  const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2601
- const localSlugs = await listLocalRoadmapSlugs(root);
2754
+ const localSlugs = await listCachedSlugs(process.env, projectId);
2602
2755
  const localSlugSet = new Set(localSlugs);
2603
2756
  const allSlugs = [.../* @__PURE__ */ new Set([...localSlugs, ...serverBySlug.keys()])].sort();
2604
2757
  if (requestedSlug != null && !allSlugs.includes(requestedSlug)) {
@@ -2612,9 +2765,8 @@ function register7(program, deps) {
2612
2765
  for (const slug of targetSlugs) {
2613
2766
  let local = null;
2614
2767
  if (localSlugSet.has(slug)) {
2615
- const localPath = path14.join(root, ".nolto", "roadmaps", `${slug}.json`);
2616
2768
  try {
2617
- local = await loadValidRoadmap(localPath, (filePath) => readFile8(filePath, "utf8"));
2769
+ local = (await readCache(process.env, projectId, slug))?.roadmap ?? null;
2618
2770
  } catch (err) {
2619
2771
  const message = err instanceof Error ? err.message : String(err);
2620
2772
  process.stderr.write(`Warning: could not diff ${slug}.json: ${message}
@@ -2656,347 +2808,307 @@ function register7(program, deps) {
2656
2808
  });
2657
2809
  }
2658
2810
 
2659
- // src/commands/pull.ts
2660
- import { mkdir as mkdir7, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
2661
- import path15 from "path";
2811
+ // src/roadmap-commands.ts
2812
+ import path14 from "path";
2813
+ import { existsSync as existsSync4 } from "fs";
2814
+ import { readFile as readFile9, readdir as readdir4, writeFile as writeFile7, rename as rename4, unlink as unlink3, realpath as realpath3 } from "fs/promises";
2815
+ import { randomUUID as randomUUID5 } from "crypto";
2816
+ import readline4 from "readline/promises";
2662
2817
 
2663
- // src/roadmap-merge.ts
2664
- import { isDeepStrictEqual } from "util";
2665
- function taskLocations(roadmap) {
2666
- const result = /* @__PURE__ */ new Map();
2667
- for (const phase of roadmap?.phases ?? []) {
2668
- for (const task of phase.tasks) result.set(task.id, { task, phaseId: phase.id });
2818
+ // src/commands/pull.ts
2819
+ function register8(program, deps) {
2820
+ program.command("pull [slug]").description("Pull server roadmaps into the local cache.").option("--all", "Pull all roadmaps (the default when no slug is specified)").option("--force", "Overwrite local changes that have not been synced").action(async (requestedSlug, opts) => {
2821
+ await runPull(deps, { ...opts, slug: requestedSlug });
2822
+ });
2823
+ }
2824
+ async function runPull(deps, opts = {}) {
2825
+ const messages = [];
2826
+ const { projectId } = await resolveRoadmapReadContext(deps);
2827
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2828
+ const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2829
+ if (opts.slug != null && !serverBySlug.has(opts.slug)) {
2830
+ throw new CliError(`Roadmap "${opts.slug}" was not found on the server.`, 2);
2831
+ }
2832
+ const slugs = opts.slug == null ? [...serverBySlug.keys()] : [opts.slug];
2833
+ let skipped = false;
2834
+ for (const slug of slugs) {
2835
+ if (!await pullRoadmapCache({
2836
+ env: process.env,
2837
+ http: deps.http,
2838
+ projectId,
2839
+ slug,
2840
+ force: opts.force,
2841
+ log: (line) => {
2842
+ messages.push(line);
2843
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
2844
+ },
2845
+ warn: (line) => {
2846
+ process.stderr.write(line + "\n");
2847
+ }
2848
+ })) skipped = true;
2669
2849
  }
2670
- return result;
2850
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
2851
+ if (!opts.quiet && deps.output.mode === "json") printResult({ messages }, "json");
2671
2852
  }
2672
- function chooseField(args) {
2673
- if (args.baseExists && isDeepStrictEqual(args.ours, args.base)) return args.theirs;
2674
- if (args.baseExists && isDeepStrictEqual(args.theirs, args.base)) return args.ours;
2675
- if (isDeepStrictEqual(args.ours, args.theirs)) return args.ours;
2676
- return args.newer === "ours" ? args.ours : args.theirs;
2677
- }
2678
- function chooseStatus(base, ours, theirs) {
2679
- if (base !== void 0) {
2680
- const oursChanged = ours.status !== base.status;
2681
- const theirsChanged = theirs.status !== base.status;
2682
- if (!oursChanged) return theirs.status;
2683
- if (!theirsChanged) return ours.status;
2853
+
2854
+ // src/roadmap-commands.ts
2855
+ var warn = (line) => {
2856
+ process.stderr.write(line + "\n");
2857
+ };
2858
+ async function pull(deps, projectId, slug) {
2859
+ if (!await pullRoadmapCache({ env: process.env, http: deps.http, projectId, slug, log: () => void 0, warn })) {
2860
+ throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2861
+ }
2862
+ }
2863
+ async function selectRoadmap(deps, requestedSlug) {
2864
+ const context2 = await resolveRoadmapReadContext(deps);
2865
+ let slug = requestedSlug;
2866
+ if (slug === void 0) {
2867
+ let slugs = await listCachedSlugs(process.env, context2.projectId);
2868
+ if (slugs.length === 0) {
2869
+ await runPull(deps, { quiet: true });
2870
+ slugs = await listCachedSlugs(process.env, context2.projectId);
2871
+ }
2872
+ if (slugs.length !== 1) {
2873
+ throw new CliError(slugs.length === 0 ? "No roadmap found. Run `nolto init`." : `Multiple roadmaps found (${slugs.join(", ")}); specify a slug (task commands: --slug <slug>).`, 2);
2874
+ }
2875
+ slug = slugs[0];
2876
+ }
2877
+ const paths = cachePaths(process.env, context2.projectId, slug);
2878
+ if (!existsSync4(paths.json)) await pull(deps, context2.projectId, slug);
2879
+ return { ...context2, slug, paths };
2880
+ }
2881
+ async function roadmapPath(deps, slug) {
2882
+ const { paths } = await selectRoadmap(deps, slug);
2883
+ printResult(path14.resolve(paths.json), deps.output.mode);
2884
+ }
2885
+ async function roadmapStatus(deps, slug, fresh = false) {
2886
+ const selected = await selectRoadmap(deps, slug);
2887
+ if (fresh) await pull(deps, selected.projectId, selected.slug);
2888
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2889
+ const { roadmap, meta } = entry;
2890
+ const stats = deriveTaskStats(roadmap);
2891
+ const tasks = roadmap.phases.flatMap((phase) => phase.tasks);
2892
+ const current = tasks.find((task) => task.id === meta?.currentTaskId);
2893
+ const blocked = tasks.filter((task) => task.status === "blocked");
2894
+ const age = meta ? (Date.now() - Date.parse(meta.pulledAt)) / 6e4 : NaN;
2895
+ if (age > 10) warn(`Warning: cache is ${Math.floor(age)} minutes old; run with --fresh or nolto roadmap pull`);
2896
+ if (deps.output.mode === "json") {
2897
+ printResult({ roadmap, stats, currentTaskId: meta?.currentTaskId ?? null, revision: meta?.revision ?? 0, pulledAt: meta?.pulledAt ?? null }, "json");
2898
+ return;
2684
2899
  }
2685
- const candidates = [ours, theirs];
2686
- if (candidates.some((task) => task.status === "done" && task.completedAt != null)) {
2687
- return "done";
2900
+ printResult([
2901
+ `${roadmap.project.name}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
2902
+ `Current: ${current ? `${current.id} \u2014 ${current.title}` : "none"}`,
2903
+ `Blocked: ${blocked.map((task) => `${task.id} \u2014 ${task.title}`).join(", ") || "none"}`,
2904
+ `Summary: ${roadmap.summary}`,
2905
+ `Revision: ${meta?.revision ?? 0} (pulled ${meta?.pulledAt ?? "unknown"})`
2906
+ ].join("\n"), "human");
2907
+ }
2908
+ async function roadmapValidate(deps, slug) {
2909
+ const { paths } = await selectRoadmap(deps, slug);
2910
+ let parsed;
2911
+ try {
2912
+ parsed = JSON.parse(await readFile9(paths.json, "utf8"));
2913
+ } catch {
2914
+ throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
2688
2915
  }
2689
- for (const status of ["blocked", "in-progress", "todo"]) {
2690
- if (candidates.some((task) => task.status === status)) return status;
2916
+ const result = validateRoadmap(parsed);
2917
+ for (const warning of result.warnings) warn(`WARN ${warning}`);
2918
+ if (result.errors.length) {
2919
+ for (const error of result.errors) warn(`ERROR ${error}`);
2920
+ throw new CliError(`Roadmap validation failed: ${paths.json}`, 1);
2691
2921
  }
2692
- return base?.status !== "done" ? base?.status ?? "todo" : "todo";
2693
- }
2694
- function earliest(values) {
2695
- return values.filter((value) => value != null).sort((a, b) => Date.parse(a) - Date.parse(b))[0];
2922
+ printResult(deps.output.mode === "json" ? { path: paths.json, ...result } : `OK ${paths.json}`, deps.output.mode);
2696
2923
  }
2697
- function latest(values) {
2698
- return values.filter((value) => value != null).sort((a, b) => Date.parse(b) - Date.parse(a))[0];
2699
- }
2700
- function assignOptional(target, key, value) {
2701
- if (value !== void 0) Object.assign(target, { [key]: value });
2702
- }
2703
- function cloneSingleTask(task) {
2704
- const cloned = { ...task };
2705
- if (task.dependsOn !== void 0) cloned.dependsOn = [...task.dependsOn];
2706
- if (task.issues !== void 0) cloned.issues = [...task.issues];
2707
- if (cloned.status !== "done") delete cloned.completedAt;
2708
- return cloned;
2924
+ async function roadmapSummary(deps, slug, text) {
2925
+ const selected = await selectRoadmap(deps, slug);
2926
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2927
+ entry.roadmap.summary = text;
2928
+ const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
2929
+ try {
2930
+ await writeFile7(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
2931
+ await rename4(temp, selected.paths.json);
2932
+ } finally {
2933
+ await unlink3(temp).catch(() => void 0);
2934
+ }
2935
+ await runSyncCommand(deps, { slug: selected.slug });
2936
+ }
2937
+ async function patchTask(args) {
2938
+ const { env, projectId, slug, taskId } = args;
2939
+ const entry = await readCache(env, projectId, slug);
2940
+ if (entry && isDirty(entry)) throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2941
+ let response;
2942
+ try {
2943
+ response = await args.http.patch(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}`, args.body);
2944
+ } catch (error) {
2945
+ if (error instanceof CliError && error.status === 404) throw new CliError(`Task ${taskId} not found in ${slug}.`, 2);
2946
+ throw error;
2947
+ }
2948
+ const { errors } = validateRoadmap(response.roadmap);
2949
+ if (errors.length) throw new CliError(`Server roadmap "${slug}" failed validation: ${errors.join("; ")}`, 5);
2950
+ await writeCache(env, projectId, slug, response.roadmap, {
2951
+ repoIdentity: entry?.meta?.repoIdentity ?? null,
2952
+ revision: response.revision,
2953
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2954
+ currentTaskId: response.currentTaskId
2955
+ });
2956
+ return response;
2709
2957
  }
2710
- function mergeTask(args) {
2711
- const baseExists = args.base !== void 0;
2712
- const status = chooseStatus(args.base, args.ours, args.theirs);
2713
- const merged = {
2714
- id: args.ours.id,
2715
- title: chooseField({
2716
- baseExists,
2717
- base: args.base?.title,
2718
- ours: args.ours.title,
2719
- theirs: args.theirs.title,
2720
- newer: args.newer
2721
- }),
2722
- status
2723
- };
2724
- assignOptional(
2725
- merged,
2726
- "startedAt",
2727
- earliest([args.base?.startedAt, args.ours.startedAt, args.theirs.startedAt])
2728
- );
2729
- if (status === "done") {
2730
- assignOptional(
2731
- merged,
2732
- "completedAt",
2733
- latest([args.base?.completedAt, args.ours.completedAt, args.theirs.completedAt])
2734
- );
2958
+ async function roadmapTask(deps, taskId, slug, body) {
2959
+ const selected = await selectRoadmap(deps, slug);
2960
+ if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
2961
+ if (body.plan !== void 0) {
2962
+ const absolute = path14.resolve(selected.root, body.plan);
2963
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path14.resolve(selected.root) + path14.sep)) {
2964
+ throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
2965
+ }
2966
+ if (!existsSync4(absolute)) warn(`WARN plan file not found at ${absolute}`);
2967
+ }
2968
+ const response = await patchTask({ ...selected, env: process.env, http: deps.http, taskId, body });
2969
+ if (body.plan !== void 0) await runSyncCommand(deps, { slug: selected.slug, quiet: true });
2970
+ printResult(deps.output.mode === "json" ? response : body.plan !== void 0 ? `${taskId} plan -> ${body.plan}` : `${taskId} -> ${body.status}`, deps.output.mode);
2971
+ }
2972
+ async function roadmapEvents(deps, slug, opts) {
2973
+ const selected = await selectRoadmap(deps, slug);
2974
+ const query = new URLSearchParams();
2975
+ if (opts.since !== void 0) query.set("since", opts.since);
2976
+ if (opts.limit !== void 0) query.set("limit", opts.limit);
2977
+ const response = await deps.http.get(`/api/projects/${selected.projectId}/roadmaps/${encodeURIComponent(selected.slug)}/events${query.size ? `?${query}` : ""}`);
2978
+ if (deps.output.mode === "json") printResult(response, "json");
2979
+ else for (const event of response.events) {
2980
+ printResult(`rev ${event.revision} ${event.createdAt} ${event.actor?.name ?? "system"} ${event.source} ${event.taskId} ${event.field}: ${event.from ?? "\u2014"} \u2192 ${event.to ?? "\u2014"}`, "human");
2981
+ }
2982
+ }
2983
+ async function roadmapMigrate(deps, yes = false) {
2984
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2985
+ const dir = path14.join(root, ".nolto", "roadmaps");
2986
+ let files;
2987
+ try {
2988
+ files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
2989
+ } catch (error) {
2990
+ if (error.code !== "ENOENT") throw error;
2991
+ files = [];
2735
2992
  }
2736
- assignOptional(merged, "note", chooseField({
2737
- baseExists,
2738
- base: args.base?.note,
2739
- ours: args.ours.note,
2740
- theirs: args.theirs.note,
2741
- newer: args.newer
2742
- }));
2743
- assignOptional(merged, "plan", chooseField({
2744
- baseExists,
2745
- base: args.base?.plan,
2746
- ours: args.ours.plan,
2747
- theirs: args.theirs.plan,
2748
- newer: args.newer
2749
- }));
2750
- const dependsOn = [
2751
- ...args.ours.dependsOn ?? [],
2752
- ...args.theirs.dependsOn ?? []
2753
- ].filter((id, index, values) => values.indexOf(id) === index);
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;
2757
- return merged;
2758
- }
2759
- function shouldKeep(base, ours, theirs) {
2760
- if (base === void 0) return ours !== void 0 || theirs !== void 0;
2761
- if (ours === void 0 && theirs === void 0) return false;
2762
- if (ours === void 0) return !isDeepStrictEqual(theirs, base);
2763
- if (theirs === void 0) return !isDeepStrictEqual(ours, base);
2764
- return true;
2765
- }
2766
- function orderTasks(args) {
2767
- const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
2768
- const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
2769
- const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
2770
- let nearestCommon = null;
2771
- let insertAfter = null;
2772
- for (const task of theirsPhase?.tasks ?? []) {
2773
- if (!args.taskIds.has(task.id)) continue;
2774
- if (args.oursLocations.has(task.id)) {
2775
- if (ordered.includes(task.id)) {
2776
- nearestCommon = task.id;
2777
- insertAfter = task.id;
2993
+ if (!files.length) {
2994
+ printResult("Nothing to migrate.", deps.output.mode);
2995
+ return;
2996
+ }
2997
+ const local = [];
2998
+ for (const file of files) {
2999
+ const slug = file.slice(0, -5);
3000
+ cachePaths(process.env, projectId, slug);
3001
+ const roadmap = await loadValidRoadmap(path14.join(dir, file), (p) => readFile9(p, "utf8"));
3002
+ roadmap.schemaVersion = 3;
3003
+ delete roadmap.updatedAt;
3004
+ delete roadmap.currentTaskId;
3005
+ local.push({ slug, roadmap });
3006
+ }
3007
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
3008
+ const results = [];
3009
+ for (const { slug, roadmap } of local) {
3010
+ let server;
3011
+ if (list.roadmaps.some((item) => item.slug === slug)) server = await deps.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
3012
+ const unchanged = server !== void 0 && serializeRoadmap(roadmap) === serializeRoadmap(server.roadmap);
3013
+ if (server && !unchanged && !yes) {
3014
+ if (!process.stdin.isTTY) throw new CliError(`Replacing ${slug} at server rev ${server.revision} requires confirmation; rerun with --yes.`, 2);
3015
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stderr });
3016
+ try {
3017
+ const answer = await rl.question(`Replace ${slug} on the server at rev ${server.revision} with the local file? [y/N] `);
3018
+ if (!/^y(es)?$/i.test(answer.trim())) throw new CliError(`Migration of ${slug} cancelled.`, 2);
3019
+ } finally {
3020
+ rl.close();
2778
3021
  }
2779
- continue;
2780
3022
  }
2781
- if (nearestCommon === null || insertAfter === null) {
2782
- ordered.push(task.id);
2783
- continue;
3023
+ const repoIdentity = (await readCache(process.env, projectId, slug))?.meta?.repoIdentity ?? null;
3024
+ let revision = server?.revision ?? 0;
3025
+ let saved = unchanged ? server.roadmap : roadmap;
3026
+ let currentTaskId = server?.currentTaskId;
3027
+ if (unchanged || !server) {
3028
+ await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2784
3029
  }
2785
- const index = ordered.indexOf(insertAfter);
2786
- ordered.splice(index + 1, 0, task.id);
2787
- insertAfter = task.id;
2788
- }
2789
- return ordered;
2790
- }
2791
- function mergeRoadmaps(args) {
2792
- const newer = Date.parse(args.theirs.updatedAt) > Date.parse(args.ours.updatedAt) ? "theirs" : "ours";
2793
- const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
2794
- const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
2795
- const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
2796
- const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
2797
- const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
2798
- const baseLocations = taskLocations(args.base);
2799
- const oursLocations = taskLocations(args.ours);
2800
- const theirsLocations = taskLocations(args.theirs);
2801
- const keptTasks = /* @__PURE__ */ new Map();
2802
- const targetPhaseByTask = /* @__PURE__ */ new Map();
2803
- const taskIds = /* @__PURE__ */ new Set([
2804
- ...baseLocations.keys(),
2805
- ...oursLocations.keys(),
2806
- ...theirsLocations.keys()
2807
- ]);
2808
- for (const taskId of taskIds) {
2809
- const baseLocation = baseLocations.get(taskId);
2810
- const oursLocation = oursLocations.get(taskId);
2811
- const theirsLocation = theirsLocations.get(taskId);
2812
- if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
2813
- const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
2814
- base: baseLocation?.task,
2815
- ours: oursLocation.task,
2816
- theirs: theirsLocation.task,
2817
- newer
2818
- }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
2819
- keptTasks.set(taskId, task);
2820
- targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
2821
- }
2822
- const keptPhaseIds = /* @__PURE__ */ new Set();
2823
- const allPhaseIds = /* @__PURE__ */ new Set([
2824
- ...basePhases.keys(),
2825
- ...oursPhases.keys(),
2826
- ...theirsPhases.keys()
2827
- ]);
2828
- for (const phaseId of allPhaseIds) {
2829
- if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
2830
- keptPhaseIds.add(phaseId);
3030
+ if (!unchanged) {
3031
+ const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
3032
+ http: deps.http,
3033
+ readFile: (p) => readFile9(p, "utf8"),
3034
+ realpath: realpath3,
3035
+ fileExists: existsSync4,
3036
+ log: () => void 0,
3037
+ warn
3038
+ });
3039
+ revision = response.revision;
3040
+ saved = response.roadmap ?? roadmap;
3041
+ if (response.currentTaskId !== void 0) currentTaskId = response.currentTaskId;
3042
+ await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2831
3043
  }
3044
+ const action = unchanged ? "unchanged" : server ? "replaced" : "created";
3045
+ results.push({ slug, action, revision });
3046
+ if (deps.output.mode !== "json") printResult(`${action} ${slug} (rev ${revision})`, "human");
2832
3047
  }
2833
- const phaseOrder = [
2834
- ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
2835
- ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
2836
- ];
2837
- const phases = phaseOrder.map((phaseId) => {
2838
- const base = basePhases.get(phaseId);
2839
- const ours = oursPhases.get(phaseId);
2840
- const theirs = theirsPhases.get(phaseId);
2841
- const source = ours ?? theirs;
2842
- const title = ours !== void 0 && theirs !== void 0 ? chooseField({
2843
- baseExists: base !== void 0,
2844
- base: base?.title,
2845
- ours: ours.title,
2846
- theirs: theirs.title,
2847
- newer
2848
- }) : source.title;
2849
- const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
2850
- baseExists: base !== void 0,
2851
- base: base?.plan,
2852
- ours: ours.plan,
2853
- theirs: theirs.plan,
2854
- newer
2855
- }) : source.plan;
2856
- const phaseTaskIds = new Set(
2857
- [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
2858
- );
2859
- const tasks = orderTasks({
2860
- phaseId,
2861
- taskIds: phaseTaskIds,
2862
- ours: args.ours,
2863
- theirs: args.theirs,
2864
- oursLocations
2865
- }).map((taskId) => keptTasks.get(taskId));
2866
- const phase = { id: phaseId, title, status: "todo", tasks };
2867
- if (plan !== void 0) phase.plan = plan;
2868
- phase.status = derivePhaseStatus(phase);
2869
- return phase;
2870
- });
2871
- const mergedTasks = new Map(
2872
- phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
2873
- );
2874
- const validCurrentTask = (roadmap) => {
2875
- const id = roadmap.currentTaskId ?? null;
2876
- return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
2877
- };
2878
- const merged = {
2879
- schemaVersion: 2,
2880
- project: { ...newerRoadmap.project },
2881
- updatedAt: newerRoadmap.updatedAt,
2882
- currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
2883
- summary: newerRoadmap.summary,
2884
- phases
2885
- };
2886
- const validation = validateRoadmap(merged);
2887
- if (validation.errors.length > 0) {
2888
- throw new CliError(
2889
- `Merged roadmap failed validation:
2890
- ${validation.errors.join("\n ")}`,
2891
- 1
2892
- );
2893
- }
2894
- return merged;
2895
- }
2896
-
2897
- // src/commands/pull.ts
2898
- async function readExisting(filePath) {
3048
+ const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3049
+ let attributes = "";
2899
3050
  try {
2900
- return await readFile9(filePath, "utf8");
2901
- } catch (err) {
2902
- if (err != null && typeof err === "object" && "code" in err && err.code === "ENOENT") {
2903
- return null;
2904
- }
2905
- throw err;
3051
+ attributes = await readFile9(path14.join(root, ".gitattributes"), "utf8");
3052
+ } catch (error) {
3053
+ if (error.code !== "ENOENT") throw error;
2906
3054
  }
3055
+ if (attributes.split(/\r?\n/).some((line) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line))) {
3056
+ nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
3057
+ }
3058
+ nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
3059
+ await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
3060
+ printResult(deps.output.mode === "json" ? { results, nextSteps } : nextSteps.join("\n"), deps.output.mode);
2907
3061
  }
2908
- function register8(program, deps) {
2909
- program.command("pull [slug]").description(
2910
- "Pull server roadmaps, optionally merging them with valid local copies."
2911
- ).option("--merge", "Structurally merge server and local roadmap changes").action(async (requestedSlug, opts) => {
2912
- const { root, projectId } = await resolveRoadmapReadContext(deps);
2913
- const list = await deps.http.get(
2914
- `/api/projects/${projectId}/roadmaps`
2915
- );
2916
- const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2917
- if (requestedSlug != null && !serverBySlug.has(requestedSlug)) {
2918
- throw new CliError(`Roadmap "${requestedSlug}" was not found on the server.`, 2);
2919
- }
2920
- const targets = requestedSlug == null ? [...serverBySlug.values()] : [serverBySlug.get(requestedSlug)];
2921
- const roadmapsDir = path15.join(root, ".nolto", "roadmaps");
2922
- for (const summary of targets) {
2923
- const response = await deps.http.get(
2924
- `/api/projects/${projectId}/roadmaps/${encodeURIComponent(summary.slug)}`
2925
- );
2926
- const validation = validateRoadmap(response.roadmap);
2927
- if (validation.errors.length > 0) {
2928
- throw new CliError(
2929
- `Server roadmap "${summary.slug}" failed validation: ${validation.errors.join("; ")}`,
2930
- 5
2931
- );
2932
- }
2933
- const filePath = path15.join(roadmapsDir, `${summary.slug}.json`);
2934
- const existing = await readExisting(filePath);
2935
- let roadmap = response.roadmap;
2936
- let outputVerb = "pulled";
2937
- if (opts.merge === true && existing !== null) {
2938
- let local;
2939
- try {
2940
- local = JSON.parse(existing);
2941
- } catch {
2942
- process.stderr.write(
2943
- `Warning: skipped ${summary.slug}.json because the local roadmap contains malformed JSON.
2944
- `
2945
- );
2946
- continue;
2947
- }
2948
- const localValidation = validateRoadmap(local);
2949
- if (localValidation.errors.length > 0) {
2950
- process.stderr.write(
2951
- `Warning: skipped ${summary.slug}.json because the local roadmap is invalid: ${localValidation.errors.join("; ")}
2952
- `
2953
- );
2954
- continue;
2955
- }
2956
- roadmap = mergeRoadmaps({
2957
- base: null,
2958
- ours: local,
2959
- theirs: response.roadmap
2960
- });
2961
- outputVerb = "merged";
2962
- }
2963
- const serialized = JSON.stringify(roadmap, null, 2) + "\n";
2964
- if (existing === serialized) {
2965
- process.stdout.write(`unchanged ${summary.slug}.json
2966
- `);
2967
- continue;
2968
- }
2969
- await mkdir7(roadmapsDir, { recursive: true });
2970
- await writeFile8(filePath, serialized, "utf8");
2971
- process.stdout.write(
2972
- outputVerb === "merged" ? `merged ${summary.slug}.json
2973
- ` : `pulled ${summary.slug}.json (${summary.taskDone}/${summary.taskTotal} done)
2974
- `
2975
- );
2976
- }
2977
- process.stdout.write("Review with git diff before committing.\n");
2978
- });
3062
+
3063
+ // src/commands/roadmap.ts
3064
+ function register9(program, deps) {
3065
+ const roadmap = program.command("roadmap").description("Read and update server roadmaps through the local cache.");
3066
+ roadmap.command("path [slug]").description("Print the cached roadmap path").action((slug) => roadmapPath(deps, slug));
3067
+ roadmap.command("pull [slug]").description("Pull one roadmap, or all when slug is omitted").option("--all", "Pull all roadmaps (default without a slug)").option("--force", "Overwrite unsynced local changes").action((slug, opts) => runPull(deps, { ...opts, slug }));
3068
+ roadmap.command("sync [slug]").description("Push one roadmap, or all when slug is omitted").option("--no-git-links", "Skip commit / PR issue links").action((slug, opts) => runSyncCommand(deps, { ...opts, slug }).then(() => void 0));
3069
+ roadmap.command("status [slug]").description("Show progress and cache revision").option("--fresh", "Pull before showing status").action((slug, opts) => roadmapStatus(deps, slug, opts.fresh));
3070
+ roadmap.command("validate [slug]").description("Validate cached JSON").action((slug) => roadmapValidate(deps, slug));
3071
+ roadmap.command("summary [slug]").description("Replace the summary and sync").requiredOption("--text <text>", "New summary").action((slug, opts) => roadmapSummary(deps, slug, opts.text));
3072
+ const bodies = {
3073
+ start: { status: "in-progress", currentTask: true },
3074
+ done: { status: "done" },
3075
+ block: { status: "blocked" },
3076
+ todo: { status: "todo", startedAt: null, completedAt: null }
3077
+ };
3078
+ for (const [name, body] of Object.entries(bodies)) {
3079
+ const command = roadmap.command(`${name} <task>`).description(`Set task status to ${body.status}`).option("--slug <slug>", "Roadmap slug (required with multiple cached roadmaps)");
3080
+ if (name === "block") command.requiredOption("--note <text>", "Blocker description");
3081
+ else command.option("--note <text>", "Task note");
3082
+ command.action((task, opts) => roadmapTask(deps, task, opts.slug, {
3083
+ ...body,
3084
+ ...opts.note !== void 0 ? { note: opts.note } : {}
3085
+ }));
3086
+ }
3087
+ roadmap.command("plan <task>").description("Attach a plan and sync its contents").option("--slug <slug>", "Roadmap slug (required with multiple cached roadmaps)").requiredOption("--path <path>", "Repository-relative plan path").action((task, opts) => roadmapTask(deps, task, opts.slug, { plan: opts.path }));
3088
+ roadmap.command("events [slug]").description("Show task event history").option("--since <revision>", "Events after this revision").option("--limit <number>", "Maximum events (1\u2013200)").action((slug, opts) => roadmapEvents(deps, slug, opts));
3089
+ roadmap.command("migrate").description("Migrate repository roadmaps to the server and cache").option("--yes", "Replace differing server roadmaps without prompting").action((opts) => roadmapMigrate(deps, opts.yes));
2979
3090
  }
2980
3091
 
2981
3092
  // src/commands/watch.ts
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";
2985
- import { existsSync as existsSync4 } from "fs";
3093
+ import { execFile as execFile3 } from "child_process";
3094
+ import { promisify as promisify2 } from "util";
3095
+ import { readFile as readFile10, realpath as realpath4 } from "fs/promises";
3096
+ import { existsSync as existsSync5, mkdirSync } from "fs";
2986
3097
  import path17 from "path";
2987
3098
  import chokidar from "chokidar";
2988
3099
 
2989
3100
  // src/watch-core.ts
3101
+ import path15 from "path";
2990
3102
  var WatchSet = class {
2991
3103
  constructor(deps) {
2992
3104
  this.deps = deps;
2993
3105
  }
2994
3106
  deps;
2995
3107
  handles = /* @__PURE__ */ new Map();
2996
- async reconcile(roots) {
2997
- const nextRoots = new Set(roots);
2998
- for (const [root, handle] of this.handles) {
2999
- if (nextRoots.has(root)) continue;
3108
+ async reconcile(repos) {
3109
+ const nextRoots = new Map(repos.map((repo) => [repo.root, repo]));
3110
+ for (const [root, { handle, projectId }] of this.handles) {
3111
+ if (nextRoots.get(root)?.projectId === projectId) continue;
3000
3112
  try {
3001
3113
  await handle.stop();
3002
3114
  } catch (err) {
@@ -3007,9 +3119,9 @@ var WatchSet = class {
3007
3119
  this.handles.delete(root);
3008
3120
  this.deps.log(`Stopped watching ${root}`);
3009
3121
  }
3010
- for (const root of nextRoots) {
3122
+ for (const [root, repo] of nextRoots) {
3011
3123
  if (this.handles.has(root)) continue;
3012
- this.handles.set(root, this.deps.start(root));
3124
+ this.handles.set(root, { handle: this.deps.start(repo), projectId: repo.projectId });
3013
3125
  this.deps.log(`Watching ${root}`);
3014
3126
  }
3015
3127
  }
@@ -3025,16 +3137,24 @@ async function reloadRoots(deps) {
3025
3137
  try {
3026
3138
  registry = await deps.load();
3027
3139
  } catch (err) {
3028
- deps.warn(
3029
- `registry reload failed: ${err instanceof Error ? err.message : String(err)} \u2014 keeping current watch set`
3030
- );
3140
+ deps.warn(`registry reload failed: ${err instanceof Error ? err.message : String(err)} \u2014 keeping current watch set`);
3031
3141
  return null;
3032
3142
  }
3033
- return registry.repos.map((repo) => repo.root).filter((root) => {
3034
- if (deps.exists(root)) return true;
3035
- deps.warn(`registered repo no longer exists, skipping: ${root}`);
3036
- return false;
3037
- });
3143
+ const repos = [];
3144
+ for (const repo of registry.repos) {
3145
+ if (!deps.exists(repo.root)) {
3146
+ deps.warn(`registered repo no longer exists, skipping: ${repo.root}`);
3147
+ continue;
3148
+ }
3149
+ try {
3150
+ const projectId = repo.projectId ?? (await loadRepoBinding(path15.join(repo.root, "nolto.json")))?.projectId;
3151
+ if (projectId) repos.push({ root: repo.root, projectId });
3152
+ else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3153
+ } catch (err) {
3154
+ deps.warn(`cannot read project binding, skipping ${repo.root}: ${String(err)}`);
3155
+ }
3156
+ }
3157
+ return repos;
3038
3158
  }
3039
3159
  var RepoWatch = class {
3040
3160
  constructor(root, deps) {
@@ -3046,8 +3166,15 @@ var RepoWatch = class {
3046
3166
  timer = null;
3047
3167
  running = false;
3048
3168
  pending = false;
3169
+ onlyDirty = true;
3049
3170
  watchedPlans = [];
3050
- handleEvent(_filePath) {
3171
+ handleEvent(filePath) {
3172
+ if (filePath.endsWith(".meta.json")) return;
3173
+ if (this.watchedPlans.includes(filePath)) this.onlyDirty = false;
3174
+ if (this.running) {
3175
+ this.pending = true;
3176
+ return;
3177
+ }
3051
3178
  if (this.timer != null) {
3052
3179
  this.deps.clearTimeoutFn(this.timer);
3053
3180
  }
@@ -3062,8 +3189,10 @@ var RepoWatch = class {
3062
3189
  return;
3063
3190
  }
3064
3191
  this.running = true;
3192
+ const onlyDirty = this.onlyDirty;
3193
+ this.onlyDirty = true;
3065
3194
  try {
3066
- const result = await this.deps.sync();
3195
+ const result = await this.deps.sync(onlyDirty);
3067
3196
  this.rearmPlanWatches(result.planAbsPaths);
3068
3197
  } catch (err) {
3069
3198
  this.deps.warn(
@@ -3135,18 +3264,18 @@ async function installServiceWith(deps) {
3135
3264
  deps.log("Service nolto-watch enabled and started. Logs: journalctl --user -u nolto-watch -f");
3136
3265
  }
3137
3266
  async function installService() {
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);
3267
+ const { writeFile: writeFile10, mkdir: mkdir7 } = await import("fs/promises");
3268
+ const { execFile: execFile5 } = await import("child_process");
3269
+ const { promisify: promisify4 } = await import("util");
3270
+ const execFileAsync = promisify4(execFile5);
3142
3271
  await installServiceWith({
3143
3272
  platform: process.platform,
3144
3273
  env: process.env,
3145
3274
  nodePath: process.execPath,
3146
3275
  scriptPath: path16.resolve(process.argv[1] ?? ""),
3147
- writeFile: (p, content) => writeFile11(p, content, "utf8"),
3276
+ writeFile: (p, content) => writeFile10(p, content, "utf8"),
3148
3277
  mkdir: async (p) => {
3149
- await mkdir10(p, { recursive: true });
3278
+ await mkdir7(p, { recursive: true });
3150
3279
  },
3151
3280
  exec: async (cmd) => {
3152
3281
  try {
@@ -3201,9 +3330,9 @@ async function uninstallServiceWith(deps) {
3201
3330
  }
3202
3331
  async function uninstallService() {
3203
3332
  const { unlink: unlink4 } = await import("fs/promises");
3204
- const { execFile: execFile6 } = await import("child_process");
3205
- const { promisify: promisify5 } = await import("util");
3206
- const execFileAsync = promisify5(execFile6);
3333
+ const { execFile: execFile5 } = await import("child_process");
3334
+ const { promisify: promisify4 } = await import("util");
3335
+ const execFileAsync = promisify4(execFile5);
3207
3336
  await uninstallServiceWith({
3208
3337
  platform: process.platform,
3209
3338
  env: process.env,
@@ -3223,7 +3352,7 @@ async function uninstallService() {
3223
3352
  }
3224
3353
 
3225
3354
  // src/commands/watch.ts
3226
- function register9(program, deps) {
3355
+ function register10(program, deps) {
3227
3356
  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) => {
3228
3357
  if (opts.installService && opts.uninstallService) {
3229
3358
  throw new CliError("--install-service and --uninstall-service cannot be used together.", 2);
@@ -3244,14 +3373,15 @@ function register9(program, deps) {
3244
3373
  throw new CliError("--debounce must be a non-negative integer.", 2);
3245
3374
  }
3246
3375
  const registryPath = getRegistryPath(process.env);
3247
- const registry = await loadRegistry(registryPath);
3248
- const roots = registry.repos.map((r) => r.root).filter((root) => {
3249
- if (existsSync4(root)) return true;
3250
- process.stderr.write(`Warning: registered repo no longer exists, skipping: ${root}
3376
+ const roots = await reloadRoots({
3377
+ load: () => loadRegistry(registryPath),
3378
+ exists: existsSync5,
3379
+ warn: (line) => {
3380
+ process.stderr.write(`Warning: ${line}
3251
3381
  `);
3252
- return false;
3382
+ }
3253
3383
  });
3254
- if (roots.length === 0) {
3384
+ if (roots == null || roots.length === 0) {
3255
3385
  throw new CliError("No watchable repositories in the registry. Run `nolto init` in a repo first.", 2);
3256
3386
  }
3257
3387
  const http = createHttpClient({
@@ -3259,35 +3389,29 @@ function register9(program, deps) {
3259
3389
  version: deps.version,
3260
3390
  token: deps.settings.token
3261
3391
  });
3262
- const startRepo = (root) => {
3263
- const roadmapsPath = path17.join(root, ".nolto", "roadmaps");
3264
- const legacyRoadmapPath = path17.join(root, ".roadmap", "roadmap.json");
3265
- const warn = (line) => {
3266
- process.stderr.write(`Warning: [${path17.basename(root)}] ${line}
3392
+ const startRepo = ({ root, projectId }) => {
3393
+ const roadmapsPath = cacheDir(process.env, projectId);
3394
+ const warn2 = (line) => {
3395
+ process.stderr.write(line.startsWith(" ") ? line + "\n" : `Warning: [${path17.basename(root)}] ${line}
3267
3396
  `);
3268
3397
  };
3269
- const watcher = chokidar.watch([roadmapsPath, legacyRoadmapPath], { ignoreInitial: true });
3398
+ mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
3399
+ const watcher = chokidar.watch(roadmapsPath, { ignoreInitial: true, ignored: /\.meta\.json$/ });
3270
3400
  const repoWatch = new RepoWatch(root, {
3271
- sync: () => syncRepo(
3272
- // #316: watch must warn about legacy roadmaps without migrating them.
3273
- { root, defaultProjectId: deps.settings.defaultProjectId, migrateLegacy: false },
3401
+ sync: (onlyDirty) => syncRepo(
3402
+ { root, projectId, onlyDirty },
3274
3403
  {
3404
+ env: process.env,
3275
3405
  readFile: (p) => readFile10(p, "utf8"),
3276
- realpath: (p) => realpath2(p),
3277
- fileExists: (p) => existsSync4(p),
3278
- listDir: (p) => readdir5(p),
3279
- rename: rename4,
3280
- copyFile: copyFile2,
3281
- mkdir: (p) => mkdir8(p, { recursive: true }).then(() => void 0),
3282
- unlink: unlink3,
3283
- rmdir: rmdir2,
3406
+ realpath: (p) => realpath4(p),
3407
+ fileExists: (p) => existsSync5(p),
3284
3408
  repoIdentity: makeRepoIdentityResolver(deps),
3285
- exec: promisify3(execFile4),
3409
+ exec: promisify2(execFile3),
3286
3410
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3287
3411
  http,
3288
3412
  log: (line) => process.stdout.write(`[${path17.basename(root)}] ${line}
3289
3413
  `),
3290
- warn
3414
+ warn: warn2
3291
3415
  }
3292
3416
  ),
3293
3417
  watcher,
@@ -3297,10 +3421,13 @@ function register9(program, deps) {
3297
3421
  log: (line) => process.stdout.write(line + "\n"),
3298
3422
  warn: (line) => process.stderr.write(line + "\n")
3299
3423
  });
3300
- watcher.on("all", (_event, filePath) => repoWatch.handleEvent(filePath));
3424
+ watcher.on("all", (_event, filePath) => {
3425
+ if (path17.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3426
+ repoWatch.handleEvent(filePath);
3427
+ });
3301
3428
  void checkSkillVersionDrift(root, deps.version).then((drifted) => {
3302
3429
  if (drifted.length > 0) {
3303
- warn(formatSkillVersionDriftWarning(root, deps.version, drifted));
3430
+ warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
3304
3431
  }
3305
3432
  }).catch(() => {
3306
3433
  });
@@ -3320,7 +3447,7 @@ function register9(program, deps) {
3320
3447
  registryReloadTimer = null;
3321
3448
  void reloadRoots({
3322
3449
  load: () => loadRegistry(registryPath),
3323
- exists: (root) => existsSync4(root),
3450
+ exists: (root) => existsSync5(root),
3324
3451
  warn: (line) => process.stderr.write(`Warning: ${line}
3325
3452
  `)
3326
3453
  }).then(async (newRoots) => {
@@ -3348,16 +3475,16 @@ function register9(program, deps) {
3348
3475
  }
3349
3476
 
3350
3477
  // src/update-cli.ts
3351
- import { execFile as execFile5 } from "child_process";
3352
- import { existsSync as existsSync5 } from "fs";
3353
- import { realpath as realpath3 } from "fs/promises";
3478
+ import { execFile as execFile4 } from "child_process";
3479
+ import { existsSync as existsSync6 } from "fs";
3480
+ import { realpath as realpath5 } from "fs/promises";
3354
3481
  import { createRequire as createRequire2 } from "module";
3355
3482
  import path19 from "path";
3356
3483
  import { fileURLToPath as fileURLToPath3 } from "url";
3357
- import { promisify as promisify4 } from "util";
3484
+ import { promisify as promisify3 } from "util";
3358
3485
 
3359
3486
  // src/update-notifier.ts
3360
- import { readFile as readFile11, writeFile as writeFile9, mkdir as mkdir9 } from "fs/promises";
3487
+ import { readFile as readFile11, writeFile as writeFile8, mkdir as mkdir6 } from "fs/promises";
3361
3488
  import https from "https";
3362
3489
  import path18 from "path";
3363
3490
  var PACKAGE = "@nolto/cli";
@@ -3417,9 +3544,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3417
3544
  });
3418
3545
  }
3419
3546
  async function writeUpdateCache(cachePath, now, latest2) {
3420
- await mkdir9(path18.dirname(cachePath), { recursive: true });
3547
+ await mkdir6(path18.dirname(cachePath), { recursive: true });
3421
3548
  const payload = { checkedAt: now, latest: latest2 };
3422
- await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
3549
+ await writeFile8(cachePath, JSON.stringify(payload), { mode: 384 });
3423
3550
  }
3424
3551
  async function refreshCache(cachePath, now, fetchLatest) {
3425
3552
  const latest2 = await fetchLatest();
@@ -3577,8 +3704,8 @@ function getCurrentVersion() {
3577
3704
  }
3578
3705
  }
3579
3706
  async function updateCli(opts = {}) {
3580
- const execFileAsync = promisify4(execFile5);
3581
- const scriptPath = await realpath3(process.argv[1] ?? "");
3707
+ const execFileAsync = promisify3(execFile4);
3708
+ const scriptPath = await realpath5(process.argv[1] ?? "");
3582
3709
  return updateCliWith({
3583
3710
  currentVersion: getCurrentVersion(),
3584
3711
  scriptPath,
@@ -3599,17 +3726,17 @@ async function updateCli(opts = {}) {
3599
3726
  };
3600
3727
  }
3601
3728
  },
3602
- realpath: realpath3,
3729
+ realpath: realpath5,
3603
3730
  fetchLatest: () => fetchLatestFromRegistry(UPDATE_REQUEST_TIMEOUT_MS, UPDATE_FETCH_OPTIONS),
3604
3731
  writeCache: writeUpdateCache,
3605
- unitExists: existsSync5,
3732
+ unitExists: existsSync6,
3606
3733
  log: opts.quiet === true ? () => void 0 : (line) => process.stdout.write(line + "\n"),
3607
3734
  warn: (line) => process.stderr.write("Warning: " + line + "\n")
3608
3735
  });
3609
3736
  }
3610
3737
 
3611
3738
  // src/commands/update.ts
3612
- function register10(program, deps) {
3739
+ function register11(program, deps) {
3613
3740
  program.command("update").description("Update @nolto/cli to the latest version and restart the watch service if installed").action(async () => {
3614
3741
  const mode2 = deps.output.mode;
3615
3742
  const result = await updateCli({ quiet: mode2 === "json" });
@@ -3620,7 +3747,243 @@ function register10(program, deps) {
3620
3747
  }
3621
3748
 
3622
3749
  // src/commands/merge-file.ts
3623
- import { readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
3750
+ import { readFile as readFile12, writeFile as writeFile9 } from "fs/promises";
3751
+
3752
+ // src/roadmap-merge.ts
3753
+ import { isDeepStrictEqual } from "util";
3754
+ function taskLocations(roadmap) {
3755
+ const result = /* @__PURE__ */ new Map();
3756
+ for (const phase of roadmap?.phases ?? []) {
3757
+ for (const task of phase.tasks) result.set(task.id, { task, phaseId: phase.id });
3758
+ }
3759
+ return result;
3760
+ }
3761
+ function chooseField(args) {
3762
+ if (args.baseExists && isDeepStrictEqual(args.ours, args.base)) return args.theirs;
3763
+ if (args.baseExists && isDeepStrictEqual(args.theirs, args.base)) return args.ours;
3764
+ if (isDeepStrictEqual(args.ours, args.theirs)) return args.ours;
3765
+ return args.newer === "ours" ? args.ours : args.theirs;
3766
+ }
3767
+ function chooseStatus(base, ours, theirs) {
3768
+ if (base !== void 0) {
3769
+ const oursChanged = ours.status !== base.status;
3770
+ const theirsChanged = theirs.status !== base.status;
3771
+ if (!oursChanged) return theirs.status;
3772
+ if (!theirsChanged) return ours.status;
3773
+ }
3774
+ const candidates = [ours, theirs];
3775
+ if (candidates.some((task) => task.status === "done" && task.completedAt != null)) {
3776
+ return "done";
3777
+ }
3778
+ for (const status of ["blocked", "in-progress", "todo"]) {
3779
+ if (candidates.some((task) => task.status === status)) return status;
3780
+ }
3781
+ return base?.status !== "done" ? base?.status ?? "todo" : "todo";
3782
+ }
3783
+ function earliest(values) {
3784
+ return values.filter((value) => value != null).sort((a, b) => Date.parse(a) - Date.parse(b))[0];
3785
+ }
3786
+ function latest(values) {
3787
+ return values.filter((value) => value != null).sort((a, b) => Date.parse(b) - Date.parse(a))[0];
3788
+ }
3789
+ function assignOptional(target, key, value) {
3790
+ if (value !== void 0) Object.assign(target, { [key]: value });
3791
+ }
3792
+ function cloneSingleTask(task) {
3793
+ const cloned = { ...task };
3794
+ if (task.dependsOn !== void 0) cloned.dependsOn = [...task.dependsOn];
3795
+ if (task.issues !== void 0) cloned.issues = [...task.issues];
3796
+ if (cloned.status !== "done") delete cloned.completedAt;
3797
+ return cloned;
3798
+ }
3799
+ function mergeTask(args) {
3800
+ const baseExists = args.base !== void 0;
3801
+ const status = chooseStatus(args.base, args.ours, args.theirs);
3802
+ const merged = {
3803
+ id: args.ours.id,
3804
+ title: chooseField({
3805
+ baseExists,
3806
+ base: args.base?.title,
3807
+ ours: args.ours.title,
3808
+ theirs: args.theirs.title,
3809
+ newer: args.newer
3810
+ }),
3811
+ status
3812
+ };
3813
+ assignOptional(
3814
+ merged,
3815
+ "startedAt",
3816
+ earliest([args.base?.startedAt, args.ours.startedAt, args.theirs.startedAt])
3817
+ );
3818
+ if (status === "done") {
3819
+ assignOptional(
3820
+ merged,
3821
+ "completedAt",
3822
+ latest([args.base?.completedAt, args.ours.completedAt, args.theirs.completedAt])
3823
+ );
3824
+ }
3825
+ assignOptional(merged, "note", chooseField({
3826
+ baseExists,
3827
+ base: args.base?.note,
3828
+ ours: args.ours.note,
3829
+ theirs: args.theirs.note,
3830
+ newer: args.newer
3831
+ }));
3832
+ assignOptional(merged, "plan", chooseField({
3833
+ baseExists,
3834
+ base: args.base?.plan,
3835
+ ours: args.ours.plan,
3836
+ theirs: args.theirs.plan,
3837
+ newer: args.newer
3838
+ }));
3839
+ const dependsOn = [
3840
+ ...args.ours.dependsOn ?? [],
3841
+ ...args.theirs.dependsOn ?? []
3842
+ ].filter((id, index, values) => values.indexOf(id) === index);
3843
+ if (dependsOn.length > 0) merged.dependsOn = dependsOn;
3844
+ const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
3845
+ if (issues.length > 0) merged.issues = issues;
3846
+ return merged;
3847
+ }
3848
+ function shouldKeep(base, ours, theirs) {
3849
+ if (base === void 0) return ours !== void 0 || theirs !== void 0;
3850
+ if (ours === void 0 && theirs === void 0) return false;
3851
+ if (ours === void 0) return !isDeepStrictEqual(theirs, base);
3852
+ if (theirs === void 0) return !isDeepStrictEqual(ours, base);
3853
+ return true;
3854
+ }
3855
+ function orderTasks(args) {
3856
+ const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
3857
+ const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
3858
+ const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
3859
+ let nearestCommon = null;
3860
+ let insertAfter = null;
3861
+ for (const task of theirsPhase?.tasks ?? []) {
3862
+ if (!args.taskIds.has(task.id)) continue;
3863
+ if (args.oursLocations.has(task.id)) {
3864
+ if (ordered.includes(task.id)) {
3865
+ nearestCommon = task.id;
3866
+ insertAfter = task.id;
3867
+ }
3868
+ continue;
3869
+ }
3870
+ if (nearestCommon === null || insertAfter === null) {
3871
+ ordered.push(task.id);
3872
+ continue;
3873
+ }
3874
+ const index = ordered.indexOf(insertAfter);
3875
+ ordered.splice(index + 1, 0, task.id);
3876
+ insertAfter = task.id;
3877
+ }
3878
+ return ordered;
3879
+ }
3880
+ function mergeRoadmaps(args) {
3881
+ const newer = Date.parse(args.theirs.updatedAt ?? "") > Date.parse(args.ours.updatedAt ?? "") ? "theirs" : "ours";
3882
+ const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
3883
+ const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
3884
+ const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
3885
+ const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
3886
+ const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
3887
+ const baseLocations = taskLocations(args.base);
3888
+ const oursLocations = taskLocations(args.ours);
3889
+ const theirsLocations = taskLocations(args.theirs);
3890
+ const keptTasks = /* @__PURE__ */ new Map();
3891
+ const targetPhaseByTask = /* @__PURE__ */ new Map();
3892
+ const taskIds = /* @__PURE__ */ new Set([
3893
+ ...baseLocations.keys(),
3894
+ ...oursLocations.keys(),
3895
+ ...theirsLocations.keys()
3896
+ ]);
3897
+ for (const taskId of taskIds) {
3898
+ const baseLocation = baseLocations.get(taskId);
3899
+ const oursLocation = oursLocations.get(taskId);
3900
+ const theirsLocation = theirsLocations.get(taskId);
3901
+ if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
3902
+ const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
3903
+ base: baseLocation?.task,
3904
+ ours: oursLocation.task,
3905
+ theirs: theirsLocation.task,
3906
+ newer
3907
+ }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
3908
+ keptTasks.set(taskId, task);
3909
+ targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
3910
+ }
3911
+ const keptPhaseIds = /* @__PURE__ */ new Set();
3912
+ const allPhaseIds = /* @__PURE__ */ new Set([
3913
+ ...basePhases.keys(),
3914
+ ...oursPhases.keys(),
3915
+ ...theirsPhases.keys()
3916
+ ]);
3917
+ for (const phaseId of allPhaseIds) {
3918
+ if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
3919
+ keptPhaseIds.add(phaseId);
3920
+ }
3921
+ }
3922
+ const phaseOrder = [
3923
+ ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
3924
+ ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
3925
+ ];
3926
+ const phases = phaseOrder.map((phaseId) => {
3927
+ const base = basePhases.get(phaseId);
3928
+ const ours = oursPhases.get(phaseId);
3929
+ const theirs = theirsPhases.get(phaseId);
3930
+ const source = ours ?? theirs;
3931
+ const title = ours !== void 0 && theirs !== void 0 ? chooseField({
3932
+ baseExists: base !== void 0,
3933
+ base: base?.title,
3934
+ ours: ours.title,
3935
+ theirs: theirs.title,
3936
+ newer
3937
+ }) : source.title;
3938
+ const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
3939
+ baseExists: base !== void 0,
3940
+ base: base?.plan,
3941
+ ours: ours.plan,
3942
+ theirs: theirs.plan,
3943
+ newer
3944
+ }) : source.plan;
3945
+ const phaseTaskIds = new Set(
3946
+ [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
3947
+ );
3948
+ const tasks = orderTasks({
3949
+ phaseId,
3950
+ taskIds: phaseTaskIds,
3951
+ ours: args.ours,
3952
+ theirs: args.theirs,
3953
+ oursLocations
3954
+ }).map((taskId) => keptTasks.get(taskId));
3955
+ const phase = { id: phaseId, title, status: "todo", tasks };
3956
+ if (plan !== void 0) phase.plan = plan;
3957
+ phase.status = derivePhaseStatus(phase);
3958
+ return phase;
3959
+ });
3960
+ const mergedTasks = new Map(
3961
+ phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
3962
+ );
3963
+ const validCurrentTask = (roadmap) => {
3964
+ const id = roadmap.currentTaskId ?? null;
3965
+ return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
3966
+ };
3967
+ const merged = {
3968
+ schemaVersion: newerRoadmap.updatedAt === void 0 ? 3 : 2,
3969
+ project: { ...newerRoadmap.project },
3970
+ updatedAt: newerRoadmap.updatedAt,
3971
+ currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
3972
+ summary: newerRoadmap.summary,
3973
+ phases
3974
+ };
3975
+ const validation = validateRoadmap(merged);
3976
+ if (validation.errors.length > 0) {
3977
+ throw new CliError(
3978
+ `Merged roadmap failed validation:
3979
+ ${validation.errors.join("\n ")}`,
3980
+ 1
3981
+ );
3982
+ }
3983
+ return merged;
3984
+ }
3985
+
3986
+ // src/commands/merge-file.ts
3624
3987
  async function readRoadmap(filePath) {
3625
3988
  let parsed;
3626
3989
  try {
@@ -3639,15 +4002,16 @@ async function readRoadmap(filePath) {
3639
4002
  }
3640
4003
  return parsed;
3641
4004
  }
3642
- function register11(program) {
4005
+ function register12(program) {
3643
4006
  program.command("merge-file <ours> <theirs>").description(
3644
4007
  'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
3645
4008
  ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
4009
+ process.stderr.write("Warning: merge-file is deprecated and will be removed; roadmaps are no longer stored in git.\n");
3646
4010
  const ours = await readRoadmap(oursPath);
3647
4011
  const theirs = await readRoadmap(theirsPath);
3648
4012
  const base = opts.base == null ? null : await readRoadmap(opts.base);
3649
4013
  const merged = mergeRoadmaps({ base, ours, theirs });
3650
- await writeFile10(
4014
+ await writeFile9(
3651
4015
  opts.output ?? oursPath,
3652
4016
  JSON.stringify(merged, null, 2) + "\n",
3653
4017
  "utf8"
@@ -3677,7 +4041,8 @@ function buildProgram(deps) {
3677
4041
  register8(program, deps);
3678
4042
  register9(program, deps);
3679
4043
  register10(program, deps);
3680
- register11(program);
4044
+ register11(program, deps);
4045
+ register12(program);
3681
4046
  program.action(() => {
3682
4047
  program.help();
3683
4048
  });