@nolto/cli 0.19.3 → 0.20.0

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