@nolto/cli 0.13.2 → 0.14.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,
@@ -585,10 +611,10 @@ function validateRoadmap(value) {
585
611
  const warnings = [];
586
612
  if (!isRecord(value)) return { errors: ["Root must be an object."], warnings };
587
613
  checkKeys(value, ALLOWED_KEYS.roadmap, "roadmap", errors);
588
- if (value["schemaVersion"] !== 1 && value["schemaVersion"] !== 2) {
589
- errors.push("schemaVersion must be 1 or 2.");
614
+ if (value["schemaVersion"] !== 1 && value["schemaVersion"] !== 2 && value["schemaVersion"] !== 3) {
615
+ errors.push("schemaVersion must be 1, 2 or 3.");
590
616
  } else if (value["schemaVersion"] === 1) {
591
- warnings.push("schemaVersion 1 is legacy; the next roadmap-progress mutation migrates this file to 2.");
617
+ warnings.push("schemaVersion 1 is legacy; the next roadmap-progress mutation migrates this file to 3.");
592
618
  }
593
619
  const project = value["project"];
594
620
  checkKeys(project, ALLOWED_KEYS.project, "project", errors);
@@ -596,7 +622,9 @@ function validateRoadmap(value) {
596
622
  if (typeof projectRecord["id"] !== "string" || !ID_PATTERN.test(projectRecord["id"])) errors.push("project.id is invalid.");
597
623
  if (typeof projectRecord["name"] !== "string" || projectRecord["name"].length === 0) errors.push("project.name must be a non-empty string.");
598
624
  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"));
625
+ if (value["schemaVersion"] !== 3 || value["updatedAt"] !== void 0) {
626
+ errors.push(...validateDateTime(value["updatedAt"], "updatedAt"));
627
+ }
600
628
  if (typeof value["summary"] !== "string") errors.push("summary must be a string.");
601
629
  if (!Array.isArray(value["phases"])) errors.push("phases must be an array.");
602
630
  const allIds = /* @__PURE__ */ new Set();
@@ -723,6 +751,33 @@ function deriveTaskStats(roadmap) {
723
751
  progressPct: total > 0 ? Math.round(done / total * 100) : 0
724
752
  };
725
753
  }
754
+ function serializeRoadmap(roadmap) {
755
+ const ordered = {
756
+ schemaVersion: roadmap.schemaVersion,
757
+ project: { id: roadmap.project.id, name: roadmap.project.name, repository: roadmap.project.repository },
758
+ updatedAt: roadmap.updatedAt,
759
+ currentTaskId: roadmap.currentTaskId,
760
+ summary: roadmap.summary,
761
+ phases: roadmap.phases.map((phase) => ({
762
+ id: phase.id,
763
+ title: phase.title,
764
+ status: phase.status,
765
+ plan: phase.plan,
766
+ tasks: phase.tasks.map((task) => ({
767
+ id: task.id,
768
+ title: task.title,
769
+ status: task.status,
770
+ startedAt: task.startedAt,
771
+ completedAt: task.completedAt,
772
+ note: task.note,
773
+ plan: task.plan,
774
+ dependsOn: task.dependsOn,
775
+ issues: task.issues
776
+ }))
777
+ }))
778
+ };
779
+ return JSON.stringify(ordered, null, 2) + "\n";
780
+ }
726
781
 
727
782
  // src/issue-core.ts
728
783
  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 +1038,302 @@ import readline2 from "readline/promises";
983
1038
  import { createRequire } from "module";
984
1039
  import { fileURLToPath as fileURLToPath2 } from "url";
985
1040
  import os3 from "os";
986
- import path10 from "path";
1041
+ import path11 from "path";
987
1042
  import fs from "fs";
988
1043
 
1044
+ // src/roadmap-bootstrap.ts
1045
+ import { existsSync } from "fs";
1046
+ import { readFile as readFile4, realpath } from "fs/promises";
1047
+ import path5 from "path";
1048
+
1049
+ // src/roadmap-cache.ts
1050
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, writeFile as writeFile3, rename as rename2, unlink } from "fs/promises";
1051
+ import { randomUUID as randomUUID2 } from "crypto";
1052
+ import path4 from "path";
1053
+
1054
+ // src/sync-core.ts
1055
+ import { createHash } from "crypto";
1056
+ import path3 from "path";
1057
+ function sha256Hex(content) {
1058
+ return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1059
+ }
1060
+ function collectPlanRefs(roadmap) {
1061
+ const seen = /* @__PURE__ */ new Set();
1062
+ const refs = [];
1063
+ for (const phase of roadmap.phases) {
1064
+ if (phase.plan != null && !seen.has(phase.plan)) {
1065
+ seen.add(phase.plan);
1066
+ refs.push({ path: phase.plan, ownerId: phase.id });
1067
+ }
1068
+ for (const task of phase.tasks) {
1069
+ if (task.plan != null && !seen.has(task.plan)) {
1070
+ seen.add(task.plan);
1071
+ refs.push({ path: task.plan, ownerId: task.id });
1072
+ }
1073
+ }
1074
+ }
1075
+ return refs;
1076
+ }
1077
+ async function loadValidRoadmap(filePath, readFile13) {
1078
+ let raw;
1079
+ try {
1080
+ raw = await readFile13(filePath);
1081
+ } catch {
1082
+ throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1083
+ }
1084
+ let parsed;
1085
+ try {
1086
+ parsed = JSON.parse(raw);
1087
+ } catch {
1088
+ throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1089
+ }
1090
+ const { errors } = validateRoadmap(parsed);
1091
+ if (errors.length > 0) {
1092
+ throw new CliError(
1093
+ `${filePath} failed validation \u2014 not syncing:
1094
+ ${errors.join("\n ")}`,
1095
+ 2
1096
+ );
1097
+ }
1098
+ return parsed;
1099
+ }
1100
+ async function buildSyncBody(args) {
1101
+ const planDocuments = [];
1102
+ for (const ref of collectPlanRefs(args.roadmap)) {
1103
+ const root = path3.resolve(args.repoRoot);
1104
+ const absolute = path3.resolve(root, ref.path);
1105
+ if (absolute !== root && !absolute.startsWith(root + path3.sep)) {
1106
+ args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1107
+ continue;
1108
+ }
1109
+ if (!args.deps.fileExists(absolute)) {
1110
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1111
+ continue;
1112
+ }
1113
+ if (args.deps.realpath !== void 0) {
1114
+ let real;
1115
+ let realRoot;
1116
+ try {
1117
+ real = await args.deps.realpath(absolute);
1118
+ realRoot = await args.deps.realpath(root);
1119
+ } catch {
1120
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1121
+ continue;
1122
+ }
1123
+ if (real !== realRoot && !real.startsWith(realRoot + path3.sep)) {
1124
+ args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1125
+ continue;
1126
+ }
1127
+ }
1128
+ const content = await args.deps.readFile(absolute);
1129
+ planDocuments.push({
1130
+ path: ref.path,
1131
+ taskId: ref.ownerId,
1132
+ content,
1133
+ contentHash: sha256Hex(content)
1134
+ });
1135
+ }
1136
+ return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1137
+ }
1138
+ async function runSync(args, deps) {
1139
+ const body = await buildSyncBody({
1140
+ roadmap: args.roadmap,
1141
+ repoRoot: args.repoRoot,
1142
+ repoIdentity: args.repoIdentity,
1143
+ deps
1144
+ });
1145
+ const response = await deps.http.put(
1146
+ `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1147
+ { ...body, baseRevision: args.baseRevision }
1148
+ );
1149
+ for (const warning of response.warnings ?? []) deps.warn(warning);
1150
+ const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1151
+ deps.log(
1152
+ `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})` : ""}`
1153
+ );
1154
+ return response;
1155
+ }
1156
+
1157
+ // src/roadmap-cache.ts
1158
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1159
+ var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1160
+ function cacheDir(env, projectId) {
1161
+ if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1162
+ return path4.join(getConfigDir(env), "projects", projectId, "roadmaps");
1163
+ }
1164
+ function cachePaths(env, projectId, slug) {
1165
+ if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1166
+ const dir = cacheDir(env, projectId);
1167
+ return { json: path4.join(dir, `${slug}.json`), meta: path4.join(dir, `${slug}.meta.json`) };
1168
+ }
1169
+ async function listCachedSlugs(env, projectId) {
1170
+ try {
1171
+ const entries = await readdir2(cacheDir(env, projectId), { withFileTypes: true });
1172
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
1173
+ } catch (err) {
1174
+ if (err.code === "ENOENT") return [];
1175
+ throw err;
1176
+ }
1177
+ }
1178
+ async function readCache(env, projectId, slug) {
1179
+ const paths = cachePaths(env, projectId, slug);
1180
+ let raw;
1181
+ try {
1182
+ raw = await readFile3(paths.json, "utf8");
1183
+ } catch (err) {
1184
+ if (err.code === "ENOENT") return null;
1185
+ throw err;
1186
+ }
1187
+ let roadmap;
1188
+ try {
1189
+ roadmap = JSON.parse(raw);
1190
+ } catch {
1191
+ throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
1192
+ }
1193
+ const { errors } = validateRoadmap(roadmap);
1194
+ if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1195
+ let meta = null;
1196
+ try {
1197
+ const parsed = JSON.parse(await readFile3(paths.meta, "utf8"));
1198
+ 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") {
1199
+ throw new Error("Invalid cache metadata");
1200
+ }
1201
+ if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
1202
+ throw new Error("Invalid currentTaskId");
1203
+ }
1204
+ meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null };
1205
+ } catch (err) {
1206
+ if (err.code !== "ENOENT") {
1207
+ throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
1208
+ }
1209
+ }
1210
+ return { roadmap, meta, raw };
1211
+ }
1212
+ async function writeCache(env, projectId, slug, roadmap, meta) {
1213
+ const paths = cachePaths(env, projectId, slug);
1214
+ const raw = serializeRoadmap(roadmap);
1215
+ const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, contentHash: sha256Hex(raw) };
1216
+ await mkdir2(cacheDir(env, projectId), { recursive: true, mode: 448 });
1217
+ for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1218
+ const temp = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1219
+ try {
1220
+ await writeFile3(temp, content, { mode: 384 });
1221
+ await rename2(temp, filePath);
1222
+ } finally {
1223
+ await unlink(temp).catch(() => void 0);
1224
+ }
1225
+ }
1226
+ }
1227
+ function isDirty(entry) {
1228
+ return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
1229
+ }
1230
+
1231
+ // src/roadmap-scaffold.ts
1232
+ function slugifyProjectId(name) {
1233
+ const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1234
+ return slug.length > 0 ? slug : "project";
1235
+ }
1236
+ function buildScaffold(projectName, repoBasename) {
1237
+ return {
1238
+ schemaVersion: 3,
1239
+ project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
1240
+ summary: "",
1241
+ phases: []
1242
+ };
1243
+ }
1244
+
1245
+ // src/roadmap-bootstrap.ts
1246
+ async function pullRoadmapCache(args) {
1247
+ const { env, projectId, slug } = args;
1248
+ const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
1249
+ const validation = validateRoadmap(response.roadmap);
1250
+ if (validation.errors.length > 0) {
1251
+ throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
1252
+ }
1253
+ let existing;
1254
+ try {
1255
+ existing = await readCache(env, projectId, slug);
1256
+ } catch (err) {
1257
+ if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
1258
+ existing = null;
1259
+ }
1260
+ if (existing && isDirty(existing) && !args.force) {
1261
+ args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1262
+ return false;
1263
+ }
1264
+ const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
1265
+ await writeCache(env, projectId, slug, response.roadmap, {
1266
+ revision: response.revision,
1267
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
1268
+ currentTaskId: response.currentTaskId
1269
+ });
1270
+ args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
1271
+ return true;
1272
+ }
1273
+ async function ensureRoadmapCache(args) {
1274
+ const { env, projectId } = args;
1275
+ const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1276
+ const warn2 = (line) => {
1277
+ process.stderr.write(line + "\n");
1278
+ };
1279
+ const log = (line) => args.log(`roadmap: ${line}`);
1280
+ if (list.roadmaps.length > 0) {
1281
+ let skipped = false;
1282
+ for (const { slug: slug2 } of list.roadmaps) {
1283
+ if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
1284
+ }
1285
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1286
+ return;
1287
+ }
1288
+ const basename = path5.basename(args.repoRoot);
1289
+ const slug = slugifyProjectId(basename);
1290
+ let existing;
1291
+ try {
1292
+ existing = await readCache(env, projectId, slug);
1293
+ } catch (err) {
1294
+ if (!(err instanceof CliError)) throw err;
1295
+ existing = null;
1296
+ }
1297
+ if (existing && isDirty(existing)) {
1298
+ warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1299
+ throw new CliError("Roadmap has local changes that are not synced.", 4);
1300
+ }
1301
+ const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
1302
+ await writeCache(env, projectId, slug, roadmap, { revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1303
+ const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1304
+ http: args.http,
1305
+ readFile: (p) => readFile4(p, "utf8"),
1306
+ realpath,
1307
+ fileExists: existsSync,
1308
+ log: () => void 0,
1309
+ warn: warn2
1310
+ });
1311
+ await writeCache(env, projectId, slug, response.roadmap ?? roadmap, { revision: response.revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : existing?.meta?.currentTaskId });
1312
+ log(`created ${slug} on server (rev ${response.revision})`);
1313
+ }
1314
+
989
1315
  // src/commands/link.ts
