@nolto/cli 0.19.2 → 0.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +5 -5
  2. package/dist/index.js +2014 -2025
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/memory-hooks.ts
4
4
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
5
- import { existsSync as existsSync2 } from "fs";
5
+ import { existsSync as existsSync2, statSync } from "fs";
6
6
  import path2 from "path";
7
7
 
8
8
  // src/errors.ts
@@ -218,12 +218,7 @@ async function checkSkillDrift(repoRoot, opts = {}) {
218
218
  for (const parent of [".claude", ".agents"]) {
219
219
  const dir = path.join(repoRoot, parent, "skills", name);
220
220
  if (!existsSync(dir)) continue;
221
- let installed = null;
222
- try {
223
- installed = (await readFile(path.join(dir, VERSION_MARKER), "utf8")).trim();
224
- } catch {
225
- }
226
- if (installed !== sourceHash) drifted.push(path.relative(repoRoot, dir).split(path.sep).join("/"));
221
+ if (await skillContentHash(dir) !== sourceHash) drifted.push(path.relative(repoRoot, dir).split(path.sep).join("/"));
227
222
  }
228
223
  if (drifted.length) warnings.push(`${name} skill differs from the version bundled with this CLI in ${drifted.join(", ")}. Run \`nolto init\` in this repo to update it.`);
229
224
  for (const parent of opts.homeSkillDirs ?? []) {
@@ -249,6 +244,10 @@ async function installSkill(args) {
249
244
  if (dirExists && installedHash === sourceHash && args.force !== true) {
250
245
  return { action: "skipped", targetDir };
251
246
  }
247
+ if (dirExists && args.force !== true && await skillContentHash(targetDir) === sourceHash) {
248
+ await writeFile(markerPath, sourceHash + "\n", "utf8");
249
+ return { action: "updated", targetDir };
250
+ }
252
251
  await rm(targetDir, { recursive: true, force: true });
253
252
  await mkdir(args.skillsParentDir, { recursive: true });
254
253
  await cp(args.sourceDir, targetDir, { recursive: true });
@@ -274,10 +273,17 @@ function hookAgentFromArgv(argv) {
274
273
  if (arg.includes("=")) return arg.slice(arg.indexOf("=") + 1);
275
274
  return argv[hook + 1]?.startsWith("-") === false ? argv[hook + 1] : true;
276
275
  }
276
+ function isDirectory(file) {
277
+ try {
278
+ return statSync(file).isDirectory();
279
+ } catch {
280
+ return false;
281
+ }
282
+ }
277
283
  async function installMemorySkill(root) {
278
284
  const sourceDir = resolveSkillSourceDir("project-memory");
279
285
  const parents = [".claude"];
280
- if ([".agents", ".codex", "AGENTS.md"].some((name) => existsSync2(path2.join(root, name)))) parents.push(".agents");
286
+ if ([".agents", "AGENTS.md"].some((name) => existsSync2(path2.join(root, name))) || isDirectory(path2.join(root, ".codex"))) parents.push(".agents");
281
287
  const results = [];
282
288
  for (const parent of parents) {
283
289
  results.push(await installSkill({ name: "project-memory", skillsParentDir: path2.join(root, parent, "skills"), sourceDir }));
@@ -288,7 +294,7 @@ function object(value) {
288
294
  return value !== null && typeof value === "object" && !Array.isArray(value);
289
295
  }
290
296
  function detectMemoryAgents(root) {
291
- const selected = ["claude", "codex", "gemini"].filter((a) => existsSync2(path2.join(root, `.${a}`)));
297
+ const selected = ["claude", "codex", "gemini"].filter((a) => isDirectory(path2.join(root, `.${a}`)));
292
298
  return selected.length ? selected : ["claude"];
293
299
  }
294
300
  function hookCommand(agent) {
@@ -328,12 +334,16 @@ async function installMemoryHooks(root, agent, writeAgentsMd = false) {
328
334
  if (agent && agent !== "all" && !agents.includes(agent)) throw new CliError("--agent \u306F claude|codex|gemini|all", 2);
329
335
  const selected = agent && agent !== "all" ? [agent] : detectMemoryAgents(root);
330
336
  const messages = [];
337
+ if (!agent || agent === "all") {
338
+ for (const a of agents) if (existsSync2(path2.join(root, `.${a}`)) && !isDirectory(path2.join(root, `.${a}`))) messages.push(`hook ${a}: .${a} \u304C\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3067\u306F\u306A\u3044\u305F\u3081\u7701\u7565`);
339
+ }
331
340
  for (const a of selected) {
332
341
  const file = path2.join(root, `.${a}`, a === "codex" ? "hooks.json" : "settings.json");
333
342
  let settings = {};
334
343
  try {
335
344
  settings = JSON.parse(await readFile2(file, "utf8"));
336
345
  } catch (error) {
346
+ if (error.code === "ENOTDIR") throw new CliError(`${path2.dirname(file)} \u304C\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3067\u306F\u306A\u3044\u305F\u3081 hook \u3092\u8A2D\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002`, 2);
337
347
  if (error.code !== "ENOENT") throw new CliError(`${file} \u3092\u8AAD\u3081\u307E\u305B\u3093\u3002`, 2);
338
348
  }
339
349
  if (!object(settings) || settings.hooks !== void 0 && !object(settings.hooks)) throw new CliError(`${file}: hooks \u306E\u5F62\u304C\u4E0D\u6B63\u3067\u3059\u3002`, 2);
@@ -376,13 +386,13 @@ ${MEMORY_INSTRUCTIONS}
376
386
  // src/index.ts
377
387
  import { createRequire as createRequire3 } from "module";
378
388
  import { fileURLToPath as fileURLToPath4 } from "url";
379
- import path24 from "path";
389
+ import path23 from "path";
380
390
  import os5 from "os";
381
391
  import { CommanderError } from "commander";
382
392
 
383
393
  // src/config.ts
384
394
  import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3, stat } from "fs/promises";
385
- import { statSync } from "fs";
395
+ import { statSync as statSync2 } from "fs";
386
396
  import os from "os";
387
397
  import path3 from "path";
388
398
  import { z } from "zod";
@@ -435,7 +445,7 @@ function findNoltoJsonSync(startDir) {
435
445
  while (true) {
436
446
  const candidate = path3.join(current, "nolto.json");
437
447
  try {
438
- statSync(candidate);
448
+ statSync2(candidate);
439
449
  return candidate;
440
450
  } catch {
441
451
  }
@@ -595,11 +605,11 @@ function maskToken(token) {
595
605
  function createHttpClient(opts) {
596
606
  const { baseUrl, version, token } = opts;
597
607
  const base = baseUrl.replace(/\/+$/, "");
598
- async function request(method, path25, body, extraHeaders, signal) {
599
- if (!path25.startsWith("/api/")) {
600
- throw new CliError(`HTTP client path must start with /api/, got: ${path25}`, 2);
608
+ async function request(method, path24, body, extraHeaders, signal) {
609
+ if (!path24.startsWith("/api/")) {
610
+ throw new CliError(`HTTP client path must start with /api/, got: ${path24}`, 2);
601
611
  }
602
- const url = `${base}${path25}`;
612
+ const url = `${base}${path24}`;
603
613
  const headers2 = {
604
614
  ...extraHeaders,
605
615
  "Content-Type": "application/json",
@@ -672,9 +682,7 @@ function createHttpClient(opts) {
672
682
  import { Command } from "commander";
673
683
 
674
684
  // src/commands/issue.ts
675
- import { readFile as readFile4, readdir as readdir2, writeFile as writeFile4, rename, rm as rm2 } from "fs/promises";
676
- import path4 from "path";
677
- import { randomUUID } from "crypto";
685
+ import { readFile as readFile10 } from "fs/promises";
678
686
 
679
687
  // src/output.ts
680
688
  function printResult(value, mode2, opts = {}) {
@@ -739,6 +747,66 @@ function formatValue(value) {
739
747
  return JSON.stringify(value, null, 2);
740
748
  }
741
749
 
750
+ // src/watch-state.ts
751
+ import * as fs from "fs/promises";
752
+ import { randomUUID } from "crypto";
753
+ import path4 from "path";
754
+ import { z as z2 } from "zod";
755
+ var watchStateSchema = z2.object({
756
+ pid: z2.number().int().positive(),
757
+ version: z2.string().min(1),
758
+ startedAt: z2.string().datetime()
759
+ });
760
+ function getWatchStatePath(env) {
761
+ return path4.join(getConfigDir(env), "watch.json");
762
+ }
763
+ async function readWatchState(filePath, io = fs) {
764
+ try {
765
+ const result = watchStateSchema.safeParse(JSON.parse(await io.readFile(filePath, "utf8")));
766
+ return result.success ? result.data : null;
767
+ } catch {
768
+ return null;
769
+ }
770
+ }
771
+ async function writeWatchState(filePath, state, io = fs) {
772
+ await io.mkdir(path4.dirname(filePath), { recursive: true, mode: 448 });
773
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID()}`;
774
+ try {
775
+ await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
776
+ await io.rename(tempPath, filePath);
777
+ } catch (error) {
778
+ await io.unlink(tempPath).catch(() => void 0);
779
+ throw error;
780
+ }
781
+ }
782
+ async function removeWatchState(filePath, pid, io = fs) {
783
+ if ((await readWatchState(filePath, io))?.pid === pid) {
784
+ await io.unlink(filePath).catch(() => void 0);
785
+ }
786
+ }
787
+ function isAlive(pid, kill = process.kill) {
788
+ try {
789
+ kill(pid, 0);
790
+ return true;
791
+ } catch (error) {
792
+ if (error.code === "ESRCH") return false;
793
+ if (error.code === "EPERM") return true;
794
+ throw error;
795
+ }
796
+ }
797
+ async function staleWatchWarning(env, currentVersion, kill = process.kill) {
798
+ const state = await readWatchState(getWatchStatePath(env));
799
+ if (!state || state.version === currentVersion || !isAlive(state.pid, kill)) return null;
800
+ return `Warning: nolto watch (pid ${state.pid}) is running CLI v${state.version}, this CLI is v${currentVersion}. Restart it: nolto watch stop, then start it again (or nolto update).`;
801
+ }
802
+
803
+ // src/roadmap-commands.ts
804
+ import path14 from "path";
805
+ import { existsSync as existsSync5 } from "fs";
806
+ import { readFile as readFile9, readdir as readdir4, writeFile as writeFile7, rename as rename3, unlink as unlink3, realpath as realpath3 } from "fs/promises";
807
+ import { randomUUID as randomUUID5 } from "crypto";
808
+ import readline2 from "readline/promises";
809
+
742
810
  // ../roadmap-schema/src/repo-identity.ts
743
811
  var HOSTED_LOWERCASE_PATH = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
744
812
  function normalizeRemote(raw) {
@@ -758,12 +826,12 @@ function normalizeRemote(raw) {
758
826
  const firstSlash = s.indexOf("/");
759
827
  if (firstSlash <= 0) return null;
760
828
  let host = s.slice(0, firstSlash).toLowerCase();
761
- let path25 = s.slice(firstSlash + 1);
829
+ let path24 = s.slice(firstSlash + 1);
762
830
  if (hadScheme) host = host.replace(/:\d+$/, "");
763
- path25 = path25.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
764
- if (path25.length === 0) return null;
765
- if (HOSTED_LOWERCASE_PATH.has(host)) path25 = path25.toLowerCase();
766
- return `${host}/${path25}`;
831
+ path24 = path24.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
832
+ if (path24.length === 0) return null;
833
+ if (HOSTED_LOWERCASE_PATH.has(host)) path24 = path24.toLowerCase();
834
+ return `${host}/${path24}`;
767
835
  }
768
836
  function repoIdentityToString(id) {
769
837
  return `${id.kind}:${id.value}`;
@@ -977,10 +1045,11 @@ function deriveTaskStats(roadmap) {
977
1045
  let inProgress = 0;
978
1046
  let todo = 0;
979
1047
  for (const phase of roadmap.phases) {
980
- for (const task of phase.tasks) {
981
- if (task.status === "done") done += 1;
982
- else if (task.status === "blocked") blocked += 1;
983
- else if (task.status === "in-progress") inProgress += 1;
1048
+ const items = phase.tasks.length > 0 ? phase.tasks : [phase];
1049
+ for (const item of items) {
1050
+ if (item.status === "done") done += 1;
1051
+ else if (item.status === "blocked") blocked += 1;
1052
+ else if (item.status === "in-progress") inProgress += 1;
984
1053
  else todo += 1;
985
1054
  }
986
1055
  }
@@ -1101,14 +1170,14 @@ function formatIssueView(bundle) {
1101
1170
  ${comment.deletedAt ? "\u30B3\u30E1\u30F3\u30C8\u306F\u524A\u9664\u3055\u308C\u3066\u3044\u307E\u3059\u3002" : comment.body}`);
1102
1171
  return [attributes, issue.body, ...comments].join("\n\n");
1103
1172
  }
1104
- function addIssueToRoadmapTask(roadmapJson, taskId, key, now) {
1173
+ function addIssueToRoadmapTask(roadmapJson, taskId, key) {
1105
1174
  const validation = validateRoadmap(roadmapJson);
1106
1175
  if (validation.errors.length) return { error: `Invalid roadmap: ${validation.errors.join("; ")}` };
1107
1176
  const input = roadmapJson;
1108
1177
  const target = input.phases.flatMap((phase) => phase.tasks).find((task) => task.id === taskId);
1109
1178
  if (!target) return { error: `roadmap task ${taskId} was not found` };
1110
1179
  if (target.issues?.includes(key)) return { roadmap: input, changed: false };
1111
- const roadmap = { ...input, schemaVersion: 2, updatedAt: now, phases: input.phases.map((phase) => ({
1180
+ const roadmap = { ...input, phases: input.phases.map((phase) => ({
1112
1181
  ...phase,
1113
1182
  tasks: phase.tasks.map((task) => task.id === taskId ? { ...task, issues: [...task.issues ?? [], key] } : task)
1114
1183
  })) };
@@ -1122,426 +1191,430 @@ function draftUrl(baseUrl, projectId, id) {
1122
1191
  return `${baseUrl.replace(/\/+$/, "")}/projects/${encodeURIComponent(projectId)}/issues/drafts/${id}`;
1123
1192
  }
1124
1193
 
1125
- // src/commands/issue.ts
1126
- var emptySettings = { types: [], statuses: [], categories: [] };
1127
- function context(deps, command) {
1128
- if (!deps.settings.token) throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
1129
- const globals = command.optsWithGlobals();
1130
- const projectId = globals.project ?? deps.settings.defaultProjectId;
1131
- if (!projectId) throw new CliError("No project. Pass --project <id> or run nolto link.", 2);
1132
- return {
1133
- projectId,
1134
- root: `/api/projects/${encodeURIComponent(projectId)}`,
1135
- mode: globals.json ? "json" : deps.output.mode
1136
- };
1194
+ // src/roadmap-cache.ts
1195
+ import { mkdir as mkdir4, readdir as readdir2, readFile as readFile4, writeFile as writeFile4, rename, unlink } from "fs/promises";
1196
+ import { randomUUID as randomUUID2 } from "crypto";
1197
+ import path6 from "path";
1198
+
1199
+ // src/sync-core.ts
1200
+ import { createHash as createHash2 } from "crypto";
1201
+ import path5 from "path";
1202
+ function sha256Hex(content) {
1203
+ return "sha256:" + createHash2("sha256").update(content, "utf8").digest("hex");
1137
1204
  }
1138
- async function bodyText(body, file) {
1139
- if (body !== void 0 && file !== void 0) throw new CliError("Use either --body/-m or --body-file, not both.", 2);
1140
- if (file === void 0) return body;
1141
- try {
1142
- if (file !== "-") return await readFile4(file, "utf8");
1143
- const chunks = [];
1144
- for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1145
- return Buffer.concat(chunks).toString("utf8");
1146
- } catch (error) {
1147
- throw new CliError(`Cannot read body from ${file}: ${String(error)}`, 2);
1205
+ function collectPlanRefs(roadmap) {
1206
+ const seen = /* @__PURE__ */ new Set();
1207
+ const refs = [];
1208
+ for (const phase of roadmap.phases) {
1209
+ if (phase.plan != null && !seen.has(phase.plan)) {
1210
+ seen.add(phase.plan);
1211
+ refs.push({ path: phase.plan, ownerId: phase.id });
1212
+ }
1213
+ for (const task of phase.tasks) {
1214
+ if (task.plan != null && !seen.has(task.plan)) {
1215
+ seen.add(task.plan);
1216
+ refs.push({ path: task.plan, ownerId: task.id });
1217
+ }
1218
+ }
1148
1219
  }
1220
+ return refs;
1149
1221
  }
1150
- async function writeInput(deps, root, flags, create) {
1151
- const body = await bodyText(flags.body, flags.bodyFile);
1152
- const settings = flags.type || flags.status || flags.category ? await deps.http.get(`${root}/issue-settings`) : emptySettings;
1153
- const typeId = flags.type === void 0 ? void 0 : resolveMaster("type", flags.type, settings).id;
1154
- const template = create && body === void 0 && typeId !== void 0 ? settings.types.find((type) => type.id === typeId)?.bodyTemplate : void 0;
1155
- let assigneeId;
1156
- if (flags.assignee !== void 0) {
1157
- if (flags.assignee === "none") assigneeId = null;
1158
- else if (flags.assignee === "me") assigneeId = (await deps.http.get("/api/me/profile")).profile.id;
1159
- else if (isUuid(flags.assignee)) assigneeId = flags.assignee;
1160
- else throw new CliError("--assignee must be me, none or a UUID.", 2);
1222
+ async function loadValidRoadmap(filePath, readFile19) {
1223
+ let raw;
1224
+ try {
1225
+ raw = await readFile19(filePath);
1226
+ } catch {
1227
+ throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1161
1228
  }
1162
- let parentId;
1163
- if (flags.parent === false) parentId = null;
1164
- else if (flags.parent !== void 0) parentId = (await deps.http.get(`${root}/issues/${parseIssueRef(flags.parent)}`)).issue.id;
1165
- if (typeof flags.due === "string" && (!/^\d{4}-\d{2}-\d{2}$/.test(flags.due) || !Number.isFinite(Date.parse(flags.due)) || new Date(flags.due).toISOString().slice(0, 10) !== flags.due)) {
1166
- throw new CliError("--due must be a valid YYYY-MM-DD date.", 2);
1229
+ let parsed;
1230
+ try {
1231
+ parsed = JSON.parse(raw);
1232
+ } catch {
1233
+ throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1167
1234
  }
1168
- if (flags.priority !== void 0 && !["high", "normal", "low"].includes(flags.priority)) throw new CliError("--priority must be high, normal or low.", 2);
1169
- const input = {
1170
- ...flags.subject !== void 0 ? { subject: flags.subject } : {},
1171
- ...body !== void 0 ? { body } : template != null ? { body: template } : {},
1172
- ...typeId !== void 0 ? { typeId } : {},
1173
- ...flags.status !== void 0 ? { statusId: resolveMaster("status", flags.status, settings).id } : {},
1174
- ...flags.priority !== void 0 ? { priority: flags.priority } : {},
1175
- ...assigneeId !== void 0 ? { assigneeId } : {},
1176
- ...flags.due !== void 0 ? { dueDate: flags.due === false ? null : flags.due } : {},
1177
- ...flags.category !== void 0 ? { categoryIds: flags.category.map((name) => resolveMaster("category", name, settings).id) } : {},
1178
- ...parentId !== void 0 ? { parentId } : {},
1179
- ...flags.comment !== void 0 ? { comment: flags.comment } : {}
1180
- };
1181
- if (Object.keys(input).length === 0) throw new CliError("No changes. Pass a field option or --comment.", 2);
1182
- return { input, fromTemplate: template != null };
1183
- }
1184
- function localTimestamp() {
1185
- const date = /* @__PURE__ */ new Date();
1186
- const minutes = -date.getTimezoneOffset();
1187
- const pad = (value) => String(Math.abs(value)).padStart(2, "0");
1188
- return `${new Date(date.getTime() + minutes * 6e4).toISOString().slice(0, -1)}${minutes >= 0 ? "+" : "-"}${pad(Math.trunc(minutes / 60))}:${pad(minutes % 60)}`;
1235
+ const { errors } = validateRoadmap(parsed);
1236
+ if (errors.length > 0) {
1237
+ throw new CliError(
1238
+ `${filePath} failed validation \u2014 not syncing:
1239
+ ${errors.join("\n ")}`,
1240
+ 2
1241
+ );
1242
+ }
1243
+ return parsed;
1189
1244
  }
1190
- async function attachRoadmap(deps, taskId, slug, key) {
1191
- let directory = path4.dirname(deps.repoBinding?.path ?? deps.projectBindingPath ?? path4.join(process.cwd(), "nolto.json"));
1192
- let file = "";
1193
- try {
1194
- if (slug !== void 0 && !/^[a-z0-9][a-z0-9._-]*$/.test(slug)) throw new Error("Invalid --roadmap slug.");
1195
- let entries;
1196
- for (; ; ) {
1197
- try {
1198
- entries = await readdir2(path4.join(directory, ".nolto", "roadmaps"));
1199
- break;
1200
- } catch (error) {
1201
- if (error.code !== "ENOENT" || path4.dirname(directory) === directory) throw error;
1202
- directory = path4.dirname(directory);
1245
+ async function buildSyncBody(args) {
1246
+ const planDocuments = [];
1247
+ for (const ref of collectPlanRefs(args.roadmap)) {
1248
+ if (!isValidPlanPath(ref.path)) {
1249
+ args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1250
+ continue;
1251
+ }
1252
+ try {
1253
+ if (await args.deps.isIgnored?.(args.repoRoot, ref.path)) {
1254
+ args.deps.warn(`plan path is git-ignored, skipping: ${ref.path}`);
1255
+ continue;
1203
1256
  }
1257
+ } catch {
1258
+ }
1259
+ const root = path5.resolve(args.repoRoot);
1260
+ const absolute = path5.resolve(root, ref.path);
1261
+ if (absolute !== root && !absolute.startsWith(root + path5.sep)) {
1262
+ args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1263
+ continue;
1264
+ }
1265
+ if (!args.deps.fileExists(absolute)) {
1266
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1267
+ continue;
1204
1268
  }
1205
- const names = entries.filter((name) => name.endsWith(".json")).sort();
1206
- if (slug === void 0 && names.length !== 1) throw new Error(`Choose --roadmap <slug>. Candidates: ${names.map((name) => name.slice(0, -5)).join(", ") || "(none)"}`);
1207
- file = path4.join(directory, ".nolto", "roadmaps", slug === void 0 ? names[0] : `${slug}.json`);
1208
- const result = addIssueToRoadmapTask(JSON.parse(await readFile4(file, "utf8")), taskId, key, localTimestamp());
1209
- if ("error" in result) throw new Error(`${result.error} in ${file}`);
1210
- if (result.changed) {
1211
- const temp = `${file}.${randomUUID()}.tmp`;
1269
+ if (args.deps.realpath !== void 0) {
1270
+ let real;
1271
+ let realRoot;
1212
1272
  try {
1213
- await writeFile4(temp, JSON.stringify(result.roadmap, null, 2) + "\n", { flag: "wx" });
1214
- await rename(temp, file);
1215
- } finally {
1216
- await rm2(temp, { force: true });
1273
+ real = await args.deps.realpath(absolute);
1274
+ realRoot = await args.deps.realpath(root);
1275
+ } catch {
1276
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1277
+ continue;
1278
+ }
1279
+ if (real !== realRoot && !real.startsWith(realRoot + path5.sep)) {
1280
+ args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1281
+ continue;
1282
+ }
1283
+ if (!isValidPlanPath(path5.relative(realRoot, real).split(path5.sep).join("/"))) {
1284
+ args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1285
+ continue;
1217
1286
  }
1218
1287
  }
1219
- process.stderr.write("Run `nolto sync` to link it on Nolto.\n");
1220
- return { file, taskId };
1221
- } catch (error) {
1222
- throw new CliError(
1223
- `Issue ${key} was created, but ${error instanceof Error ? error.message : String(error)}`,
1224
- 2,
1225
- "Do not create it again. Add the existing issue key to the roadmap task, then run `nolto sync`."
1226
- );
1288
+ const content = await args.deps.readFile(absolute);
1289
+ planDocuments.push({
1290
+ path: ref.path,
1291
+ taskId: ref.ownerId,
1292
+ content,
1293
+ contentHash: sha256Hex(content)
1294
+ });
1227
1295
  }
1296
+ return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1228
1297
  }
1229
- function writeOptions(command, create) {
1230
- if (create) command.requiredOption("--subject <text>", "Issue subject");
1231
- else command.option("--subject <text>", "Issue subject");
1232
- command.option("--body <text>", "Issue body").option("--body-file <path>", "Read body from file (- for stdin)").option("--type <name-or-id>", "Issue type").option("--status <name-or-id>", "Issue status").option("--priority <priority>", "high, normal or low").option("--assignee <assignee>", "me, none or UUID").option("--due <YYYY-MM-DD>", "Due date").option("--category <names...>", "Category names or UUIDs").option("--parent <ref>", "Parent issue key or number");
1233
- if (create) command.option("--draft", "Create a draft visible only to you instead of an issue").option("--phase <task-id>", "Attach the created key to a local roadmap task").option("--roadmap <slug>", "Roadmap filename slug (with --phase)");
1234
- else command.option("--no-due", "Clear due date").option("--no-parent", "Clear parent").option("-m, --comment <text>", "Comment in the same update");
1235
- return command;
1298
+ async function runSync(args, deps) {
1299
+ const body = await buildSyncBody({
1300
+ roadmap: args.roadmap,
1301
+ repoRoot: args.repoRoot,
1302
+ repoIdentity: args.repoIdentity,
1303
+ deps
1304
+ });
1305
+ const response = await deps.http.put(
1306
+ `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1307
+ { ...body, baseRevision: args.baseRevision }
1308
+ );
1309
+ for (const warning of response.warnings ?? []) deps.warn(warning);
1310
+ const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1311
+ deps.log(
1312
+ `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})` : ""}`
1313
+ );
1314
+ return response;
1236
1315
  }
1237
- function register(program, deps) {
1238
- const group = program.command("issue").description("List, view and manage project issues.").addHelpText("after", `
1239
- All commands accept global \`--project <id>\`, \`--json\`, \`--token <value>\` and \`--base-url <url>\`.
1240
- Project priority: flag \u2192 NOLTO_PROJECT \u2192 nearest ancestor nolto.json \u2192 config defaultProjectId. Git is not required. An invalid nolto.json remains an error.
1241
-
1242
- nolto issue create --draft --subject "\u2026"
1243
- nolto issue drafts
1244
- nolto issue publish <draft-id>
1245
1316
 
1246
- | Exit | Meaning |
1247
- |---|---|
1248
- | 0 | Success |
1249
- | 2 | Invalid input, recognized API 404, HTTP 422 (details shown), or local roadmap failure after creation |
1250
- | 3 | HTTP 401/403; token_scope/token_project includes a token settings hint |
1251
- | 4 | HTTP 402/429 (quota/rate limit). API token writes: 60/minute. On 429, wait Retry-After seconds before retrying. |
1252
- | 5 | Network/generic HTTP errors, including a 404 without an API error string |
1253
- `);
1254
- group.command("list").description("List or search issues.").option("--status <names...>", "Status names or UUIDs").option("--assignee <assignee>", "me, none or UUID").option("--closed <mode>", "exclude, include or only").option("--q <text>", "Search text").option("--sort <field>", "updated, due, priority, number, created, assignee, status, type or subject").option("--order <order>", "asc or desc").option("--page <number>", "Page number").option("--type <name-or-id>", "Issue type").option("--priority <priority>", "high, normal or low").option("--category <name-or-id>", "Category").option("--parent <ref>", "Parent issue or none").action(async (flags, command) => {
1255
- const ctx = context(deps, command);
1256
- const settings = flags.status || flags.type || flags.category ? await deps.http.get(`${ctx.root}/issue-settings`) : emptySettings;
1257
- const query = buildListQuery(flags, settings).toString();
1258
- const result = await deps.http.get(`${ctx.root}/issues${query ? `?${query}` : ""}`);
1259
- printResult(ctx.mode === "json" ? result : formatIssueList(result.issues, result), ctx.mode);
1260
- });
1261
- group.command("view <ref>").description("Show issue details and comments.").action(async (ref, _flags, command) => {
1262
- const ctx = context(deps, command);
1263
- const result = await deps.http.get(`${ctx.root}/issues/${parseIssueRef(ref)}`);
1264
- printResult(ctx.mode === "json" ? result : formatIssueView(result), ctx.mode);
1265
- });
1266
- writeOptions(group.command("create").description("Create an issue."), true).action(async (flags, command) => {
1267
- const ctx = context(deps, command);
1268
- if (flags.draft && (flags.phase !== void 0 || flags.roadmap !== void 0)) throw new CliError("--phase and --roadmap cannot be used with --draft. Publish the draft first.", 2);
1269
- if (flags.roadmap !== void 0 && flags.phase === void 0) throw new CliError("--roadmap requires --phase.", 2);
1270
- const { input, fromTemplate } = await writeInput(deps, ctx.root, flags, true);
1271
- if (flags.draft) {
1272
- const result2 = await deps.http.post(`${ctx.root}/issue-drafts`, input);
1273
- printResult(ctx.mode === "json" ? result2 : `draft ${result2.draft.id} created
1274
- ${draftUrl(deps.settings.baseUrl, ctx.projectId, result2.draft.id)}`, ctx.mode);
1275
- return;
1276
- }
1277
- const result = await deps.http.post(`${ctx.root}/issues`, input);
1278
- const roadmap = flags.phase === void 0 ? void 0 : await attachRoadmap(deps, flags.phase, flags.roadmap, result.issue.key);
1279
- printResult(ctx.mode === "json" ? { ...result, ...roadmap ? { roadmap } : {} } : `${result.issue.key} created
1280
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${fromTemplate ? "\nbody: from template" : ""}`, ctx.mode);
1281
- });
1282
- group.command("drafts").description("List your issue drafts (visible only to you).").action(async (_flags, command) => {
1283
- const ctx = context(deps, command);
1284
- const result = await deps.http.get(`${ctx.root}/issue-drafts`);
1285
- printResult(ctx.mode === "json" ? result : formatDraftList(result), ctx.mode);
1286
- });
1287
- group.command("publish <draft-id>").description("Publish a draft as an issue.").action(async (id, _flags, command) => {
1288
- const ctx = context(deps, command);
1289
- if (!isUuid(id)) throw new CliError("<draft-id> must be a UUID. Run `nolto issue drafts` to list drafts.", 2);
1290
- const result = await deps.http.post(`${ctx.root}/issue-drafts/${id}/publish`, void 0);
1291
- printResult(ctx.mode === "json" ? result : `${result.issue.key} published
1292
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}`, ctx.mode);
1293
- });
1294
- writeOptions(group.command("update <ref>").description("Update issue fields."), false).action(async (ref, flags, command) => {
1295
- const ctx = context(deps, command);
1296
- const number = parseIssueRef(ref);
1297
- const { input } = await writeInput(deps, ctx.root, flags, false);
1298
- const result = await deps.http.patch(`${ctx.root}/issues/${number}`, input);
1299
- printResult(ctx.mode === "json" ? result : `${result.issue.key} updated
1300
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1301
- });
1302
- group.command("comment <ref>").description("Post a comment.").option("-m, --comment <text>", "Comment text").option("--body-file <path>", "Read comment from file (- for stdin)").action(async (ref, flags, command) => {
1303
- const ctx = context(deps, command);
1304
- const number = parseIssueRef(ref);
1305
- const body = await bodyText(flags.comment, flags.bodyFile);
1306
- if (!body?.trim()) throw new CliError("A comment is required. Use -m or --body-file.", 2);
1307
- const issue = ctx.mode === "human" ? (await deps.http.get(`${ctx.root}/issues/${number}`)).issue : void 0;
1308
- const result = await deps.http.post(`${ctx.root}/issues/${number}/comments`, { body });
1309
- printResult(ctx.mode === "json" ? result : `${issue.key} commented
1310
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1311
- });
1312
- group.command("close <ref>").description("Move an issue to a closed status.").option("--status <name-or-id>", "Closed status (defaults to first by sort order)").option("-m, --comment <text>", "Comment in the same update").action(async (ref, flags, command) => {
1313
- const ctx = context(deps, command);
1314
- const number = parseIssueRef(ref);
1315
- const settings = await deps.http.get(`${ctx.root}/issue-settings`);
1316
- const status = pickClosedStatus(settings, flags.status);
1317
- const result = await deps.http.patch(`${ctx.root}/issues/${number}`, { statusId: status.id, ...flags.comment !== void 0 ? { comment: flags.comment } : {} });
1318
- printResult(ctx.mode === "json" ? result : `${result.issue.key} closed
1319
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1320
- });
1321
- }
1322
-
1323
- // src/memory-import.ts
1324
- import { readFile as readFile7, readdir as readdir3 } from "fs/promises";
1325
- import path8 from "path";
1326
-
1327
- // src/memory-format.ts
1328
- var oneLine = (value) => value.replace(/[\r\n\u0085\u2028\u2029]/g, " ");
1329
- var shellArg = (value) => /^[A-Za-z0-9._/-]+$/.test(value) ? value : JSON.stringify(value);
1330
- var memoryClient = (via) => via?.client || via?.tokenName || "Web";
1331
- function parseMemory(text, importing = false) {
1332
- const lines = text.replace(/\r\n/g, "\n").split("\n");
1333
- if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
1334
- if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
1335
- const end = lines.indexOf("---");
1336
- if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
1337
- const fields = {};
1338
- let metadata = false;
1339
- for (const line2 of lines.slice(0, end)) {
1340
- const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
1341
- if (!match) continue;
1342
- const indent = match[1], key = match[2], raw = match[3];
1343
- if (!indent) metadata = key === "metadata";
1344
- if (indent && !(importing && metadata && key === "type")) continue;
1345
- let value = raw.trim();
1346
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
1347
- if (["name", "description", "type", "scope", "branch", "revision"].includes(key)) fields[key] = value;
1348
- }
1349
- const body = lines.slice(end + 1);
1350
- if (body[0] === "") body.shift();
1351
- return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
1317
+ // src/roadmap-cache.ts
1318
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1319
+ var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1320
+ function cacheDir(env, projectId) {
1321
+ if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1322
+ return path6.join(getConfigDir(env), "projects", projectId, "roadmaps");
1352
1323
  }
1353
- function formatMemory(entry) {
1354
- const value = (s) => {
1355
- const safe = oneLine(s);
1356
- return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
1357
- };
1358
- return [
1359
- "<!-- nolto memory \u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u3002\u7DE8\u96C6\u3057\u306A\u3044\u3002\u5909\u66F4\u306F\u4E0B\u66F8\u304D\u306B\u30B3\u30D4\u30FC\u3057\u3066 nolto memory put -->",
1360
- "---",
1361
- `name: ${entry.name}`,
1362
- `description: ${value(entry.description)}`,
1363
- ...entry.type == null ? [] : [`type: ${entry.type}`],
1364
- `scope: ${entry.scope}`,
1365
- ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
1366
- `revision: ${entry.revision}`,
1367
- `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
1368
- "---",
1369
- "",
1370
- entry.body
1371
- ].join("\n");
1324
+ function cachePaths(env, projectId, slug) {
1325
+ if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1326
+ const dir = cacheDir(env, projectId);
1327
+ return { json: path6.join(dir, `${slug}.json`), meta: path6.join(dir, `${slug}.meta.json`) };
1372
1328
  }
1373
- function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
1374
- if (scope !== "project" && scope !== "user" && scope !== "branch") {
1375
- throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
1329
+ async function listCachedSlugs(env, projectId) {
1330
+ try {
1331
+ const entries = await readdir2(cacheDir(env, projectId), { withFileTypes: true });
1332
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
1333
+ } catch (err) {
1334
+ if (err.code === "ENOENT") return [];
1335
+ throw err;
1376
1336
  }
1377
- return scope;
1378
1337
  }
1379
- var count = (n) => n.toLocaleString("en-US");
1380
- var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
1381
- function validateDraft(draft) {
1382
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
1383
- throw invalidInput(draft.name ? `name \u306E\u5F62\u304C\u4E0D\u6B63\u3067\u3059(${oneLine(draft.name)})\u3002` : "name \u304C\u3042\u308A\u307E\u305B\u3093\u3002", "name \u306F\u82F1\u5C0F\u6587\u5B57\u30FB\u6570\u5B57\u30FB\u30CF\u30A4\u30D5\u30F3\u3067 64 \u5B57\u307E\u3067\u3001\u5148\u982D\u306F\u82F1\u6570\u5B57");
1384
- }
1385
- const description = draft.description.trim();
1386
- if (/[\r\n\u0085\u2028\u2029]/.test(draft.description)) throw invalidInput("description \u306B\u6539\u884C\u304C\u3042\u308A\u307E\u3059\u3002", "description \u306F 1 \u884C\u306B\u3059\u308B");
1387
- if (!description) throw invalidInput("description \u304C\u3042\u308A\u307E\u305B\u3093\u3002", "\u7D22\u5F15\u3067\u8AAD\u3080\u304B\u3069\u3046\u304B\u3092\u6C7A\u3081\u3089\u308C\u308B 1 \u884C\u3092\u66F8\u304F");
1388
- if (description.length > 200) throw invalidInput(`description \u304C 200 \u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059(${count(description.length)} \u5B57)\u3002`, "\u7D22\u5F15\u3067\u8AAD\u3080\u304B\u3069\u3046\u304B\u3092\u6C7A\u3081\u3089\u308C\u308B 1 \u884C\u306B\u7E2E\u3081\u308B");
1389
- if (draft.body.length > 1e4) throw invalidInput(`\u672C\u6587\u304C 10,000 \u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059(${count(draft.body.length)} \u5B57)\u3002`, "\u30A8\u30F3\u30C8\u30EA\u3092\u5206\u3051\u308B\u304B\u3001\u8981\u70B9\u306B\u7D5E\u308B");
1390
- if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
1391
- throw invalidInput(`type \u304C\u4E0D\u6B63\u3067\u3059(${oneLine(draft.type)})\u3002`, "type \u306F user / feedback / project / reference \u306E\u3069\u308C\u304B\u3002\u4E0D\u8981\u306A\u3089\u884C\u3054\u3068\u6D88\u3059");
1338
+ async function readCache(env, projectId, slug) {
1339
+ const paths = cachePaths(env, projectId, slug);
1340
+ let raw;
1341
+ try {
1342
+ raw = await readFile4(paths.json, "utf8");
1343
+ } catch (err) {
1344
+ if (err.code === "ENOENT") return null;
1345
+ throw err;
1392
1346
  }
1393
- }
1394
- function parseRevision(value) {
1395
- const revision = Number(value);
1396
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(revision) || revision < 1) throw new CliError("revision \u306F\u6B63\u306E\u6574\u6570\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002", 2);
1397
- return revision;
1398
- }
1399
- function detectMemoryClient(env) {
1400
- const agent = env.NOLTO_AGENT?.trim();
1401
- if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
1402
- if (env.CLAUDECODE === "1") return "Claude Code";
1403
- if (env.GEMINI_CLI === "1") return "Gemini CLI";
1404
- if (env.CODEX_THREAD_ID) return "Codex";
1405
- return "CLI";
1406
- }
1407
-
1408
- // src/memory-cache.ts
1409
- import { mkdir as mkdir4, readFile as readFile5, rename as rename2, rm as rm3, unlink, writeFile as writeFile5 } from "fs/promises";
1410
- import { randomUUID as randomUUID2 } from "crypto";
1411
- import path5 from "path";
1412
- function memoryDir(configPath, project) {
1413
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(project)) throw new CliError("Invalid project id.", 2);
1414
- return path5.join(path5.dirname(configPath), "projects", project, "memory");
1415
- }
1416
- function memoryEntryPath(entry) {
1417
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(entry.name)) throw new CliError("Invalid memory name in cache.", 2);
1418
- if (entry.scope === "project" || entry.scope === "user") return `${entry.scope}/${entry.name}.md`;
1419
- if (entry.scope !== "branch" || !entry.repoIdentity || !entry.branch) throw new CliError("Invalid memory scope in cache.", 2);
1420
- if (entry.branch.split("/").some((p) => !p || p === "." || p === ".." || p.includes("\\") || /[\x00-\x1f\x7f]/.test(p) || Buffer.byteLength(p) > 200)) throw new CliError("Unsafe memory branch path.", 2);
1421
- const repoDir = encodeURIComponent(entry.repoIdentity);
1422
- if (Buffer.byteLength(repoDir) > 200) throw new CliError("Unsafe memory repo path.", 2);
1423
- return `branch/${repoDir}/${entry.branch}/${entry.name}.md`;
1424
- }
1425
- function storableMemoryEntry(entry) {
1347
+ let roadmap;
1426
1348
  try {
1427
- memoryEntryPath(entry);
1428
- return true;
1349
+ roadmap = JSON.parse(raw);
1429
1350
  } catch {
1430
- return false;
1351
+ throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
1431
1352
  }
1432
- }
1433
- async function atomicMemoryFile(file, content) {
1434
- await mkdir4(path5.dirname(file), { recursive: true, mode: 448 });
1435
- const temp = `${file}.tmp-${randomUUID2()}`;
1353
+ const { errors } = validateRoadmap(roadmap);
1354
+ if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1355
+ let meta = null;
1436
1356
  try {
1437
- await writeFile5(temp, content, { mode: 292 });
1438
- await unlink(file).catch((error) => {
1439
- if (error.code !== "ENOENT") throw error;
1440
- });
1441
- await rename2(temp, file);
1442
- } finally {
1443
- await unlink(temp).catch(() => void 0);
1357
+ const parsed = JSON.parse(await readFile4(paths.meta, "utf8"));
1358
+ 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") {
1359
+ throw new Error("Invalid cache metadata");
1360
+ }
1361
+ if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
1362
+ throw new Error("Invalid currentTaskId");
1363
+ }
1364
+ if ("repoIdentity" in parsed && parsed.repoIdentity !== null && typeof parsed.repoIdentity !== "string") {
1365
+ throw new Error("Invalid repoIdentity");
1366
+ }
1367
+ meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null, repoIdentity: parsed.repoIdentity ?? null };
1368
+ } catch (err) {
1369
+ if (err.code !== "ENOENT") {
1370
+ throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
1371
+ }
1444
1372
  }
1373
+ return { roadmap, meta, raw };
1445
1374
  }
1446
- async function readMemoryCache(dir, project) {
1447
- const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
1448
- try {
1449
- const state = JSON.parse(await readFile5(path5.join(dir, ".entries.json"), "utf8"));
1450
- if (!Array.isArray(state.entries) || typeof state.scope !== "string" || typeof state.projectName !== "string") throw new Error("Invalid state");
1451
- if (state.entries.some((e) => e == null || typeof e !== "object" || typeof e.id !== "string" || typeof e.name !== "string")) throw new Error("Invalid entry");
1452
- let meta = empty.meta;
1375
+ async function writeCache(env, projectId, slug, roadmap, meta) {
1376
+ const paths = cachePaths(env, projectId, slug);
1377
+ const raw = serializeRoadmap(roadmap);
1378
+ const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
1379
+ await mkdir4(cacheDir(env, projectId), { recursive: true, mode: 448 });
1380
+ for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1381
+ const temp = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1453
1382
  try {
1454
- meta = JSON.parse(await readFile5(path5.join(dir, ".meta.json"), "utf8"));
1455
- } catch (error) {
1456
- if (error.code !== "ENOENT") throw error;
1383
+ await writeFile4(temp, content, { mode: 384 });
1384
+ await rename(temp, filePath);
1385
+ } finally {
1386
+ await unlink(temp).catch(() => void 0);
1457
1387
  }
1458
- if (!Number.isSafeInteger(meta.cursor) || meta.cursor < 0 || typeof meta.pulledAt !== "string") throw new Error("Invalid cursor");
1459
- return { state, meta };
1460
- } catch (error) {
1461
- if (error.code === "ENOENT") return empty;
1462
- throw new CliError(`\u30E1\u30E2\u30EA\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u8AAD\u3081\u307E\u305B\u3093: ${String(error)}`, 2, "nolto memory pull");
1463
- }
1464
- }
1465
- function mergeMemoryEntries(entries, updates) {
1466
- const byId = new Map(entries.map((entry) => [entry.id, entry]));
1467
- for (const entry of updates) {
1468
- const old = byId.get(entry.id);
1469
- if (!old || old.revision <= entry.revision) byId.set(entry.id, entry);
1470
1388
  }
1471
- return [...byId.values()];
1472
1389
  }
1473
- async function saveMemoryCache(dir, cache, previous, index, reset = false) {
1474
- const unsafe = cache.state.entries.filter((e) => !storableMemoryEntry(e));
1475
- if (reset) await rm3(dir, { recursive: true, force: true });
1476
- const livePaths = new Set(cache.state.entries.filter((e) => !e.deleted && storableMemoryEntry(e)).map(memoryEntryPath));
1477
- for (const entry of previous.filter(storableMemoryEntry)) {
1478
- const relative = memoryEntryPath(entry);
1479
- if (!livePaths.has(relative)) await rm3(path5.join(dir, relative), { force: true });
1480
- }
1481
- for (const entry of cache.state.entries) {
1482
- if (!entry.deleted && storableMemoryEntry(entry)) await atomicMemoryFile(path5.join(dir, memoryEntryPath(entry)), formatMemory(entry));
1483
- }
1484
- await atomicMemoryFile(path5.join(dir, ".entries.json"), JSON.stringify(cache.state) + "\n");
1485
- await atomicMemoryFile(path5.join(dir, "MEMORY.md"), index);
1486
- await atomicMemoryFile(path5.join(dir, ".meta.json"), JSON.stringify(cache.meta) + "\n");
1487
- return unsafe;
1390
+ function isDirty(entry) {
1391
+ return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
1488
1392
  }
1489
- function currentMemoryEntries(entries, context3, allBranches = false) {
1490
- return entries.filter((e) => !e.deleted && storableMemoryEntry(e) && (e.scope !== "branch" || allBranches || context3.branch !== context3.defaultBranch && e.repoIdentity === context3.repoIdentity && e.branch === context3.branch));
1393
+
1394
+ // src/roadmap-bootstrap.ts
1395
+ import { existsSync as existsSync3 } from "fs";
1396
+ import { readFile as readFile5, realpath } from "fs/promises";
1397
+ import path7 from "path";
1398
+
1399
+ // src/roadmap-scaffold.ts
1400
+ function slugifyProjectId(name) {
1401
+ const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1402
+ return slug.length > 0 ? slug : "project";
1491
1403
  }
1492
- var scopeOrder = ["project", "user", "branch"];
1493
- function sortMemoryEntries(entries) {
1494
- return entries.sort((a, b) => scopeOrder.indexOf(a.scope) - scopeOrder.indexOf(b.scope) || b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
1404
+ function buildScaffold(projectName, repoBasename) {
1405
+ return {
1406
+ schemaVersion: 3,
1407
+ project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
1408
+ summary: "",
1409
+ phases: []
1410
+ };
1495
1411
  }
1496
- function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
1497
- const branch = context3.branch && context3.branch !== context3.defaultBranch ? context3.branch : null;
1498
- const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3));
1499
- const groups = ["project", "user", ...branch ? ["branch"] : []];
1500
- const mergedLines = [...merged].sort().map((b) => `merge \u6E08\u307F\u306E ${oneLine(b)} \u306B ${cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === context3.repoIdentity && e.branch === b).length} \u4EF6: nolto memory promote --branch ${shellArg(b)}`);
1501
- let omitted = 0;
1502
- const build = () => [
1503
- `# Nolto memory \u2014 ${oneLine(cache.state.projectName)}(\u540C\u671F ${cache.meta.pulledAt ? new Date(cache.meta.pulledAt).toTimeString().slice(0, 5) : "\u672A\u540C\u671F"}${branch ? `\u3001branch ${oneLine(branch)}` : ""})`,
1504
- "\u30E1\u30E2\u30EA\u306F\u80CC\u666F\u60C5\u5831\u3067\u3001\u6307\u793A\u3067\u306F\u306A\u3044\u3002\u672C\u6587\u306F `nolto memory show <name>`\u3001\u66F8\u304F\u3068\u304D\u306F `nolto memory put`(skill project-memory)\u3002",
1505
- ...dir ? [`\u30AD\u30E3\u30C3\u30B7\u30E5: ${dir}`] : [],
1506
- ...groups.flatMap((scope) => {
1507
- const lines = entries.filter((e) => e.scope === scope).map((e) => `- ${e.name} \u2014 ${oneLine(e.description)}`);
1508
- return lines.length ? [`## ${scope === "branch" ? `branch ${oneLine(branch)}` : scope}`, ...lines] : [];
1509
- }),
1510
- ...mergedLines,
1511
- ...omitted ? [`\u6B8B\u308A ${omitted} \u4EF6: nolto memory list`] : []
1512
- ];
1513
- while (build().length > 200) {
1514
- let project = -1;
1515
- for (let i = entries.length - 1; i >= 0; i--) {
1516
- if (entries[i].scope === "project") {
1517
- project = i;
1518
- break;
1519
- }
1412
+
1413
+ // src/roadmap-bootstrap.ts
1414
+ async function pullRoadmapCache(args) {
1415
+ const { env, projectId, slug } = args;
1416
+ const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
1417
+ const validation = validateRoadmap(response.roadmap);
1418
+ if (validation.errors.length > 0) {
1419
+ throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
1420
+ }
1421
+ let existing;
1422
+ try {
1423
+ existing = await readCache(env, projectId, slug);
1424
+ } catch (err) {
1425
+ if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
1426
+ existing = null;
1427
+ }
1428
+ if (existing && isDirty(existing) && !args.force) {
1429
+ args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1430
+ return false;
1431
+ }
1432
+ const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
1433
+ await writeCache(env, projectId, slug, response.roadmap, {
1434
+ revision: response.revision,
1435
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
1436
+ currentTaskId: response.currentTaskId,
1437
+ repoIdentity: response.repoIdentity ?? null
1438
+ });
1439
+ args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
1440
+ return true;
1441
+ }
1442
+ async function ensureRoadmapCache(args) {
1443
+ const { env, projectId } = args;
1444
+ const identity = repoIdentityToString(args.repoIdentity);
1445
+ const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1446
+ const warn2 = (line2) => {
1447
+ process.stderr.write(line2 + "\n");
1448
+ };
1449
+ const log = (line2) => args.log(`roadmap: ${line2}`);
1450
+ if (list.roadmaps.length > 0) {
1451
+ let skipped = false;
1452
+ for (const { slug: slug2 } of list.roadmaps) {
1453
+ if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
1520
1454
  }
1521
- if (entries.length) {
1522
- entries.splice(project < 0 ? entries.length - 1 : project, 1);
1523
- omitted++;
1524
- } else {
1525
- mergedLines.pop();
1526
- omitted++;
1455
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1456
+ if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1457
+ }
1458
+ const basename = path7.basename(args.repoRoot);
1459
+ const slug = args.slug ?? slugifyProjectId(basename);
1460
+ const collision = list.roadmaps.find((row) => row.slug === slug);
1461
+ if (collision) {
1462
+ if (args.slug === void 0) {
1463
+ log(`skipped \u2014 "${slug}" is another repository's roadmap (${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <name>\` to create one for this repository.`);
1464
+ return;
1465
+ }
1466
+ throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
1467
+ }
1468
+ let existing;
1469
+ try {
1470
+ existing = await readCache(env, projectId, slug);
1471
+ } catch (err) {
1472
+ if (!(err instanceof CliError)) throw err;
1473
+ existing = null;
1474
+ }
1475
+ if (existing && isDirty(existing)) {
1476
+ warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1477
+ throw new CliError("Roadmap has local changes that are not synced.", 4);
1478
+ }
1479
+ const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
1480
+ await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1481
+ const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1482
+ http: args.http,
1483
+ readFile: (p) => readFile5(p, "utf8"),
1484
+ realpath,
1485
+ fileExists: existsSync3,
1486
+ log: () => void 0,
1487
+ warn: warn2
1488
+ });
1489
+ await writeCache(env, projectId, slug, response.roadmap ?? roadmap, { repoIdentity: identity, revision: response.revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : existing?.meta?.currentTaskId });
1490
+ log(`created ${slug} on server (rev ${response.revision})`);
1491
+ }
1492
+ async function ensureProjectRepo(args) {
1493
+ let repos;
1494
+ try {
1495
+ const project = await args.http.get(`/api/projects/${args.projectId}`);
1496
+ repos = Array.isArray(project.repos) ? project.repos : [];
1497
+ } catch (error) {
1498
+ if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
1499
+ process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
1500
+ `);
1501
+ return "unbound";
1502
+ }
1503
+ if (repos.length === 0) return "unbound";
1504
+ const identity = repoIdentityToString(args.repoIdentity);
1505
+ if (repos.some((repo) => repo.identity === identity)) return "bound";
1506
+ if (!await args.confirm(`Project is bound to ${repos.map((repo) => repo.identity).join(", ")}. Add this repository (${identity}) to the project? [Y/n] `)) return "declined";
1507
+ try {
1508
+ await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
1509
+ } catch (error) {
1510
+ if (error instanceof CliError) {
1511
+ if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
1512
+ if (error.status === 403) {
1513
+ throw new CliError(
1514
+ "Only the project owner can add a repository.",
1515
+ 2,
1516
+ "Ask the owner to run `nolto link --add` in this repository."
1517
+ );
1518
+ }
1519
+ if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
1527
1520
  }
1521
+ throw error;
1528
1522
  }
1529
- return build().join("\n") + "\n";
1523
+ args.log(`Added ${identity} to project.`);
1524
+ return "added";
1530
1525
  }
1531
1526
 
1532
- // src/memory-git.ts
1533
- import { execFile as execFile2 } from "child_process";
1534
- import { promisify } from "util";
1527
+ // src/roadmap-read.ts
1528
+ import path12 from "path";
1529
+
1530
+ // src/commands/link.ts
1531
+ import readline from "readline/promises";
1532
+ import os2 from "os";
1533
+ import path11 from "path";
1534
+ import { statSync as statSync3 } from "fs";
1535
+
1536
+ // src/registry.ts
1537
+ import { readFile as readFile6, writeFile as writeFile5, mkdir as mkdir5, rename as rename2, unlink as unlink2 } from "fs/promises";
1538
+ import { randomUUID as randomUUID3 } from "crypto";
1539
+ import path8 from "path";
1540
+ import { z as z3 } from "zod";
1541
+ var registrySchema = z3.object({
1542
+ schemaVersion: z3.literal(1),
1543
+ repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
1544
+ }).passthrough();
1545
+ function getRegistryPath(env) {
1546
+ return path8.join(getConfigDir(env), "registry.json");
1547
+ }
1548
+ async function loadRegistry(filePath) {
1549
+ let raw;
1550
+ try {
1551
+ raw = await readFile6(filePath, "utf8");
1552
+ } catch (err) {
1553
+ const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1554
+ if (code === "ENOENT") {
1555
+ return { schemaVersion: 1, repos: [] };
1556
+ }
1557
+ throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
1558
+ }
1559
+ let parsed;
1560
+ try {
1561
+ parsed = JSON.parse(raw);
1562
+ } catch {
1563
+ throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
1564
+ }
1565
+ const result = registrySchema.safeParse(parsed);
1566
+ if (!result.success) {
1567
+ const issue = result.error.issues[0];
1568
+ const fieldPath = issue?.path.join(".") ?? "";
1569
+ throw new CliError(
1570
+ `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
1571
+ 2
1572
+ );
1573
+ }
1574
+ return result.data;
1575
+ }
1576
+ async function addRepoToRegistry(filePath, entry) {
1577
+ const registry = await loadRegistry(filePath);
1578
+ const existing = registry.repos.find((repo) => repo.root === entry.root);
1579
+ if (existing?.projectId === entry.projectId) {
1580
+ return { added: false, updated: false, registry };
1581
+ }
1582
+ const updated = {
1583
+ ...registry,
1584
+ repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
1585
+ };
1586
+ await writeRegistry(filePath, updated);
1587
+ return { added: !existing, updated: !!existing, registry: updated };
1588
+ }
1589
+ async function writeRegistry(filePath, registry) {
1590
+ await mkdir5(path8.dirname(filePath), { recursive: true, mode: 448 });
1591
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1592
+ try {
1593
+ await writeFile5(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
1594
+ await rename2(tempPath, filePath);
1595
+ } catch (err) {
1596
+ await unlink2(tempPath).catch(() => void 0);
1597
+ throw err;
1598
+ }
1599
+ }
1600
+ async function removeRepoFromRegistry(filePath, root) {
1601
+ const registry = await loadRegistry(filePath);
1602
+ const repos = registry.repos.filter((repo) => repo.root !== root);
1603
+ if (repos.length === registry.repos.length) return { removed: false, registry };
1604
+ const updated = { ...registry, repos };
1605
+ await writeRegistry(filePath, updated);
1606
+ return { removed: true, registry: updated };
1607
+ }
1535
1608
 
1536
1609
  // src/repo-identity.ts
1537
1610
  import { execFile } from "child_process";
1538
1611
  import { realpathSync } from "fs";
1539
- import path7 from "path";
1612
+ import path10 from "path";
1540
1613
 
1541
1614
  // src/machine-id.ts
1542
- import { chmod, mkdir as mkdir5, readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
1543
- import { randomUUID as randomUUID3 } from "crypto";
1544
- import path6 from "path";
1615
+ import { chmod, mkdir as mkdir6, readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
1616
+ import { randomUUID as randomUUID4 } from "crypto";
1617
+ import path9 from "path";
1545
1618
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
1546
1619
  function parseMachineId(raw, file) {
1547
1620
  let parsed;
@@ -1557,10 +1630,10 @@ function parseMachineId(raw, file) {
1557
1630
  return id;
1558
1631
  }
1559
1632
  async function loadOrCreate(configDir) {
1560
- const file = path6.join(configDir, "machine.json");
1633
+ const file = path9.join(configDir, "machine.json");
1561
1634
  let raw = null;
1562
1635
  try {
1563
- raw = await readFile6(file, "utf8");
1636
+ raw = await readFile7(file, "utf8");
1564
1637
  } catch (err) {
1565
1638
  const code = err.code;
1566
1639
  if (code !== "ENOENT") {
@@ -1570,8 +1643,8 @@ async function loadOrCreate(configDir) {
1570
1643
  if (raw !== null) {
1571
1644
  return parseMachineId(raw, file);
1572
1645
  }
1573
- const machineId = randomUUID3();
1574
- await mkdir5(configDir, { recursive: true, mode: 448 });
1646
+ const machineId = randomUUID4();
1647
+ await mkdir6(configDir, { recursive: true, mode: 448 });
1575
1648
  try {
1576
1649
  await writeFile6(file, `${JSON.stringify({ machineId }, null, 2)}
1577
1650
  `, {
@@ -1580,7 +1653,7 @@ async function loadOrCreate(configDir) {
1580
1653
  });
1581
1654
  } catch (err) {
1582
1655
  if (err.code === "EEXIST") {
1583
- return parseMachineId(await readFile6(file, "utf8"), file);
1656
+ return parseMachineId(await readFile7(file, "utf8"), file);
1584
1657
  }
1585
1658
  throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1586
1659
  }
@@ -1588,7 +1661,7 @@ async function loadOrCreate(configDir) {
1588
1661
  return machineId;
1589
1662
  }
1590
1663
  function loadOrCreateMachineId(configDir) {
1591
- const key = path6.resolve(configDir);
1664
+ const key = path9.resolve(configDir);
1592
1665
  const existing = inFlightByConfigDir.get(key);
1593
1666
  if (existing !== void 0) return existing;
1594
1667
  const pending = loadOrCreate(key).finally(() => {
@@ -1622,7 +1695,7 @@ async function resolveRepoIdentity(root, deps) {
1622
1695
  try {
1623
1696
  canonicalRoot = realpathSync(root);
1624
1697
  } catch {
1625
- canonicalRoot = path7.resolve(root);
1698
+ canonicalRoot = path10.resolve(root);
1626
1699
  }
1627
1700
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1628
1701
  }
@@ -1633,1042 +1706,1470 @@ function makeRepoIdentityResolver(deps) {
1633
1706
  }));
1634
1707
  }
1635
1708
 
1636
- // src/memory-git.ts
1637
- var runMemoryGit = async (args, root) => (await promisify(execFile2)("git", args, { cwd: root, timeout: 5e3 })).stdout.trim();
1638
- async function memoryGitContext(root, deps) {
1639
- const git = deps.memoryGit ?? runMemoryGit;
1640
- const result = { repoIdentity: null, branch: null, defaultBranch: null };
1709
+ // src/commands/link.ts
1710
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1711
+ function resolveStartDir(env, cwd) {
1712
+ const cpd = env["CLAUDE_PROJECT_DIR"];
1713
+ return cpd != null && cpd.length > 0 ? cpd : cwd;
1714
+ }
1715
+ function dirHasGit(dir) {
1641
1716
  try {
1642
- await git(["rev-parse", "--show-toplevel"], root);
1643
- const identity = await makeRepoIdentityResolver(deps)(root);
1644
- result.repoIdentity = `${identity.kind}:${identity.value}`;
1645
- result.branch = await git(["symbolic-ref", "--quiet", "--short", "HEAD"], root).catch(() => null);
1646
- const remote = await git(["symbolic-ref", "refs/remotes/origin/HEAD"], root).catch(() => "");
1647
- if (remote.startsWith("refs/remotes/origin/")) result.defaultBranch = remote.slice("refs/remotes/origin/".length);
1648
- else {
1649
- for (const branch of ["main", "master"]) {
1650
- try {
1651
- await git(["show-ref", "--verify", `refs/heads/${branch}`], root);
1652
- result.defaultBranch = branch;
1653
- break;
1654
- } catch {
1655
- }
1656
- }
1657
- }
1717
+ statSync3(path11.join(dir, ".git"));
1718
+ return true;
1658
1719
  } catch {
1720
+ return false;
1659
1721
  }
1660
- return result;
1661
1722
  }
1662
- async function mergedMemoryBranches(branches, context3, root, git, mine = /* @__PURE__ */ new Set()) {
1663
- const merged = /* @__PURE__ */ new Set();
1664
- if (!context3.defaultBranch || !context3.repoIdentity) return merged;
1665
- const hasRef = async (ref) => {
1666
- try {
1667
- await git(["show-ref", "--verify", "--quiet", ref], root);
1668
- return true;
1669
- } catch (error) {
1670
- if (error.code === 1) return false;
1671
- throw error;
1672
- }
1673
- };
1674
- let checkedOut, target, targetTip;
1675
- try {
1676
- checkedOut = new Set((await git(["worktree", "list", "--porcelain"], root)).split("\n").filter((l) => l.startsWith("branch refs/heads/")).map((l) => l.slice("branch refs/heads/".length)));
1677
- target = await hasRef(`refs/heads/${context3.defaultBranch}`) ? `refs/heads/${context3.defaultBranch}` : `refs/remotes/origin/${context3.defaultBranch}`;
1678
- targetTip = await git(["rev-parse", target], root);
1679
- } catch {
1680
- return merged;
1681
- }
1682
- for (const branch of branches) {
1683
- if (branch === context3.defaultBranch || branch === context3.branch || checkedOut.has(branch)) continue;
1684
- try {
1685
- const local = `refs/heads/${branch}`;
1686
- if (await hasRef(local)) {
1687
- if (await git(["rev-parse", local], root) === targetTip) continue;
1688
- await git(["merge-base", "--is-ancestor", local, target], root);
1689
- merged.add(branch);
1690
- } else if (mine.has(branch) && !await hasRef(`refs/remotes/origin/${branch}`)) merged.add(branch);
1691
- } catch {
1723
+ function findRepoRoot(startDir, hasGit = dirHasGit) {
1724
+ let current = startDir;
1725
+ while (true) {
1726
+ if (hasGit(current)) {
1727
+ return { root: current, foundGit: true };
1692
1728
  }
1729
+ const parent = path11.dirname(current);
1730
+ if (parent === current) break;
1731
+ current = parent;
1693
1732
  }
1694
- return merged;
1695
- }
1696
-
1697
- // src/memory-import.ts
1698
- function aiHeading(response, requestedName) {
1699
- const { entry, ai } = response;
1700
- if (!ai || ai.action !== "merge" && ai.action !== "replace") return null;
1701
- if (requestedName !== void 0 && requestedName !== entry.name) {
1702
- return `\u65B0\u898F\u306E ${requestedName} \u306F\u4F5C\u3089\u305A\u3001AI \u304C ${entry.scope}/${entry.name} ${ai.action === "merge" ? "\u306B\u7D71\u5408\u3057\u307E\u3057\u305F" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88\u3057\u307E\u3057\u305F"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
1703
- }
1704
- return `AI \u304C\u6574\u7406: ${entry.scope}/${entry.name} ${ai.action === "merge" ? "\u306B\u7D71\u5408" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
1705
- }
1706
- async function createMemoryContext(opts, recover = false) {
1707
- const { projectId: project, root, git } = opts;
1708
- const dir = memoryDir(opts.configPath, project);
1709
- const cache = await readMemoryCache(dir, project).catch((error) => {
1710
- if (!recover) throw error;
1711
- return { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
1712
- });
1713
- return { project, dir, root, git, cache, api: `/api/projects/${project}/memory` };
1733
+ return { root: startDir, foundGit: false };
1714
1734
  }
1715
- async function memoryIndexText(ctx, deps) {
1716
- const entries = ctx.cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === ctx.git.repoIdentity);
1717
- const branches = [...new Set(entries.map((e) => e.branch))];
1718
- const userId = ctx.cache.state.userId;
1719
- const mine = new Set(userId ? entries.filter((e) => e.updatedBy?.id === userId).map((e) => e.branch) : []);
1720
- return memoryIndex(ctx.cache, ctx.git, await mergedMemoryBranches(branches, ctx.git, ctx.root, deps.memoryGit ?? runMemoryGit, mine), ctx.dir);
1735
+ function isHomeDirectory(dir, home = os2.homedir()) {
1736
+ return path11.resolve(dir) === path11.resolve(home);
1721
1737
  }
1722
- var cacheWarning = "Warning: \u30B5\u30FC\u30D0\u30FC\u3078\u306E\u66F8\u304D\u8FBC\u307F\u306F\u6210\u529F\u3057\u307E\u3057\u305F\u304C\u3001\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002nolto memory pull \u3067\u540C\u671F\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n";
1723
- async function updateCache(ctx, deps, entries, quiet = false) {
1724
- const previous = ctx.cache.state.entries;
1725
- try {
1726
- ctx.cache.state.entries = mergeMemoryEntries(previous, entries);
1727
- await saveMemoryCache(ctx.dir, ctx.cache, previous, await memoryIndexText(ctx, deps));
1728
- return true;
1729
- } catch {
1730
- if (!quiet) process.stderr.write(cacheWarning);
1731
- return false;
1738
+ async function handleShow(deps, projectBindingPath, mode2) {
1739
+ const startDir = resolveStartDir(process.env, process.cwd());
1740
+ const root = findRepoRoot(startDir).root;
1741
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1742
+ if (projectBindingPath == null) {
1743
+ if (mode2 === "json") {
1744
+ printResult({ bound: false, projectBindingPath: null, repoIdentity }, mode2);
1745
+ } else {
1746
+ process.stdout.write("No nolto.json binding found in this directory tree.\n");
1747
+ process.stdout.write(`repoIdentity : ${repoIdentity.kind}:${repoIdentity.value}
1748
+ `);
1749
+ }
1750
+ return;
1732
1751
  }
1733
- }
1734
- function writtenEntries(ctx, response) {
1735
- const tombstones = (response.affected ?? []).flatMap((a) => {
1736
- const cached = a.deleted && a.entryId !== response.entry.id ? ctx.cache.state.entries.find((e) => e.id === a.entryId) : void 0;
1737
- return cached ? [{ ...cached, deleted: true, revision: a.toRevision }] : [];
1752
+ const binding = deps.repoBinding != null ? deps.repoBinding.binding : await loadRepoBinding(projectBindingPath).catch((err) => {
1753
+ if (err instanceof CliError) throw err;
1754
+ throw new CliError(`Cannot read binding: ${String(err)}`, 2);
1738
1755
  });
1739
- return [response.entry, ...tombstones];
1740
- }
1741
- async function scanMemoryDir(dir) {
1742
- const ok = [], invalid = [];
1743
- const seen = /* @__PURE__ */ new Map();
1744
- for (const file of (await readdir3(dir, { withFileTypes: true })).filter((f) => f.isFile() && f.name.endsWith(".md") && f.name !== "MEMORY.md").sort((a, b) => a.name.localeCompare(b.name))) {
1745
- let original = file.name.slice(0, -3), name = original;
1746
- try {
1747
- const draft = parseMemory(await readFile7(path8.join(dir, file.name), "utf8"), true);
1748
- original = draft.name || original;
1749
- name = original.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+/, "").slice(0, 64);
1750
- if (!name) throw new CliError(`name \u3092\u6B63\u898F\u5316\u3067\u304D\u307E\u305B\u3093: ${original}`, 2);
1751
- validateDraft({ ...draft, name });
1752
- const first = seen.get(name);
1753
- if (first) throw new CliError(`import \u5185\u3067 name \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059(\u5148: ${first})\u3002`, 2);
1754
- seen.set(name, file.name);
1755
- ok.push({ file: file.name, name, original, draft: { ...draft, name } });
1756
- } catch (error) {
1757
- invalid.push({ file: file.name, name, original, status: "failed", message: error instanceof Error ? error.message : String(error) });
1756
+ if (mode2 === "json") {
1757
+ printResult({
1758
+ bound: binding != null,
1759
+ projectId: binding?.projectId ?? null,
1760
+ projectBindingPath,
1761
+ source: deps.settings.source.project === "repo" ? "repo" : "file",
1762
+ repoIdentity
1763
+ }, mode2);
1764
+ } else {
1765
+ if (binding == null) {
1766
+ process.stdout.write(`Binding file found at ${projectBindingPath} but could not be read.
1767
+ `);
1768
+ } else {
1769
+ process.stdout.write(`Binding file : ${projectBindingPath}
1770
+ `);
1771
+ process.stdout.write(`projectId : ${binding.projectId}
1772
+ `);
1773
+ const active = deps.settings.source.project === "repo" ? "repo (active)" : "repo (not active \u2014 overridden)";
1774
+ process.stdout.write(`source : ${active}
1775
+ `);
1776
+ process.stdout.write(`repoIdentity : ${repoIdentity.kind}:${repoIdentity.value}
1777
+ `);
1758
1778
  }
1759
1779
  }
1760
- return { ok, invalid };
1761
- }
1762
- function importResultLine(scope, result) {
1763
- const { status, name, original, message } = result;
1764
- return `${status} ${scope}/${name}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}`;
1765
1780
  }
1766
- async function importMemoryFiles(opts) {
1767
- const ctx = await createMemoryContext(opts, true);
1768
- let imported = 0, skipped = 0, failed = 0, cached = true;
1769
- const results = [];
1770
- for (const { file, name, original, draft } of opts.targets) {
1771
- let status, message, heading = null;
1781
+ async function handleRebind(deps, projectId, root, mode2, yes) {
1782
+ if (!UUID_RE2.test(projectId)) {
1783
+ throw new CliError(
1784
+ `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1785
+ 2
1786
+ );
1787
+ }
1788
+ const result = await deps.http.get("/api/projects");
1789
+ const projects = Array.isArray(result.projects) ? result.projects : [];
1790
+ const project = projects.find((candidate) => candidate.id === projectId);
1791
+ if (project == null) {
1792
+ throw new CliError(
1793
+ `Project ${projectId} is not in your accessible projects. Check nolto.json (nolto link --show) before rebinding.`,
1794
+ 2
1795
+ );
1796
+ }
1797
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1798
+ if (mode2 !== "json") {
1799
+ process.stdout.write(`Project : ${project.name} (${project.id})
1800
+ `);
1801
+ process.stdout.write(`Bound to : ${project.repoIdentity ?? "not bound"}
1802
+ `);
1803
+ process.stdout.write(`Rebind to : ${repoIdentity.kind}:${repoIdentity.value}
1804
+ `);
1805
+ }
1806
+ if (!yes) {
1807
+ if (mode2 === "json") {
1808
+ throw new CliError(
1809
+ "--rebind requires confirmation. Pass --yes to skip the prompt in --json mode.",
1810
+ 2
1811
+ );
1812
+ }
1813
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1814
+ let confirmed = false;
1772
1815
  try {
1773
- const response = await opts.http.put(ctx.api, {
1774
- scope: opts.scope,
1775
- name,
1776
- description: draft.description,
1777
- body: draft.body,
1778
- ...draft.type ? { type: draft.type } : {},
1779
- allowNew: true,
1780
- ...opts.ai ? {} : { aiSkip: true }
1781
- }, { "X-Nolto-Client": detectMemoryClient(process.env) });
1782
- cached = await updateCache(ctx, opts, writtenEntries(ctx, response), true) && cached;
1783
- heading = aiHeading(response);
1784
- imported++;
1785
- status = "imported";
1786
- } catch (error) {
1787
- if (error instanceof CliError && error.serverError === "memory_exists") {
1788
- skipped++;
1789
- status = "skipped";
1790
- if (error.body?.entry) cached = await updateCache(ctx, opts, [error.body.entry], true) && cached;
1791
- } else {
1792
- failed++;
1793
- status = "failed";
1794
- message = error instanceof Error ? error.message : String(error);
1795
- }
1816
+ const answer = await rl.question(`Rebind "${project.name}" to this repository? [y/N] `);
1817
+ confirmed = answer.trim().toLowerCase() === "y";
1818
+ } finally {
1819
+ rl.close();
1820
+ }
1821
+ if (!confirmed) {
1822
+ process.stdout.write("Aborted.\n");
1823
+ return;
1796
1824
  }
1797
- const result = { file, name, original, status, ...message ? { message } : {} };
1798
- results.push(result);
1799
- opts.write(heading ? `${heading} (\u5143: ${oneLine(file)})` : importResultLine(opts.scope, result));
1800
1825
  }
1801
- return { imported, skipped, failed, results, cached };
1802
- }
1803
-
1804
- // src/commands/init.ts
1805
- import { readFile as readFile11 } from "fs/promises";
1806
-
1807
- // src/watch-state.ts
1808
- import * as fs from "fs/promises";
1809
- import { randomUUID as randomUUID4 } from "crypto";
1810
- import path9 from "path";
1811
- import { z as z2 } from "zod";
1812
- var watchStateSchema = z2.object({
1813
- pid: z2.number().int().positive(),
1814
- version: z2.string().min(1),
1815
- startedAt: z2.string().datetime()
1816
- });
1817
- function getWatchStatePath(env) {
1818
- return path9.join(getConfigDir(env), "watch.json");
1819
- }
1820
- async function readWatchState(filePath, io = fs) {
1821
- try {
1822
- const result = watchStateSchema.safeParse(JSON.parse(await io.readFile(filePath, "utf8")));
1823
- return result.success ? result.data : null;
1824
- } catch {
1825
- return null;
1826
+ await deps.http.post(`/api/projects/${projectId}/repo-binding`, { repoIdentity });
1827
+ if (mode2 === "json") {
1828
+ printResult({ rebound: true, projectId, repoIdentity }, mode2);
1829
+ } else {
1830
+ process.stdout.write(`Rebound project ${projectId} to ${repoIdentity.kind}:${repoIdentity.value}.
1831
+ `);
1826
1832
  }
1827
1833
  }
1828
- async function writeWatchState(filePath, state, io = fs) {
1829
- await io.mkdir(path9.dirname(filePath), { recursive: true, mode: 448 });
1830
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID4()}`;
1834
+ async function handleUnlink(projectBindingPath, mode2) {
1835
+ const { readFile: readFile19, writeFile: writeFile11, chmod: chmod2 } = await import("fs/promises");
1836
+ let existing = {};
1831
1837
  try {
1832
- await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
1833
- await io.rename(tempPath, filePath);
1834
- } catch (error) {
1835
- await io.unlink(tempPath).catch(() => void 0);
1836
- throw error;
1837
- }
1838
- }
1839
- async function removeWatchState(filePath, pid, io = fs) {
1840
- if ((await readWatchState(filePath, io))?.pid === pid) {
1841
- await io.unlink(filePath).catch(() => void 0);
1842
- }
1843
- }
1844
- function isAlive(pid, kill = process.kill) {
1845
- try {
1846
- kill(pid, 0);
1847
- return true;
1848
- } catch (error) {
1849
- if (error.code === "ESRCH") return false;
1850
- if (error.code === "EPERM") return true;
1851
- throw error;
1852
- }
1853
- }
1854
- async function staleWatchWarning(env, currentVersion, kill = process.kill) {
1855
- const state = await readWatchState(getWatchStatePath(env));
1856
- if (!state || state.version === currentVersion || !isAlive(state.pid, kill)) return null;
1857
- return `Warning: nolto watch (pid ${state.pid}) is running CLI v${state.version}, this CLI is v${currentVersion}. Restart it: nolto watch stop, then start it again (or nolto update).`;
1858
- }
1859
-
1860
- // src/commands/init.ts
1861
- import readline2 from "readline/promises";
1862
- import { createRequire } from "module";
1863
- import { fileURLToPath as fileURLToPath2 } from "url";
1864
- import os3 from "os";
1865
- import path15 from "path";
1866
- import fs2 from "fs";
1867
-
1868
- // src/roadmap-bootstrap.ts
1869
- import { existsSync as existsSync3 } from "fs";
1870
- import { readFile as readFile9, realpath } from "fs/promises";
1871
- import path12 from "path";
1872
-
1873
- // src/roadmap-cache.ts
1874
- import { mkdir as mkdir6, readdir as readdir4, readFile as readFile8, writeFile as writeFile7, rename as rename3, unlink as unlink2 } from "fs/promises";
1875
- import { randomUUID as randomUUID5 } from "crypto";
1876
- import path11 from "path";
1877
-
1878
- // src/sync-core.ts
1879
- import { createHash as createHash2 } from "crypto";
1880
- import path10 from "path";
1881
- function sha256Hex(content) {
1882
- return "sha256:" + createHash2("sha256").update(content, "utf8").digest("hex");
1883
- }
1884
- function collectPlanRefs(roadmap) {
1885
- const seen = /* @__PURE__ */ new Set();
1886
- const refs = [];
1887
- for (const phase of roadmap.phases) {
1888
- if (phase.plan != null && !seen.has(phase.plan)) {
1889
- seen.add(phase.plan);
1890
- refs.push({ path: phase.plan, ownerId: phase.id });
1891
- }
1892
- for (const task of phase.tasks) {
1893
- if (task.plan != null && !seen.has(task.plan)) {
1894
- seen.add(task.plan);
1895
- refs.push({ path: task.plan, ownerId: task.id });
1896
- }
1838
+ const raw = await readFile19(projectBindingPath, "utf8");
1839
+ const parsed = JSON.parse(raw);
1840
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
1841
+ throw new CliError(
1842
+ `Cannot unlink ${projectBindingPath}: file contains valid JSON but is not a plain object (got ${Array.isArray(parsed) ? "array" : String(parsed)}). Remove or fix the file manually.`,
1843
+ 2
1844
+ );
1897
1845
  }
1846
+ existing = parsed;
1847
+ } catch (err) {
1848
+ if (err instanceof CliError) throw err;
1849
+ throw new CliError(`Cannot read ${projectBindingPath}: ${String(err)}`, 2);
1898
1850
  }
1899
- return refs;
1900
- }
1901
- async function loadValidRoadmap(filePath, readFile19) {
1902
- let raw;
1903
- try {
1904
- raw = await readFile19(filePath);
1905
- } catch {
1906
- throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1907
- }
1908
- let parsed;
1909
- try {
1910
- parsed = JSON.parse(raw);
1911
- } catch {
1912
- throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1851
+ const { projectId: _removed, ...rest } = existing;
1852
+ void _removed;
1853
+ await writeFile11(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1854
+ await chmod2(projectBindingPath, 420);
1855
+ if (mode2 === "json") {
1856
+ printResult({ unlinked: true, projectBindingPath }, mode2);
1857
+ } else {
1858
+ process.stdout.write(`Removed projectId from ${projectBindingPath}.
1859
+ `);
1913
1860
  }
1914
- const { errors } = validateRoadmap(parsed);
1915
- if (errors.length > 0) {
1861
+ }
1862
+ async function performLink(deps, projectId, mode2, slug, yes = false) {
1863
+ if (!UUID_RE2.test(projectId)) {
1916
1864
  throw new CliError(
1917
- `${filePath} failed validation \u2014 not syncing:
1918
- ${errors.join("\n ")}`,
1865
+ `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
1919
1866
  2
1920
1867
  );
1921
1868
  }
1922
- return parsed;
1923
- }
1924
- async function buildSyncBody(args) {
1925
- const planDocuments = [];
1926
- for (const ref of collectPlanRefs(args.roadmap)) {
1927
- if (!isValidPlanPath(ref.path)) {
1928
- args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1929
- continue;
1930
- }
1869
+ const startDir = resolveStartDir(process.env, process.cwd());
1870
+ const { root, foundGit } = findRepoRoot(startDir);
1871
+ if (!foundGit) {
1872
+ process.stderr.write(
1873
+ `Warning: no .git directory found above ${startDir}. Writing nolto.json to current directory.
1874
+ `
1875
+ );
1876
+ }
1877
+ const http = deps.http ?? createHttpClient({
1878
+ baseUrl: deps.settings.baseUrl,
1879
+ token: deps.settings.token,
1880
+ version: deps.version
1881
+ });
1882
+ let projectName = path11.basename(root);
1883
+ if (deps.settings.token != null) {
1931
1884
  try {
1932
- if (await args.deps.isIgnored?.(args.repoRoot, ref.path)) {
1933
- args.deps.warn(`plan path is git-ignored, skipping: ${ref.path}`);
1934
- continue;
1885
+ const result = await http.get(
1886
+ "/api/projects"
1887
+ );
1888
+ const projects = Array.isArray(result.projects) ? result.projects : [];
1889
+ projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
1890
+ if (!projects.some((p) => p.id === projectId)) {
1891
+ process.stderr.write(
1892
+ `Warning: project ${projectId} was not found in GET /api/projects.
1893
+ Proceeding anyway \u2014 verify the ID is correct.
1894
+ `
1895
+ );
1935
1896
  }
1936
1897
  } catch {
1898
+ process.stderr.write(
1899
+ "Warning: could not verify project membership (offline or token issue). Proceeding anyway.\n"
1900
+ );
1937
1901
  }
1938
- const root = path10.resolve(args.repoRoot);
1939
- const absolute = path10.resolve(root, ref.path);
1940
- if (absolute !== root && !absolute.startsWith(root + path10.sep)) {
1941
- args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1942
- continue;
1943
- }
1944
- if (!args.deps.fileExists(absolute)) {
1945
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1946
- continue;
1947
- }
1948
- if (args.deps.realpath !== void 0) {
1949
- let real;
1950
- let realRoot;
1951
- try {
1952
- real = await args.deps.realpath(absolute);
1953
- realRoot = await args.deps.realpath(root);
1954
- } catch {
1955
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1956
- continue;
1902
+ }
1903
+ if (deps.repoBinding?.error != null) {
1904
+ process.stderr.write(
1905
+ `Warning: existing nolto.json is invalid (${deps.repoBinding.error.message}). Overwriting it to repair.
1906
+ `
1907
+ );
1908
+ }
1909
+ await writeRepoBinding(root, projectId);
1910
+ const writtenPath = path11.join(root, "nolto.json");
1911
+ let repoAdded = false;
1912
+ if (deps.settings.token == null) {
1913
+ process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
1914
+ } else {
1915
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1916
+ const result = await ensureProjectRepo({
1917
+ http,
1918
+ projectId,
1919
+ repoIdentity,
1920
+ confirm: async (question) => {
1921
+ if (yes) return true;
1922
+ if (mode2 === "json") throw new CliError("Adding this repository requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
1923
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1924
+ try {
1925
+ const answer = (await rl.question(question)).trim().toLowerCase();
1926
+ return answer === "" || answer === "y" || answer === "yes";
1927
+ } finally {
1928
+ rl.close();
1929
+ }
1930
+ },
1931
+ log: (line2) => {
1932
+ if (mode2 !== "json") process.stdout.write(line2 + "\n");
1957
1933
  }
1958
- if (real !== realRoot && !real.startsWith(realRoot + path10.sep)) {
1959
- args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1960
- continue;
1934
+ });
1935
+ if (result === "declined") {
1936
+ process.stdout.write("Skipped adding this repository. Run `nolto link --add` later; roadmap sync will fail until then.\n");
1937
+ return;
1938
+ }
1939
+ repoAdded = result === "added";
1940
+ await ensureRoadmapCache({
1941
+ env: process.env,
1942
+ http,
1943
+ projectId,
1944
+ projectName,
1945
+ repoRoot: root,
1946
+ slug,
1947
+ repoIdentity,
1948
+ log: (line2) => {
1949
+ if (mode2 !== "json") process.stdout.write(line2 + "\n");
1961
1950
  }
1962
- if (!isValidPlanPath(path10.relative(realRoot, real).split(path10.sep).join("/"))) {
1963
- args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1964
- continue;
1951
+ });
1952
+ }
1953
+ let registryAdded = false;
1954
+ if (isHomeDirectory(root)) {
1955
+ process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
1956
+ `);
1957
+ } else {
1958
+ try {
1959
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
1960
+ if (registryAdded) {
1961
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
1962
+ if (warning) process.stderr.write(warning + "\n");
1965
1963
  }
1964
+ } catch (err) {
1965
+ const message = err instanceof Error ? err.message : String(err);
1966
+ process.stderr.write(`Warning: could not update watch registry: ${message}
1967
+ `);
1968
+ }
1969
+ }
1970
+ if (mode2 === "json") {
1971
+ printResult({
1972
+ linked: true,
1973
+ projectId,
1974
+ projectBindingPath: writtenPath,
1975
+ registryAdded,
1976
+ repoAdded
1977
+ }, mode2);
1978
+ } else {
1979
+ process.stdout.write(
1980
+ `Linked this repo to project ${projectId} (wrote ${writtenPath}).
1981
+ Commit nolto.json to share the binding with your team.
1982
+ `
1983
+ );
1984
+ if (registryAdded) {
1985
+ process.stdout.write(`watch registry: added ${root}
1986
+ `);
1966
1987
  }
1967
- const content = await args.deps.readFile(absolute);
1968
- planDocuments.push({
1969
- path: ref.path,
1970
- taskId: ref.ownerId,
1971
- content,
1972
- contentHash: sha256Hex(content)
1973
- });
1974
1988
  }
1975
- return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1976
1989
  }
1977
- async function runSync(args, deps) {
1978
- const body = await buildSyncBody({
1979
- roadmap: args.roadmap,
1980
- repoRoot: args.repoRoot,
1981
- repoIdentity: args.repoIdentity,
1982
- deps
1983
- });
1984
- const response = await deps.http.put(
1985
- `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1986
- { ...body, baseRevision: args.baseRevision }
1987
- );
1988
- for (const warning of response.warnings ?? []) deps.warn(warning);
1989
- const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1990
- deps.log(
1991
- `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})` : ""}`
1992
- );
1993
- return response;
1994
- }
1995
-
1996
- // src/roadmap-cache.ts
1997
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1998
- var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1999
- function cacheDir(env, projectId) {
2000
- if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
2001
- return path11.join(getConfigDir(env), "projects", projectId, "roadmaps");
2002
- }
2003
- function cachePaths(env, projectId, slug) {
2004
- if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
2005
- const dir = cacheDir(env, projectId);
2006
- return { json: path11.join(dir, `${slug}.json`), meta: path11.join(dir, `${slug}.meta.json`) };
2007
- }
2008
- async function listCachedSlugs(env, projectId) {
2009
- try {
2010
- const entries = await readdir4(cacheDir(env, projectId), { withFileTypes: true });
2011
- return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
2012
- } catch (err) {
2013
- if (err.code === "ENOENT") return [];
2014
- throw err;
2015
- }
2016
- }
2017
- async function readCache(env, projectId, slug) {
2018
- const paths = cachePaths(env, projectId, slug);
2019
- let raw;
2020
- try {
2021
- raw = await readFile8(paths.json, "utf8");
2022
- } catch (err) {
2023
- if (err.code === "ENOENT") return null;
2024
- throw err;
2025
- }
2026
- let roadmap;
2027
- try {
2028
- roadmap = JSON.parse(raw);
2029
- } catch {
2030
- throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
2031
- }
2032
- const { errors } = validateRoadmap(roadmap);
2033
- if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
2034
- let meta = null;
2035
- try {
2036
- const parsed = JSON.parse(await readFile8(paths.meta, "utf8"));
2037
- 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") {
2038
- throw new Error("Invalid cache metadata");
1990
+ function register(program, deps) {
1991
+ const cmd = program.command("link [projectId]").description(
1992
+ "Bind this repository to a Nolto project.\nWrites nolto.json at the repo root. Commit it to share the binding with your team.\n\nExamples:\n nolto link <uuid> Write / update nolto.json\n nolto link --show Show the current binding\n nolto link --rebind Rebind the project to this repository\n nolto link --list List project repositories\n nolto link --add Add this repository to the project\n nolto link --remove <identity-or-id> Remove a project repository\n nolto link --unlink Remove the projectId from nolto.json"
1993
+ ).option("--slug <slug>", "Name this repository's roadmap").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").option("--show", "Show the current repo binding (path + projectId + source)").option("--rebind", "Rebind the project to this repository (owner only, once per 7 days)").option("-y, --yes", "Skip repository addition, rebind, and removal confirmation prompts").option("--unlink", "Remove the projectId key from nolto.json");
1994
+ cmd.action(async (projectId) => {
1995
+ const { output } = deps;
1996
+ const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
1997
+ const bindingError = deps.repoBinding?.error ?? null;
1998
+ const mode2 = output.mode;
1999
+ if (cmd.opts()["show"]) {
2000
+ if (bindingError != null) {
2001
+ throw invalidBindingError(projectBindingPath, bindingError);
2002
+ }
2003
+ await handleShow(deps, projectBindingPath, mode2);
2004
+ return;
2039
2005
  }
2040
- if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
2041
- throw new Error("Invalid currentTaskId");
2006
+ if (cmd.opts()["unlink"]) {
2007
+ if (projectBindingPath == null) {
2008
+ throw new CliError("No nolto.json found in this directory tree. Nothing to unlink.", 2);
2009
+ }
2010
+ await handleUnlink(projectBindingPath, mode2);
2011
+ return;
2042
2012
  }
2043
- if ("repoIdentity" in parsed && parsed.repoIdentity !== null && typeof parsed.repoIdentity !== "string") {
2044
- throw new Error("Invalid repoIdentity");
2013
+ const opts = cmd.opts();
2014
+ if (opts["list"] || opts["add"] || opts["remove"] !== void 0 || opts["slug"] !== void 0) {
2015
+ if (projectId == null) {
2016
+ if (bindingError != null) throw invalidBindingError(projectBindingPath, bindingError);
2017
+ const binding = deps.repoBinding?.binding ?? (projectBindingPath ? await loadRepoBinding(projectBindingPath) : null);
2018
+ projectId = binding?.projectId;
2019
+ }
2020
+ if (projectId == null) throw new CliError("No project binding. Run `nolto link <projectId>` first.", 2);
2021
+ if (!UUID_RE2.test(projectId)) throw new CliError(`Invalid project ID: "${projectId}". Must be a UUID.`, 2);
2022
+ if (opts["add"]) {
2023
+ const root = findRepoRoot(resolveStartDir(process.env, process.cwd())).root;
2024
+ const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2025
+ const repo = await deps.http.post(`/api/projects/${projectId}/repos`, {
2026
+ repoIdentity,
2027
+ ...opts["label"] !== void 0 ? { label: opts["label"] } : {}
2028
+ });
2029
+ printResult(mode2 === "json" ? { added: true, projectId, repo } : `Added ${repoIdentity.kind}:${repoIdentity.value} to project ${projectId}.`, mode2);
2030
+ return;
2031
+ }
2032
+ if (opts["list"] || opts["remove"] !== void 0) {
2033
+ const { repos } = await deps.http.get(`/api/projects/${projectId}`);
2034
+ if (opts["list"]) {
2035
+ if (mode2 === "json") printResult({ repos }, mode2);
2036
+ else for (const repo2 of repos) printResult(`${repo2.identity}${repo2.label ? ` (${repo2.label})` : ""} ${repo2.boundAt} ${repo2.id}`, mode2);
2037
+ return;
2038
+ }
2039
+ const input = opts["remove"];
2040
+ const identity = /^(remote|local):/.test(input) ? input : `remote:${input}`;
2041
+ const repo = repos.find((row) => row.id === input || row.identity === identity);
2042
+ if (!repo) throw new CliError(`Repository ${input} is not bound to this project.`, 2);
2043
+ if (!opts["yes"]) {
2044
+ if (mode2 === "json") throw new CliError("--remove requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
2045
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2046
+ let confirmed = false;
2047
+ try {
2048
+ const answer = await rl.question(`Remove "${repo.identity}" from project ${projectId}? [y/N] `);
2049
+ confirmed = answer.trim().toLowerCase() === "y";
2050
+ } finally {
2051
+ rl.close();
2052
+ }
2053
+ if (!confirmed) {
2054
+ process.stdout.write("Aborted.\n");
2055
+ return;
2056
+ }
2057
+ }
2058
+ await deps.http.delete(`/api/projects/${projectId}/repos/${repo.id}`);
2059
+ printResult(mode2 === "json" ? { removed: true, projectId, repoId: repo.id } : `Removed ${repo.identity} from project ${projectId}.`, mode2);
2060
+ return;
2061
+ }
2045
2062
  }
2046
- meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null, repoIdentity: parsed.repoIdentity ?? null };
2047
- } catch (err) {
2048
- if (err.code !== "ENOENT") {
2049
- throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
2063
+ if (cmd.opts()["rebind"]) {
2064
+ const boundProjectId = deps.repoBinding?.binding?.projectId;
2065
+ const effectiveProjectId = projectId ?? boundProjectId;
2066
+ if (effectiveProjectId == null) {
2067
+ throw new CliError("No project binding. Run `nolto link <projectId>` first.", 2);
2068
+ }
2069
+ const startDir = resolveStartDir(process.env, process.cwd());
2070
+ const root = findRepoRoot(startDir).root;
2071
+ await handleRebind(deps, effectiveProjectId, root, mode2, cmd.opts()["yes"] === true);
2072
+ return;
2050
2073
  }
2051
- }
2052
- return { roadmap, meta, raw };
2053
- }
2054
- async function writeCache(env, projectId, slug, roadmap, meta) {
2055
- const paths = cachePaths(env, projectId, slug);
2056
- const raw = serializeRoadmap(roadmap);
2057
- const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
2058
- await mkdir6(cacheDir(env, projectId), { recursive: true, mode: 448 });
2059
- for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
2060
- const temp = `${filePath}.tmp-${process.pid}-${randomUUID5()}`;
2061
- try {
2062
- await writeFile7(temp, content, { mode: 384 });
2063
- await rename3(temp, filePath);
2064
- } finally {
2065
- await unlink2(temp).catch(() => void 0);
2074
+ if (projectId == null || projectId.trim().length === 0) {
2075
+ if (bindingError != null) {
2076
+ throw invalidBindingError(projectBindingPath, bindingError);
2077
+ }
2078
+ throw new CliError(
2079
+ "Usage: nolto link <projectId> (provide a UUID)\nOr use --show to view the current binding, --rebind to rebind it, --unlink to remove it.",
2080
+ 2
2081
+ );
2066
2082
  }
2067
- }
2068
- }
2069
- function isDirty(entry) {
2070
- return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
2071
- }
2072
-
2073
- // src/roadmap-scaffold.ts
2074
- function slugifyProjectId(name) {
2075
- const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
2076
- return slug.length > 0 ? slug : "project";
2083
+ await performLink(deps, projectId, mode2, opts["slug"], opts["yes"] === true);
2084
+ });
2077
2085
  }
2078
- function buildScaffold(projectName, repoBasename) {
2079
- return {
2080
- schemaVersion: 3,
2081
- project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
2082
- summary: "",
2083
- phases: []
2084
- };
2086
+ function invalidBindingError(projectBindingPath, error) {
2087
+ return new CliError(
2088
+ `Invalid nolto.json at ${projectBindingPath ?? "unknown path"}: ${error.message}. Repair it with \`nolto link <projectId>\` or \`nolto init\`.`,
2089
+ 2
2090
+ );
2085
2091
  }
2086
2092
 
2087
- // src/roadmap-bootstrap.ts
2088
- async function pullRoadmapCache(args) {
2089
- const { env, projectId, slug } = args;
2090
- const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
2091
- const validation = validateRoadmap(response.roadmap);
2092
- if (validation.errors.length > 0) {
2093
- throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
2093
+ // src/roadmap-read.ts
2094
+ async function resolveRoadmapReadContext(deps) {
2095
+ if (deps.settings.token == null) {
2096
+ throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2094
2097
  }
2095
- let existing;
2096
- try {
2097
- existing = await readCache(env, projectId, slug);
2098
- } catch (err) {
2099
- if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
2100
- existing = null;
2098
+ const startDir = resolveStartDir(process.env, process.cwd());
2099
+ const { root, foundGit } = findRepoRoot(startDir);
2100
+ if (!foundGit) {
2101
+ throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2101
2102
  }
2102
- if (existing && isDirty(existing) && !args.force) {
2103
- args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
2104
- return false;
2103
+ const binding = await loadRepoBinding(path12.join(root, "nolto.json"));
2104
+ const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2105
+ if (projectId == null) {
2106
+ throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
2105
2107
  }
2106
- const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
2107
- await writeCache(env, projectId, slug, response.roadmap, {
2108
- revision: response.revision,
2109
- pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2110
- currentTaskId: response.currentTaskId,
2111
- repoIdentity: response.repoIdentity ?? null
2108
+ return { root, projectId };
2109
+ }
2110
+
2111
+ // src/commands/pull.ts
2112
+ function register2(program, deps) {
2113
+ 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) => {
2114
+ await runPull(deps, { ...opts, slug: requestedSlug });
2112
2115
  });
2113
- args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
2114
- return true;
2115
2116
  }
2116
- async function ensureRoadmapCache(args) {
2117
- const { env, projectId } = args;
2118
- const identity = repoIdentityToString(args.repoIdentity);
2119
- const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
2120
- const warn2 = (line2) => {
2121
- process.stderr.write(line2 + "\n");
2122
- };
2123
- const log = (line2) => args.log(`roadmap: ${line2}`);
2124
- if (list.roadmaps.length > 0) {
2125
- let skipped = false;
2126
- for (const { slug: slug2 } of list.roadmaps) {
2127
- if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
2128
- }
2129
- if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
2130
- if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
2131
- }
2132
- const basename = path12.basename(args.repoRoot);
2133
- const slug = args.slug ?? slugifyProjectId(basename);
2134
- const collision = list.roadmaps.find((row) => row.slug === slug);
2135
- if (collision) {
2136
- if (args.slug === void 0) {
2137
- log(`skipped \u2014 "${slug}" is another repository's roadmap (${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <name>\` to create one for this repository.`);
2138
- return;
2139
- }
2140
- throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
2117
+ async function runPull(deps, opts = {}) {
2118
+ const messages = [];
2119
+ const { projectId } = await resolveRoadmapReadContext(deps);
2120
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2121
+ const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2122
+ if (opts.slug != null && !serverBySlug.has(opts.slug)) {
2123
+ throw new CliError(`Roadmap "${opts.slug}" was not found on the server.`, 2);
2141
2124
  }
2142
- let existing;
2143
- try {
2144
- existing = await readCache(env, projectId, slug);
2145
- } catch (err) {
2146
- if (!(err instanceof CliError)) throw err;
2147
- existing = null;
2148
- }
2149
- if (existing && isDirty(existing)) {
2150
- warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
2151
- throw new CliError("Roadmap has local changes that are not synced.", 4);
2152
- }
2153
- const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
2154
- await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
2155
- const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
2156
- http: args.http,
2157
- readFile: (p) => readFile9(p, "utf8"),
2158
- realpath,
2159
- fileExists: existsSync3,
2160
- log: () => void 0,
2161
- warn: warn2
2162
- });
2163
- await writeCache(env, projectId, slug, response.roadmap ?? roadmap, { repoIdentity: identity, revision: response.revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : existing?.meta?.currentTaskId });
2164
- log(`created ${slug} on server (rev ${response.revision})`);
2165
- }
2166
- async function ensureProjectRepo(args) {
2167
- let repos;
2168
- try {
2169
- const project = await args.http.get(`/api/projects/${args.projectId}`);
2170
- repos = Array.isArray(project.repos) ? project.repos : [];
2171
- } catch (error) {
2172
- if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
2173
- process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
2174
- `);
2175
- return "unbound";
2176
- }
2177
- if (repos.length === 0) return "unbound";
2178
- const identity = repoIdentityToString(args.repoIdentity);
2179
- if (repos.some((repo) => repo.identity === identity)) return "bound";
2180
- if (!await args.confirm(`Project is bound to ${repos.map((repo) => repo.identity).join(", ")}. Add this repository (${identity}) to the project? [Y/n] `)) return "declined";
2181
- try {
2182
- await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
2183
- } catch (error) {
2184
- if (error instanceof CliError) {
2185
- if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
2186
- if (error.status === 403) {
2187
- throw new CliError(
2188
- "Only the project owner can add a repository.",
2189
- 2,
2190
- "Ask the owner to run `nolto link --add` in this repository."
2191
- );
2125
+ const slugs = opts.slug == null ? [...serverBySlug.keys()] : [opts.slug];
2126
+ let skipped = false;
2127
+ for (const slug of slugs) {
2128
+ if (!await pullRoadmapCache({
2129
+ env: process.env,
2130
+ http: deps.http,
2131
+ projectId,
2132
+ slug,
2133
+ force: opts.force,
2134
+ log: (line2) => {
2135
+ messages.push(line2);
2136
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
2137
+ },
2138
+ warn: (line2) => {
2139
+ process.stderr.write(line2 + "\n");
2192
2140
  }
2193
- if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
2194
- }
2195
- throw error;
2141
+ })) skipped = true;
2196
2142
  }
2197
- args.log(`Added ${identity} to project.`);
2198
- return "added";
2143
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
2144
+ if (!opts.quiet && deps.output.mode === "json") printResult({ messages }, "json");
2199
2145
  }
2200
2146
 
2201
- // src/commands/link.ts
2202
- import readline from "readline/promises";
2203
- import os2 from "os";
2204
- import path14 from "path";
2205
- import { statSync as statSync2 } from "fs";
2147
+ // src/commands/sync.ts
2148
+ import { execFile as execFile2 } from "child_process";
2149
+ import { promisify } from "util";
2150
+ import { readFile as readFile8, realpath as realpath2 } from "fs/promises";
2151
+ import { existsSync as existsSync4 } from "fs";
2206
2152
 
2207
- // src/registry.ts
2208
- import { readFile as readFile10, writeFile as writeFile8, mkdir as mkdir7, rename as rename4, unlink as unlink3 } from "fs/promises";
2209
- import { randomUUID as randomUUID6 } from "crypto";
2210
- import path13 from "path";
2211
- import { z as z3 } from "zod";
2212
- var registrySchema = z3.object({
2213
- schemaVersion: z3.literal(1),
2214
- repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
2215
- }).passthrough();
2216
- function getRegistryPath(env) {
2217
- return path13.join(getConfigDir(env), "registry.json");
2218
- }
2219
- async function loadRegistry(filePath) {
2220
- let raw;
2221
- try {
2222
- raw = await readFile10(filePath, "utf8");
2223
- } catch (err) {
2224
- const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
2225
- if (code === "ENOENT") {
2226
- return { schemaVersion: 1, repos: [] };
2153
+ // src/git-links.ts
2154
+ function parseGitLog(raw) {
2155
+ return raw.split("\n").filter((line2) => line2.length > 0).map((line2) => {
2156
+ const fields = line2.replace(/\r$/, "").split("");
2157
+ const [ref, subject, author, committedAt] = fields;
2158
+ if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
2159
+ throw new Error("Malformed git log entry");
2227
2160
  }
2228
- throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
2229
- }
2230
- let parsed;
2231
- try {
2232
- parsed = JSON.parse(raw);
2233
- } catch {
2234
- throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
2235
- }
2236
- const result = registrySchema.safeParse(parsed);
2237
- if (!result.success) {
2238
- const issue = result.error.issues[0];
2239
- const fieldPath = issue?.path.join(".") ?? "";
2240
- throw new CliError(
2241
- `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
2242
- 2
2243
- );
2244
- }
2245
- return result.data;
2161
+ return { ref, subject, author, committedAt: new Date(committedAt).toISOString() };
2162
+ });
2246
2163
  }
2247
- async function addRepoToRegistry(filePath, entry) {
2248
- const registry = await loadRegistry(filePath);
2249
- const existing = registry.repos.find((repo) => repo.root === entry.root);
2250
- if (existing?.projectId === entry.projectId) {
2251
- return { added: false, updated: false, registry };
2252
- }
2253
- const updated = {
2254
- ...registry,
2255
- repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
2256
- };
2257
- await writeRegistry(filePath, updated);
2258
- return { added: !existing, updated: !!existing, registry: updated };
2164
+ function extractIssueKeys(subject) {
2165
+ 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]))];
2259
2166
  }
2260
- async function writeRegistry(filePath, registry) {
2261
- await mkdir7(path13.dirname(filePath), { recursive: true, mode: 448 });
2262
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID6()}`;
2263
- try {
2264
- await writeFile8(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
2265
- await rename4(tempPath, filePath);
2266
- } catch (err) {
2267
- await unlink3(tempPath).catch(() => void 0);
2268
- throw err;
2269
- }
2167
+ function extractPrNumber(subject) {
2168
+ return /\(#([1-9][0-9]{0,8})\)$/.exec(subject)?.[1] ?? /^Merge pull request #([1-9][0-9]{0,8})\b/.exec(subject)?.[1] ?? null;
2270
2169
  }
2271
- async function removeRepoFromRegistry(filePath, root) {
2272
- const registry = await loadRegistry(filePath);
2273
- const repos = registry.repos.filter((repo) => repo.root !== root);
2274
- if (repos.length === registry.repos.length) return { removed: false, registry };
2275
- const updated = { ...registry, repos };
2276
- await writeRegistry(filePath, updated);
2277
- return { removed: true, registry: updated };
2170
+ function buildGitLinksPayload(entries) {
2171
+ return { links: entries.flatMap((entry) => {
2172
+ const keys = extractIssueKeys(entry.subject);
2173
+ const pr = extractPrNumber(entry.subject);
2174
+ const refs = [{ kind: "commit", ref: entry.ref }, ...pr ? [{ kind: "pr", ref: pr }] : []];
2175
+ return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
2176
+ ...ref,
2177
+ title: entry.subject.slice(0, 500),
2178
+ author: entry.author.slice(0, 500),
2179
+ committedAt: entry.committedAt,
2180
+ issueKeys: keys.slice(index * 20, (index + 1) * 20)
2181
+ })));
2182
+ }) };
2278
2183
  }
2279
-
2280
- // src/commands/link.ts
2281
- var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2282
- function resolveStartDir(env, cwd) {
2283
- const cpd = env["CLAUDE_PROJECT_DIR"];
2284
- return cpd != null && cpd.length > 0 ? cpd : cwd;
2184
+ function stdout(result) {
2185
+ if (typeof result === "object" && result !== null && "stdout" in result && typeof result.stdout === "string") return result.stdout;
2186
+ throw new Error("Git command returned no text output");
2285
2187
  }
2286
- function dirHasGit(dir) {
2188
+ async function collectGitLinks(root, exec) {
2189
+ let probe;
2287
2190
  try {
2288
- statSync2(path14.join(dir, ".git"));
2289
- return true;
2191
+ probe = await exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root });
2290
2192
  } catch {
2291
- return false;
2193
+ return null;
2292
2194
  }
2195
+ if (stdout(probe).trim() !== "true") return null;
2196
+ const result = await exec("git", ["log", "--no-color", "--format=%H%x1f%s%x1f%an%x1f%cI", "-n", "300"], { cwd: root });
2197
+ return buildGitLinksPayload(parseGitLog(stdout(result)));
2293
2198
  }
2294
- function findRepoRoot(startDir, hasGit = dirHasGit) {
2295
- let current = startDir;
2296
- while (true) {
2297
- if (hasGit(current)) {
2298
- return { root: current, foundGit: true };
2199
+
2200
+ // src/sync-repo.ts
2201
+ import path13 from "path";
2202
+ import { readdir as readdir3 } from "fs/promises";
2203
+ function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2204
+ const planAbsPaths = /* @__PURE__ */ new Set();
2205
+ const resolvedRoot = path13.resolve(root);
2206
+ for (const roadmap of roadmaps) {
2207
+ for (const ref of collectPlanRefs(roadmap)) {
2208
+ const absolute = path13.resolve(resolvedRoot, ref.path);
2209
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path13.sep)) {
2210
+ warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2211
+ continue;
2212
+ }
2213
+ if (!isValidPlanPath(ref.path)) {
2214
+ warn2(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
2215
+ continue;
2216
+ }
2217
+ planAbsPaths.add(absolute);
2299
2218
  }
2300
- const parent = path14.dirname(current);
2301
- if (parent === current) break;
2302
- current = parent;
2303
2219
  }
2304
- return { root: startDir, foundGit: false };
2305
- }
2306
- function isHomeDirectory(dir, home = os2.homedir()) {
2307
- return path14.resolve(dir) === path14.resolve(home);
2220
+ return [...planAbsPaths];
2308
2221
  }
2309
- async function handleShow(deps, projectBindingPath, mode2) {
2310
- const startDir = resolveStartDir(process.env, process.cwd());
2311
- const root = findRepoRoot(startDir).root;
2312
- const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2313
- if (projectBindingPath == null) {
2314
- if (mode2 === "json") {
2315
- printResult({ bound: false, projectBindingPath: null, repoIdentity }, mode2);
2316
- } else {
2317
- process.stdout.write("No nolto.json binding found in this directory tree.\n");
2318
- process.stdout.write(`repoIdentity : ${repoIdentity.kind}:${repoIdentity.value}
2319
- `);
2222
+ async function syncRepo(args, io) {
2223
+ const { projectId } = args;
2224
+ const repoIdentity = await io.repoIdentity(args.root);
2225
+ const identity = repoIdentityToString(repoIdentity);
2226
+ const slugs = args.slugs ?? await listCachedSlugs(io.env, projectId);
2227
+ if (slugs.length === 0) {
2228
+ let legacyFiles = [];
2229
+ try {
2230
+ legacyFiles = await readdir3(path13.join(args.root, ".nolto", "roadmaps"));
2231
+ } catch (err) {
2232
+ if (err.code !== "ENOENT") throw err;
2320
2233
  }
2321
- return;
2234
+ if (legacyFiles.some((file) => file.endsWith(".json"))) {
2235
+ throw new CliError("Roadmaps are still in .nolto/roadmaps. Run `nolto roadmap migrate`.", 2);
2236
+ }
2237
+ throw new CliError("No cached roadmap for this project. Run `nolto pull` or `nolto init`.", 2);
2322
2238
  }
2323
- const binding = deps.repoBinding != null ? deps.repoBinding.binding : await loadRepoBinding(projectBindingPath).catch((err) => {
2324
- if (err instanceof CliError) throw err;
2325
- throw new CliError(`Cannot read binding: ${String(err)}`, 2);
2326
- });
2327
- if (mode2 === "json") {
2328
- printResult({
2329
- bound: binding != null,
2330
- projectId: binding?.projectId ?? null,
2331
- projectBindingPath,
2332
- source: deps.settings.source.project === "repo" ? "repo" : "file",
2333
- repoIdentity
2334
- }, mode2);
2335
- } else {
2336
- if (binding == null) {
2337
- process.stdout.write(`Binding file found at ${projectBindingPath} but could not be read.
2338
- `);
2339
- } else {
2340
- process.stdout.write(`Binding file : ${projectBindingPath}
2341
- `);
2342
- process.stdout.write(`projectId : ${binding.projectId}
2343
- `);
2344
- const active = deps.settings.source.project === "repo" ? "repo (active)" : "repo (not active \u2014 overridden)";
2345
- process.stdout.write(`source : ${active}
2346
- `);
2347
- process.stdout.write(`repoIdentity : ${repoIdentity.kind}:${repoIdentity.value}
2348
- `);
2239
+ const roadmaps = [];
2240
+ for (const slug of slugs) {
2241
+ const entry = await readCache(io.env, projectId, slug);
2242
+ if (!entry) throw new CliError(`No cached roadmap "${slug}". Run \`nolto roadmap pull ${slug}\`.`, 2);
2243
+ if (args.slugs === void 0 && entry.meta?.repoIdentity != null && entry.meta.repoIdentity !== identity) {
2244
+ io.log(`skipped ${slug} (belongs to ${entry.meta.repoIdentity})`);
2245
+ continue;
2349
2246
  }
2247
+ roadmaps.push({ slug, ...entry });
2350
2248
  }
2351
- }
2352
- async function handleRebind(deps, projectId, root, mode2, yes) {
2353
- if (!UUID_RE2.test(projectId)) {
2354
- throw new CliError(
2355
- `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
2356
- 2
2357
- );
2358
- }
2359
- const result = await deps.http.get("/api/projects");
2360
- const projects = Array.isArray(result.projects) ? result.projects : [];
2361
- const project = projects.find((candidate) => candidate.id === projectId);
2362
- if (project == null) {
2363
- throw new CliError(
2364
- `Project ${projectId} is not in your accessible projects. Check nolto.json (nolto link --show) before rebinding.`,
2365
- 2
2366
- );
2367
- }
2368
- const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2369
- if (mode2 !== "json") {
2370
- process.stdout.write(`Project : ${project.name} (${project.id})
2371
- `);
2372
- process.stdout.write(`Bound to : ${project.repoIdentity ?? "not bound"}
2373
- `);
2374
- process.stdout.write(`Rebind to : ${repoIdentity.kind}:${repoIdentity.value}
2375
- `);
2376
- }
2377
- if (!yes) {
2378
- if (mode2 === "json") {
2379
- throw new CliError(
2380
- "--rebind requires confirmation. Pass --yes to skip the prompt in --json mode.",
2381
- 2
2249
+ if (roadmaps.length === 0) throw new CliError("No cached roadmap belongs to this repository. Run `nolto link --slug <slug>` to create one, or `nolto pull`.", 2);
2250
+ const exec = io.exec;
2251
+ const isIgnored = exec === void 0 ? void 0 : async (root, relPath) => {
2252
+ try {
2253
+ await exec("git", ["check-ignore", "-q", "--", relPath], { cwd: root });
2254
+ return true;
2255
+ } catch {
2256
+ return false;
2257
+ }
2258
+ };
2259
+ const results = [];
2260
+ for (const entry of roadmaps) {
2261
+ const { slug, roadmap, meta } = entry;
2262
+ if (args.onlyDirty && !isDirty(entry)) continue;
2263
+ try {
2264
+ const response = await runSync(
2265
+ { repoRoot: args.root, projectId, slug, roadmap, repoIdentity, baseRevision: meta?.revision ?? 0 },
2266
+ { http: io.http, readFile: io.readFile, fileExists: io.fileExists, realpath: io.realpath, ...isIgnored ? { isIgnored } : {}, log: io.log, warn: io.warn }
2382
2267
  );
2268
+ await writeCache(io.env, projectId, slug, response.roadmap ?? roadmap, {
2269
+ repoIdentity: identity,
2270
+ revision: response.revision,
2271
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2272
+ currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : meta?.currentTaskId
2273
+ });
2274
+ results.push(response);
2275
+ entry.roadmap = response.roadmap ?? roadmap;
2276
+ } catch (err) {
2277
+ if (err instanceof CliError && err.status === 409) {
2278
+ if (err.serverError === "task_conflict") {
2279
+ const conflicts = err.body?.["conflicts"];
2280
+ if (Array.isArray(conflicts)) {
2281
+ for (const conflict of conflicts) {
2282
+ if (conflict !== null && typeof conflict === "object") {
2283
+ io.warn(` ${conflict.level} ${conflict.id} ${conflict.field}: ours=${JSON.stringify(conflict.ours)} theirs=${JSON.stringify(conflict.theirs)}`);
2284
+ }
2285
+ }
2286
+ }
2287
+ throw new CliError(`Roadmap ${slug} conflicts with the server. Run \`nolto pull\` and resolve, then sync again.`, 4);
2288
+ }
2289
+ if (err.serverError === "base_revision_expired") {
2290
+ throw new CliError(`Roadmap ${slug} is based on an expired revision. Run \`nolto pull\` and reapply your changes.`, 4);
2291
+ }
2292
+ }
2293
+ throw err;
2383
2294
  }
2384
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2385
- let confirmed = false;
2295
+ }
2296
+ let gitLinks = null;
2297
+ if (io.exec && io.gitLinks !== false) {
2386
2298
  try {
2387
- const answer = await rl.question(`Rebind "${project.name}" to this repository? [y/N] `);
2388
- confirmed = answer.trim().toLowerCase() === "y";
2389
- } finally {
2390
- rl.close();
2299
+ const body = await collectGitLinks(args.root, io.exec);
2300
+ if (body && body.links.length > 0) {
2301
+ gitLinks = { linked: 0, existing: 0, skipped: 0 };
2302
+ for (let offset = 0; offset < body.links.length; offset += 500) {
2303
+ const response = await io.http.post(
2304
+ `/api/projects/${projectId}/git-links`,
2305
+ { links: body.links.slice(offset, offset + 500), repoIdentity }
2306
+ );
2307
+ if (!Number.isSafeInteger(response.linked) || response.linked < 0 || !Number.isSafeInteger(response.existing) || response.existing < 0 || !Number.isSafeInteger(response.skipped) || response.skipped < 0 || !Array.isArray(response.warnings) || response.warnings.some((warning) => typeof warning !== "string")) throw new Error("Invalid git links response");
2308
+ gitLinks = { linked: gitLinks.linked + response.linked, existing: gitLinks.existing + response.existing, skipped: gitLinks.skipped + response.skipped };
2309
+ for (const warning of response.warnings) io.warn(`git links: ${warning}`);
2310
+ }
2311
+ io.log(`git links: linked ${gitLinks.linked} (existing ${gitLinks.existing}, skipped ${gitLinks.skipped})`);
2312
+ }
2313
+ } catch (error) {
2314
+ gitLinks = null;
2315
+ io.warn(`git links: skipped \u2014 ${error instanceof Error ? error.message : String(error)}`);
2391
2316
  }
2392
- if (!confirmed) {
2393
- process.stdout.write("Aborted.\n");
2394
- return;
2317
+ }
2318
+ return { results, planAbsPaths: collectContainedPlanAbsPaths(roadmaps.map((entry) => entry.roadmap), args.root, io.warn), gitLinks };
2319
+ }
2320
+
2321
+ // src/commands/sync.ts
2322
+ function register3(program, deps) {
2323
+ 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) => {
2324
+ await runSyncCommand(deps, opts);
2325
+ });
2326
+ }
2327
+ async function runSyncCommand(deps, opts = {}) {
2328
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2329
+ const http = deps.http;
2330
+ const warn2 = (line2) => {
2331
+ process.stderr.write((line2.startsWith(" ") ? "" : "Warning: ") + line2 + "\n");
2332
+ };
2333
+ const response = await syncRepo(
2334
+ { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2335
+ {
2336
+ env: process.env,
2337
+ readFile: (p) => readFile8(p, "utf8"),
2338
+ realpath: (p) => realpath2(p),
2339
+ fileExists: (p) => existsSync4(p),
2340
+ repoIdentity: makeRepoIdentityResolver(deps),
2341
+ exec: promisify(execFile2),
2342
+ gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2343
+ http,
2344
+ log: (line2) => {
2345
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
2346
+ },
2347
+ warn: warn2
2395
2348
  }
2349
+ );
2350
+ try {
2351
+ const drifted = await checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs });
2352
+ for (const warning of drifted) warn2(warning);
2353
+ } catch {
2396
2354
  }
2397
- await deps.http.post(`/api/projects/${projectId}/repo-binding`, { repoIdentity });
2398
- if (mode2 === "json") {
2399
- printResult({ rebound: true, projectId, repoIdentity }, mode2);
2355
+ let registryAdded = false;
2356
+ if (isHomeDirectory(root)) {
2357
+ process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2358
+ `);
2400
2359
  } else {
2401
- process.stdout.write(`Rebound project ${projectId} to ${repoIdentity.kind}:${repoIdentity.value}.
2360
+ try {
2361
+ registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
2362
+ if (registryAdded) {
2363
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
2364
+ if (warning) process.stderr.write(warning + "\n");
2365
+ }
2366
+ } catch (err) {
2367
+ const message = err instanceof Error ? err.message : String(err);
2368
+ process.stderr.write(`Warning: could not update watch registry: ${message}
2402
2369
  `);
2403
- }
2404
- }
2405
- async function handleUnlink(projectBindingPath, mode2) {
2406
- const { readFile: readFile19, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
2407
- let existing = {};
2408
- try {
2409
- const raw = await readFile19(projectBindingPath, "utf8");
2410
- const parsed = JSON.parse(raw);
2411
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
2412
- throw new CliError(
2413
- `Cannot unlink ${projectBindingPath}: file contains valid JSON but is not a plain object (got ${Array.isArray(parsed) ? "array" : String(parsed)}). Remove or fix the file manually.`,
2414
- 2
2415
- );
2416
2370
  }
2417
- existing = parsed;
2418
- } catch (err) {
2419
- if (err instanceof CliError) throw err;
2420
- throw new CliError(`Cannot read ${projectBindingPath}: ${String(err)}`, 2);
2421
2371
  }
2422
- const { projectId: _removed, ...rest } = existing;
2423
- void _removed;
2424
- await writeFile12(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
2425
- await chmod2(projectBindingPath, 420);
2426
- if (mode2 === "json") {
2427
- printResult({ unlinked: true, projectBindingPath }, mode2);
2428
- } else {
2429
- process.stdout.write(`Removed projectId from ${projectBindingPath}.
2372
+ if (!opts.quiet && deps.output.mode === "json") {
2373
+ const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
2374
+ printResult({ ...publicResponse, registryAdded }, "json");
2375
+ } else if (!opts.quiet && registryAdded) {
2376
+ process.stdout.write(`watch registry: added ${root}
2430
2377
  `);
2431
2378
  }
2379
+ return response;
2432
2380
  }
2433
- async function performLink(deps, projectId, mode2, slug, yes = false) {
2434
- if (!UUID_RE2.test(projectId)) {
2435
- throw new CliError(
2436
- `Invalid project ID: "${projectId}". Must be a UUID (e.g. 00000000-0000-0000-0000-000000000001).`,
2437
- 2
2438
- );
2439
- }
2440
- const startDir = resolveStartDir(process.env, process.cwd());
2441
- const { root, foundGit } = findRepoRoot(startDir);
2442
- if (!foundGit) {
2443
- process.stderr.write(
2444
- `Warning: no .git directory found above ${startDir}. Writing nolto.json to current directory.
2445
- `
2446
- );
2381
+
2382
+ // src/roadmap-commands.ts
2383
+ var warn = (line2) => {
2384
+ process.stderr.write(line2 + "\n");
2385
+ };
2386
+ async function pull(deps, projectId, slug) {
2387
+ if (!await pullRoadmapCache({ env: process.env, http: deps.http, projectId, slug, log: () => void 0, warn })) {
2388
+ throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2447
2389
  }
2448
- const http = deps.http ?? createHttpClient({
2449
- baseUrl: deps.settings.baseUrl,
2450
- token: deps.settings.token,
2451
- version: deps.version
2452
- });
2453
- let projectName = path14.basename(root);
2454
- if (deps.settings.token != null) {
2455
- try {
2456
- const result = await http.get(
2457
- "/api/projects"
2458
- );
2459
- const projects = Array.isArray(result.projects) ? result.projects : [];
2460
- projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
2461
- if (!projects.some((p) => p.id === projectId)) {
2462
- process.stderr.write(
2463
- `Warning: project ${projectId} was not found in GET /api/projects.
2464
- Proceeding anyway \u2014 verify the ID is correct.
2465
- `
2466
- );
2467
- }
2468
- } catch {
2469
- process.stderr.write(
2470
- "Warning: could not verify project membership (offline or token issue). Proceeding anyway.\n"
2471
- );
2390
+ }
2391
+ async function selectRoadmap(deps, requestedSlug) {
2392
+ const context3 = await resolveRoadmapReadContext(deps);
2393
+ let slug = requestedSlug;
2394
+ if (slug === void 0) {
2395
+ let slugs = await listCachedSlugs(process.env, context3.projectId);
2396
+ if (slugs.length === 0) {
2397
+ await runPull(deps, { quiet: true });
2398
+ slugs = await listCachedSlugs(process.env, context3.projectId);
2472
2399
  }
2473
- }
2474
- if (deps.repoBinding?.error != null) {
2475
- process.stderr.write(
2476
- `Warning: existing nolto.json is invalid (${deps.repoBinding.error.message}). Overwriting it to repair.
2477
- `
2478
- );
2479
- }
2480
- await writeRepoBinding(root, projectId);
2481
- const writtenPath = path14.join(root, "nolto.json");
2482
- let repoAdded = false;
2483
- if (deps.settings.token == null) {
2484
- process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
2485
- } else {
2486
- const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2487
- const result = await ensureProjectRepo({
2488
- http,
2489
- projectId,
2490
- repoIdentity,
2491
- confirm: async (question) => {
2492
- if (yes) return true;
2493
- if (mode2 === "json") throw new CliError("Adding this repository requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
2494
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2495
- try {
2496
- const answer = (await rl.question(question)).trim().toLowerCase();
2497
- return answer === "" || answer === "y" || answer === "yes";
2498
- } finally {
2499
- rl.close();
2500
- }
2501
- },
2502
- log: (line2) => {
2503
- if (mode2 !== "json") process.stdout.write(line2 + "\n");
2504
- }
2505
- });
2506
- if (result === "declined") {
2507
- process.stdout.write("Skipped adding this repository. Run `nolto link --add` later; roadmap sync will fail until then.\n");
2508
- return;
2400
+ if (slugs.length !== 1) {
2401
+ 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);
2509
2402
  }
2510
- repoAdded = result === "added";
2511
- await ensureRoadmapCache({
2512
- env: process.env,
2513
- http,
2514
- projectId,
2515
- projectName,
2516
- repoRoot: root,
2517
- slug,
2518
- repoIdentity,
2519
- log: (line2) => {
2520
- if (mode2 !== "json") process.stdout.write(line2 + "\n");
2521
- }
2522
- });
2403
+ slug = slugs[0];
2523
2404
  }
2524
- let registryAdded = false;
2525
- if (isHomeDirectory(root)) {
2526
- process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
2527
- `);
2528
- } else {
2405
+ const paths = cachePaths(process.env, context3.projectId, slug);
2406
+ if (!existsSync5(paths.json)) await pull(deps, context3.projectId, slug);
2407
+ return { ...context3, slug, paths };
2408
+ }
2409
+ async function roadmapPath(deps, slug) {
2410
+ const { paths } = await selectRoadmap(deps, slug);
2411
+ printResult(path14.resolve(paths.json), deps.output.mode);
2412
+ }
2413
+ async function roadmapStatus(deps, slug, fresh = false) {
2414
+ const selected = await selectRoadmap(deps, slug);
2415
+ if (fresh) await pull(deps, selected.projectId, selected.slug);
2416
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2417
+ const { roadmap, meta } = entry;
2418
+ const stats = deriveTaskStats(roadmap);
2419
+ const tasks = roadmap.phases.flatMap((phase) => phase.tasks);
2420
+ const current = tasks.find((task) => task.id === meta?.currentTaskId && task.status === "in-progress");
2421
+ const blocked = tasks.filter((task) => task.status === "blocked");
2422
+ const age = meta ? (Date.now() - Date.parse(meta.pulledAt)) / 6e4 : NaN;
2423
+ if (age > 10) warn(`Warning: cache is ${Math.floor(age)} minutes old; run with --fresh or nolto roadmap pull`);
2424
+ if (deps.output.mode === "json") {
2425
+ printResult({ roadmap, stats, currentTaskId: current?.id ?? null, revision: meta?.revision ?? 0, pulledAt: meta?.pulledAt ?? null }, "json");
2426
+ return;
2427
+ }
2428
+ printResult([
2429
+ `${roadmap.project.name}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
2430
+ `Current: ${current ? `${current.id} \u2014 ${current.title}` : "none"}`,
2431
+ `Blocked: ${blocked.map((task) => `${task.id} \u2014 ${task.title}`).join(", ") || "none"}`,
2432
+ `Summary: ${roadmap.summary}`,
2433
+ `Revision: ${meta?.revision ?? 0} (pulled ${meta?.pulledAt ?? "unknown"})`
2434
+ ].join("\n"), "human");
2435
+ }
2436
+ async function roadmapValidate(deps, slug) {
2437
+ const { paths } = await selectRoadmap(deps, slug);
2438
+ let parsed;
2439
+ try {
2440
+ parsed = JSON.parse(await readFile9(paths.json, "utf8"));
2441
+ } catch {
2442
+ throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
2443
+ }
2444
+ const result = validateRoadmap(parsed);
2445
+ for (const warning of result.warnings) warn(`WARN ${warning}`);
2446
+ if (result.errors.length) {
2447
+ for (const error of result.errors) warn(`ERROR ${error}`);
2448
+ throw new CliError(`Roadmap validation failed: ${paths.json}`, 1);
2449
+ }
2450
+ printResult(deps.output.mode === "json" ? { path: paths.json, ...result } : `OK ${paths.json}`, deps.output.mode);
2451
+ }
2452
+ async function roadmapSummary(deps, slug, text) {
2453
+ const selected = await selectRoadmap(deps, slug);
2454
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2455
+ entry.roadmap.summary = text;
2456
+ const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
2457
+ try {
2458
+ await writeFile7(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
2459
+ await rename3(temp, selected.paths.json);
2460
+ } finally {
2461
+ await unlink3(temp).catch(() => void 0);
2462
+ }
2463
+ await runSyncCommand(deps, { slug: selected.slug });
2464
+ }
2465
+ async function roadmapAddIssue(deps, slug, taskId, key) {
2466
+ const selected = await selectRoadmap(deps, slug);
2467
+ const entry = await readCache(process.env, selected.projectId, selected.slug);
2468
+ const result = addIssueToRoadmapTask(entry.roadmap, taskId, key);
2469
+ if ("error" in result) throw new CliError(`${result.error} in ${selected.paths.json}`, 2);
2470
+ if (result.changed) {
2471
+ const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
2529
2472
  try {
2530
- registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
2531
- if (registryAdded) {
2532
- const warning = await staleWatchWarning(process.env, deps.version, process.kill);
2533
- if (warning) process.stderr.write(warning + "\n");
2534
- }
2535
- } catch (err) {
2536
- const message = err instanceof Error ? err.message : String(err);
2537
- process.stderr.write(`Warning: could not update watch registry: ${message}
2538
- `);
2473
+ await writeFile7(temp, serializeRoadmap(result.roadmap), { mode: 384 });
2474
+ await rename3(temp, selected.paths.json);
2475
+ } finally {
2476
+ await unlink3(temp).catch(() => void 0);
2539
2477
  }
2478
+ await runSyncCommand(deps, { slug: selected.slug, quiet: true });
2540
2479
  }
2541
- if (mode2 === "json") {
2542
- printResult({
2543
- linked: true,
2544
- projectId,
2545
- projectBindingPath: writtenPath,
2546
- registryAdded,
2547
- repoAdded
2548
- }, mode2);
2549
- } else {
2550
- process.stdout.write(
2551
- `Linked this repo to project ${projectId} (wrote ${writtenPath}).
2552
- Commit nolto.json to share the binding with your team.
2553
- `
2554
- );
2555
- if (registryAdded) {
2556
- process.stdout.write(`watch registry: added ${root}
2557
- `);
2480
+ return { file: selected.paths.json, taskId };
2481
+ }
2482
+ async function patchTask(args) {
2483
+ const { env, projectId, slug, taskId } = args;
2484
+ const entry = await readCache(env, projectId, slug);
2485
+ if (entry && isDirty(entry)) throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
2486
+ let response;
2487
+ try {
2488
+ response = await args.http.patch(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}`, args.body);
2489
+ } catch (error) {
2490
+ if (error instanceof CliError && error.status === 404) throw new CliError(`Task ${taskId} not found in ${slug}.`, 2);
2491
+ throw error;
2492
+ }
2493
+ const { errors } = validateRoadmap(response.roadmap);
2494
+ if (errors.length) throw new CliError(`Server roadmap "${slug}" failed validation: ${errors.join("; ")}`, 5);
2495
+ await writeCache(env, projectId, slug, response.roadmap, {
2496
+ repoIdentity: entry?.meta?.repoIdentity ?? null,
2497
+ revision: response.revision,
2498
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2499
+ currentTaskId: response.currentTaskId
2500
+ });
2501
+ return response;
2502
+ }
2503
+ async function roadmapTask(deps, taskId, slug, body) {
2504
+ const selected = await selectRoadmap(deps, slug);
2505
+ if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
2506
+ if (body.plan !== void 0) {
2507
+ const absolute = path14.resolve(selected.root, body.plan);
2508
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path14.resolve(selected.root) + path14.sep)) {
2509
+ throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
2558
2510
  }
2511
+ if (!existsSync5(absolute)) warn(`WARN plan file not found at ${absolute}`);
2559
2512
  }
2513
+ const response = await patchTask({ ...selected, env: process.env, http: deps.http, taskId, body });
2514
+ if (body.plan !== void 0) await runSyncCommand(deps, { slug: selected.slug, quiet: true });
2515
+ printResult(deps.output.mode === "json" ? response : body.plan !== void 0 ? `${taskId} plan -> ${body.plan}` : `${taskId} -> ${body.status}`, deps.output.mode);
2560
2516
  }
2561
- function register2(program, deps) {
2562
- const cmd = program.command("link [projectId]").description(
2563
- "Bind this repository to a Nolto project.\nWrites nolto.json at the repo root. Commit it to share the binding with your team.\n\nExamples:\n nolto link <uuid> Write / update nolto.json\n nolto link --show Show the current binding\n nolto link --rebind Rebind the project to this repository\n nolto link --list List project repositories\n nolto link --add Add this repository to the project\n nolto link --remove <identity-or-id> Remove a project repository\n nolto link --unlink Remove the projectId from nolto.json"
2564
- ).option("--slug <slug>", "Name this repository's roadmap").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").option("--show", "Show the current repo binding (path + projectId + source)").option("--rebind", "Rebind the project to this repository (owner only, once per 7 days)").option("-y, --yes", "Skip repository addition, rebind, and removal confirmation prompts").option("--unlink", "Remove the projectId key from nolto.json");
2565
- cmd.action(async (projectId) => {
2566
- const { output } = deps;
2567
- const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
2568
- const bindingError = deps.repoBinding?.error ?? null;
2569
- const mode2 = output.mode;
2570
- if (cmd.opts()["show"]) {
2571
- if (bindingError != null) {
2572
- throw invalidBindingError(projectBindingPath, bindingError);
2517
+ async function roadmapEvents(deps, slug, opts) {
2518
+ const selected = await selectRoadmap(deps, slug);
2519
+ const query = new URLSearchParams();
2520
+ if (opts.since !== void 0) query.set("since", opts.since);
2521
+ if (opts.limit !== void 0) query.set("limit", opts.limit);
2522
+ const response = await deps.http.get(`/api/projects/${selected.projectId}/roadmaps/${encodeURIComponent(selected.slug)}/events${query.size ? `?${query}` : ""}`);
2523
+ if (deps.output.mode === "json") printResult(response, "json");
2524
+ else for (const event of response.events) {
2525
+ printResult(`rev ${event.revision} ${event.createdAt} ${event.actor?.name ?? "system"} ${event.source} ${event.taskId} ${event.field}: ${event.from ?? "\u2014"} \u2192 ${event.to ?? "\u2014"}`, "human");
2526
+ }
2527
+ }
2528
+ async function roadmapMigrate(deps, yes = false) {
2529
+ const { root, projectId } = await resolveRoadmapReadContext(deps);
2530
+ const dir = path14.join(root, ".nolto", "roadmaps");
2531
+ let files;
2532
+ try {
2533
+ files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
2534
+ } catch (error) {
2535
+ if (error.code !== "ENOENT") throw error;
2536
+ files = [];
2537
+ }
2538
+ if (!files.length) {
2539
+ printResult("Nothing to migrate.", deps.output.mode);
2540
+ return;
2541
+ }
2542
+ const local = [];
2543
+ for (const file of files) {
2544
+ const slug = file.slice(0, -5);
2545
+ cachePaths(process.env, projectId, slug);
2546
+ const roadmap = await loadValidRoadmap(path14.join(dir, file), (p) => readFile9(p, "utf8"));
2547
+ roadmap.schemaVersion = 3;
2548
+ delete roadmap.updatedAt;
2549
+ delete roadmap.currentTaskId;
2550
+ local.push({ slug, roadmap });
2551
+ }
2552
+ const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2553
+ const results = [];
2554
+ for (const { slug, roadmap } of local) {
2555
+ let server;
2556
+ if (list.roadmaps.some((item) => item.slug === slug)) server = await deps.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
2557
+ const unchanged = server !== void 0 && serializeRoadmap(roadmap) === serializeRoadmap(server.roadmap);
2558
+ if (server && !unchanged && !yes) {
2559
+ if (!process.stdin.isTTY) throw new CliError(`Replacing ${slug} at server rev ${server.revision} requires confirmation; rerun with --yes.`, 2);
2560
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stderr });
2561
+ try {
2562
+ const answer = await rl.question(`Replace ${slug} on the server at rev ${server.revision} with the local file? [y/N] `);
2563
+ if (!/^y(es)?$/i.test(answer.trim())) throw new CliError(`Migration of ${slug} cancelled.`, 2);
2564
+ } finally {
2565
+ rl.close();
2573
2566
  }
2574
- await handleShow(deps, projectBindingPath, mode2);
2575
- return;
2576
2567
  }
2577
- if (cmd.opts()["unlink"]) {
2578
- if (projectBindingPath == null) {
2579
- throw new CliError("No nolto.json found in this directory tree. Nothing to unlink.", 2);
2568
+ const repoIdentity = (await readCache(process.env, projectId, slug))?.meta?.repoIdentity ?? null;
2569
+ let revision = server?.revision ?? 0;
2570
+ let saved = unchanged ? server.roadmap : roadmap;
2571
+ let currentTaskId = server?.currentTaskId;
2572
+ if (unchanged || !server) {
2573
+ await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2574
+ }
2575
+ if (!unchanged) {
2576
+ const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
2577
+ http: deps.http,
2578
+ readFile: (p) => readFile9(p, "utf8"),
2579
+ realpath: realpath3,
2580
+ fileExists: existsSync5,
2581
+ log: () => void 0,
2582
+ warn
2583
+ });
2584
+ revision = response.revision;
2585
+ saved = response.roadmap ?? roadmap;
2586
+ if (response.currentTaskId !== void 0) currentTaskId = response.currentTaskId;
2587
+ await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
2588
+ }
2589
+ const action = unchanged ? "unchanged" : server ? "replaced" : "created";
2590
+ results.push({ slug, action, revision });
2591
+ if (deps.output.mode !== "json") printResult(`${action} ${slug} (rev ${revision})`, "human");
2592
+ }
2593
+ const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
2594
+ let attributes = "";
2595
+ try {
2596
+ attributes = await readFile9(path14.join(root, ".gitattributes"), "utf8");
2597
+ } catch (error) {
2598
+ if (error.code !== "ENOENT") throw error;
2599
+ }
2600
+ if (attributes.split(/\r?\n/).some((line2) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line2))) {
2601
+ nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
2602
+ }
2603
+ nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
2604
+ const { added } = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
2605
+ if (added) {
2606
+ const warning = await staleWatchWarning(process.env, deps.version, process.kill);
2607
+ if (warning) process.stderr.write(warning + "\n");
2608
+ }
2609
+ printResult(deps.output.mode === "json" ? { results, nextSteps } : nextSteps.join("\n"), deps.output.mode);
2610
+ }
2611
+
2612
+ // src/commands/issue.ts
2613
+ var emptySettings = { types: [], statuses: [], categories: [] };
2614
+ function context(deps, command) {
2615
+ if (!deps.settings.token) throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2616
+ const globals = command.optsWithGlobals();
2617
+ const projectId = globals.project ?? deps.settings.defaultProjectId;
2618
+ if (!projectId) throw new CliError("No project. Pass --project <id> or run nolto link.", 2);
2619
+ return {
2620
+ projectId,
2621
+ root: `/api/projects/${encodeURIComponent(projectId)}`,
2622
+ mode: globals.json ? "json" : deps.output.mode
2623
+ };
2624
+ }
2625
+ async function bodyText(body, file) {
2626
+ if (body !== void 0 && file !== void 0) throw new CliError("Use either --body/-m or --body-file, not both.", 2);
2627
+ if (file === void 0) return body;
2628
+ try {
2629
+ if (file !== "-") return await readFile10(file, "utf8");
2630
+ const chunks = [];
2631
+ for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
2632
+ return Buffer.concat(chunks).toString("utf8");
2633
+ } catch (error) {
2634
+ throw new CliError(`Cannot read body from ${file}: ${String(error)}`, 2);
2635
+ }
2636
+ }
2637
+ async function writeInput(deps, root, flags, create) {
2638
+ const body = await bodyText(flags.body, flags.bodyFile);
2639
+ const settings = flags.type || flags.status || flags.category ? await deps.http.get(`${root}/issue-settings`) : emptySettings;
2640
+ const typeId = flags.type === void 0 ? void 0 : resolveMaster("type", flags.type, settings).id;
2641
+ const template = create && body === void 0 && typeId !== void 0 ? settings.types.find((type) => type.id === typeId)?.bodyTemplate : void 0;
2642
+ let assigneeId;
2643
+ if (flags.assignee !== void 0) {
2644
+ if (flags.assignee === "none") assigneeId = null;
2645
+ else if (flags.assignee === "me") assigneeId = (await deps.http.get("/api/me/profile")).profile.id;
2646
+ else if (isUuid(flags.assignee)) assigneeId = flags.assignee;
2647
+ else throw new CliError("--assignee must be me, none or a UUID.", 2);
2648
+ }
2649
+ let parentId;
2650
+ if (flags.parent === false) parentId = null;
2651
+ else if (flags.parent !== void 0) parentId = (await deps.http.get(`${root}/issues/${parseIssueRef(flags.parent)}`)).issue.id;
2652
+ if (typeof flags.due === "string" && (!/^\d{4}-\d{2}-\d{2}$/.test(flags.due) || !Number.isFinite(Date.parse(flags.due)) || new Date(flags.due).toISOString().slice(0, 10) !== flags.due)) {
2653
+ throw new CliError("--due must be a valid YYYY-MM-DD date.", 2);
2654
+ }
2655
+ if (flags.priority !== void 0 && !["high", "normal", "low"].includes(flags.priority)) throw new CliError("--priority must be high, normal or low.", 2);
2656
+ const input = {
2657
+ ...flags.subject !== void 0 ? { subject: flags.subject } : {},
2658
+ ...body !== void 0 ? { body } : template != null ? { body: template } : {},
2659
+ ...typeId !== void 0 ? { typeId } : {},
2660
+ ...flags.status !== void 0 ? { statusId: resolveMaster("status", flags.status, settings).id } : {},
2661
+ ...flags.priority !== void 0 ? { priority: flags.priority } : {},
2662
+ ...assigneeId !== void 0 ? { assigneeId } : {},
2663
+ ...flags.due !== void 0 ? { dueDate: flags.due === false ? null : flags.due } : {},
2664
+ ...flags.category !== void 0 ? { categoryIds: flags.category.map((name) => resolveMaster("category", name, settings).id) } : {},
2665
+ ...parentId !== void 0 ? { parentId } : {},
2666
+ ...flags.comment !== void 0 ? { comment: flags.comment } : {}
2667
+ };
2668
+ if (Object.keys(input).length === 0) throw new CliError("No changes. Pass a field option or --comment.", 2);
2669
+ return { input, fromTemplate: template != null };
2670
+ }
2671
+ async function attachRoadmap(deps, taskId, slug, key) {
2672
+ try {
2673
+ return await roadmapAddIssue(deps, slug, taskId, key);
2674
+ } catch (error) {
2675
+ throw new CliError(
2676
+ `Issue ${key} was created, but ${error instanceof Error ? error.message : String(error)}`,
2677
+ 2,
2678
+ "Do not create it again. Add the existing issue key to the task's issues in the `nolto roadmap path` cache, then run `nolto roadmap sync`."
2679
+ );
2680
+ }
2681
+ }
2682
+ function writeOptions(command, create) {
2683
+ if (create) command.requiredOption("--subject <text>", "Issue subject");
2684
+ else command.option("--subject <text>", "Issue subject");
2685
+ command.option("--body <text>", "Issue body").option("--body-file <path>", "Read body from file (- for stdin)").option("--type <name-or-id>", "Issue type").option("--status <name-or-id>", "Issue status").option("--priority <priority>", "high, normal or low").option("--assignee <assignee>", "me, none or UUID").option("--due <YYYY-MM-DD>", "Due date").option("--category <names...>", "Category names or UUIDs").option("--parent <ref>", "Parent issue key or number");
2686
+ if (create) command.option("--draft", "Create a draft visible only to you instead of an issue").option("--phase <task-id>", "Attach the created key to a roadmap task (cache) and sync").option("--roadmap <slug>", "Roadmap slug (with --phase; required with multiple cached roadmaps)");
2687
+ else command.option("--no-due", "Clear due date").option("--no-parent", "Clear parent").option("-m, --comment <text>", "Comment in the same update");
2688
+ return command;
2689
+ }
2690
+ function register4(program, deps) {
2691
+ const group = program.command("issue").description("List, view and manage project issues.").addHelpText("after", `
2692
+ All commands accept global \`--project <id>\`, \`--json\`, \`--token <value>\` and \`--base-url <url>\`.
2693
+ Project priority: flag \u2192 NOLTO_PROJECT \u2192 nearest ancestor nolto.json \u2192 config defaultProjectId. Git is not required. An invalid nolto.json remains an error.
2694
+
2695
+ nolto issue create --draft --subject "\u2026"
2696
+ nolto issue drafts
2697
+ nolto issue publish <draft-id>
2698
+
2699
+ | Exit | Meaning |
2700
+ |---|---|
2701
+ | 0 | Success |
2702
+ | 2 | Invalid input, recognized API 404, HTTP 422 (details shown), or roadmap cache/sync failure after creation |
2703
+ | 3 | HTTP 401/403; token_scope/token_project includes a token settings hint |
2704
+ | 4 | HTTP 402/429 (quota/rate limit). API token writes: 60/minute. On 429, wait Retry-After seconds before retrying. |
2705
+ | 5 | Network/generic HTTP errors, including a 404 without an API error string |
2706
+ `);
2707
+ group.command("list").description("List or search issues.").option("--status <names...>", "Status names or UUIDs").option("--assignee <assignee>", "me, none or UUID").option("--closed <mode>", "exclude, include or only").option("--q <text>", "Search text").option("--sort <field>", "updated, due, priority, number, created, assignee, status, type or subject").option("--order <order>", "asc or desc").option("--page <number>", "Page number").option("--type <name-or-id>", "Issue type").option("--priority <priority>", "high, normal or low").option("--category <name-or-id>", "Category").option("--parent <ref>", "Parent issue or none").action(async (flags, command) => {
2708
+ const ctx = context(deps, command);
2709
+ const settings = flags.status || flags.type || flags.category ? await deps.http.get(`${ctx.root}/issue-settings`) : emptySettings;
2710
+ const query = buildListQuery(flags, settings).toString();
2711
+ const result = await deps.http.get(`${ctx.root}/issues${query ? `?${query}` : ""}`);
2712
+ printResult(ctx.mode === "json" ? result : formatIssueList(result.issues, result), ctx.mode);
2713
+ });
2714
+ group.command("view <ref>").description("Show issue details and comments.").action(async (ref, _flags, command) => {
2715
+ const ctx = context(deps, command);
2716
+ const result = await deps.http.get(`${ctx.root}/issues/${parseIssueRef(ref)}`);
2717
+ printResult(ctx.mode === "json" ? result : formatIssueView(result), ctx.mode);
2718
+ });
2719
+ writeOptions(group.command("create").description("Create an issue."), true).action(async (flags, command) => {
2720
+ const ctx = context(deps, command);
2721
+ if (flags.draft && (flags.phase !== void 0 || flags.roadmap !== void 0)) throw new CliError("--phase and --roadmap cannot be used with --draft. Publish the draft first.", 2);
2722
+ if (flags.roadmap !== void 0 && flags.phase === void 0) throw new CliError("--roadmap requires --phase.", 2);
2723
+ const { input, fromTemplate } = await writeInput(deps, ctx.root, flags, true);
2724
+ if (flags.draft) {
2725
+ const result2 = await deps.http.post(`${ctx.root}/issue-drafts`, input);
2726
+ printResult(ctx.mode === "json" ? result2 : `draft ${result2.draft.id} created
2727
+ ${draftUrl(deps.settings.baseUrl, ctx.projectId, result2.draft.id)}`, ctx.mode);
2728
+ return;
2729
+ }
2730
+ const result = await deps.http.post(`${ctx.root}/issues`, input);
2731
+ const roadmap = flags.phase === void 0 ? void 0 : await attachRoadmap(deps, flags.phase, flags.roadmap, result.issue.key);
2732
+ printResult(ctx.mode === "json" ? { ...result, ...roadmap ? { roadmap } : {} } : `${result.issue.key} created
2733
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${fromTemplate ? "\nbody: from template" : ""}`, ctx.mode);
2734
+ });
2735
+ group.command("drafts").description("List your issue drafts (visible only to you).").action(async (_flags, command) => {
2736
+ const ctx = context(deps, command);
2737
+ const result = await deps.http.get(`${ctx.root}/issue-drafts`);
2738
+ printResult(ctx.mode === "json" ? result : formatDraftList(result), ctx.mode);
2739
+ });
2740
+ group.command("publish <draft-id>").description("Publish a draft as an issue.").action(async (id, _flags, command) => {
2741
+ const ctx = context(deps, command);
2742
+ if (!isUuid(id)) throw new CliError("<draft-id> must be a UUID. Run `nolto issue drafts` to list drafts.", 2);
2743
+ const result = await deps.http.post(`${ctx.root}/issue-drafts/${id}/publish`, void 0);
2744
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} published
2745
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}`, ctx.mode);
2746
+ });
2747
+ writeOptions(group.command("update <ref>").description("Update issue fields."), false).action(async (ref, flags, command) => {
2748
+ const ctx = context(deps, command);
2749
+ const number = parseIssueRef(ref);
2750
+ const { input } = await writeInput(deps, ctx.root, flags, false);
2751
+ const result = await deps.http.patch(`${ctx.root}/issues/${number}`, input);
2752
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} updated
2753
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
2754
+ });
2755
+ group.command("comment <ref>").description("Post a comment.").option("-m, --comment <text>", "Comment text").option("--body-file <path>", "Read comment from file (- for stdin)").action(async (ref, flags, command) => {
2756
+ const ctx = context(deps, command);
2757
+ const number = parseIssueRef(ref);
2758
+ const body = await bodyText(flags.comment, flags.bodyFile);
2759
+ if (!body?.trim()) throw new CliError("A comment is required. Use -m or --body-file.", 2);
2760
+ const issue = ctx.mode === "human" ? (await deps.http.get(`${ctx.root}/issues/${number}`)).issue : void 0;
2761
+ const result = await deps.http.post(`${ctx.root}/issues/${number}/comments`, { body });
2762
+ printResult(ctx.mode === "json" ? result : `${issue.key} commented
2763
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
2764
+ });
2765
+ group.command("close <ref>").description("Move an issue to a closed status.").option("--status <name-or-id>", "Closed status (defaults to first by sort order)").option("-m, --comment <text>", "Comment in the same update").action(async (ref, flags, command) => {
2766
+ const ctx = context(deps, command);
2767
+ const number = parseIssueRef(ref);
2768
+ const settings = await deps.http.get(`${ctx.root}/issue-settings`);
2769
+ const status = pickClosedStatus(settings, flags.status);
2770
+ const result = await deps.http.patch(`${ctx.root}/issues/${number}`, { statusId: status.id, ...flags.comment !== void 0 ? { comment: flags.comment } : {} });
2771
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} closed
2772
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
2773
+ });
2774
+ }
2775
+
2776
+ // src/memory-import.ts
2777
+ import { readFile as readFile12, readdir as readdir5 } from "fs/promises";
2778
+ import path16 from "path";
2779
+
2780
+ // src/memory-format.ts
2781
+ var oneLine = (value) => value.replace(/[\r\n\u0085\u2028\u2029]/g, " ");
2782
+ var shellArg = (value) => /^[A-Za-z0-9._/-]+$/.test(value) ? value : JSON.stringify(value);
2783
+ var memoryClient = (via) => via?.client || via?.tokenName || "Web";
2784
+ function parseMemory(text, importing = false) {
2785
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
2786
+ if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
2787
+ if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
2788
+ const end = lines.indexOf("---");
2789
+ if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
2790
+ const fields = {};
2791
+ let metadata = false;
2792
+ for (const line2 of lines.slice(0, end)) {
2793
+ const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
2794
+ if (!match) continue;
2795
+ const indent = match[1], key = match[2], raw = match[3];
2796
+ if (!indent) metadata = key === "metadata";
2797
+ if (indent && !(importing && metadata && key === "type")) continue;
2798
+ let value = raw.trim();
2799
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2800
+ if (["name", "description", "type", "scope", "branch", "revision"].includes(key)) fields[key] = value;
2801
+ }
2802
+ const body = lines.slice(end + 1);
2803
+ if (body[0] === "") body.shift();
2804
+ return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
2805
+ }
2806
+ function formatMemory(entry) {
2807
+ const value = (s) => {
2808
+ const safe = oneLine(s);
2809
+ return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
2810
+ };
2811
+ return [
2812
+ "<!-- nolto memory \u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u3002\u7DE8\u96C6\u3057\u306A\u3044\u3002\u5909\u66F4\u306F\u4E0B\u66F8\u304D\u306B\u30B3\u30D4\u30FC\u3057\u3066 nolto memory put -->",
2813
+ "---",
2814
+ `name: ${entry.name}`,
2815
+ `description: ${value(entry.description)}`,
2816
+ ...entry.type == null ? [] : [`type: ${entry.type}`],
2817
+ `scope: ${entry.scope}`,
2818
+ ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
2819
+ `revision: ${entry.revision}`,
2820
+ `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
2821
+ "---",
2822
+ "",
2823
+ entry.body
2824
+ ].join("\n");
2825
+ }
2826
+ function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
2827
+ if (scope !== "project" && scope !== "user" && scope !== "branch") {
2828
+ throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
2829
+ }
2830
+ return scope;
2831
+ }
2832
+ var count = (n) => n.toLocaleString("en-US");
2833
+ var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
2834
+ function validateDraft(draft) {
2835
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
2836
+ throw invalidInput(draft.name ? `name \u306E\u5F62\u304C\u4E0D\u6B63\u3067\u3059(${oneLine(draft.name)})\u3002` : "name \u304C\u3042\u308A\u307E\u305B\u3093\u3002", "name \u306F\u82F1\u5C0F\u6587\u5B57\u30FB\u6570\u5B57\u30FB\u30CF\u30A4\u30D5\u30F3\u3067 64 \u5B57\u307E\u3067\u3001\u5148\u982D\u306F\u82F1\u6570\u5B57");
2837
+ }
2838
+ const description = draft.description.trim();
2839
+ if (/[\r\n\u0085\u2028\u2029]/.test(draft.description)) throw invalidInput("description \u306B\u6539\u884C\u304C\u3042\u308A\u307E\u3059\u3002", "description \u306F 1 \u884C\u306B\u3059\u308B");
2840
+ if (!description) throw invalidInput("description \u304C\u3042\u308A\u307E\u305B\u3093\u3002", "\u7D22\u5F15\u3067\u8AAD\u3080\u304B\u3069\u3046\u304B\u3092\u6C7A\u3081\u3089\u308C\u308B 1 \u884C\u3092\u66F8\u304F");
2841
+ if (description.length > 200) throw invalidInput(`description \u304C 200 \u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059(${count(description.length)} \u5B57)\u3002`, "\u7D22\u5F15\u3067\u8AAD\u3080\u304B\u3069\u3046\u304B\u3092\u6C7A\u3081\u3089\u308C\u308B 1 \u884C\u306B\u7E2E\u3081\u308B");
2842
+ if (draft.body.length > 1e4) throw invalidInput(`\u672C\u6587\u304C 10,000 \u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059(${count(draft.body.length)} \u5B57)\u3002`, "\u30A8\u30F3\u30C8\u30EA\u3092\u5206\u3051\u308B\u304B\u3001\u8981\u70B9\u306B\u7D5E\u308B");
2843
+ if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
2844
+ throw invalidInput(`type \u304C\u4E0D\u6B63\u3067\u3059(${oneLine(draft.type)})\u3002`, "type \u306F user / feedback / project / reference \u306E\u3069\u308C\u304B\u3002\u4E0D\u8981\u306A\u3089\u884C\u3054\u3068\u6D88\u3059");
2845
+ }
2846
+ }
2847
+ function parseRevision(value) {
2848
+ const revision = Number(value);
2849
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(revision) || revision < 1) throw new CliError("revision \u306F\u6B63\u306E\u6574\u6570\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002", 2);
2850
+ return revision;
2851
+ }
2852
+ function detectMemoryClient(env) {
2853
+ const agent = env.NOLTO_AGENT?.trim();
2854
+ if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
2855
+ if (env.CLAUDECODE === "1") return "Claude Code";
2856
+ if (env.GEMINI_CLI === "1") return "Gemini CLI";
2857
+ if (env.CODEX_THREAD_ID) return "Codex";
2858
+ return "CLI";
2859
+ }
2860
+
2861
+ // src/memory-cache.ts
2862
+ import { mkdir as mkdir7, readFile as readFile11, rename as rename4, rm as rm2, unlink as unlink4, writeFile as writeFile8 } from "fs/promises";
2863
+ import { randomUUID as randomUUID6 } from "crypto";
2864
+ import path15 from "path";
2865
+ function memoryDir(configPath, project) {
2866
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(project)) throw new CliError("Invalid project id.", 2);
2867
+ return path15.join(path15.dirname(configPath), "projects", project, "memory");
2868
+ }
2869
+ function memoryEntryPath(entry) {
2870
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(entry.name)) throw new CliError("Invalid memory name in cache.", 2);
2871
+ if (entry.scope === "project" || entry.scope === "user") return `${entry.scope}/${entry.name}.md`;
2872
+ if (entry.scope !== "branch" || !entry.repoIdentity || !entry.branch) throw new CliError("Invalid memory scope in cache.", 2);
2873
+ if (entry.branch.split("/").some((p) => !p || p === "." || p === ".." || p.includes("\\") || /[\x00-\x1f\x7f]/.test(p) || Buffer.byteLength(p) > 200)) throw new CliError("Unsafe memory branch path.", 2);
2874
+ const repoDir = encodeURIComponent(entry.repoIdentity);
2875
+ if (Buffer.byteLength(repoDir) > 200) throw new CliError("Unsafe memory repo path.", 2);
2876
+ return `branch/${repoDir}/${entry.branch}/${entry.name}.md`;
2877
+ }
2878
+ function storableMemoryEntry(entry) {
2879
+ try {
2880
+ memoryEntryPath(entry);
2881
+ return true;
2882
+ } catch {
2883
+ return false;
2884
+ }
2885
+ }
2886
+ async function atomicMemoryFile(file, content) {
2887
+ await mkdir7(path15.dirname(file), { recursive: true, mode: 448 });
2888
+ const temp = `${file}.tmp-${randomUUID6()}`;
2889
+ try {
2890
+ await writeFile8(temp, content, { mode: 292 });
2891
+ await unlink4(file).catch((error) => {
2892
+ if (error.code !== "ENOENT") throw error;
2893
+ });
2894
+ await rename4(temp, file);
2895
+ } finally {
2896
+ await unlink4(temp).catch(() => void 0);
2897
+ }
2898
+ }
2899
+ async function readMemoryCache(dir, project) {
2900
+ const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
2901
+ try {
2902
+ const state = JSON.parse(await readFile11(path15.join(dir, ".entries.json"), "utf8"));
2903
+ if (!Array.isArray(state.entries) || typeof state.scope !== "string" || typeof state.projectName !== "string") throw new Error("Invalid state");
2904
+ if (state.entries.some((e) => e == null || typeof e !== "object" || typeof e.id !== "string" || typeof e.name !== "string")) throw new Error("Invalid entry");
2905
+ let meta = empty.meta;
2906
+ try {
2907
+ meta = JSON.parse(await readFile11(path15.join(dir, ".meta.json"), "utf8"));
2908
+ } catch (error) {
2909
+ if (error.code !== "ENOENT") throw error;
2910
+ }
2911
+ if (!Number.isSafeInteger(meta.cursor) || meta.cursor < 0 || typeof meta.pulledAt !== "string") throw new Error("Invalid cursor");
2912
+ return { state, meta };
2913
+ } catch (error) {
2914
+ if (error.code === "ENOENT") return empty;
2915
+ throw new CliError(`\u30E1\u30E2\u30EA\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u8AAD\u3081\u307E\u305B\u3093: ${String(error)}`, 2, "nolto memory pull");
2916
+ }
2917
+ }
2918
+ function mergeMemoryEntries(entries, updates) {
2919
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
2920
+ for (const entry of updates) {
2921
+ const old = byId.get(entry.id);
2922
+ if (!old || old.revision <= entry.revision) byId.set(entry.id, entry);
2923
+ }
2924
+ return [...byId.values()];
2925
+ }
2926
+ async function saveMemoryCache(dir, cache, previous, index, reset = false) {
2927
+ const unsafe = cache.state.entries.filter((e) => !storableMemoryEntry(e));
2928
+ if (reset) await rm2(dir, { recursive: true, force: true });
2929
+ const livePaths = new Set(cache.state.entries.filter((e) => !e.deleted && storableMemoryEntry(e)).map(memoryEntryPath));
2930
+ for (const entry of previous.filter(storableMemoryEntry)) {
2931
+ const relative = memoryEntryPath(entry);
2932
+ if (!livePaths.has(relative)) await rm2(path15.join(dir, relative), { force: true });
2933
+ }
2934
+ for (const entry of cache.state.entries) {
2935
+ if (!entry.deleted && storableMemoryEntry(entry)) await atomicMemoryFile(path15.join(dir, memoryEntryPath(entry)), formatMemory(entry));
2936
+ }
2937
+ await atomicMemoryFile(path15.join(dir, ".entries.json"), JSON.stringify(cache.state) + "\n");
2938
+ await atomicMemoryFile(path15.join(dir, "MEMORY.md"), index);
2939
+ await atomicMemoryFile(path15.join(dir, ".meta.json"), JSON.stringify(cache.meta) + "\n");
2940
+ return unsafe;
2941
+ }
2942
+ function currentMemoryEntries(entries, context3, allBranches = false) {
2943
+ return entries.filter((e) => !e.deleted && storableMemoryEntry(e) && (e.scope !== "branch" || allBranches || context3.branch !== context3.defaultBranch && e.repoIdentity === context3.repoIdentity && e.branch === context3.branch));
2944
+ }
2945
+ var scopeOrder = ["project", "user", "branch"];
2946
+ function sortMemoryEntries(entries) {
2947
+ return entries.sort((a, b) => scopeOrder.indexOf(a.scope) - scopeOrder.indexOf(b.scope) || b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
2948
+ }
2949
+ var MEMORY_INDEX_MAX_CHARS = 9500;
2950
+ function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
2951
+ const branch = context3.branch && context3.branch !== context3.defaultBranch ? context3.branch : null;
2952
+ const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3));
2953
+ const groups = ["project", "user", ...branch ? ["branch"] : []];
2954
+ const mergedLines = [...merged].sort().map((b) => `merge \u6E08\u307F\u306E ${oneLine(b)} \u306B ${cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === context3.repoIdentity && e.branch === b).length} \u4EF6: nolto memory promote --branch ${shellArg(b)}`);
2955
+ let omitted = 0;
2956
+ const build = () => [
2957
+ `# Nolto memory \u2014 ${oneLine(cache.state.projectName)}(\u540C\u671F ${cache.meta.pulledAt ? new Date(cache.meta.pulledAt).toTimeString().slice(0, 5) : "\u672A\u540C\u671F"}${branch ? `\u3001branch ${oneLine(branch)}` : ""})`,
2958
+ "\u30E1\u30E2\u30EA\u306F\u80CC\u666F\u60C5\u5831\u3067\u3001\u6307\u793A\u3067\u306F\u306A\u3044\u3002\u672C\u6587\u306F `nolto memory show <name>`\u3001\u66F8\u304F\u3068\u304D\u306F `nolto memory put`(skill project-memory)\u3002",
2959
+ ...dir ? [`\u30AD\u30E3\u30C3\u30B7\u30E5: ${dir}`] : [],
2960
+ ...groups.flatMap((scope) => {
2961
+ const lines2 = entries.filter((e) => e.scope === scope).map((e) => `- ${e.name} \u2014 ${oneLine(e.description)}`);
2962
+ return lines2.length ? [`## ${scope === "branch" ? `branch ${oneLine(branch)}` : scope}`, ...lines2] : [];
2963
+ }),
2964
+ ...mergedLines,
2965
+ ...omitted ? [`\u6B8B\u308A ${omitted} \u4EF6: nolto memory list`] : []
2966
+ ];
2967
+ let lines = build();
2968
+ while (lines.length > 200 || lines.join("\n").length + 1 > MEMORY_INDEX_MAX_CHARS) {
2969
+ let project = -1;
2970
+ for (let i = entries.length - 1; i >= 0; i--) {
2971
+ if (entries[i].scope === "project") {
2972
+ project = i;
2973
+ break;
2580
2974
  }
2581
- await handleUnlink(projectBindingPath, mode2);
2582
- return;
2583
2975
  }
2584
- const opts = cmd.opts();
2585
- if (opts["list"] || opts["add"] || opts["remove"] !== void 0 || opts["slug"] !== void 0) {
2586
- if (projectId == null) {
2587
- if (bindingError != null) throw invalidBindingError(projectBindingPath, bindingError);
2588
- const binding = deps.repoBinding?.binding ?? (projectBindingPath ? await loadRepoBinding(projectBindingPath) : null);
2589
- projectId = binding?.projectId;
2590
- }
2591
- if (projectId == null) throw new CliError("No project binding. Run `nolto link <projectId>` first.", 2);
2592
- if (!UUID_RE2.test(projectId)) throw new CliError(`Invalid project ID: "${projectId}". Must be a UUID.`, 2);
2593
- if (opts["add"]) {
2594
- const root = findRepoRoot(resolveStartDir(process.env, process.cwd())).root;
2595
- const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2596
- const repo = await deps.http.post(`/api/projects/${projectId}/repos`, {
2597
- repoIdentity,
2598
- ...opts["label"] !== void 0 ? { label: opts["label"] } : {}
2599
- });
2600
- printResult(mode2 === "json" ? { added: true, projectId, repo } : `Added ${repoIdentity.kind}:${repoIdentity.value} to project ${projectId}.`, mode2);
2601
- return;
2602
- }
2603
- if (opts["list"] || opts["remove"] !== void 0) {
2604
- const { repos } = await deps.http.get(`/api/projects/${projectId}`);
2605
- if (opts["list"]) {
2606
- if (mode2 === "json") printResult({ repos }, mode2);
2607
- else for (const repo2 of repos) printResult(`${repo2.identity}${repo2.label ? ` (${repo2.label})` : ""} ${repo2.boundAt} ${repo2.id}`, mode2);
2608
- return;
2609
- }
2610
- const input = opts["remove"];
2611
- const identity = /^(remote|local):/.test(input) ? input : `remote:${input}`;
2612
- const repo = repos.find((row) => row.id === input || row.identity === identity);
2613
- if (!repo) throw new CliError(`Repository ${input} is not bound to this project.`, 2);
2614
- if (!opts["yes"]) {
2615
- if (mode2 === "json") throw new CliError("--remove requires confirmation. Pass --yes to skip the prompt in --json mode.", 2);
2616
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2617
- let confirmed = false;
2618
- try {
2619
- const answer = await rl.question(`Remove "${repo.identity}" from project ${projectId}? [y/N] `);
2620
- confirmed = answer.trim().toLowerCase() === "y";
2621
- } finally {
2622
- rl.close();
2623
- }
2624
- if (!confirmed) {
2625
- process.stdout.write("Aborted.\n");
2626
- return;
2627
- }
2976
+ if (entries.length) {
2977
+ entries.splice(project < 0 ? entries.length - 1 : project, 1);
2978
+ omitted++;
2979
+ } else if (mergedLines.length) {
2980
+ mergedLines.pop();
2981
+ omitted++;
2982
+ } else break;
2983
+ lines = build();
2984
+ }
2985
+ return lines.join("\n") + "\n";
2986
+ }
2987
+
2988
+ // src/memory-git.ts
2989
+ import { execFile as execFile3 } from "child_process";
2990
+ import { promisify as promisify2 } from "util";
2991
+ var runMemoryGit = async (args, root) => (await promisify2(execFile3)("git", args, { cwd: root, timeout: 5e3 })).stdout.trim();
2992
+ async function memoryGitContext(root, deps) {
2993
+ const git = deps.memoryGit ?? runMemoryGit;
2994
+ const result = { repoIdentity: null, branch: null, defaultBranch: null };
2995
+ try {
2996
+ await git(["rev-parse", "--show-toplevel"], root);
2997
+ const identity = await makeRepoIdentityResolver(deps)(root);
2998
+ result.repoIdentity = `${identity.kind}:${identity.value}`;
2999
+ result.branch = await git(["symbolic-ref", "--quiet", "--short", "HEAD"], root).catch(() => null);
3000
+ const remote = await git(["symbolic-ref", "refs/remotes/origin/HEAD"], root).catch(() => "");
3001
+ if (remote.startsWith("refs/remotes/origin/")) result.defaultBranch = remote.slice("refs/remotes/origin/".length);
3002
+ else {
3003
+ for (const branch of ["main", "master"]) {
3004
+ try {
3005
+ await git(["show-ref", "--verify", `refs/heads/${branch}`], root);
3006
+ result.defaultBranch = branch;
3007
+ break;
3008
+ } catch {
2628
3009
  }
2629
- await deps.http.delete(`/api/projects/${projectId}/repos/${repo.id}`);
2630
- printResult(mode2 === "json" ? { removed: true, projectId, repoId: repo.id } : `Removed ${repo.identity} from project ${projectId}.`, mode2);
2631
- return;
2632
3010
  }
2633
3011
  }
2634
- if (cmd.opts()["rebind"]) {
2635
- const boundProjectId = deps.repoBinding?.binding?.projectId;
2636
- const effectiveProjectId = projectId ?? boundProjectId;
2637
- if (effectiveProjectId == null) {
2638
- throw new CliError("No project binding. Run `nolto link <projectId>` first.", 2);
2639
- }
2640
- const startDir = resolveStartDir(process.env, process.cwd());
2641
- const root = findRepoRoot(startDir).root;
2642
- await handleRebind(deps, effectiveProjectId, root, mode2, cmd.opts()["yes"] === true);
2643
- return;
3012
+ } catch {
3013
+ }
3014
+ return result;
3015
+ }
3016
+ async function mergedMemoryBranches(branches, context3, root, git, mine = /* @__PURE__ */ new Set()) {
3017
+ const merged = /* @__PURE__ */ new Set();
3018
+ if (!context3.defaultBranch || !context3.repoIdentity) return merged;
3019
+ const hasRef = async (ref) => {
3020
+ try {
3021
+ await git(["show-ref", "--verify", "--quiet", ref], root);
3022
+ return true;
3023
+ } catch (error) {
3024
+ if (error.code === 1) return false;
3025
+ throw error;
2644
3026
  }
2645
- if (projectId == null || projectId.trim().length === 0) {
2646
- if (bindingError != null) {
2647
- throw invalidBindingError(projectBindingPath, bindingError);
2648
- }
2649
- throw new CliError(
2650
- "Usage: nolto link <projectId> (provide a UUID)\nOr use --show to view the current binding, --rebind to rebind it, --unlink to remove it.",
2651
- 2
2652
- );
3027
+ };
3028
+ let checkedOut, target, targetTip;
3029
+ try {
3030
+ checkedOut = new Set((await git(["worktree", "list", "--porcelain"], root)).split("\n").filter((l) => l.startsWith("branch refs/heads/")).map((l) => l.slice("branch refs/heads/".length)));
3031
+ target = await hasRef(`refs/heads/${context3.defaultBranch}`) ? `refs/heads/${context3.defaultBranch}` : `refs/remotes/origin/${context3.defaultBranch}`;
3032
+ targetTip = await git(["rev-parse", target], root);
3033
+ } catch {
3034
+ return merged;
3035
+ }
3036
+ for (const branch of branches) {
3037
+ if (branch === context3.defaultBranch || branch === context3.branch || checkedOut.has(branch)) continue;
3038
+ try {
3039
+ const local = `refs/heads/${branch}`;
3040
+ if (await hasRef(local)) {
3041
+ if (await git(["rev-parse", local], root) === targetTip) continue;
3042
+ await git(["merge-base", "--is-ancestor", local, target], root);
3043
+ merged.add(branch);
3044
+ } else if (mine.has(branch) && !await hasRef(`refs/remotes/origin/${branch}`)) merged.add(branch);
3045
+ } catch {
2653
3046
  }
2654
- await performLink(deps, projectId, mode2, opts["slug"], opts["yes"] === true);
3047
+ }
3048
+ return merged;
3049
+ }
3050
+
3051
+ // src/memory-import.ts
3052
+ function aiHeading(response, requestedName) {
3053
+ const { entry, ai } = response;
3054
+ if (!ai || ai.action !== "merge" && ai.action !== "replace") return null;
3055
+ if (requestedName !== void 0 && requestedName !== entry.name) {
3056
+ return `\u65B0\u898F\u306E ${requestedName} \u306F\u4F5C\u3089\u305A\u3001AI \u304C ${entry.scope}/${entry.name} ${ai.action === "merge" ? "\u306B\u7D71\u5408\u3057\u307E\u3057\u305F" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88\u3057\u307E\u3057\u305F"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
3057
+ }
3058
+ return `AI \u304C\u6574\u7406: ${entry.scope}/${entry.name} ${ai.action === "merge" ? "\u306B\u7D71\u5408" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
3059
+ }
3060
+ async function createMemoryContext(opts, recover = false) {
3061
+ const { projectId: project, root, git } = opts;
3062
+ const dir = memoryDir(opts.configPath, project);
3063
+ const cache = await readMemoryCache(dir, project).catch((error) => {
3064
+ if (!recover) throw error;
3065
+ return { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
2655
3066
  });
3067
+ return { project, dir, root, git, cache, api: `/api/projects/${project}/memory` };
2656
3068
  }
2657
- function invalidBindingError(projectBindingPath, error) {
2658
- return new CliError(
2659
- `Invalid nolto.json at ${projectBindingPath ?? "unknown path"}: ${error.message}. Repair it with \`nolto link <projectId>\` or \`nolto init\`.`,
2660
- 2
2661
- );
3069
+ async function memoryIndexText(ctx, deps) {
3070
+ const entries = ctx.cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === ctx.git.repoIdentity);
3071
+ const branches = [...new Set(entries.map((e) => e.branch))];
3072
+ const userId = ctx.cache.state.userId;
3073
+ const mine = new Set(userId ? entries.filter((e) => e.updatedBy?.id === userId).map((e) => e.branch) : []);
3074
+ return memoryIndex(ctx.cache, ctx.git, await mergedMemoryBranches(branches, ctx.git, ctx.root, deps.memoryGit ?? runMemoryGit, mine), ctx.dir);
3075
+ }
3076
+ var cacheWarning = "Warning: \u30B5\u30FC\u30D0\u30FC\u3078\u306E\u66F8\u304D\u8FBC\u307F\u306F\u6210\u529F\u3057\u307E\u3057\u305F\u304C\u3001\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002nolto memory pull \u3067\u540C\u671F\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n";
3077
+ async function updateCache(ctx, deps, entries, quiet = false) {
3078
+ const previous = ctx.cache.state.entries;
3079
+ try {
3080
+ ctx.cache.state.entries = mergeMemoryEntries(previous, entries);
3081
+ await saveMemoryCache(ctx.dir, ctx.cache, previous, await memoryIndexText(ctx, deps));
3082
+ return true;
3083
+ } catch {
3084
+ if (!quiet) process.stderr.write(cacheWarning);
3085
+ return false;
3086
+ }
3087
+ }
3088
+ function writtenEntries(ctx, response) {
3089
+ const tombstones = (response.affected ?? []).flatMap((a) => {
3090
+ const cached = a.deleted && a.entryId !== response.entry.id ? ctx.cache.state.entries.find((e) => e.id === a.entryId) : void 0;
3091
+ return cached ? [{ ...cached, deleted: true, revision: a.toRevision }] : [];
3092
+ });
3093
+ return [response.entry, ...tombstones];
3094
+ }
3095
+ async function scanMemoryDir(dir) {
3096
+ const ok = [], invalid = [];
3097
+ const seen = /* @__PURE__ */ new Map();
3098
+ for (const file of (await readdir5(dir, { withFileTypes: true })).filter((f) => f.isFile() && f.name.endsWith(".md") && f.name !== "MEMORY.md").sort((a, b) => a.name.localeCompare(b.name))) {
3099
+ let original = file.name.slice(0, -3), name = original;
3100
+ try {
3101
+ const draft = parseMemory(await readFile12(path16.join(dir, file.name), "utf8"), true);
3102
+ original = draft.name || original;
3103
+ name = original.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+/, "").slice(0, 64);
3104
+ if (!name) throw new CliError(`name \u3092\u6B63\u898F\u5316\u3067\u304D\u307E\u305B\u3093: ${original}`, 2);
3105
+ validateDraft({ ...draft, name });
3106
+ const first = seen.get(name);
3107
+ if (first) throw new CliError(`import \u5185\u3067 name \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059(\u5148: ${first})\u3002`, 2);
3108
+ seen.set(name, file.name);
3109
+ ok.push({ file: file.name, name, original, draft: { ...draft, name } });
3110
+ } catch (error) {
3111
+ invalid.push({ file: file.name, name, original, status: "failed", message: error instanceof Error ? error.message : String(error) });
3112
+ }
3113
+ }
3114
+ return { ok, invalid };
3115
+ }
3116
+ function importResultLine(scope, result) {
3117
+ const { status, name, original, message } = result;
3118
+ return `${status} ${scope}/${name}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}`;
3119
+ }
3120
+ async function importMemoryFiles(opts) {
3121
+ const ctx = await createMemoryContext(opts, true);
3122
+ let imported = 0, skipped = 0, failed = 0, cached = true;
3123
+ const results = [];
3124
+ for (const { file, name, original, draft } of opts.targets) {
3125
+ let status, message, heading = null;
3126
+ try {
3127
+ const response = await opts.http.put(ctx.api, {
3128
+ scope: opts.scope,
3129
+ name,
3130
+ description: draft.description,
3131
+ body: draft.body,
3132
+ ...draft.type ? { type: draft.type } : {},
3133
+ allowNew: true,
3134
+ ...opts.ai ? {} : { aiSkip: true }
3135
+ }, { "X-Nolto-Client": detectMemoryClient(process.env) });
3136
+ cached = await updateCache(ctx, opts, writtenEntries(ctx, response), true) && cached;
3137
+ heading = aiHeading(response);
3138
+ imported++;
3139
+ status = "imported";
3140
+ } catch (error) {
3141
+ if (error instanceof CliError && error.serverError === "memory_exists") {
3142
+ skipped++;
3143
+ status = "skipped";
3144
+ if (error.body?.entry) cached = await updateCache(ctx, opts, [error.body.entry], true) && cached;
3145
+ } else {
3146
+ failed++;
3147
+ status = "failed";
3148
+ message = error instanceof Error ? error.message : String(error);
3149
+ }
3150
+ }
3151
+ const result = { file, name, original, status, ...message ? { message } : {} };
3152
+ results.push(result);
3153
+ opts.write(heading ? `${heading} (\u5143: ${oneLine(file)})` : importResultLine(opts.scope, result));
3154
+ }
3155
+ return { imported, skipped, failed, results, cached };
2662
3156
  }
2663
3157
 
2664
3158
  // src/commands/init.ts
2665
- var __dirname2 = path15.dirname(fileURLToPath2(import.meta.url));
3159
+ import { readFile as readFile13 } from "fs/promises";
3160
+ import readline3 from "readline/promises";
3161
+ import { createRequire } from "module";
3162
+ import { fileURLToPath as fileURLToPath2 } from "url";
3163
+ import os3 from "os";
3164
+ import path17 from "path";
3165
+ import fs2 from "fs";
3166
+ var __dirname2 = path17.dirname(fileURLToPath2(import.meta.url));
2666
3167
  var _require = createRequire(import.meta.url);
2667
3168
  function getCliVersion() {
2668
3169
  const candidates = [
2669
- path15.resolve(__dirname2, "../package.json"),
3170
+ path17.resolve(__dirname2, "../package.json"),
2670
3171
  // bundled: dist/../package.json
2671
- path15.resolve(__dirname2, "../../package.json")
3172
+ path17.resolve(__dirname2, "../../package.json")
2672
3173
  // source: src/commands/../../package.json
2673
3174
  ];
2674
3175
  for (const pkgPath of candidates) {
@@ -2817,10 +3318,10 @@ async function setupMemory(opts) {
2817
3318
  }
2818
3319
  }
2819
3320
  if (!agents.includes("claude")) return;
2820
- const file = path15.join(root, ".claude", "settings.local.json");
3321
+ const file = path17.join(root, ".claude", "settings.local.json");
2821
3322
  let settings = {};
2822
3323
  try {
2823
- settings = JSON.parse(await readFile11(file, "utf8"));
3324
+ settings = JSON.parse(await readFile13(file, "utf8"));
2824
3325
  } catch (error) {
2825
3326
  if (error.code !== "ENOENT") {
2826
3327
  process.stderr.write(`Warning: ${file} \u3092\u8AAD\u3081\u306A\u3044\u305F\u3081\u3001\u81EA\u52D5\u30E1\u30E2\u30EA\u306E\u8A2D\u5B9A\u3092\u7701\u7565\u3057\u307E\u3057\u305F\u3002
@@ -2839,10 +3340,10 @@ async function setupMemory(opts) {
2839
3340
  else process.stdout.write(`memory: Claude Code \u306E\u81EA\u52D5\u30E1\u30E2\u30EA\u505C\u6B62${result === "already" ? "\u306F\u8A2D\u5B9A\u6E08\u307F" : "\u3092\u8A2D\u5B9A\u3057\u307E\u3057\u305F"}
2840
3341
  `);
2841
3342
  }
2842
- function register3(program, deps) {
3343
+ function register5(program, deps) {
2843
3344
  program.command("init").description("Interactive setup: configure token, base URL, and default project.").option("--force", "Overwrite existing config without prompting").option("--memory", "Set up Nolto memory without the initial confirmation").option("--no-memory", "Skip memory setup").action(async (opts) => {
2844
3345
  const configPath = deps.configPath;
2845
- const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
3346
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
2846
3347
  try {
2847
3348
  let configureGlobal = opts.force === true;
2848
3349
  if (!configureGlobal) {
@@ -2932,7 +3433,7 @@ Saved ${configPath}
2932
3433
  }
2933
3434
  if (isHomeDirectory(root)) {
2934
3435
  process.stderr.write(
2935
- `Refusing to set up your home directory as a repository root (found ${path15.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
3436
+ `Refusing to set up your home directory as a repository root (found ${path17.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
2936
3437
  `
2937
3438
  );
2938
3439
  return;
@@ -2964,7 +3465,7 @@ Saved ${configPath}
2964
3465
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
2965
3466
  );
2966
3467
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
2967
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path15.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
3468
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path17.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2968
3469
  } else {
2969
3470
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2970
3471
  }
@@ -2978,7 +3479,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2978
3479
  process.stdout.write("Skipped repo setup.\n");
2979
3480
  return;
2980
3481
  }
2981
- const bindingPath = deps.repoBinding?.path ?? path15.join(root, "nolto.json");
3482
+ const bindingPath = deps.repoBinding?.path ?? path17.join(root, "nolto.json");
2982
3483
  if (keepExistingBinding) {
2983
3484
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
2984
3485
  `);
@@ -2990,20 +3491,20 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2990
3491
  );
2991
3492
  }
2992
3493
  await writeRepoBinding(root, repoProject.id);
2993
- process.stdout.write(`binding: wrote ${path15.join(root, "nolto.json")}
3494
+ process.stdout.write(`binding: wrote ${path17.join(root, "nolto.json")}
2994
3495
  `);
2995
3496
  }
2996
3497
  const sourceDir = resolveSkillSourceDir();
2997
3498
  const claudeInstall = await installSkill({
2998
- skillsParentDir: path15.join(root, ".claude", "skills"),
3499
+ skillsParentDir: path17.join(root, ".claude", "skills"),
2999
3500
  sourceDir
3000
3501
  });
3001
3502
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
3002
3503
  `);
3003
- const usesAgentsTooling = fs2.existsSync(path15.join(root, ".agents")) || fs2.existsSync(path15.join(root, ".codex")) || fs2.existsSync(path15.join(root, "AGENTS.md"));
3504
+ const usesAgentsTooling = fs2.existsSync(path17.join(root, ".agents")) || fs2.existsSync(path17.join(root, ".codex")) || fs2.existsSync(path17.join(root, "AGENTS.md"));
3004
3505
  if (usesAgentsTooling) {
3005
3506
  const agentsInstall = await installSkill({
3006
- skillsParentDir: path15.join(root, ".agents", "skills"),
3507
+ skillsParentDir: path17.join(root, ".agents", "skills"),
3007
3508
  sourceDir
3008
3509
  });
3009
3510
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
@@ -3081,7 +3582,7 @@ async function promptHidden(rl, prompt) {
3081
3582
  }
3082
3583
 
3083
3584
  // src/commands/login.ts
3084
- import readline3 from "readline/promises";
3585
+ import readline4 from "readline/promises";
3085
3586
 
3086
3587
  // src/login-poll.ts
3087
3588
  async function pollUntilToken(opts) {
@@ -3136,7 +3637,7 @@ function sleep(ms) {
3136
3637
  }
3137
3638
 
3138
3639
  // src/commands/login.ts
3139
- function register4(program, deps) {
3640
+ function register6(program, deps) {
3140
3641
  program.command("login").description("Authenticate via browser and save an API token to the config file.").option("--force", "Overwrite existing token without prompting").action(
3141
3642
  async (opts) => {
3142
3643
  const { configPath, settings, output } = deps;
@@ -3147,7 +3648,7 @@ function register4(program, deps) {
3147
3648
  } catch {
3148
3649
  }
3149
3650
  if (existing?.token) {
3150
- const rl = readline3.createInterface({
3651
+ const rl = readline4.createInterface({
3151
3652
  input: process.stdin,
3152
3653
  output: process.stdout
3153
3654
  });
@@ -3218,7 +3719,7 @@ function register4(program, deps) {
3218
3719
  }
3219
3720
 
3220
3721
  // src/commands/whoami.ts
3221
- function register5(program, deps) {
3722
+ function register7(program, deps) {
3222
3723
  program.command("whoami").description("Show the current authentication and configuration state.").action(async () => {
3223
3724
  const { settings, output, configPath } = deps;
3224
3725
  const mode2 = output.mode;
@@ -3260,280 +3761,26 @@ function register5(program, deps) {
3260
3761
  },
3261
3762
  mode2
3262
3763
  );
3263
- } else {
3264
- const tokenDisplay = settings.token != null ? `${maskToken(settings.token)} (source: ${settings.source.token})` : "(not configured)";
3265
- const bindingDisplay = settings.source.project === "repo" && projectBindingPath != null ? `${settings.defaultProjectId ?? "none"} (source: repo, binding: ${projectBindingPath})` : `${settings.defaultProjectId ?? "none"} (source: ${settings.source.project})`;
3266
- const lines = [
3267
- ["baseUrl", `${settings.baseUrl} (source: ${settings.source.baseUrl})`],
3268
- ["configPath", configPath],
3269
- ["token", tokenDisplay],
3270
- ["defaultProject", bindingDisplay],
3271
- ["projects", projectCount != null ? String(projectCount) : settings.token != null ? "(unavailable)" : "(no token)"]
3272
- ];
3273
- if (tokenInfo) {
3274
- lines.push(["scopes", tokenInfo.scopes === null ? "full" : tokenInfo.scopes.join(", ")], ["project", tokenInfo.projectId ?? "all"]);
3275
- }
3276
- const maxKey = lines.reduce((m, [k]) => Math.max(m, k.length), 0);
3277
- for (const [key, val] of lines) {
3278
- process.stdout.write(`${key.padEnd(maxKey)}: ${val}
3279
- `);
3280
- }
3281
- }
3282
- });
3283
- }
3284
-
3285
- // src/commands/sync.ts
3286
- import { execFile as execFile3 } from "child_process";
3287
- import { promisify as promisify2 } from "util";
3288
- import { readFile as readFile12, realpath as realpath2 } from "fs/promises";
3289
- import { existsSync as existsSync4 } from "fs";
3290
-
3291
- // src/roadmap-read.ts
3292
- import path16 from "path";
3293
- async function resolveRoadmapReadContext(deps) {
3294
- if (deps.settings.token == null) {
3295
- throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
3296
- }
3297
- const startDir = resolveStartDir(process.env, process.cwd());
3298
- const { root, foundGit } = findRepoRoot(startDir);
3299
- if (!foundGit) {
3300
- throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
3301
- }
3302
- const binding = await loadRepoBinding(path16.join(root, "nolto.json"));
3303
- const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
3304
- if (projectId == null) {
3305
- throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
3306
- }
3307
- return { root, projectId };
3308
- }
3309
-
3310
- // src/git-links.ts
3311
- function parseGitLog(raw) {
3312
- return raw.split("\n").filter((line2) => line2.length > 0).map((line2) => {
3313
- const fields = line2.replace(/\r$/, "").split("");
3314
- const [ref, subject, author, committedAt] = fields;
3315
- if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
3316
- throw new Error("Malformed git log entry");
3317
- }
3318
- return { ref, subject, author, committedAt: new Date(committedAt).toISOString() };
3319
- });
3320
- }
3321
- function extractIssueKeys(subject) {
3322
- 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]))];
3323
- }
3324
- function extractPrNumber(subject) {
3325
- return /\(#([1-9][0-9]{0,8})\)$/.exec(subject)?.[1] ?? /^Merge pull request #([1-9][0-9]{0,8})\b/.exec(subject)?.[1] ?? null;
3326
- }
3327
- function buildGitLinksPayload(entries) {
3328
- return { links: entries.flatMap((entry) => {
3329
- const keys = extractIssueKeys(entry.subject);
3330
- const pr = extractPrNumber(entry.subject);
3331
- const refs = [{ kind: "commit", ref: entry.ref }, ...pr ? [{ kind: "pr", ref: pr }] : []];
3332
- return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
3333
- ...ref,
3334
- title: entry.subject.slice(0, 500),
3335
- author: entry.author.slice(0, 500),
3336
- committedAt: entry.committedAt,
3337
- issueKeys: keys.slice(index * 20, (index + 1) * 20)
3338
- })));
3339
- }) };
3340
- }
3341
- function stdout(result) {
3342
- if (typeof result === "object" && result !== null && "stdout" in result && typeof result.stdout === "string") return result.stdout;
3343
- throw new Error("Git command returned no text output");
3344
- }
3345
- async function collectGitLinks(root, exec) {
3346
- let probe;
3347
- try {
3348
- probe = await exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root });
3349
- } catch {
3350
- return null;
3351
- }
3352
- if (stdout(probe).trim() !== "true") return null;
3353
- const result = await exec("git", ["log", "--no-color", "--format=%H%x1f%s%x1f%an%x1f%cI", "-n", "300"], { cwd: root });
3354
- return buildGitLinksPayload(parseGitLog(stdout(result)));
3355
- }
3356
-
3357
- // src/sync-repo.ts
3358
- import path17 from "path";
3359
- import { readdir as readdir5 } from "fs/promises";
3360
- function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
3361
- const planAbsPaths = /* @__PURE__ */ new Set();
3362
- const resolvedRoot = path17.resolve(root);
3363
- for (const roadmap of roadmaps) {
3364
- for (const ref of collectPlanRefs(roadmap)) {
3365
- const absolute = path17.resolve(resolvedRoot, ref.path);
3366
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path17.sep)) {
3367
- warn2(`chokidar target outside repo, skipping: ${ref.path}`);
3368
- continue;
3369
- }
3370
- if (!isValidPlanPath(ref.path)) {
3371
- warn2(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
3372
- continue;
3373
- }
3374
- planAbsPaths.add(absolute);
3375
- }
3376
- }
3377
- return [...planAbsPaths];
3378
- }
3379
- async function syncRepo(args, io) {
3380
- const { projectId } = args;
3381
- const repoIdentity = await io.repoIdentity(args.root);
3382
- const identity = repoIdentityToString(repoIdentity);
3383
- const slugs = args.slugs ?? await listCachedSlugs(io.env, projectId);
3384
- if (slugs.length === 0) {
3385
- let legacyFiles = [];
3386
- try {
3387
- legacyFiles = await readdir5(path17.join(args.root, ".nolto", "roadmaps"));
3388
- } catch (err) {
3389
- if (err.code !== "ENOENT") throw err;
3390
- }
3391
- if (legacyFiles.some((file) => file.endsWith(".json"))) {
3392
- throw new CliError("Roadmaps are still in .nolto/roadmaps. Run `nolto roadmap migrate`.", 2);
3393
- }
3394
- throw new CliError("No cached roadmap for this project. Run `nolto pull` or `nolto init`.", 2);
3395
- }
3396
- const roadmaps = [];
3397
- for (const slug of slugs) {
3398
- const entry = await readCache(io.env, projectId, slug);
3399
- if (!entry) throw new CliError(`No cached roadmap "${slug}". Run \`nolto roadmap pull ${slug}\`.`, 2);
3400
- if (args.slugs === void 0 && entry.meta?.repoIdentity != null && entry.meta.repoIdentity !== identity) {
3401
- io.log(`skipped ${slug} (belongs to ${entry.meta.repoIdentity})`);
3402
- continue;
3403
- }
3404
- roadmaps.push({ slug, ...entry });
3405
- }
3406
- if (roadmaps.length === 0) throw new CliError("No cached roadmap belongs to this repository. Run `nolto link --slug <slug>` to create one, or `nolto pull`.", 2);
3407
- const exec = io.exec;
3408
- const isIgnored = exec === void 0 ? void 0 : async (root, relPath) => {
3409
- try {
3410
- await exec("git", ["check-ignore", "-q", "--", relPath], { cwd: root });
3411
- return true;
3412
- } catch {
3413
- return false;
3414
- }
3415
- };
3416
- const results = [];
3417
- for (const entry of roadmaps) {
3418
- const { slug, roadmap, meta } = entry;
3419
- if (args.onlyDirty && !isDirty(entry)) continue;
3420
- try {
3421
- const response = await runSync(
3422
- { repoRoot: args.root, projectId, slug, roadmap, repoIdentity, baseRevision: meta?.revision ?? 0 },
3423
- { http: io.http, readFile: io.readFile, fileExists: io.fileExists, realpath: io.realpath, ...isIgnored ? { isIgnored } : {}, log: io.log, warn: io.warn }
3424
- );
3425
- await writeCache(io.env, projectId, slug, response.roadmap ?? roadmap, {
3426
- repoIdentity: identity,
3427
- revision: response.revision,
3428
- pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
3429
- currentTaskId: response.currentTaskId !== void 0 ? response.currentTaskId : meta?.currentTaskId
3430
- });
3431
- results.push(response);
3432
- entry.roadmap = response.roadmap ?? roadmap;
3433
- } catch (err) {
3434
- if (err instanceof CliError && err.status === 409) {
3435
- if (err.serverError === "task_conflict") {
3436
- const conflicts = err.body?.["conflicts"];
3437
- if (Array.isArray(conflicts)) {
3438
- for (const conflict of conflicts) {
3439
- if (conflict !== null && typeof conflict === "object") {
3440
- io.warn(` ${conflict.level} ${conflict.id} ${conflict.field}: ours=${JSON.stringify(conflict.ours)} theirs=${JSON.stringify(conflict.theirs)}`);
3441
- }
3442
- }
3443
- }
3444
- throw new CliError(`Roadmap ${slug} conflicts with the server. Run \`nolto pull\` and resolve, then sync again.`, 4);
3445
- }
3446
- if (err.serverError === "base_revision_expired") {
3447
- throw new CliError(`Roadmap ${slug} is based on an expired revision. Run \`nolto pull\` and reapply your changes.`, 4);
3448
- }
3449
- }
3450
- throw err;
3451
- }
3452
- }
3453
- let gitLinks = null;
3454
- if (io.exec && io.gitLinks !== false) {
3455
- try {
3456
- const body = await collectGitLinks(args.root, io.exec);
3457
- if (body && body.links.length > 0) {
3458
- gitLinks = { linked: 0, existing: 0, skipped: 0 };
3459
- for (let offset = 0; offset < body.links.length; offset += 500) {
3460
- const response = await io.http.post(
3461
- `/api/projects/${projectId}/git-links`,
3462
- { links: body.links.slice(offset, offset + 500), repoIdentity }
3463
- );
3464
- if (!Number.isSafeInteger(response.linked) || response.linked < 0 || !Number.isSafeInteger(response.existing) || response.existing < 0 || !Number.isSafeInteger(response.skipped) || response.skipped < 0 || !Array.isArray(response.warnings) || response.warnings.some((warning) => typeof warning !== "string")) throw new Error("Invalid git links response");
3465
- gitLinks = { linked: gitLinks.linked + response.linked, existing: gitLinks.existing + response.existing, skipped: gitLinks.skipped + response.skipped };
3466
- for (const warning of response.warnings) io.warn(`git links: ${warning}`);
3467
- }
3468
- io.log(`git links: linked ${gitLinks.linked} (existing ${gitLinks.existing}, skipped ${gitLinks.skipped})`);
3469
- }
3470
- } catch (error) {
3471
- gitLinks = null;
3472
- io.warn(`git links: skipped \u2014 ${error instanceof Error ? error.message : String(error)}`);
3473
- }
3474
- }
3475
- return { results, planAbsPaths: collectContainedPlanAbsPaths(roadmaps.map((entry) => entry.roadmap), args.root, io.warn), gitLinks };
3476
- }
3477
-
3478
- // src/commands/sync.ts
3479
- function register6(program, deps) {
3480
- 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) => {
3481
- await runSyncCommand(deps, opts);
3482
- });
3483
- }
3484
- async function runSyncCommand(deps, opts = {}) {
3485
- const { root, projectId } = await resolveRoadmapReadContext(deps);
3486
- const http = deps.http;
3487
- const warn2 = (line2) => {
3488
- process.stderr.write((line2.startsWith(" ") ? "" : "Warning: ") + line2 + "\n");
3489
- };
3490
- const response = await syncRepo(
3491
- { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
3492
- {
3493
- env: process.env,
3494
- readFile: (p) => readFile12(p, "utf8"),
3495
- realpath: (p) => realpath2(p),
3496
- fileExists: (p) => existsSync4(p),
3497
- repoIdentity: makeRepoIdentityResolver(deps),
3498
- exec: promisify2(execFile3),
3499
- gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
3500
- http,
3501
- log: (line2) => {
3502
- if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
3503
- },
3504
- warn: warn2
3505
- }
3506
- );
3507
- try {
3508
- const drifted = await checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs });
3509
- for (const warning of drifted) warn2(warning);
3510
- } catch {
3511
- }
3512
- let registryAdded = false;
3513
- if (isHomeDirectory(root)) {
3514
- process.stderr.write(`Warning: refusing to add home directory ${root} to the watch registry.
3515
- `);
3516
- } else {
3517
- try {
3518
- registryAdded = (await addRepoToRegistry(getRegistryPath(process.env), { root, projectId })).added;
3519
- if (registryAdded) {
3520
- const warning = await staleWatchWarning(process.env, deps.version, process.kill);
3521
- if (warning) process.stderr.write(warning + "\n");
3764
+ } else {
3765
+ const tokenDisplay = settings.token != null ? `${maskToken(settings.token)} (source: ${settings.source.token})` : "(not configured)";
3766
+ const bindingDisplay = settings.source.project === "repo" && projectBindingPath != null ? `${settings.defaultProjectId ?? "none"} (source: repo, binding: ${projectBindingPath})` : `${settings.defaultProjectId ?? "none"} (source: ${settings.source.project})`;
3767
+ const lines = [
3768
+ ["baseUrl", `${settings.baseUrl} (source: ${settings.source.baseUrl})`],
3769
+ ["configPath", configPath],
3770
+ ["token", tokenDisplay],
3771
+ ["defaultProject", bindingDisplay],
3772
+ ["projects", projectCount != null ? String(projectCount) : settings.token != null ? "(unavailable)" : "(no token)"]
3773
+ ];
3774
+ if (tokenInfo) {
3775
+ lines.push(["scopes", tokenInfo.scopes === null ? "full" : tokenInfo.scopes.join(", ")], ["project", tokenInfo.projectId ?? "all"]);
3522
3776
  }
3523
- } catch (err) {
3524
- const message = err instanceof Error ? err.message : String(err);
3525
- process.stderr.write(`Warning: could not update watch registry: ${message}
3777
+ const maxKey = lines.reduce((m, [k]) => Math.max(m, k.length), 0);
3778
+ for (const [key, val] of lines) {
3779
+ process.stdout.write(`${key.padEnd(maxKey)}: ${val}
3526
3780
  `);
3781
+ }
3527
3782
  }
3528
- }
3529
- if (!opts.quiet && deps.output.mode === "json") {
3530
- const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
3531
- printResult({ ...publicResponse, registryAdded }, "json");
3532
- } else if (!opts.quiet && registryAdded) {
3533
- process.stdout.write(`watch registry: added ${root}
3534
- `);
3535
- }
3536
- return response;
3783
+ });
3537
3784
  }
3538
3785
 
3539
3786
  // src/roadmap-diff.ts
@@ -3579,390 +3826,132 @@ function diffRoadmaps(local, server) {
3579
3826
  if (!localTaskIds.has(serverTask.id)) {
3580
3827
  entries.push({
3581
3828
  kind: "task-added",
3582
- id: serverTask.id,
3583
- title: serverTask.title,
3584
- side: "server"
3585
- });
3586
- }
3587
- }
3588
- }
3589
- const localPhaseIds = new Set(local.phases.map((phase) => phase.id));
3590
- for (const serverPhase of server.phases) {
3591
- if (!localPhaseIds.has(serverPhase.id)) {
3592
- entries.push({
3593
- kind: "phase-added",
3594
- id: serverPhase.id,
3595
- title: serverPhase.title,
3596
- side: "server"
3597
- });
3598
- }
3599
- }
3600
- const meta = [
3601
- { field: "updatedAt", local: local.updatedAt ?? null, server: server.updatedAt ?? null },
3602
- {
3603
- field: "currentTaskId",
3604
- local: local.currentTaskId ?? null,
3605
- server: server.currentTaskId ?? null
3606
- },
3607
- { field: "summary", local: local.summary, server: server.summary }
3608
- ];
3609
- for (const item of meta) {
3610
- if (item.local !== item.server) entries.push({ kind: "meta", ...item });
3611
- }
3612
- return entries;
3613
- }
3614
- function truncate(value) {
3615
- if (value == null) return "none";
3616
- const singleLine2 = value.replace(/\s+/g, " ");
3617
- return singleLine2.length <= 60 ? singleLine2 : singleLine2.slice(0, 57) + "...";
3618
- }
3619
- function formatRoadmapDiff(slug, entries) {
3620
- if (entries.length === 0) return [];
3621
- const lines = [`${slug}:`];
3622
- for (const entry of entries) {
3623
- if (entry.kind === "task-status") {
3624
- lines.push(` ${entry.id}: ${entry.local} (local) != ${entry.server} (server)`);
3625
- } else if (entry.kind === "task-added" || entry.kind === "task-removed") {
3626
- lines.push(` ${entry.side} only task ${entry.id} "${truncate(entry.title)}"`);
3627
- } else if (entry.kind === "phase-added" || entry.kind === "phase-removed") {
3628
- lines.push(` ${entry.side} only phase ${entry.id} "${truncate(entry.title)}"`);
3629
- } else if (entry.field === "roadmap") {
3630
- lines.push(` ${entry.side} only roadmap`);
3631
- } else {
3632
- lines.push(
3633
- ` ${entry.field}: ${truncate(entry.local)} (local) != ${truncate(entry.server)} (server)`
3634
- );
3635
- }
3636
- }
3637
- return lines;
3638
- }
3639
-
3640
- // src/commands/diff.ts
3641
- function register7(program, deps) {
3642
- program.command("diff [slug]").description("Compare local roadmaps with the server without changing either side.").action(async (requestedSlug) => {
3643
- const { projectId } = await resolveRoadmapReadContext(deps);
3644
- const list = await deps.http.get(
3645
- `/api/projects/${projectId}/roadmaps`
3646
- );
3647
- const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
3648
- const localSlugs = await listCachedSlugs(process.env, projectId);
3649
- const localSlugSet = new Set(localSlugs);
3650
- const allSlugs = [.../* @__PURE__ */ new Set([...localSlugs, ...serverBySlug.keys()])].sort();
3651
- if (requestedSlug != null && !allSlugs.includes(requestedSlug)) {
3652
- throw new CliError(
3653
- `Roadmap "${requestedSlug}" was not found locally or on the server.`,
3654
- 2
3655
- );
3656
- }
3657
- const targetSlugs = requestedSlug == null ? allSlugs : [requestedSlug];
3658
- let differing = 0;
3659
- for (const slug of targetSlugs) {
3660
- let local = null;
3661
- if (localSlugSet.has(slug)) {
3662
- try {
3663
- local = (await readCache(process.env, projectId, slug))?.roadmap ?? null;
3664
- } catch (err) {
3665
- const message = err instanceof Error ? err.message : String(err);
3666
- process.stderr.write(`Warning: could not diff ${slug}.json: ${message}
3667
- `);
3668
- process.stdout.write(`${slug}:
3669
- local roadmap is present but invalid
3670
- `);
3671
- differing += 1;
3672
- continue;
3673
- }
3674
- }
3675
- let server = null;
3676
- if (serverBySlug.has(slug) && local !== null) {
3677
- const response = await deps.http.get(
3678
- `/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`
3679
- );
3680
- const validation = validateRoadmap(response.roadmap);
3681
- if (validation.errors.length > 0) {
3682
- throw new CliError(
3683
- `Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`,
3684
- 5
3685
- );
3686
- }
3687
- server = response.roadmap;
3688
- }
3689
- const entries = local === null && serverBySlug.has(slug) ? [{ kind: "meta", field: "roadmap", side: "server" }] : diffRoadmaps(local, server);
3690
- if (entries.length === 0) continue;
3691
- differing += 1;
3692
- process.stdout.write(formatRoadmapDiff(slug, entries).join("\n") + "\n");
3693
- }
3694
- if (differing === 0) {
3695
- process.stdout.write("Up to date with the server.\n");
3696
- process.exitCode = 0;
3697
- } else {
3698
- process.stdout.write(`${differing} roadmap(s) differ
3699
- `);
3700
- process.exitCode = 1;
3701
- }
3702
- });
3703
- }
3704
-
3705
- // src/commands/roadmap.ts
3706
- import { readFile as readFile14 } from "fs/promises";
3707
- import { existsSync as existsSync6 } from "fs";
3708
-
3709
- // src/roadmap-commands.ts
3710
- import path18 from "path";
3711
- import { existsSync as existsSync5 } from "fs";
3712
- import { readFile as readFile13, readdir as readdir6, writeFile as writeFile9, rename as rename5, unlink as unlink4, realpath as realpath3 } from "fs/promises";
3713
- import { randomUUID as randomUUID7 } from "crypto";
3714
- import readline4 from "readline/promises";
3715
-
3716
- // src/commands/pull.ts
3717
- function register8(program, deps) {
3718
- 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) => {
3719
- await runPull(deps, { ...opts, slug: requestedSlug });
3720
- });
3721
- }
3722
- async function runPull(deps, opts = {}) {
3723
- const messages = [];
3724
- const { projectId } = await resolveRoadmapReadContext(deps);
3725
- const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
3726
- const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
3727
- if (opts.slug != null && !serverBySlug.has(opts.slug)) {
3728
- throw new CliError(`Roadmap "${opts.slug}" was not found on the server.`, 2);
3729
- }
3730
- const slugs = opts.slug == null ? [...serverBySlug.keys()] : [opts.slug];
3731
- let skipped = false;
3732
- for (const slug of slugs) {
3733
- if (!await pullRoadmapCache({
3734
- env: process.env,
3735
- http: deps.http,
3736
- projectId,
3737
- slug,
3738
- force: opts.force,
3739
- log: (line2) => {
3740
- messages.push(line2);
3741
- if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
3742
- },
3743
- warn: (line2) => {
3744
- process.stderr.write(line2 + "\n");
3745
- }
3746
- })) skipped = true;
3747
- }
3748
- if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
3749
- if (!opts.quiet && deps.output.mode === "json") printResult({ messages }, "json");
3750
- }
3751
-
3752
- // src/roadmap-commands.ts
3753
- var warn = (line2) => {
3754
- process.stderr.write(line2 + "\n");
3755
- };
3756
- async function pull(deps, projectId, slug) {
3757
- if (!await pullRoadmapCache({ env: process.env, http: deps.http, projectId, slug, log: () => void 0, warn })) {
3758
- throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
3759
- }
3760
- }
3761
- async function selectRoadmap(deps, requestedSlug) {
3762
- const context3 = await resolveRoadmapReadContext(deps);
3763
- let slug = requestedSlug;
3764
- if (slug === void 0) {
3765
- let slugs = await listCachedSlugs(process.env, context3.projectId);
3766
- if (slugs.length === 0) {
3767
- await runPull(deps, { quiet: true });
3768
- slugs = await listCachedSlugs(process.env, context3.projectId);
3769
- }
3770
- if (slugs.length !== 1) {
3771
- 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);
3772
- }
3773
- slug = slugs[0];
3774
- }
3775
- const paths = cachePaths(process.env, context3.projectId, slug);
3776
- if (!existsSync5(paths.json)) await pull(deps, context3.projectId, slug);
3777
- return { ...context3, slug, paths };
3778
- }
3779
- async function roadmapPath(deps, slug) {
3780
- const { paths } = await selectRoadmap(deps, slug);
3781
- printResult(path18.resolve(paths.json), deps.output.mode);
3782
- }
3783
- async function roadmapStatus(deps, slug, fresh = false) {
3784
- const selected = await selectRoadmap(deps, slug);
3785
- if (fresh) await pull(deps, selected.projectId, selected.slug);
3786
- const entry = await readCache(process.env, selected.projectId, selected.slug);
3787
- const { roadmap, meta } = entry;
3788
- const stats = deriveTaskStats(roadmap);
3789
- const tasks = roadmap.phases.flatMap((phase) => phase.tasks);
3790
- const current = tasks.find((task) => task.id === meta?.currentTaskId && task.status === "in-progress");
3791
- const blocked = tasks.filter((task) => task.status === "blocked");
3792
- const age = meta ? (Date.now() - Date.parse(meta.pulledAt)) / 6e4 : NaN;
3793
- if (age > 10) warn(`Warning: cache is ${Math.floor(age)} minutes old; run with --fresh or nolto roadmap pull`);
3794
- if (deps.output.mode === "json") {
3795
- printResult({ roadmap, stats, currentTaskId: current?.id ?? null, revision: meta?.revision ?? 0, pulledAt: meta?.pulledAt ?? null }, "json");
3796
- return;
3797
- }
3798
- printResult([
3799
- `${roadmap.project.name}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
3800
- `Current: ${current ? `${current.id} \u2014 ${current.title}` : "none"}`,
3801
- `Blocked: ${blocked.map((task) => `${task.id} \u2014 ${task.title}`).join(", ") || "none"}`,
3802
- `Summary: ${roadmap.summary}`,
3803
- `Revision: ${meta?.revision ?? 0} (pulled ${meta?.pulledAt ?? "unknown"})`
3804
- ].join("\n"), "human");
3805
- }
3806
- async function roadmapValidate(deps, slug) {
3807
- const { paths } = await selectRoadmap(deps, slug);
3808
- let parsed;
3809
- try {
3810
- parsed = JSON.parse(await readFile13(paths.json, "utf8"));
3811
- } catch {
3812
- throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
3829
+ id: serverTask.id,
3830
+ title: serverTask.title,
3831
+ side: "server"
3832
+ });
3833
+ }
3834
+ }
3813
3835
  }
3814
- const result = validateRoadmap(parsed);
3815
- for (const warning of result.warnings) warn(`WARN ${warning}`);
3816
- if (result.errors.length) {
3817
- for (const error of result.errors) warn(`ERROR ${error}`);
3818
- throw new CliError(`Roadmap validation failed: ${paths.json}`, 1);
3836
+ const localPhaseIds = new Set(local.phases.map((phase) => phase.id));
3837
+ for (const serverPhase of server.phases) {
3838
+ if (!localPhaseIds.has(serverPhase.id)) {
3839
+ entries.push({
3840
+ kind: "phase-added",
3841
+ id: serverPhase.id,
3842
+ title: serverPhase.title,
3843
+ side: "server"
3844
+ });
3845
+ }
3819
3846
  }
3820
- printResult(deps.output.mode === "json" ? { path: paths.json, ...result } : `OK ${paths.json}`, deps.output.mode);
3821
- }
3822
- async function roadmapSummary(deps, slug, text) {
3823
- const selected = await selectRoadmap(deps, slug);
3824
- const entry = await readCache(process.env, selected.projectId, selected.slug);
3825
- entry.roadmap.summary = text;
3826
- const temp = `${selected.paths.json}.tmp-${randomUUID7()}`;
3827
- try {
3828
- await writeFile9(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3829
- await rename5(temp, selected.paths.json);
3830
- } finally {
3831
- await unlink4(temp).catch(() => void 0);
3847
+ const meta = [
3848
+ { field: "updatedAt", local: local.updatedAt ?? null, server: server.updatedAt ?? null },
3849
+ {
3850
+ field: "currentTaskId",
3851
+ local: local.currentTaskId ?? null,
3852
+ server: server.currentTaskId ?? null
3853
+ },
3854
+ { field: "summary", local: local.summary, server: server.summary }
3855
+ ];
3856
+ for (const item of meta) {
3857
+ if (item.local !== item.server) entries.push({ kind: "meta", ...item });
3832
3858
  }
3833
- await runSyncCommand(deps, { slug: selected.slug });
3859
+ return entries;
3834
3860
  }
3835
- async function patchTask(args) {
3836
- const { env, projectId, slug, taskId } = args;
3837
- const entry = await readCache(env, projectId, slug);
3838
- if (entry && isDirty(entry)) throw new CliError("Cache has unsynced structural changes; run nolto roadmap sync first.", 4);
3839
- let response;
3840
- try {
3841
- response = await args.http.patch(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}`, args.body);
3842
- } catch (error) {
3843
- if (error instanceof CliError && error.status === 404) throw new CliError(`Task ${taskId} not found in ${slug}.`, 2);
3844
- throw error;
3845
- }
3846
- const { errors } = validateRoadmap(response.roadmap);
3847
- if (errors.length) throw new CliError(`Server roadmap "${slug}" failed validation: ${errors.join("; ")}`, 5);
3848
- await writeCache(env, projectId, slug, response.roadmap, {
3849
- repoIdentity: entry?.meta?.repoIdentity ?? null,
3850
- revision: response.revision,
3851
- pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
3852
- currentTaskId: response.currentTaskId
3853
- });
3854
- return response;
3861
+ function truncate(value) {
3862
+ if (value == null) return "none";
3863
+ const singleLine2 = value.replace(/\s+/g, " ");
3864
+ return singleLine2.length <= 60 ? singleLine2 : singleLine2.slice(0, 57) + "...";
3855
3865
  }
3856
- async function roadmapTask(deps, taskId, slug, body) {
3857
- const selected = await selectRoadmap(deps, slug);
3858
- if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
3859
- if (body.plan !== void 0) {
3860
- const absolute = path18.resolve(selected.root, body.plan);
3861
- if (!isValidPlanPath(body.plan) || !absolute.startsWith(path18.resolve(selected.root) + path18.sep)) {
3862
- throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
3866
+ function formatRoadmapDiff(slug, entries) {
3867
+ if (entries.length === 0) return [];
3868
+ const lines = [`${slug}:`];
3869
+ for (const entry of entries) {
3870
+ if (entry.kind === "task-status") {
3871
+ lines.push(` ${entry.id}: ${entry.local} (local) != ${entry.server} (server)`);
3872
+ } else if (entry.kind === "task-added" || entry.kind === "task-removed") {
3873
+ lines.push(` ${entry.side} only task ${entry.id} "${truncate(entry.title)}"`);
3874
+ } else if (entry.kind === "phase-added" || entry.kind === "phase-removed") {
3875
+ lines.push(` ${entry.side} only phase ${entry.id} "${truncate(entry.title)}"`);
3876
+ } else if (entry.field === "roadmap") {
3877
+ lines.push(` ${entry.side} only roadmap`);
3878
+ } else {
3879
+ lines.push(
3880
+ ` ${entry.field}: ${truncate(entry.local)} (local) != ${truncate(entry.server)} (server)`
3881
+ );
3863
3882
  }
3864
- if (!existsSync5(absolute)) warn(`WARN plan file not found at ${absolute}`);
3865
- }
3866
- const response = await patchTask({ ...selected, env: process.env, http: deps.http, taskId, body });
3867
- if (body.plan !== void 0) await runSyncCommand(deps, { slug: selected.slug, quiet: true });
3868
- printResult(deps.output.mode === "json" ? response : body.plan !== void 0 ? `${taskId} plan -> ${body.plan}` : `${taskId} -> ${body.status}`, deps.output.mode);
3869
- }
3870
- async function roadmapEvents(deps, slug, opts) {
3871
- const selected = await selectRoadmap(deps, slug);
3872
- const query = new URLSearchParams();
3873
- if (opts.since !== void 0) query.set("since", opts.since);
3874
- if (opts.limit !== void 0) query.set("limit", opts.limit);
3875
- const response = await deps.http.get(`/api/projects/${selected.projectId}/roadmaps/${encodeURIComponent(selected.slug)}/events${query.size ? `?${query}` : ""}`);
3876
- if (deps.output.mode === "json") printResult(response, "json");
3877
- else for (const event of response.events) {
3878
- printResult(`rev ${event.revision} ${event.createdAt} ${event.actor?.name ?? "system"} ${event.source} ${event.taskId} ${event.field}: ${event.from ?? "\u2014"} \u2192 ${event.to ?? "\u2014"}`, "human");
3879
3883
  }
3884
+ return lines;
3880
3885
  }
3881
- async function roadmapMigrate(deps, yes = false) {
3882
- const { root, projectId } = await resolveRoadmapReadContext(deps);
3883
- const dir = path18.join(root, ".nolto", "roadmaps");
3884
- let files;
3885
- try {
3886
- files = (await readdir6(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
3887
- } catch (error) {
3888
- if (error.code !== "ENOENT") throw error;
3889
- files = [];
3890
- }
3891
- if (!files.length) {
3892
- printResult("Nothing to migrate.", deps.output.mode);
3893
- return;
3894
- }
3895
- const local = [];
3896
- for (const file of files) {
3897
- const slug = file.slice(0, -5);
3898
- cachePaths(process.env, projectId, slug);
3899
- const roadmap = await loadValidRoadmap(path18.join(dir, file), (p) => readFile13(p, "utf8"));
3900
- roadmap.schemaVersion = 3;
3901
- delete roadmap.updatedAt;
3902
- delete roadmap.currentTaskId;
3903
- local.push({ slug, roadmap });
3904
- }
3905
- const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
3906
- const results = [];
3907
- for (const { slug, roadmap } of local) {
3908
- let server;
3909
- if (list.roadmaps.some((item) => item.slug === slug)) server = await deps.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
3910
- const unchanged = server !== void 0 && serializeRoadmap(roadmap) === serializeRoadmap(server.roadmap);
3911
- if (server && !unchanged && !yes) {
3912
- if (!process.stdin.isTTY) throw new CliError(`Replacing ${slug} at server rev ${server.revision} requires confirmation; rerun with --yes.`, 2);
3913
- const rl = readline4.createInterface({ input: process.stdin, output: process.stderr });
3914
- try {
3915
- const answer = await rl.question(`Replace ${slug} on the server at rev ${server.revision} with the local file? [y/N] `);
3916
- if (!/^y(es)?$/i.test(answer.trim())) throw new CliError(`Migration of ${slug} cancelled.`, 2);
3917
- } finally {
3918
- rl.close();
3919
- }
3886
+
3887
+ // src/commands/diff.ts
3888
+ function register8(program, deps) {
3889
+ program.command("diff [slug]").description("Compare local roadmaps with the server without changing either side.").action(async (requestedSlug) => {
3890
+ const { projectId } = await resolveRoadmapReadContext(deps);
3891
+ const list = await deps.http.get(
3892
+ `/api/projects/${projectId}/roadmaps`
3893
+ );
3894
+ const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
3895
+ const localSlugs = await listCachedSlugs(process.env, projectId);
3896
+ const localSlugSet = new Set(localSlugs);
3897
+ const allSlugs = [.../* @__PURE__ */ new Set([...localSlugs, ...serverBySlug.keys()])].sort();
3898
+ if (requestedSlug != null && !allSlugs.includes(requestedSlug)) {
3899
+ throw new CliError(
3900
+ `Roadmap "${requestedSlug}" was not found locally or on the server.`,
3901
+ 2
3902
+ );
3920
3903
  }
3921
- const repoIdentity = (await readCache(process.env, projectId, slug))?.meta?.repoIdentity ?? null;
3922
- let revision = server?.revision ?? 0;
3923
- let saved = unchanged ? server.roadmap : roadmap;
3924
- let currentTaskId = server?.currentTaskId;
3925
- if (unchanged || !server) {
3926
- await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
3904
+ const targetSlugs = requestedSlug == null ? allSlugs : [requestedSlug];
3905
+ let differing = 0;
3906
+ for (const slug of targetSlugs) {
3907
+ let local = null;
3908
+ if (localSlugSet.has(slug)) {
3909
+ try {
3910
+ local = (await readCache(process.env, projectId, slug))?.roadmap ?? null;
3911
+ } catch (err) {
3912
+ const message = err instanceof Error ? err.message : String(err);
3913
+ process.stderr.write(`Warning: could not diff ${slug}.json: ${message}
3914
+ `);
3915
+ process.stdout.write(`${slug}:
3916
+ local roadmap is present but invalid
3917
+ `);
3918
+ differing += 1;
3919
+ continue;
3920
+ }
3921
+ }
3922
+ let server = null;
3923
+ if (serverBySlug.has(slug) && local !== null) {
3924
+ const response = await deps.http.get(
3925
+ `/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`
3926
+ );
3927
+ const validation = validateRoadmap(response.roadmap);
3928
+ if (validation.errors.length > 0) {
3929
+ throw new CliError(
3930
+ `Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`,
3931
+ 5
3932
+ );
3933
+ }
3934
+ server = response.roadmap;
3935
+ }
3936
+ const entries = local === null && serverBySlug.has(slug) ? [{ kind: "meta", field: "roadmap", side: "server" }] : diffRoadmaps(local, server);
3937
+ if (entries.length === 0) continue;
3938
+ differing += 1;
3939
+ process.stdout.write(formatRoadmapDiff(slug, entries).join("\n") + "\n");
3927
3940
  }
3928
- if (!unchanged) {
3929
- const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
3930
- http: deps.http,
3931
- readFile: (p) => readFile13(p, "utf8"),
3932
- realpath: realpath3,
3933
- fileExists: existsSync5,
3934
- log: () => void 0,
3935
- warn
3936
- });
3937
- revision = response.revision;
3938
- saved = response.roadmap ?? roadmap;
3939
- if (response.currentTaskId !== void 0) currentTaskId = response.currentTaskId;
3940
- await writeCache(process.env, projectId, slug, saved, { repoIdentity, revision, pulledAt: (/* @__PURE__ */ new Date()).toISOString(), currentTaskId });
3941
+ if (differing === 0) {
3942
+ process.stdout.write("Up to date with the server.\n");
3943
+ process.exitCode = 0;
3944
+ } else {
3945
+ process.stdout.write(`${differing} roadmap(s) differ
3946
+ `);
3947
+ process.exitCode = 1;
3941
3948
  }
3942
- const action = unchanged ? "unchanged" : server ? "replaced" : "created";
3943
- results.push({ slug, action, revision });
3944
- if (deps.output.mode !== "json") printResult(`${action} ${slug} (rev ${revision})`, "human");
3945
- }
3946
- const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3947
- let attributes = "";
3948
- try {
3949
- attributes = await readFile13(path18.join(root, ".gitattributes"), "utf8");
3950
- } catch (error) {
3951
- if (error.code !== "ENOENT") throw error;
3952
- }
3953
- if (attributes.split(/\r?\n/).some((line2) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line2))) {
3954
- nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
3955
- }
3956
- nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
3957
- const { added } = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId });
3958
- if (added) {
3959
- const warning = await staleWatchWarning(process.env, deps.version, process.kill);
3960
- if (warning) process.stderr.write(warning + "\n");
3961
- }
3962
- printResult(deps.output.mode === "json" ? { results, nextSteps } : nextSteps.join("\n"), deps.output.mode);
3949
+ });
3963
3950
  }
3964
3951
 
3965
3952
  // src/commands/roadmap.ts
3953
+ import { readFile as readFile14 } from "fs/promises";
3954
+ import { existsSync as existsSync6 } from "fs";
3966
3955
  function register9(program, deps) {
3967
3956
  const roadmap = program.command("roadmap").description("Read and update server roadmaps through the local cache.");
3968
3957
  roadmap.command("schema").description("Print the roadmap schema reference").action(async () => {
@@ -4001,11 +3990,11 @@ import { execFile as execFile4 } from "child_process";
4001
3990
  import { promisify as promisify3 } from "util";
4002
3991
  import { readFile as readFile15, realpath as realpath4 } from "fs/promises";
4003
3992
  import { existsSync as existsSync7, mkdirSync } from "fs";
4004
- import path21 from "path";
3993
+ import path20 from "path";
4005
3994
  import chokidar from "chokidar";
4006
3995
 
4007
3996
  // src/watch-core.ts
4008
- import path19 from "path";
3997
+ import path18 from "path";
4009
3998
  var WatchSet = class {
4010
3999
  constructor(deps) {
4011
4000
  this.deps = deps;
@@ -4054,7 +4043,7 @@ async function reloadRoots(deps) {
4054
4043
  continue;
4055
4044
  }
4056
4045
  try {
4057
- const projectId = repo.projectId ?? (await loadRepoBinding(path19.join(repo.root, "nolto.json")))?.projectId;
4046
+ const projectId = repo.projectId ?? (await loadRepoBinding(path18.join(repo.root, "nolto.json")))?.projectId;
4058
4047
  if (projectId) repos.push({ root: repo.root, projectId });
4059
4048
  else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
4060
4049
  } catch (err) {
@@ -4125,7 +4114,7 @@ var RepoWatch = class {
4125
4114
  };
4126
4115
 
4127
4116
  // src/service-install.ts
4128
- import path20 from "path";
4117
+ import path19 from "path";
4129
4118
  import os4 from "os";
4130
4119
  function buildUnitFile(args) {
4131
4120
  return [
@@ -4145,8 +4134,8 @@ function buildUnitFile(args) {
4145
4134
  }
4146
4135
  function getUnitPath(env) {
4147
4136
  const xdg = env["XDG_CONFIG_HOME"];
4148
- const base = xdg != null && xdg.length > 0 ? xdg : path20.join(os4.homedir(), ".config");
4149
- return path20.join(base, "systemd", "user", "nolto-watch.service");
4137
+ const base = xdg != null && xdg.length > 0 ? xdg : path19.join(os4.homedir(), ".config");
4138
+ return path19.join(base, "systemd", "user", "nolto-watch.service");
4150
4139
  }
4151
4140
  async function installServiceWith(deps) {
4152
4141
  if (deps.platform !== "linux") {
@@ -4157,7 +4146,7 @@ async function installServiceWith(deps) {
4157
4146
  );
4158
4147
  }
4159
4148
  const unitPath = getUnitPath(deps.env);
4160
- await deps.mkdir(path20.dirname(unitPath));
4149
+ await deps.mkdir(path19.dirname(unitPath));
4161
4150
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
4162
4151
  deps.log(`Wrote ${unitPath}`);
4163
4152
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -4171,7 +4160,7 @@ async function installServiceWith(deps) {
4171
4160
  deps.log("Service nolto-watch enabled and started. Logs: journalctl --user -u nolto-watch -f");
4172
4161
  }
4173
4162
  async function installService() {
4174
- const { writeFile: writeFile12, mkdir: mkdir9 } = await import("fs/promises");
4163
+ const { writeFile: writeFile11, mkdir: mkdir9 } = await import("fs/promises");
4175
4164
  const { execFile: execFile6 } = await import("child_process");
4176
4165
  const { promisify: promisify5 } = await import("util");
4177
4166
  const execFileAsync = promisify5(execFile6);
@@ -4179,8 +4168,8 @@ async function installService() {
4179
4168
  platform: process.platform,
4180
4169
  env: process.env,
4181
4170
  nodePath: process.execPath,
4182
- scriptPath: path20.resolve(process.argv[1] ?? ""),
4183
- writeFile: (p, content) => writeFile12(p, content, "utf8"),
4171
+ scriptPath: path19.resolve(process.argv[1] ?? ""),
4172
+ writeFile: (p, content) => writeFile11(p, content, "utf8"),
4184
4173
  mkdir: async (p) => {
4185
4174
  await mkdir9(p, { recursive: true });
4186
4175
  },
@@ -4321,7 +4310,7 @@ function register10(program, deps) {
4321
4310
  const startRepo = ({ root, projectId }) => {
4322
4311
  const roadmapsPath = cacheDir(process.env, projectId);
4323
4312
  const warn2 = (line2) => {
4324
- process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path21.basename(root)}] ${line2}
4313
+ process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path20.basename(root)}] ${line2}
4325
4314
  `);
4326
4315
  };
4327
4316
  mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
@@ -4338,7 +4327,7 @@ function register10(program, deps) {
4338
4327
  exec: promisify3(execFile4),
4339
4328
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
4340
4329
  http,
4341
- log: (line2) => process.stdout.write(`[${path21.basename(root)}] ${line2}
4330
+ log: (line2) => process.stdout.write(`[${path20.basename(root)}] ${line2}
4342
4331
  `),
4343
4332
  warn: warn2
4344
4333
  }
@@ -4351,7 +4340,7 @@ function register10(program, deps) {
4351
4340
  warn: (line2) => process.stderr.write(line2 + "\n")
4352
4341
  });
4353
4342
  watcher.on("all", (_event, filePath) => {
4354
- if (path21.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
4343
+ if (path20.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
4355
4344
  repoWatch.handleEvent(filePath);
4356
4345
  });
4357
4346
  void checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs }).then((drifted) => {
@@ -4471,7 +4460,7 @@ stale: ${result.stale}`, deps.output.mode);
4471
4460
  printResult(deps.output.mode === "json" ? { repos } : repos.map((repo) => `${repo.root} ${repo.projectId ?? "\u2014"}${repo.exists ? "" : " (missing)"}`).join("\n"), deps.output.mode);
4472
4461
  });
4473
4462
  watch.command("remove [root]").description("Remove a repository from the watch registry.").action(async (arg) => {
4474
- const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path21.resolve(arg);
4463
+ const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path20.resolve(arg);
4475
4464
  const { removed } = await removeRepoFromRegistry(getRegistryPath(process.env), root);
4476
4465
  if (!removed) throw new CliError(`${root} is not in the watch registry.`, 2, "Run `nolto watch list` to see registered repositories.");
4477
4466
  printResult(deps.output.mode === "json" ? { removed: true, root } : `Removed ${root} from the watch registry.`, deps.output.mode);
@@ -4483,14 +4472,14 @@ import { execFile as execFile5 } from "child_process";
4483
4472
  import { existsSync as existsSync8 } from "fs";
4484
4473
  import { realpath as realpath5 } from "fs/promises";
4485
4474
  import { createRequire as createRequire2 } from "module";
4486
- import path23 from "path";
4475
+ import path22 from "path";
4487
4476
  import { fileURLToPath as fileURLToPath3 } from "url";
4488
4477
  import { promisify as promisify4 } from "util";
4489
4478
 
4490
4479
  // src/update-notifier.ts
4491
- import { readFile as readFile16, writeFile as writeFile10, mkdir as mkdir8 } from "fs/promises";
4480
+ import { readFile as readFile16, writeFile as writeFile9, mkdir as mkdir8 } from "fs/promises";
4492
4481
  import https from "https";
4493
- import path22 from "path";
4482
+ import path21 from "path";
4494
4483
  var PACKAGE = "@nolto/cli";
4495
4484
  var CACHE_FILE = "update-check.json";
4496
4485
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -4548,9 +4537,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
4548
4537
  });
4549
4538
  }
4550
4539
  async function writeUpdateCache(cachePath, now, latest2) {
4551
- await mkdir8(path22.dirname(cachePath), { recursive: true });
4540
+ await mkdir8(path21.dirname(cachePath), { recursive: true });
4552
4541
  const payload = { checkedAt: now, latest: latest2 };
4553
- await writeFile10(cachePath, JSON.stringify(payload), { mode: 384 });
4542
+ await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
4554
4543
  }
4555
4544
  async function refreshCache(cachePath, now, fetchLatest) {
4556
4545
  const latest2 = await fetchLatest();
@@ -4559,7 +4548,7 @@ async function refreshCache(cachePath, now, fetchLatest) {
4559
4548
  }
4560
4549
  async function checkForUpdate(opts) {
4561
4550
  if (isDisabled(opts.env)) return null;
4562
- const cachePath = path22.join(opts.configDir, CACHE_FILE);
4551
+ const cachePath = path21.join(opts.configDir, CACHE_FILE);
4563
4552
  let cache = {};
4564
4553
  try {
4565
4554
  cache = JSON.parse(await readFile16(cachePath, "utf8"));
@@ -4667,7 +4656,7 @@ async function updateCliWith(deps) {
4667
4656
  }
4668
4657
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
4669
4658
  await deps.writeCache(
4670
- path23.join(deps.configDir, UPDATE_CACHE_FILE),
4659
+ path22.join(deps.configDir, UPDATE_CACHE_FILE),
4671
4660
  deps.now,
4672
4661
  latest2
4673
4662
  ).catch(() => void 0);
@@ -4698,10 +4687,10 @@ async function updateCliWith(deps) {
4698
4687
  };
4699
4688
  }
4700
4689
  function getCurrentVersion() {
4701
- const dirname = path23.dirname(fileURLToPath3(import.meta.url));
4690
+ const dirname = path22.dirname(fileURLToPath3(import.meta.url));
4702
4691
  const require3 = createRequire2(import.meta.url);
4703
4692
  try {
4704
- const pkg = require3(path23.resolve(dirname, "../package.json"));
4693
+ const pkg = require3(path22.resolve(dirname, "../package.json"));
4705
4694
  return pkg.version ?? "0.0.0";
4706
4695
  } catch {
4707
4696
  return "0.0.0";
@@ -4751,7 +4740,7 @@ function register11(program, deps) {
4751
4740
  }
4752
4741
 
4753
4742
  // src/commands/merge-file.ts
4754
- import { readFile as readFile17, writeFile as writeFile11 } from "fs/promises";
4743
+ import { readFile as readFile17, writeFile as writeFile10 } from "fs/promises";
4755
4744
 
4756
4745
  // src/roadmap-merge.ts
4757
4746
  import { isDeepStrictEqual } from "util";
@@ -5015,7 +5004,7 @@ function register12(program) {
5015
5004
  const theirs = await readRoadmap(theirsPath);
5016
5005
  const base = opts.base == null ? null : await readRoadmap(opts.base);
5017
5006
  const merged = mergeRoadmaps({ base, ours, theirs });
5018
- await writeFile11(
5007
+ await writeFile10(
5019
5008
  opts.output ?? oursPath,
5020
5009
  JSON.stringify(merged, null, 2) + "\n",
5021
5010
  "utf8"
@@ -5319,14 +5308,14 @@ function buildProgram(deps) {
5319
5308
  };
5320
5309
  const program = new Command("nolto").version(deps.version, "-V, --version", "Print version number").exitOverride().configureOutput({ writeErr }).description("Nolto CLI \u2014 sync repository roadmaps with Nolto.").option("--token <value>", "API token (overrides env/file)").option("--base-url <url>", "Nolto base URL (default: https://nolto.app)").option("--project <projectId>", "Default project ID").option("--json", "Output as JSON");
5321
5310
  register13(program, deps);
5322
- register(program, deps);
5323
- register3(program, deps);
5324
5311
  register4(program, deps);
5325
5312
  register5(program, deps);
5326
- register2(program, deps);
5327
5313
  register6(program, deps);
5328
5314
  register7(program, deps);
5315
+ register(program, deps);
5316
+ register3(program, deps);
5329
5317
  register8(program, deps);
5318
+ register2(program, deps);
5330
5319
  register9(program, deps);
5331
5320
  register10(program, deps);
5332
5321
  register11(program, deps);
@@ -5346,11 +5335,11 @@ function buildProgram(deps) {
5346
5335
  }
5347
5336
 
5348
5337
  // src/index.ts
5349
- var __dirname3 = path24.dirname(fileURLToPath4(import.meta.url));
5338
+ var __dirname3 = path23.dirname(fileURLToPath4(import.meta.url));
5350
5339
  var require2 = createRequire3(import.meta.url);
5351
5340
  function getVersion() {
5352
5341
  try {
5353
- const pkgPath = path24.resolve(__dirname3, "../package.json");
5342
+ const pkgPath = path23.resolve(__dirname3, "../package.json");
5354
5343
  const pkg = require2(pkgPath);
5355
5344
  return pkg.version ?? "0.0.0";
5356
5345
  } catch {
@@ -5404,10 +5393,10 @@ async function main() {
5404
5393
  output: { mode },
5405
5394
  version,
5406
5395
  configPath,
5407
- claudeProjectsDir: path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "projects"),
5396
+ claudeProjectsDir: path23.join(process.env.CLAUDE_CONFIG_DIR ?? path23.join(os5.homedir(), ".claude"), "projects"),
5408
5397
  homeSkillDirs: [
5409
- path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "skills"),
5410
- path24.join(os5.homedir(), ".agents", "skills")
5398
+ path23.join(process.env.CLAUDE_CONFIG_DIR ?? path23.join(os5.homedir(), ".claude"), "skills"),
5399
+ path23.join(os5.homedir(), ".agents", "skills")
5411
5400
  ],
5412
5401
  repoBinding
5413
5402
  });