990
1316
  import readline from "readline/promises";
991
1317
  import os2 from "os";
992
- import path6 from "path";
1318
+ import path9 from "path";
993
1319
  import { statSync as statSync2 } from "fs";
994
1320
 
995
1321
  // 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";
1322
+ import { readFile as readFile5, writeFile as writeFile4, mkdir as mkdir3, rename as rename3, unlink as unlink2 } from "fs/promises";
1323
+ import { randomUUID as randomUUID3 } from "crypto";
1324
+ import path6 from "path";
999
1325
  import { z as z2 } from "zod";
1000
1326
  var registrySchema = z2.object({
1001
1327
  schemaVersion: z2.literal(1),
1002
- repos: z2.array(z2.object({ root: z2.string().min(1) }).passthrough())
1328
+ repos: z2.array(z2.object({ root: z2.string().min(1), projectId: z2.string().uuid().optional() }).passthrough())
1003
1329
  }).passthrough();
1004
1330
  function getRegistryPath(env) {
1005
- return path3.join(getConfigDir(env), "registry.json");
1331
+ return path6.join(getConfigDir(env), "registry.json");
1006
1332
  }
1007
1333
  async function loadRegistry(filePath) {
1008
1334
  let raw;
1009
1335
  try {
1010
- raw = await readFile3(filePath, "utf8");
1336
+ raw = await readFile5(filePath, "utf8");
1011
1337
  } catch (err) {
1012
1338
  const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1013
1339
  if (code === "ENOENT") {
@@ -1032,33 +1358,37 @@ async function loadRegistry(filePath) {
1032
1358
  }
1033
1359
  return result.data;
1034
1360
  }
1035
- async function addRepoToRegistry(filePath, repoRoot) {
1361
+ async function addRepoToRegistry(filePath, entry) {
1036
1362
  const registry = await loadRegistry(filePath);
1037
- if (registry.repos.some((repo) => repo.root === repoRoot)) {
1038
- return { added: false, registry };
1363
+ const existing = registry.repos.find((repo) => repo.root === entry.root);
1364
+ if (existing?.projectId === entry.projectId) {
1365
+ return { added: false, updated: false, registry };
1039
1366
  }
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()}`;
1367
+ const updated = {
1368
+ ...registry,
1369
+ repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
1370
+ };
1371
+ await mkdir3(path6.dirname(filePath), { recursive: true, mode: 448 });
1372
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1043
1373
  try {
1044
- await writeFile3(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1045
- await rename2(tempPath, filePath);
1374
+ await writeFile4(tempPath, JSON.stringify(updated, null, 2) + "\n", "utf8");
1375
+ await rename3(tempPath, filePath);
1046
1376
  } catch (err) {
1047
- await unlink(tempPath).catch(() => void 0);
1377
+ await unlink2(tempPath).catch(() => void 0);
1048
1378
  throw err;
1049
1379
  }
1050
- return { added: true, registry: updated };
1380
+ return { added: !existing, updated: !!existing, registry: updated };
1051
1381
  }
1052
1382
 
1053
1383
  // src/repo-identity.ts
1054
1384
  import { execFile } from "child_process";
1055
1385
  import { realpathSync } from "fs";
1056
- import path5 from "path";
1386
+ import path8 from "path";
1057
1387
 
1058
1388
  // 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";
1389
+ import { chmod, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5 } from "fs/promises";
1390
+ import { randomUUID as randomUUID4 } from "crypto";
1391
+ import path7 from "path";
1062
1392
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
1063
1393
  function parseMachineId(raw, file) {
1064
1394
  let parsed;
@@ -1074,10 +1404,10 @@ function parseMachineId(raw, file) {
1074
1404
  return id;
1075
1405
  }
1076
1406
  async function loadOrCreate(configDir) {
1077
- const file = path4.join(configDir, "machine.json");
1407
+ const file = path7.join(configDir, "machine.json");
1078
1408
  let raw = null;
1079
1409
  try {
1080
- raw = await readFile4(file, "utf8");
1410
+ raw = await readFile6(file, "utf8");
1081
1411
  } catch (err) {
1082
1412
  const code = err.code;
1083
1413
  if (code !== "ENOENT") {
@@ -1087,17 +1417,17 @@ async function loadOrCreate(configDir) {
1087
1417
  if (raw !== null) {
1088
1418
  return parseMachineId(raw, file);
1089
1419
  }
1090
- const machineId = randomUUID3();
1091
- await mkdir3(configDir, { recursive: true, mode: 448 });
1420
+ const machineId = randomUUID4();
1421
+ await mkdir4(configDir, { recursive: true, mode: 448 });
1092
1422
  try {
1093
- await writeFile4(file, `${JSON.stringify({ machineId }, null, 2)}
1423
+ await writeFile5(file, `${JSON.stringify({ machineId }, null, 2)}
1094
1424
  `, {
1095
1425
  flag: "wx",
1096
1426
  mode: 384
1097
1427
  });
1098
1428
  } catch (err) {
1099
1429
  if (err.code === "EEXIST") {
1100
- return parseMachineId(await readFile4(file, "utf8"), file);
1430
+ return parseMachineId(await readFile6(file, "utf8"), file);
1101
1431
  }
1102
1432
  throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1103
1433
  }
@@ -1105,7 +1435,7 @@ async function loadOrCreate(configDir) {
1105
1435
  return machineId;
1106
1436
  }
1107
1437
  function loadOrCreateMachineId(configDir) {
1108
- const key = path4.resolve(configDir);
1438
+ const key = path7.resolve(configDir);
1109
1439
  const existing = inFlightByConfigDir.get(key);
1110
1440
  if (existing !== void 0) return existing;
1111
1441
  const pending = loadOrCreate(key).finally(() => {
@@ -1139,7 +1469,7 @@ async function resolveRepoIdentity(root, deps) {
1139
1469
  try {
1140
1470
  canonicalRoot = realpathSync(root);
1141
1471
  } catch {
1142
- canonicalRoot = path5.resolve(root);
1472
+ canonicalRoot = path8.resolve(root);
1143
1473
  }
1144
1474
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1145
1475
  }
@@ -1151,14 +1481,14 @@ function makeRepoIdentityResolver(deps) {
1151
1481
  }
1152
1482
 
1153
1483
  // 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;
1484
+ 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
1485
  function resolveStartDir(env, cwd) {
1156
1486
  const cpd = env["CLAUDE_PROJECT_DIR"];
1157
1487
  return cpd != null && cpd.length > 0 ? cpd : cwd;
1158
1488
  }
1159
1489
  function dirHasGit(dir) {
1160
1490
  try {
1161
- statSync2(path6.join(dir, ".git"));
1491
+ statSync2(path9.join(dir, ".git"));
1162
1492
  return true;
1163
1493
  } catch {
1164
1494
  return false;
@@ -1170,14 +1500,14 @@ function findRepoRoot(startDir, hasGit = dirHasGit) {
1170
1500
  if (hasGit(current)) {
1171
1501
  return { root: current, foundGit: true };
1172
1502
  }
1173
- const parent = path6.dirname(current);
1503
+ const parent = path9.dirname(current);
1174
1504
  if (parent === current) break;
1175
1505
  current = parent;
1176
1506
  }
1177
1507
  return { root: startDir, foundGit: false };
1178
1508
  }
1179
1509
  function isHomeDirectory(dir, home = os2.homedir()) {
1180
- return path6.resolve(dir) === path6.resolve(home);
1510
+ return path9.resolve(dir) === path9.resolve(home);
1181
1511
  }
1182
1512
  async function handleShow(deps, projectBindingPath, mode2) {
1183
1513
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1223,7 +1553,7 @@ async function handleShow(deps, projectBindingPath, mode2) {
1223
1553
  }
1224
1554
  }
1225
1555
  async function handleRebind(deps, projectId, root, mode2, yes) {
1226
- if (!UUID_RE.test(projectId)) {
1556
+ if (!UUID_RE2.test(projectId)) {
1227
1557
  throw new CliError(
1228
1558
  `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1229
1559
  2
@@ -1276,7 +1606,7 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1276
1606
  }
1277
1607
  }
1278
1608
  async function handleUnlink(projectBindingPath, mode2) {
1279
- const { readFile: readFile13, writeFile: writeFile11, chmod: chmod2 } = await import("fs/promises");
1609
+ const { readFile: readFile13, writeFile: writeFile10, chmod: chmod2 } = await import("fs/promises");
1280
1610
  let existing = {};
1281
1611
  try {
1282
1612
  const raw = await readFile13(projectBindingPath, "utf8");
@@ -1294,7 +1624,7 @@ async function handleUnlink(projectBindingPath, mode2) {
1294
1624
  }
1295
1625
  const { projectId: _removed, ...rest } = existing;
1296
1626
  void _removed;
1297
- await writeFile11(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1627
+ await writeFile10(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1298
1628
  await chmod2(projectBindingPath, 420);
1299
1629
  if (mode2 === "json") {
1300
1630
  printResult({ unlinked: true, projectBindingPath }, mode2);
@@ -1304,7 +1634,7 @@ async function handleUnlink(projectBindingPath, mode2) {
1304
1634
  }
1305
1635
  }
1306
1636
  async function performLink(deps, projectId, mode2) {
1307
- if (!UUID_RE.test(projectId)) {
1637
+ if (!UUID_RE2.test(projectId)) {
1308
1638
  throw new CliError(
1309
1639
  `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1310
1640
  2
@@ -1318,17 +1648,19 @@ async function performLink(deps, projectId, mode2) {
1318
1648
  `
1319
1649
  );
1320
1650
  }
1651
+ const http = deps.http ?? createHttpClient({
1652
+ baseUrl: deps.settings.baseUrl,
1653
+ token: deps.settings.token,
1654
+ version: deps.version
1655
+ });
1656
+ let projectName = path9.basename(root);
1321
1657
  if (deps.settings.token != null) {
1322
1658
  try {
1323
- const http = deps.http ?? createHttpClient({
1324
- baseUrl: deps.settings.baseUrl,
1325
- token: deps.settings.token,
1326
- version: deps.version
1327
- });
1328
1659
  const result = await http.get(
1329
1660
  "/api/projects"
1330
1661
  );
1331
1662
  const projects = Array.isArray(result.projects) ? result.projects : [];
1663
+ projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
1332
1664
  if (!projects.some((p) => p.id === projectId)) {
1333
1665
  process.stderr.write(
1334
1666
  `Warning: project ${projectId} was not found in GET /api/projects.
@@ -1349,14 +1681,29 @@ Proceeding anyway \u2014 verify the ID is correct.
1349
1681
  );
1350
1682
  }
1351
1683
  await writeRepoBinding(root, projectId);
1352
- const writtenPath = path6.join(root, "nolto.json");
1684
+ const writtenPath = path9.join(root, "nolto.json");
1685
+ if (deps.settings.token == null) {
1686
+ process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
1687
+ } else {
1688
+ await ensureRoadmapCache({
1689
+ env: process.env,
1690
+ http,
1691
+ projectId,
1692
+ projectName,
1693
+ repoRoot: root,
1694
+ repoIdentity: await makeRepoIdentityResolver(deps)(root),
1695
+ log: (line) => {
1696
+ if (mode2 !== "json") process.stdout.write(line + "\n");
1697
+ }
1698
+ });
1699
+ }
1353
1700
  let registryAdded = false;
1354
1701
  if (isHomeDirectory(root)) {
1355
1702
  process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
1356
1703
  `);
1357
1704
  } else {
1358
1705
  try {
1359
- registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), root)).added;
1706
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
1360
1707
  } catch (err) {
1361
1708
  const message = err instanceof Error ? err.message : String(err);
1362
1709
  process.stderr.write(`Warning: could not update watch registry: ${message}
@@ -1436,35 +1783,35 @@ function invalidBindingError(projectBindingPath, error) {
1436
1783
  }
1437
1784
 
1438
1785
  // 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";
1786
+ import { cp, mkdir as mkdir5, readFile as readFile7, writeFile as writeFile6, rm as rm2 } from "fs/promises";
1787
+ import { existsSync as existsSync2 } from "fs";
1788
+ import path10 from "path";
1442
1789
  import { fileURLToPath } from "url";
1443
- var __dirname = path7.dirname(fileURLToPath(import.meta.url));
1790
+ var __dirname = path10.dirname(fileURLToPath(import.meta.url));
1444
1791
  function resolveSkillSourceDir() {
1445
1792
  const candidates = [
1446
- path7.resolve(__dirname, "skill/roadmap-progress"),
1793
+ path10.resolve(__dirname, "skill/roadmap-progress"),
1447
1794
  // bundled: dist/skill/...
1448
- path7.resolve(__dirname, "../../../skills/roadmap-progress")
1795
+ path10.resolve(__dirname, "../../../skills/roadmap-progress")
1449
1796
  // source: <repo>/skills/...
1450
1797
  ];
1451
1798
  for (const candidate of candidates) {
1452
- if (existsSync(path7.join(candidate, "SKILL.md"))) return candidate;
1799
+ if (existsSync2(path10.join(candidate, "SKILL.md"))) return candidate;
1453
1800
  }
1454
1801
  throw new Error("Bundled roadmap-progress skill not found. Reinstall @nolto/cli.");
1455
1802
  }
1456
1803
  var VERSION_MARKER = ".nolto-skill-version";
1457
1804
  async function checkSkillVersionDrift(repoRoot, cliVersion) {
1458
1805
  const skillDirs = [
1459
- path7.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1460
- path7.join(repoRoot, ".agents", "skills", "roadmap-progress")
1806
+ path10.join(repoRoot, ".claude", "skills", "roadmap-progress"),
1807
+ path10.join(repoRoot, ".agents", "skills", "roadmap-progress")
1461
1808
  ];
1462
1809
  const drifted = [];
1463
1810
  for (const dir of skillDirs) {
1464
- if (!existsSync(dir)) continue;
1811
+ if (!existsSync2(dir)) continue;
1465
1812
  let installed;
1466
1813
  try {
1467
- const marker = (await readFile5(path7.join(dir, VERSION_MARKER), "utf8")).trim();
1814
+ const marker = (await readFile7(path10.join(dir, VERSION_MARKER), "utf8")).trim();
1468
1815
  installed = marker.length > 0 ? marker : null;
1469
1816
  } catch {
1470
1817
  installed = null;
@@ -1474,18 +1821,18 @@ async function checkSkillVersionDrift(repoRoot, cliVersion) {
1474
1821
  return drifted;
1475
1822
  }
1476
1823
  function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
1477
- const dirs = drifted.map(({ dir }) => path7.relative(repoRoot, dir).split(path7.sep).join("/")).join(", ");
1824
+ const dirs = drifted.map(({ dir }) => path10.relative(repoRoot, dir).split(path10.sep).join("/")).join(", ");
1478
1825
  const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
1479
1826
  return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
1480
1827
  }
1481
1828
  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);
1829
+ const targetDir = path10.join(args.skillsParentDir, "roadmap-progress");
1830
+ const markerPath = path10.join(targetDir, VERSION_MARKER);
1831
+ const dirExists = existsSync2(targetDir);
1485
1832
  let installedVersion = null;
1486
1833
  if (dirExists) {
1487
1834
  try {
1488
- installedVersion = (await readFile5(markerPath, "utf8")).trim();
1835
+ installedVersion = (await readFile7(markerPath, "utf8")).trim();
1489
1836
  } catch {
1490
1837
  installedVersion = null;
1491
1838
  }
@@ -1494,104 +1841,20 @@ async function installSkill(args) {
1494
1841
  return { action: "skipped", targetDir };
1495
1842
  }
1496
1843
  await rm2(targetDir, { recursive: true, force: true });
1497
- await mkdir4(args.skillsParentDir, { recursive: true });
1844
+ await mkdir5(args.skillsParentDir, { recursive: true });
1498
1845
  await cp(args.sourceDir, targetDir, { recursive: true });
1499
- await writeFile5(markerPath, args.version + "\n", "utf8");
1846
+ await writeFile6(markerPath, args.version + "\n", "utf8");
1500
1847
  return { action: dirExists ? "updated" : "installed", targetDir };
1501
1848
  }
1502
1849
 
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
1850
  // src/commands/init.ts
1588
- var __dirname2 = path10.dirname(fileURLToPath2(import.meta.url));
1851
+ var __dirname2 = path11.dirname(fileURLToPath2(import.meta.url));
1589
1852
  var _require = createRequire(import.meta.url);
1590
1853
  function getCliVersion() {
1591
1854
  const candidates = [
1592
- path10.resolve(__dirname2, "../package.json"),
1855
+ path11.resolve(__dirname2, "../package.json"),
1593
1856
  // bundled: dist/../package.json
1594
- path10.resolve(__dirname2, "../../package.json")
1857
+ path11.resolve(__dirname2, "../../package.json")
1595
1858
  // source: src/commands/../../package.json
1596
1859
  ];
1597
1860
  for (const pkgPath of candidates) {
@@ -1752,7 +2015,7 @@ Saved ${configPath}
1752
2015
  }
1753
2016
  if (isHomeDirectory(root)) {
1754
2017
  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.
2018
+ `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
2019
  `
1757
2020
  );
1758
2021
  return;
@@ -1784,7 +2047,7 @@ Saved ${configPath}
1784
2047
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
1785
2048
  );
1786
2049
  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);
2050
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path11.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1788
2051
  } else {
1789
2052
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId);
1790
2053
  }
@@ -1798,7 +2061,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1798
2061
  process.stdout.write("Skipped repo setup.\n");
1799
2062
  return;
1800
2063
  }
1801
- const bindingPath = deps.repoBinding?.path ?? path10.join(root, "nolto.json");
2064
+ const bindingPath = deps.repoBinding?.path ?? path11.join(root, "nolto.json");
1802
2065
  if (keepExistingBinding) {
1803
2066
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
1804
2067
  `);
@@ -1810,50 +2073,45 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
1810
2073
  );
1811
2074
  }
1812
2075
  await writeRepoBinding(root, repoProject.id);
1813
- process.stdout.write(`binding: wrote ${path10.join(root, "nolto.json")}
2076
+ process.stdout.write(`binding: wrote ${path11.join(root, "nolto.json")}
1814
2077
  `);
1815
2078
  }
1816
2079
  const sourceDir = resolveSkillSourceDir();
1817
2080
  const version = getCliVersion();
1818
2081
  const claudeInstall = await installSkill({
1819
- skillsParentDir: path10.join(root, ".claude", "skills"),
2082
+ skillsParentDir: path11.join(root, ".claude", "skills"),
1820
2083
  sourceDir,
1821
2084
  version
1822
2085
  });
1823
2086
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
1824
2087
  `);
1825
- const usesAgentsTooling = fs.existsSync(path10.join(root, ".agents")) || fs.existsSync(path10.join(root, ".codex")) || fs.existsSync(path10.join(root, "AGENTS.md"));
2088
+ const usesAgentsTooling = fs.existsSync(path11.join(root, ".agents")) || fs.existsSync(path11.join(root, ".codex")) || fs.existsSync(path11.join(root, "AGENTS.md"));
1826
2089
  if (usesAgentsTooling) {
1827
2090
  const agentsInstall = await installSkill({
1828
- skillsParentDir: path10.join(root, ".agents", "skills"),
2091
+ skillsParentDir: path11.join(root, ".agents", "skills"),
1829
2092
  sourceDir,
1830
2093
  version
1831
2094
  });
1832
2095
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
1833
2096
  `);
1834
2097
  }
1835
- const scaffold = await scaffoldRoadmap({
2098
+ await ensureRoadmapCache({
2099
+ env: process.env,
2100
+ http: repoHttp,
2101
+ projectId: repoProject.id,
2102
+ projectName: repoProject.name,
1836
2103
  repoRoot: root,
1837
- projectName: repoProject.name
2104
+ repoIdentity: await makeRepoIdentityResolver(deps)(root),
2105
+ log: (line) => {
2106
+ process.stdout.write(line + "\n");
2107
+ }
1838
2108
  });
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);
2109
+ const registryResult = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId: repoProject.id });
1845
2110
  process.stdout.write(
1846
2111
  registryResult.added ? `watch registry: added ${root}
1847
2112
  ` : `watch registry: already registered
1848
2113
  `
1849
2114
  );
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
2115
  } finally {
1858
2116
  rl.close();
1859
2117
  }
@@ -2085,25 +2343,44 @@ function register5(program, deps) {
2085
2343
  }
2086
2344
 
2087
2345
  // 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";
2346
+ import { execFile as execFile2 } from "child_process";
2347
+ import { promisify } from "util";
2348
+ import { readFile as readFile8, realpath as realpath2 } from "fs/promises";
2091
2349
  import { existsSync as existsSync3 } from "fs";
2092
2350
 
2093
- // src/git-links.ts
2094
- function parseGitLog(raw) {
2095
- return raw.split("\n").filter((line) => line.length > 0).map((line) => {
2096
- const fields = line.replace(/\r$/, "").split("");
2097
- const [ref, subject, author, committedAt] = fields;
2098
- if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
2099
- throw new Error("Malformed git log entry");
2100
- }
2101
- return { ref, subject, author, committedAt: new Date(committedAt).toISOString() };
2102
- });
2103
- }
2104
- function extractIssueKeys(subject) {
2105
- return [...new Set([...subject.matchAll(/\b([A-Z][A-Z0-9]{1,9})-([1-9][0-9]{0,8})\b/g)].map((match) => match[0]))];
2106
- }
2351
+ // src/roadmap-read.ts
2352
+ import path12 from "path";
2353
+ async function resolveRoadmapReadContext(deps) {
2354
+ if (deps.settings.token == null) {
2355
+ throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2356
+ }
2357
+ const startDir = resolveStartDir(process.env, process.cwd());
2358
+ const { root, foundGit } = findRepoRoot(startDir);
2359
+ if (!foundGit) {
2360
+ throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2361
+ }
2362
+ const binding = await loadRepoBinding(path12.join(root, "nolto.json"));
2363
+ const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2364
+ if (projectId == null) {
2365
+ throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
2366
+ }
2367
+ return { root, projectId };
2368
+ }
2369
+
2370
+ // src/git-links.ts
2371
+ function parseGitLog(raw) {
2372
+ return raw.split("\n").filter((line) => line.length > 0).map((line) => {
2373
+ const fields = line.replace(/\r$/, "").split("");
2374
+ const [ref, subject, author, committedAt] = fields;
2375
+ if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
2376
+ throw new Error("Malformed git log entry");
2377
+ }
2378
+ return { ref, subject, author, committedAt: new Date(committedAt).toISOString() };
2379
+ });
2380
+ }
2381
+ function extractIssueKeys(subject) {
2382
+ return [...new Set([...subject.matchAll(/\b([A-Z][A-Z0-9]{1,9})-([1-9][0-9]{0,8})\b/g)].map((match) => match[0]))];
2383
+ }
2107
2384
  function extractPrNumber(subject) {
2108
2385
  return /\(#([1-9][0-9]{0,8})\)$/.exec(subject)?.[1] ?? /^Merge pull request #([1-9][0-9]{0,8})\b/.exec(subject)?.[1] ?? null;
2109
2386
  }
@@ -2138,121 +2415,16 @@ async function collectGitLinks(root, exec) {
2138
2415
  }
2139
2416
 
2140
2417
  // 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) {
2418
+ import path13 from "path";
2419
+ import { readdir as readdir3 } from "fs/promises";
2420
+ function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2249
2421
  const planAbsPaths = /* @__PURE__ */ new Set();
2250
- const resolvedRoot = path12.resolve(root);
2422
+ const resolvedRoot = path13.resolve(root);
2251
2423
  for (const roadmap of roadmaps) {
2252
2424
  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}`);
2425
+ const absolute = path13.resolve(resolvedRoot, ref.path);
2426
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path13.sep)) {
2427
+ warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2256
2428
  continue;
2257
2429
  }
2258
2430
  planAbsPaths.add(absolute);
@@ -2260,107 +2432,63 @@ function collectContainedPlanAbsPaths(roadmaps, root, warn) {
2260
2432
  }
2261
2433
  return [...planAbsPaths];
2262
2434
  }
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
2435
  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
- );
2436
+ const { projectId } = args;
2437
+ const slugs = args.slugs ?? await listCachedSlugs(io.env, projectId);
2438
+ if (slugs.length === 0) {
2439
+ let legacyFiles = [];
2440
+ try {
2441
+ legacyFiles = await readdir3(path13.join(args.root, ".nolto", "roadmaps"));
2442
+ } catch (err) {
2443
+ if (err.code !== "ENOENT") throw err;
2307
2444
  }
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
- );
2445
+ if (legacyFiles.some((file) => file.endsWith(".json"))) {
2446
+ throw new CliError("Roadmaps are still in .nolto/roadmaps. Run `nolto roadmap migrate`.", 2);
2447
+ }
2448
+ throw new CliError("No cached roadmap for this project. Run `nolto pull` or `nolto init`.", 2);
2449
+ }
2450
+ const roadmaps = [];
2451
+ for (const slug of slugs) {
2452
+ const entry = await readCache(io.env, projectId, slug);
2453
+ if (!entry) throw new CliError(`No cached roadmap "${slug}". Run \`nolto roadmap pull ${slug}\`.`, 2);
2454
+ roadmaps.push({ slug, ...entry });
2329
2455
  }
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
- );
2348
2456
  const results = [];
2349
2457
  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
2458
+ for (const entry of roadmaps) {
2459
+ const { slug, roadmap, meta } = entry;
2460
+ if (args.onlyDirty && !isDirty(entry)) continue;
2461
+ try {
2462
+ const response = await runSync(
2463
+ { repoRoot: args.root, projectId, slug, roadmap, repoIdentity, baseRevision: meta?.revision ?? 0 },
2464
+ { http: io.http, readFile: io.readFile, fileExists: io.fileExists, realpath: io.realpath, log: io.log, warn: io.warn }
2465
+ );
2466
+ await writeCache(io.env, projectId, slug, response.roadmap ?? roadmap, {
2467
+ revision: response.revision,
2468
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2469
+ currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : meta?.currentTaskId
2470
+ });
2471
+ results.push(response);
2472
+ entry.roadmap = response.roadmap ?? roadmap;
2473
+ } catch (err) {
2474
+ if (err instanceof CliError && err.status === 409) {
2475
+ if (err.serverError === "task_conflict") {
2476
+ const conflicts = err.body?.["conflicts"];
2477
+ if (Array.isArray(conflicts)) {
2478
+ for (const conflict of conflicts) {
2479
+ if (conflict !== null && typeof conflict === "object") {
2480
+ io.warn(` ${conflict.level} ${conflict.id} ${conflict.field}: ours=${JSON.stringify(conflict.ours)} theirs=${JSON.stringify(conflict.theirs)}`);
2481
+ }
2482
+ }
2483
+ }
2484
+ throw new CliError(`Roadmap ${slug} conflicts with the server. Run \`nolto pull\` and resolve, then sync again.`, 4);
2361
2485
  }
2362
- )
2363
- );
2486
+ if (err.serverError === "base_revision_expired") {
2487
+ throw new CliError(`Roadmap ${slug} is based on an expired revision. Run \`nolto pull\` and reapply your changes.`, 4);
2488
+ }
2489
+ }
2490
+ throw err;
2491
+ }
2364
2492
  }
2365
2493
  let gitLinks = null;
2366
2494
  if (io.exec && io.gitLinks !== false) {
@@ -2384,80 +2512,68 @@ async function syncRepo(args, io) {
2384
2512
  io.warn(`git links: skipped \u2014 ${error instanceof Error ? error.message : String(error)}`);
2385
2513
  }
2386
2514
  }
2387
- return { results, planAbsPaths, gitLinks };
2515
+ return { results, planAbsPaths: collectContainedPlanAbsPaths(roadmaps.map((entry) => entry.roadmap), args.root, io.warn), gitLinks };
2388
2516
  }
2389
2517
 
2390
2518
  // src/commands/sync.ts
2391
2519
  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);
2520
+ 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) => {
2521
+ await runSyncCommand(deps, opts);
2522
+ });
2523
+ }
2524
+ async function runSyncCommand(deps, opts = {}) {
2525
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2526
+ const http = deps.http;
2527
+ const warn2 = (line) => {
2528
+ process.stderr.write((line.startsWith(" ") ? "" : "Warning: ") + line + "\n");
2529
+ };
2530
+ const response = await syncRepo(
2531
+ { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2532
+ {
2533
+ env: process.env,
2534
+ readFile: (p) => readFile8(p, "utf8"),
2535
+ realpath: (p) => realpath2(p),
2536
+ fileExists: (p) => existsSync3(p),
2537
+ repoIdentity: makeRepoIdentityResolver(deps),
2538
+ exec: promisify(execFile2),
2539
+ gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2540
+ http,
2541
+ log: (line) => {
2542
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
2543
+ },
2544
+ warn: warn2
2400
2545
  }
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 {
2546
+ );
2547
+ try {
2548
+ const drifted = await checkSkillVersionDrift(root, deps.version);
2549
+ if (drifted.length > 0) {
2550
+ warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
2433
2551
  }
2434
- let registryAdded = false;
2435
- if (isHomeDirectory(root)) {
2436
- process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2552
+ } catch {
2553
+ }
2554
+ let registryAdded = false;
2555
+ if (isHomeDirectory(root)) {
2556
+ process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2437
2557
  `);
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}
2558
+ } else {
2559
+ try {
2560
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
2561
+ } catch (err) {
2562
+ const message = err instanceof Error ? err.message : String(err);
2563
+ process.stderr.write(`Warning: could not update watch registry: ${message}
2444
2564
  `);
2445
- }
2446
2565
  }
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}
2566
+ }
2567
+ if (!opts.quiet && deps.output.mode === "json") {
2568
+ const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
2569
+ printResult({ ...publicResponse, registryAdded }, "json");
2570
+ } else if (!opts.quiet && registryAdded) {
2571
+ process.stdout.write(`watch registry: added ${root}
2452
2572
  `);
2453
- }
2454
- });
2573
+ }
2574
+ return response;
2455
2575
  }
2456
2576
 
2457
- // src/commands/diff.ts
2458
- import { readFile as readFile8 } from "fs/promises";
2459
- import path14 from "path";
2460
-
2461
2577
  // src/roadmap-diff.ts
2462
2578
  function diffRoadmaps(local, server) {
2463
2579
  if (local === null && server === null) return [];
@@ -2520,7 +2636,7 @@ function diffRoadmaps(local, server) {
2520
2636
  }
2521
2637
  }
2522
2638
  const meta = [
2523
- { field: "updatedAt", local: local.updatedAt, server: server.updatedAt },
2639
+ { field: "updatedAt", local: local.updatedAt ?? null, server: server.updatedAt ?? null },
2524
2640
  {
2525
2641
  field: "currentTaskId",
2526
2642
  local: local.currentTaskId ?? null,
@@ -2559,46 +2675,15 @@ function formatRoadmapDiff(slug, entries) {
2559
2675
  return lines;
2560
2676
  }
2561
2677
 
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
2678
  // src/commands/diff.ts
2594
2679
  function register7(program, deps) {
2595
2680
  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);
2681
+ const { projectId } = await resolveRoadmapReadContext(deps);
2597
2682
  const list = await deps.http.get(
2598
2683
  `/api/projects/${projectId}/roadmaps`
2599
2684
  );
2600
2685
  const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2601
- const localSlugs = await listLocalRoadmapSlugs(root);
2686
+ const localSlugs = await listCachedSlugs(process.env, projectId);
2602
2687
  const localSlugSet = new Set(localSlugs);
2603
2688
  const allSlugs = [.../* @__PURE__ */ new Set([...localSlugs, ...serverBySlug.keys()])].sort();
2604
2689
  if (requestedSlug != null && !allSlugs.includes(requestedSlug)) {
@@ -2612,9 +2697,8 @@ function register7(program, deps) {
2612
2697
  for (const slug of targetSlugs) {
2613
2698
  let local = null;
2614
2699
  if (localSlugSet.has(slug)) {
2615
- const localPath = path14.join(root, ".nolto", "roadmaps", `${slug}.json`);
2616
2700
  try {
2617
- local = await loadValidRoadmap(localPath, (filePath) => readFile8(filePath, "utf8"));
2701
+ local = (await readCache(process.env, projectId, slug))?.roadmap ?? null;
2618
2702
  } catch (err) {
2619
2703
  const message = err instanceof Error ? err.message : String(err);
2620
2704
  process.stderr.write(`Warning: could not diff ${slug}.json: ${message}
@@ -2656,347 +2740,305 @@ function register7(program, deps) {
2656
2740
  });
2657
2741
  }
2658
2742
 
2743
+ // src/roadmap-commands.ts
2744
+ import path14 from "path";
2745
+ import { existsSync as existsSync4 } from "fs";
2746
+ import { readFile as readFile9, readdir as readdir4, writeFile as writeFile7, rename as rename4, unlink as unlink3, realpath as realpath3 } from "fs/promises";
2747
+ import { randomUUID as randomUUID5 } from "crypto";
2748
+ import readline4 from "readline/promises";
2749
+
2659
2750
  // src/commands/pull.ts
2660
- import { mkdir as mkdir7, readFile as readFile9, writeFile as writeFile8 } from "fs/promises";
2661
- import path15 from "path";
2751
+ function register8(program, deps) {
2752
+ 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) => {
2753
+ await runPull(deps, { ...opts, slug: requestedSlug });
2754
+ });
2755
+ }
2756
+ async function runPull(deps, opts = {}) {
2757
+ const messages = [];
2758
+ const { projectId } = await resolveRoadmapReadContext(deps);
2759
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2760
+ const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2761
+ if (opts.slug != null && !serverBySlug.has(opts.slug)) {
2762
+ throw new CliError(`Roadmap "${opts.slug}" was not found on the server.`, 2);
2763
+ }
2764
+ const slugs = opts.slug == null ? [...serverBySlug.keys()] : [opts.slug];
2765
+ let skipped = false;
2766
+ for (const slug of slugs) {
2767
+ if (!await pullRoadmapCache({
2768
+ env: process.env,
2769
+ http: deps.http,
2770
+ projectId,
2771
+ slug,
2772
+ force: opts.force,
2773
+ log: (line) => {
2774
+ messages.push(line);
2775
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
2776
+ },
2777
+ warn: (line) => {
2778
+ process.stderr.write(line + "\n");
2779
+ }
2780
+ })) skipped = true;
2781
+ }
2782
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
2783
+ if (!opts.quiet && deps.output.mode === "json") printResult({ messages }, "json");
2784
+ }
2662
2785
 
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 });
2786
+ // src/roadmap-commands.ts
2787
+ var warn = (line) => {
2788
+ process.stderr.write(line + "\n");
2789
+ };
2790
+ async function pull(deps, projectId, slug) {
2791
+ if (!await pullRoadmapCache({ env: process.env, http: deps.http, projectId, slug, log: () => void 0, warn })) {
2792
+ throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2793
+ }
2794
+ }
2795
+ async function selectRoadmap(deps, requestedSlug) {
2796
+ const context2 = await resolveRoadmapReadContext(deps);
2797
+ let slug = requestedSlug;
2798
+ if (slug === void 0) {
2799
+ let slugs = await listCachedSlugs(process.env, context2.projectId);
2800
+ if (slugs.length === 0) {
2801
+ await runPull(deps, { quiet: true });
2802
+ slugs = await listCachedSlugs(process.env, context2.projectId);
2803
+ }
2804
+ if (slugs.length !== 1) {
2805
+ 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);
2806
+ }
2807
+ slug = slugs[0];
2808
+ }
2809
+ const paths = cachePaths(process.env, context2.projectId, slug);
2810
+ if (!existsSync4(paths.json)) await pull(deps, context2.projectId, slug);
2811
+ return { ...context2, slug, paths };
2812
+ }
2813
+ async function roadmapPath(deps, slug) {
2814
+ const { paths } = await selectRoadmap(deps, slug);
2815
+ printResult(path14.resolve(paths.json), deps.output.mode);
2816
+ }
2817
+ async function roadmapStatus(deps, slug, fresh = false) {
2818
+ const selected = await selectRoadmap(deps, slug);
2819
+ if (fresh) await pull(deps, selected.projectId, selected.slug);
2820
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2821
+ const { roadmap, meta } = entry;
2822
+ const stats = deriveTaskStats(roadmap);
2823
+ const tasks = roadmap.phases.flatMap((phase) => phase.tasks);
2824
+ const current = tasks.find((task) => task.id === meta?.currentTaskId);
2825
+ const blocked = tasks.filter((task) => task.status === "blocked");
2826
+ const age = meta ? (Date.now() - Date.parse(meta.pulledAt)) / 6e4 : NaN;
2827
+ if (age > 10) warn(`Warning: cache is ${Math.floor(age)} minutes old; run with --fresh or nolto roadmap pull`);
2828
+ if (deps.output.mode === "json") {
2829
+ printResult({ roadmap, stats, currentTaskId: meta?.currentTaskId ?? null, revision: meta?.revision ?? 0, pulledAt: meta?.pulledAt ?? null }, "json");
2830
+ return;
2669
2831
  }
2670
- return result;
2832
+ printResult([
2833
+ `${roadmap.project.name}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
2834
+ `Current: ${current ? `${current.id} \u2014 ${current.title}` : "none"}`,
2835
+ `Blocked: ${blocked.map((task) => `${task.id} \u2014 ${task.title}`).join(", ") || "none"}`,
2836
+ `Summary: ${roadmap.summary}`,
2837
+ `Revision: ${meta?.revision ?? 0} (pulled ${meta?.pulledAt ?? "unknown"})`
2838
+ ].join("\n"), "human");
2671
2839
  }
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;
2684
- }
2685
- const candidates = [ours, theirs];
2686
- if (candidates.some((task) => task.status === "done" && task.completedAt != null)) {
2687
- return "done";
2840
+ async function roadmapValidate(deps, slug) {
2841
+ const { paths } = await selectRoadmap(deps, slug);
2842
+ let parsed;
2843
+ try {
2844
+ parsed = JSON.parse(await readFile9(paths.json, "utf8"));
2845
+ } catch {
2846
+ throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
2688
2847
  }
2689
- for (const status of ["blocked", "in-progress", "todo"]) {
2690
- if (candidates.some((task) => task.status === status)) return status;
2848
+ const result = validateRoadmap(parsed);
2849
+ for (const warning of result.warnings) warn(`WARN ${warning}`);
2850
+ if (result.errors.length) {
2851
+ for (const error of result.errors) warn(`ERROR ${error}`);
2852
+ throw new CliError(`Roadmap validation failed: ${paths.json}`, 1);
2691
2853
  }
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];
2696
- }
2697
- function latest(values) {
2698
- return values.filter((value) => value != null).sort((a, b) => Date.parse(b) - Date.parse(a))[0];
2854
+ printResult(deps.output.mode === "json" ? { path: paths.json, ...result } : `OK ${paths.json}`, deps.output.mode);
2699
2855
  }
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;
2856
+ async function roadmapSummary(deps, slug, text) {
2857
+ const selected = await selectRoadmap(deps, slug);
2858
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2859
+ entry.roadmap.summary = text;
2860
+ const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
2861
+ try {
2862
+ await writeFile7(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
2863
+ await rename4(temp, selected.paths.json);
2864
+ } finally {
2865
+ await unlink3(temp).catch(() => void 0);
2866
+ }
2867
+ await runSyncCommand(deps, { slug: selected.slug });
2868
+ }
2869
+ async function patchTask(args) {
2870
+ const { env, projectId, slug, taskId } = args;
2871
+ const entry = await readCache(env, projectId, slug);
2872
+ if (entry && isDirty(entry)) throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2873
+ let response;
2874
+ try {
2875
+ response = await args.http.patch(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}`, args.body);
2876
+ } catch (error) {
2877
+ if (error instanceof CliError && error.status === 404) throw new CliError(`Task ${taskId} not found in ${slug}.`, 2);
2878
+ throw error;
2879
+ }
2880
+ const { errors } = validateRoadmap(response.roadmap);
2881
+ if (errors.length) throw new CliError(`Server roadmap "${slug}" failed validation: ${errors.join("; ")}`, 5);
2882
+ await writeCache(env, projectId, slug, response.roadmap, {
2883
+ revision: response.revision,
2884
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2885
+ currentTaskId: response.currentTaskId
2886
+ });
2887
+ return response;
2709
2888
  }
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
- );
2889
+ async function roadmapTask(deps, taskId, slug, body) {
2890
+ const selected = await selectRoadmap(deps, slug);
2891
+ if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
2892
+ if (body.plan !== void 0) {
2893
+ const absolute = path14.resolve(selected.root, body.plan);
2894
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path14.resolve(selected.root) + path14.sep)) {
2895
+ throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
2896
+ }
2897
+ if (!existsSync4(absolute)) warn(`WARN plan file not found at ${absolute}`);
2898
+ }
2899
+ const response = await patchTask({ ...selected, env: process.env, http: deps.http, taskId, body });
2900
+ if (body.plan !== void 0) await runSyncCommand(deps, { slug: selected.slug, quiet: true });
2901
+ printResult(deps.output.mode === "json" ? response : body.plan !== void 0 ? `${taskId} plan -> ${body.plan}` : `${taskId} -> ${body.status}`, deps.output.mode);
2902
+ }
2903
+ async function roadmapEvents(deps, slug, opts) {
2904
+ const selected = await selectRoadmap(deps, slug);
2905
+ const query = new URLSearchParams();
2906
+ if (opts.since !== void 0) query.set("since", opts.since);
2907
+ if (opts.limit !== void 0) query.set("limit", opts.limit);
2908
+ const response = await deps.http.get(`/api/projects/${selected.projectId}/roadmaps/${encodeURIComponent(selected.slug)}/events${query.size ? `?${query}` : ""}`);
2909
+ if (deps.output.mode === "json") printResult(response, "json");
2910
+ else for (const event of response.events) {
2911
+ printResult(`rev ${event.revision} ${event.createdAt} ${event.actor?.name ?? "system"} ${event.source} ${event.taskId} ${event.field}: ${event.from ?? "\u2014"} \u2192 ${event.to ?? "\u2014"}`, "human");
2912
+ }
2913
+ }
2914
+ async function roadmapMigrate(deps, yes = false) {
2915
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2916
+ const dir = path14.join(root, ".nolto", "roadmaps");
2917
+ let files;
2918
+ try {
2919
+ files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
2920
+ } catch (error) {
2921
+ if (error.code !== "ENOENT") throw error;
2922
+ files = [];
2735
2923
  }
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;
2924
+ if (!files.length) {
2925
+ printResult("Nothing to migrate.", deps.output.mode);
2926
+ return;
2927
+ }
2928
+ const local = [];
2929
+ for (const file of files) {
2930
+ const slug = file.slice(0, -5);
2931
+ cachePaths(process.env, projectId, slug);
2932
+ const roadmap = await loadValidRoadmap(path14.join(dir, file), (p) => readFile9(p, "utf8"));
2933
+ roadmap.schemaVersion = 3;
2934
+ delete roadmap.updatedAt;
2935
+ delete roadmap.currentTaskId;
2936
+ local.push({ slug, roadmap });
2937
+ }
2938
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2939
+ const results = [];
2940
+ for (const { slug, roadmap } of local) {
2941
+ let server;
2942
+ if (list.roadmaps.some((item) => item.slug === slug)) server = await deps.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
2943
+ const unchanged = server !== void 0 && serializeRoadmap(roadmap) === serializeRoadmap(server.roadmap);
2944
+ if (server && !unchanged && !yes) {
2945
+ if (!process.stdin.isTTY) throw new CliError(`Replacing ${slug} at server rev ${server.revision} requires confirmation; rerun with --yes.`, 2);
2946
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stderr });
2947
+ try {
2948
+ const answer = await rl.question(`Replace ${slug} on the server at rev ${server.revision} with the local file? [y/N] `);
2949
+ if (!/^y(es)?$/i.test(answer.trim())) throw new CliError(`Migration of ${slug} cancelled.`, 2);
2950
+ } finally {
2951
+ rl.close();
2778
2952
  }
2779
- continue;
2780
2953
  }
2781
- if (nearestCommon === null || insertAfter === null) {
2782
- ordered.push(task.id);
2783
- continue;
2954
+ let revision = server?.revision ?? 0;
2955
+ let saved = unchanged ? server.roadmap : roadmap;
2956
+ let currentTaskId = server?.currentTaskId;
2957
+ if (unchanged || !server) {
2958
+ await writeCache(process.env, projectId, slug, saved, { revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2959
+ }
2960
+ if (!unchanged) {
2961
+ const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
2962
+ http: deps.http,
2963
+ readFile: (p) => readFile9(p, "utf8"),
2964
+ realpath: realpath3,
2965
+ fileExists: existsSync4,
2966
+ log: () => void 0,
2967
+ warn
2968
+ });
2969
+ revision = response.revision;
2970
+ saved = response.roadmap ?? roadmap;
2971
+ if (response.currentTaskId !== void 0) currentTaskId = response.currentTaskId;
2972
+ await writeCache(process.env, projectId, slug, saved, { revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2784
2973
  }
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);
2974
+ const action = unchanged ? "unchanged" : server ? "replaced" : "created";
2975
+ results.push({ slug, action, revision });
2976
+ if (deps.output.mode !== "json") printResult(`${action} ${slug} (rev ${revision})`, "human");
2821
2977
  }
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);
2831
- }
2978
+ const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
2979
+ let attributes = "";
2980
+ try {
2981
+ attributes = await readFile9(path14.join(root, ".gitattributes"), "utf8");
2982
+ } catch (error) {
2983
+ if (error.code !== "ENOENT") throw error;
2832
2984
  }
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
- );
2985
+ if (attributes.split(/\r?\n/).some((line) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line))) {
2986
+ nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
2893
2987
  }
2894
- return merged;
2988
+ nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
2989
+ await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
2990
+ printResult(deps.output.mode === "json" ? { results, nextSteps } : nextSteps.join("\n"), deps.output.mode);
2895
2991
  }
2896
2992
 
2897
- // src/commands/pull.ts
2898
- async function readExisting(filePath) {
2899
- 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;
2906
- }
2907
- }
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
- });
2993
+ // src/commands/roadmap.ts
2994
+ function register9(program, deps) {
2995
+ const roadmap = program.command("roadmap").description("Read and update server roadmaps through the local cache.");
2996
+ roadmap.command("path [slug]").description("Print the cached roadmap path").action((slug) => roadmapPath(deps, slug));
2997
+ 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 }));
2998
+ 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));
2999
+ roadmap.command("status [slug]").description("Show progress and cache revision").option("--fresh", "Pull before showing status").action((slug, opts) => roadmapStatus(deps, slug, opts.fresh));
3000
+ roadmap.command("validate [slug]").description("Validate cached JSON").action((slug) => roadmapValidate(deps, slug));
3001
+ roadmap.command("summary [slug]").description("Replace the summary and sync").requiredOption("--text <text>", "New summary").action((slug, opts) => roadmapSummary(deps, slug, opts.text));
3002
+ const bodies = {
3003
+ start: { status: "in-progress", currentTask: true },
3004
+ done: { status: "done" },
3005
+ block: { status: "blocked" },
3006
+ todo: { status: "todo", startedAt: null, completedAt: null }
3007
+ };
3008
+ for (const [name, body] of Object.entries(bodies)) {
3009
+ const command = roadmap.command(`${name} <task>`).description(`Set task status to ${body.status}`).option("--slug <slug>", "Roadmap slug (required with multiple cached roadmaps)");
3010
+ if (name === "block") command.requiredOption("--note <text>", "Blocker description");
3011
+ else command.option("--note <text>", "Task note");
3012
+ command.action((task, opts) => roadmapTask(deps, task, opts.slug, {
3013
+ ...body,
3014
+ ...opts.note !== void 0 ? { note: opts.note } : {}
3015
+ }));
3016
+ }
3017
+ 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 }));
3018
+ 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));
3019
+ 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
3020
  }
2980
3021
 
2981
3022
  // 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";
3023
+ import { execFile as execFile3 } from "child_process";
3024
+ import { promisify as promisify2 } from "util";
3025
+ import { readFile as readFile10, realpath as realpath4 } from "fs/promises";
3026
+ import { existsSync as existsSync5, mkdirSync } from "fs";
2986
3027
  import path17 from "path";
2987
3028
  import chokidar from "chokidar";
2988
3029
 
2989
3030
  // src/watch-core.ts
3031
+ import path15 from "path";
2990
3032
  var WatchSet = class {
2991
3033
  constructor(deps) {
2992
3034
  this.deps = deps;
2993
3035
  }
2994
3036
  deps;
2995
3037
  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;
3038
+ async reconcile(repos) {
3039
+ const nextRoots = new Map(repos.map((repo) => [repo.root, repo]));
3040
+ for (const [root, { handle, projectId }] of this.handles) {
3041
+ if (nextRoots.get(root)?.projectId === projectId) continue;
3000
3042
  try {
3001
3043
  await handle.stop();
3002
3044
  } catch (err) {
@@ -3007,9 +3049,9 @@ var WatchSet = class {
3007
3049
  this.handles.delete(root);
3008
3050
  this.deps.log(`Stopped watching ${root}`);
3009
3051
  }
3010
- for (const root of nextRoots) {
3052
+ for (const [root, repo] of nextRoots) {
3011
3053
  if (this.handles.has(root)) continue;
3012
- this.handles.set(root, this.deps.start(root));
3054
+ this.handles.set(root, { handle: this.deps.start(repo), projectId: repo.projectId });
3013
3055
  this.deps.log(`Watching ${root}`);
3014
3056
  }
3015
3057
  }
@@ -3025,16 +3067,24 @@ async function reloadRoots(deps) {
3025
3067
  try {
3026
3068
  registry = await deps.load();
3027
3069
  } catch (err) {
3028
- deps.warn(
3029
- `registry reload failed: ${err instanceof Error ? err.message : String(err)} \u2014 keeping current watch set`
3030
- );
3070
+ deps.warn(`registry reload failed: ${err instanceof Error ? err.message : String(err)} \u2014 keeping current watch set`);
3031
3071
  return null;
3032
3072
  }
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
- });
3073
+ const repos = [];
3074
+ for (const repo of registry.repos) {
3075
+ if (!deps.exists(repo.root)) {
3076
+ deps.warn(`registered repo no longer exists, skipping: ${repo.root}`);
3077
+ continue;
3078
+ }
3079
+ try {
3080
+ const projectId = repo.projectId ?? (await loadRepoBinding(path15.join(repo.root, "nolto.json")))?.projectId;
3081
+ if (projectId) repos.push({ root: repo.root, projectId });
3082
+ else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3083
+ } catch (err) {
3084
+ deps.warn(`cannot read project binding, skipping ${repo.root}: ${String(err)}`);
3085
+ }
3086
+ }
3087
+ return repos;
3038
3088
  }
3039
3089
  var RepoWatch = class {
3040
3090
  constructor(root, deps) {
@@ -3046,8 +3096,15 @@ var RepoWatch = class {
3046
3096
  timer = null;
3047
3097
  running = false;
3048
3098
  pending = false;
3099
+ onlyDirty = true;
3049
3100
  watchedPlans = [];
3050
- handleEvent(_filePath) {
3101
+ handleEvent(filePath) {
3102
+ if (filePath.endsWith(".meta.json")) return;
3103
+ if (this.watchedPlans.includes(filePath)) this.onlyDirty = false;
3104
+ if (this.running) {
3105
+ this.pending = true;
3106
+ return;
3107
+ }
3051
3108
  if (this.timer != null) {
3052
3109
  this.deps.clearTimeoutFn(this.timer);
3053
3110
  }
@@ -3062,8 +3119,10 @@ var RepoWatch = class {
3062
3119
  return;
3063
3120
  }
3064
3121
  this.running = true;
3122
+ const onlyDirty = this.onlyDirty;
3123
+ this.onlyDirty = true;
3065
3124
  try {
3066
- const result = await this.deps.sync();
3125
+ const result = await this.deps.sync(onlyDirty);
3067
3126
  this.rearmPlanWatches(result.planAbsPaths);
3068
3127
  } catch (err) {
3069
3128
  this.deps.warn(
@@ -3135,18 +3194,18 @@ async function installServiceWith(deps) {
3135
3194
  deps.log("Service nolto-watch enabled and started. Logs: journalctl --user -u nolto-watch -f");
3136
3195
  }
3137
3196
  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);
3197
+ const { writeFile: writeFile10, mkdir: mkdir7 } = await import("fs/promises");
3198
+ const { execFile: execFile5 } = await import("child_process");
3199
+ const { promisify: promisify4 } = await import("util");
3200
+ const execFileAsync = promisify4(execFile5);
3142
3201
  await installServiceWith({
3143
3202
  platform: process.platform,
3144
3203
  env: process.env,
3145
3204
  nodePath: process.execPath,
3146
3205
  scriptPath: path16.resolve(process.argv[1] ?? ""),
3147
- writeFile: (p, content) => writeFile11(p, content, "utf8"),
3206
+ writeFile: (p, content) => writeFile10(p, content, "utf8"),
3148
3207
  mkdir: async (p) => {
3149
- await mkdir10(p, { recursive: true });
3208
+ await mkdir7(p, { recursive: true });
3150
3209
  },
3151
3210
  exec: async (cmd) => {
3152
3211
  try {
@@ -3201,9 +3260,9 @@ async function uninstallServiceWith(deps) {
3201
3260
  }
3202
3261
  async function uninstallService() {
3203
3262
  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);
3263
+ const { execFile: execFile5 } = await import("child_process");
3264
+ const { promisify: promisify4 } = await import("util");
3265
+ const execFileAsync = promisify4(execFile5);
3207
3266
  await uninstallServiceWith({
3208
3267
  platform: process.platform,
3209
3268
  env: process.env,
@@ -3223,7 +3282,7 @@ async function uninstallService() {
3223
3282
  }
3224
3283
 
3225
3284
  // src/commands/watch.ts
3226
- function register9(program, deps) {
3285
+ function register10(program, deps) {
3227
3286
  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
3287
  if (opts.installService && opts.uninstallService) {
3229
3288
  throw new CliError("--install-service and --uninstall-service cannot be used together.", 2);
@@ -3244,14 +3303,15 @@ function register9(program, deps) {
3244
3303
  throw new CliError("--debounce must be a non-negative integer.", 2);
3245
3304
  }
3246
3305
  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}
3306
+ const roots = await reloadRoots({
3307
+ load: () => loadRegistry(registryPath),
3308
+ exists: existsSync5,
3309
+ warn: (line) => {
3310
+ process.stderr.write(`Warning: ${line}
3251
3311
  `);
3252
- return false;
3312
+ }
3253
3313
  });
3254
- if (roots.length === 0) {
3314
+ if (roots == null || roots.length === 0) {
3255
3315
  throw new CliError("No watchable repositories in the registry. Run `nolto init` in a repo first.", 2);
3256
3316
  }
3257
3317
  const http = createHttpClient({
@@ -3259,35 +3319,29 @@ function register9(program, deps) {
3259
3319
  version: deps.version,
3260
3320
  token: deps.settings.token
3261
3321
  });
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}
3322
+ const startRepo = ({ root, projectId }) => {
3323
+ const roadmapsPath = cacheDir(process.env, projectId);
3324
+ const warn2 = (line) => {
3325
+ process.stderr.write(line.startsWith(" ") ? line + "\n" : `Warning: [${path17.basename(root)}] ${line}
3267
3326
  `);
3268
3327
  };
3269
- const watcher = chokidar.watch([roadmapsPath, legacyRoadmapPath], { ignoreInitial: true });
3328
+ mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
3329
+ const watcher = chokidar.watch(roadmapsPath, { ignoreInitial: true, ignored: /\.meta\.json$/ });
3270
3330
  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 },
3331
+ sync: (onlyDirty) => syncRepo(
3332
+ { root, projectId, onlyDirty },
3274
3333
  {
3334
+ env: process.env,
3275
3335
  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,
3336
+ realpath: (p) => realpath4(p),
3337
+ fileExists: (p) => existsSync5(p),
3284
3338
  repoIdentity: makeRepoIdentityResolver(deps),
3285
- exec: promisify3(execFile4),
3339
+ exec: promisify2(execFile3),
3286
3340
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3287
3341
  http,
3288
3342
  log: (line) => process.stdout.write(`[${path17.basename(root)}] ${line}
3289
3343
  `),
3290
- warn
3344
+ warn: warn2
3291
3345
  }
3292
3346
  ),
3293
3347
  watcher,
@@ -3297,10 +3351,13 @@ function register9(program, deps) {
3297
3351
  log: (line) => process.stdout.write(line + "\n"),
3298
3352
  warn: (line) => process.stderr.write(line + "\n")
3299
3353
  });
3300
- watcher.on("all", (_event, filePath) => repoWatch.handleEvent(filePath));
3354
+ watcher.on("all", (_event, filePath) => {
3355
+ if (path17.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3356
+ repoWatch.handleEvent(filePath);
3357
+ });
3301
3358
  void checkSkillVersionDrift(root, deps.version).then((drifted) => {
3302
3359
  if (drifted.length > 0) {
3303
- warn(formatSkillVersionDriftWarning(root, deps.version, drifted));
3360
+ warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
3304
3361
  }
3305
3362
  }).catch(() => {
3306
3363
  });
@@ -3320,7 +3377,7 @@ function register9(program, deps) {
3320
3377
  registryReloadTimer = null;
3321
3378
  void reloadRoots({
3322
3379
  load: () => loadRegistry(registryPath),
3323
- exists: (root) => existsSync4(root),
3380
+ exists: (root) => existsSync5(root),
3324
3381
  warn: (line) => process.stderr.write(`Warning: ${line}
3325
3382
  `)
3326
3383
  }).then(async (newRoots) => {
@@ -3348,16 +3405,16 @@ function register9(program, deps) {
3348
3405
  }
3349
3406
 
3350
3407
  // 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";
3408
+ import { execFile as execFile4 } from "child_process";
3409
+ import { existsSync as existsSync6 } from "fs";
3410
+ import { realpath as realpath5 } from "fs/promises";
3354
3411
  import { createRequire as createRequire2 } from "module";
3355
3412
  import path19 from "path";
3356
3413
  import { fileURLToPath as fileURLToPath3 } from "url";
3357
- import { promisify as promisify4 } from "util";
3414
+ import { promisify as promisify3 } from "util";
3358
3415
 
3359
3416
  // src/update-notifier.ts
3360
- import { readFile as readFile11, writeFile as writeFile9, mkdir as mkdir9 } from "fs/promises";
3417
+ import { readFile as readFile11, writeFile as writeFile8, mkdir as mkdir6 } from "fs/promises";
3361
3418
  import https from "https";
3362
3419
  import path18 from "path";
3363
3420
  var PACKAGE = "@nolto/cli";
@@ -3417,9 +3474,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3417
3474
  });
3418
3475
  }
3419
3476
  async function writeUpdateCache(cachePath, now, latest2) {
3420
- await mkdir9(path18.dirname(cachePath), { recursive: true });
3477
+ await mkdir6(path18.dirname(cachePath), { recursive: true });
3421
3478
  const payload = { checkedAt: now, latest: latest2 };
3422
- await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
3479
+ await writeFile8(cachePath, JSON.stringify(payload), { mode: 384 });
3423
3480
  }
3424
3481
  async function refreshCache(cachePath, now, fetchLatest) {
3425
3482
  const latest2 = await fetchLatest();
@@ -3577,8 +3634,8 @@ function getCurrentVersion() {
3577
3634
  }
3578
3635
  }
3579
3636
  async function updateCli(opts = {}) {
3580
- const execFileAsync = promisify4(execFile5);
3581
- const scriptPath = await realpath3(process.argv[1] ?? "");
3637
+ const execFileAsync = promisify3(execFile4);
3638
+ const scriptPath = await realpath5(process.argv[1] ?? "");
3582
3639
  return updateCliWith({
3583
3640
  currentVersion: getCurrentVersion(),
3584
3641
  scriptPath,
@@ -3599,17 +3656,17 @@ async function updateCli(opts = {}) {
3599
3656
  };
3600
3657
  }
3601
3658
  },
3602
- realpath: realpath3,
3659
+ realpath: realpath5,
3603
3660
  fetchLatest: () => fetchLatestFromRegistry(UPDATE_REQUEST_TIMEOUT_MS, UPDATE_FETCH_OPTIONS),
3604
3661
  writeCache: writeUpdateCache,
3605
- unitExists: existsSync5,
3662
+ unitExists: existsSync6,
3606
3663
  log: opts.quiet === true ? () => void 0 : (line) => process.stdout.write(line + "\n"),
3607
3664
  warn: (line) => process.stderr.write("Warning: " + line + "\n")
3608
3665
  });
3609
3666
  }
3610
3667
 
3611
3668
  // src/commands/update.ts
3612
- function register10(program, deps) {
3669
+ function register11(program, deps) {
3613
3670
  program.command("update").description("Update @nolto/cli to the latest version and restart the watch service if installed").action(async () => {
3614
3671
  const mode2 = deps.output.mode;
3615
3672
  const result = await updateCli({ quiet: mode2 === "json" });
@@ -3620,7 +3677,243 @@ function register10(program, deps) {
3620
3677
  }
3621
3678
 
3622
3679
  // src/commands/merge-file.ts
3623
- import { readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
3680
+ import { readFile as readFile12, writeFile as writeFile9 } from "fs/promises";
3681
+
3682
+ // src/roadmap-merge.ts
3683
+ import { isDeepStrictEqual } from "util";
3684
+ function taskLocations(roadmap) {
3685
+ const result = /* @__PURE__ */ new Map();
3686
+ for (const phase of roadmap?.phases ?? []) {
3687
+ for (const task of phase.tasks) result.set(task.id, { task, phaseId: phase.id });
3688
+ }
3689
+ return result;
3690
+ }
3691
+ function chooseField(args) {
3692
+ if (args.baseExists && isDeepStrictEqual(args.ours, args.base)) return args.theirs;
3693
+ if (args.baseExists && isDeepStrictEqual(args.theirs, args.base)) return args.ours;
3694
+ if (isDeepStrictEqual(args.ours, args.theirs)) return args.ours;
3695
+ return args.newer === "ours" ? args.ours : args.theirs;
3696
+ }
3697
+ function chooseStatus(base, ours, theirs) {
3698
+ if (base !== void 0) {
3699
+ const oursChanged = ours.status !== base.status;
3700
+ const theirsChanged = theirs.status !== base.status;
3701
+ if (!oursChanged) return theirs.status;
3702
+ if (!theirsChanged) return ours.status;
3703
+ }
3704
+ const candidates = [ours, theirs];
3705
+ if (candidates.some((task) => task.status === "done" && task.completedAt != null)) {
3706
+ return "done";
3707
+ }
3708
+ for (const status of ["blocked", "in-progress", "todo"]) {
3709
+ if (candidates.some((task) => task.status === status)) return status;
3710
+ }
3711
+ return base?.status !== "done" ? base?.status ?? "todo" : "todo";
3712
+ }
3713
+ function earliest(values) {
3714
+ return values.filter((value) => value != null).sort((a, b) => Date.parse(a) - Date.parse(b))[0];
3715
+ }
3716
+ function latest(values) {
3717
+ return values.filter((value) => value != null).sort((a, b) => Date.parse(b) - Date.parse(a))[0];
3718
+ }
3719
+ function assignOptional(target, key, value) {
3720
+ if (value !== void 0) Object.assign(target, { [key]: value });
3721
+ }
3722
+ function cloneSingleTask(task) {
3723
+ const cloned = { ...task };
3724
+ if (task.dependsOn !== void 0) cloned.dependsOn = [...task.dependsOn];
3725
+ if (task.issues !== void 0) cloned.issues = [...task.issues];
3726
+ if (cloned.status !== "done") delete cloned.completedAt;
3727
+ return cloned;
3728
+ }
3729
+ function mergeTask(args) {
3730
+ const baseExists = args.base !== void 0;
3731
+ const status = chooseStatus(args.base, args.ours, args.theirs);
3732
+ const merged = {
3733
+ id: args.ours.id,
3734
+ title: chooseField({
3735
+ baseExists,
3736
+ base: args.base?.title,
3737
+ ours: args.ours.title,
3738
+ theirs: args.theirs.title,
3739
+ newer: args.newer
3740
+ }),
3741
+ status
3742
+ };
3743
+ assignOptional(
3744
+ merged,
3745
+ "startedAt",
3746
+ earliest([args.base?.startedAt, args.ours.startedAt, args.theirs.startedAt])
3747
+ );
3748
+ if (status === "done") {
3749
+ assignOptional(
3750
+ merged,
3751
+ "completedAt",
3752
+ latest([args.base?.completedAt, args.ours.completedAt, args.theirs.completedAt])
3753
+ );
3754
+ }
3755
+ assignOptional(merged, "note", chooseField({
3756
+ baseExists,
3757
+ base: args.base?.note,
3758
+ ours: args.ours.note,
3759
+ theirs: args.theirs.note,
3760
+ newer: args.newer
3761
+ }));
3762
+ assignOptional(merged, "plan", chooseField({
3763
+ baseExists,
3764
+ base: args.base?.plan,
3765
+ ours: args.ours.plan,
3766
+ theirs: args.theirs.plan,
3767
+ newer: args.newer
3768
+ }));
3769
+ const dependsOn = [
3770
+ ...args.ours.dependsOn ?? [],
3771
+ ...args.theirs.dependsOn ?? []
3772
+ ].filter((id, index, values) => values.indexOf(id) === index);
3773
+ if (dependsOn.length > 0) merged.dependsOn = dependsOn;
3774
+ const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
3775
+ if (issues.length > 0) merged.issues = issues;
3776
+ return merged;
3777
+ }
3778
+ function shouldKeep(base, ours, theirs) {
3779
+ if (base === void 0) return ours !== void 0 || theirs !== void 0;
3780
+ if (ours === void 0 && theirs === void 0) return false;
3781
+ if (ours === void 0) return !isDeepStrictEqual(theirs, base);
3782
+ if (theirs === void 0) return !isDeepStrictEqual(ours, base);
3783
+ return true;
3784
+ }
3785
+ function orderTasks(args) {
3786
+ const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
3787
+ const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
3788
+ const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
3789
+ let nearestCommon = null;
3790
+ let insertAfter = null;
3791
+ for (const task of theirsPhase?.tasks ?? []) {
3792
+ if (!args.taskIds.has(task.id)) continue;
3793
+ if (args.oursLocations.has(task.id)) {
3794
+ if (ordered.includes(task.id)) {
3795
+ nearestCommon = task.id;
3796
+ insertAfter = task.id;
3797
+ }
3798
+ continue;
3799
+ }
3800
+ if (nearestCommon === null || insertAfter === null) {
3801
+ ordered.push(task.id);
3802
+ continue;
3803
+ }
3804
+ const index = ordered.indexOf(insertAfter);
3805
+ ordered.splice(index + 1, 0, task.id);
3806
+ insertAfter = task.id;
3807
+ }
3808
+ return ordered;
3809
+ }
3810
+ function mergeRoadmaps(args) {
3811
+ const newer = Date.parse(args.theirs.updatedAt ?? "") > Date.parse(args.ours.updatedAt ?? "") ? "theirs" : "ours";
3812
+ const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
3813
+ const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
3814
+ const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
3815
+ const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
3816
+ const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
3817
+ const baseLocations = taskLocations(args.base);
3818
+ const oursLocations = taskLocations(args.ours);
3819
+ const theirsLocations = taskLocations(args.theirs);
3820
+ const keptTasks = /* @__PURE__ */ new Map();
3821
+ const targetPhaseByTask = /* @__PURE__ */ new Map();
3822
+ const taskIds = /* @__PURE__ */ new Set([
3823
+ ...baseLocations.keys(),
3824
+ ...oursLocations.keys(),
3825
+ ...theirsLocations.keys()
3826
+ ]);
3827
+ for (const taskId of taskIds) {
3828
+ const baseLocation = baseLocations.get(taskId);
3829
+ const oursLocation = oursLocations.get(taskId);
3830
+ const theirsLocation = theirsLocations.get(taskId);
3831
+ if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
3832
+ const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
3833
+ base: baseLocation?.task,
3834
+ ours: oursLocation.task,
3835
+ theirs: theirsLocation.task,
3836
+ newer
3837
+ }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
3838
+ keptTasks.set(taskId, task);
3839
+ targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
3840
+ }
3841
+ const keptPhaseIds = /* @__PURE__ */ new Set();
3842
+ const allPhaseIds = /* @__PURE__ */ new Set([
3843
+ ...basePhases.keys(),
3844
+ ...oursPhases.keys(),
3845
+ ...theirsPhases.keys()
3846
+ ]);
3847
+ for (const phaseId of allPhaseIds) {
3848
+ if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
3849
+ keptPhaseIds.add(phaseId);
3850
+ }
3851
+ }
3852
+ const phaseOrder = [
3853
+ ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
3854
+ ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
3855
+ ];
3856
+ const phases = phaseOrder.map((phaseId) => {
3857
+ const base = basePhases.get(phaseId);
3858
+ const ours = oursPhases.get(phaseId);
3859
+ const theirs = theirsPhases.get(phaseId);
3860
+ const source = ours ?? theirs;
3861
+ const title = ours !== void 0 && theirs !== void 0 ? chooseField({
3862
+ baseExists: base !== void 0,
3863
+ base: base?.title,
3864
+ ours: ours.title,
3865
+ theirs: theirs.title,
3866
+ newer
3867
+ }) : source.title;
3868
+ const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
3869
+ baseExists: base !== void 0,
3870
+ base: base?.plan,
3871
+ ours: ours.plan,
3872
+ theirs: theirs.plan,
3873
+ newer
3874
+ }) : source.plan;
3875
+ const phaseTaskIds = new Set(
3876
+ [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
3877
+ );
3878
+ const tasks = orderTasks({
3879
+ phaseId,
3880
+ taskIds: phaseTaskIds,
3881
+ ours: args.ours,
3882
+ theirs: args.theirs,
3883
+ oursLocations
3884
+ }).map((taskId) => keptTasks.get(taskId));
3885
+ const phase = { id: phaseId, title, status: "todo", tasks };
3886
+ if (plan !== void 0) phase.plan = plan;
3887
+ phase.status = derivePhaseStatus(phase);
3888
+ return phase;
3889
+ });
3890
+ const mergedTasks = new Map(
3891
+ phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
3892
+ );
3893
+ const validCurrentTask = (roadmap) => {
3894
+ const id = roadmap.currentTaskId ?? null;
3895
+ return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
3896
+ };
3897
+ const merged = {
3898
+ schemaVersion: newerRoadmap.updatedAt === void 0 ? 3 : 2,
3899
+ project: { ...newerRoadmap.project },
3900
+ updatedAt: newerRoadmap.updatedAt,
3901
+ currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
3902
+ summary: newerRoadmap.summary,
3903
+ phases
3904
+ };
3905
+ const validation = validateRoadmap(merged);
3906
+ if (validation.errors.length > 0) {
3907
+ throw new CliError(
3908
+ `Merged roadmap failed validation:
3909
+ ${validation.errors.join("\n ")}`,
3910
+ 1
3911
+ );
3912
+ }
3913
+ return merged;
3914
+ }
3915
+
3916
+ // src/commands/merge-file.ts
3624
3917
  async function readRoadmap(filePath) {
3625
3918
  let parsed;
3626
3919
  try {
@@ -3639,15 +3932,16 @@ async function readRoadmap(filePath) {
3639
3932
  }
3640
3933
  return parsed;
3641
3934
  }
3642
- function register11(program) {
3935
+ function register12(program) {
3643
3936
  program.command("merge-file <ours> <theirs>").description(
3644
3937
  'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
3645
3938
  ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
3939
+ process.stderr.write("Warning: merge-file is deprecated and will be removed; roadmaps are no longer stored in git.\n");
3646
3940
  const ours = await readRoadmap(oursPath);
3647
3941
  const theirs = await readRoadmap(theirsPath);
3648
3942
  const base = opts.base == null ? null : await readRoadmap(opts.base);
3649
3943
  const merged = mergeRoadmaps({ base, ours, theirs });
3650
- await writeFile10(
3944
+ await writeFile9(
3651
3945
  opts.output ?? oursPath,
3652
3946
  JSON.stringify(merged, null, 2) + "\n",
3653
3947
  "utf8"
@@ -3677,7 +3971,8 @@ function buildProgram(deps) {
3677
3971
  register8(program, deps);
3678
3972
  register9(program, deps);
3679
3973
  register10(program, deps);
3680
- register11(program);
3974
+ register11(program, deps);
3975
+ register12(program);
3681
3976
  program.action(() => {
3682
3977
  program.help();
3683
3978
  });