@nolto/cli 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -174,7 +174,8 @@ function isNetworkError(err) {
174
174
  }
175
175
 
176
176
  // src/skill-install.ts
177
- import { cp, mkdir, readFile, writeFile, rm } from "fs/promises";
177
+ import { cp, mkdir, readFile, writeFile, rm, readdir } from "fs/promises";
178
+ import { createHash } from "crypto";
178
179
  import { existsSync } from "fs";
179
180
  import path from "path";
180
181
  import { fileURLToPath } from "url";
@@ -192,49 +193,66 @@ function resolveSkillSourceDir(name = "roadmap-progress") {
192
193
  throw new Error(`Bundled ${name} skill not found. Reinstall @nolto/cli.`);
193
194
  }
194
195
  var VERSION_MARKER = ".nolto-skill-version";
195
- async function checkSkillVersionDrift(repoRoot, cliVersion) {
196
- const skillDirs = [
197
- path.join(repoRoot, ".claude", "skills", "roadmap-progress"),
198
- path.join(repoRoot, ".agents", "skills", "roadmap-progress")
199
- ];
200
- const drifted = [];
201
- for (const dir of skillDirs) {
202
- if (!existsSync(dir)) continue;
203
- let installed;
204
- try {
205
- const marker = (await readFile(path.join(dir, VERSION_MARKER), "utf8")).trim();
206
- installed = marker.length > 0 ? marker : null;
207
- } catch {
208
- installed = null;
196
+ async function skillContentHash(dir) {
197
+ const files = [];
198
+ async function walk(relative) {
199
+ for (const entry of await readdir(path.join(dir, relative), { withFileTypes: true })) {
200
+ if (entry.name === VERSION_MARKER) continue;
201
+ const file = relative ? `${relative}/${entry.name}` : entry.name;
202
+ if (entry.isDirectory()) await walk(file);
203
+ else if (entry.isFile()) files.push(file);
209
204
  }
210
- if (installed !== cliVersion) drifted.push({ dir, installed });
211
205
  }
212
- return drifted;
206
+ await walk("");
207
+ const hash = createHash("sha256");
208
+ for (const file of files.sort()) {
209
+ hash.update(file).update("\0").update(await readFile(path.join(dir, file))).update("\0");
210
+ }
211
+ return `sha256:${hash.digest("hex").slice(0, 12)}`;
213
212
  }
214
- function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
215
- const dirs = drifted.map(({ dir }) => path.relative(repoRoot, dir).split(path.sep).join("/")).join(", ");
216
- const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
217
- return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
213
+ async function checkSkillDrift(repoRoot, opts = {}) {
214
+ const warnings = [];
215
+ for (const name of ["roadmap-progress", "project-memory"]) {
216
+ const sourceHash = await skillContentHash(resolveSkillSourceDir(name));
217
+ const drifted = [];
218
+ for (const parent of [".claude", ".agents"]) {
219
+ const dir = path.join(repoRoot, parent, "skills", name);
220
+ if (!existsSync(dir)) continue;
221
+ let installed = null;
222
+ try {
223
+ installed = (await readFile(path.join(dir, VERSION_MARKER), "utf8")).trim();
224
+ } catch {
225
+ }
226
+ if (installed !== sourceHash) drifted.push(path.relative(repoRoot, dir).split(path.sep).join("/"));
227
+ }
228
+ 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
+ for (const parent of opts.homeSkillDirs ?? []) {
230
+ const dir = path.join(parent, name);
231
+ if (existsSync(dir)) warnings.push(`Stale ${name} skill found in ${dir}; it is not managed by nolto init and may override the repo skill. Remove it.`);
232
+ }
233
+ }
234
+ return warnings;
218
235
  }
219
236
  async function installSkill(args) {
237
+ const sourceHash = await skillContentHash(args.sourceDir);
220
238
  const targetDir = path.join(args.skillsParentDir, args.name ?? "roadmap-progress");
221
239
  const markerPath = path.join(targetDir, VERSION_MARKER);
222
240
  const dirExists = existsSync(targetDir);
223
- let installedVersion = null;
241
+ let installedHash = null;
224
242
  if (dirExists) {
225
243
  try {
226
- installedVersion = (await readFile(markerPath, "utf8")).trim();
244
+ installedHash = (await readFile(markerPath, "utf8")).trim();
227
245
  } catch {
228
- installedVersion = null;
246
+ installedHash = null;
229
247
  }
230
248
  }
231
- if (dirExists && installedVersion === args.version && args.force !== true) {
249
+ if (dirExists && installedHash === sourceHash && args.force !== true) {
232
250
  return { action: "skipped", targetDir };
233
251
  }
234
252
  await rm(targetDir, { recursive: true, force: true });
235
253
  await mkdir(args.skillsParentDir, { recursive: true });
236
254
  await cp(args.sourceDir, targetDir, { recursive: true });
237
- await writeFile(markerPath, args.version + "\n", "utf8");
255
+ await writeFile(markerPath, sourceHash + "\n", "utf8");
238
256
  return { action: dirExists ? "updated" : "installed", targetDir };
239
257
  }
240
258
 
@@ -256,24 +274,59 @@ function hookAgentFromArgv(argv) {
256
274
  if (arg.includes("=")) return arg.slice(arg.indexOf("=") + 1);
257
275
  return argv[hook + 1]?.startsWith("-") === false ? argv[hook + 1] : true;
258
276
  }
259
- async function installMemorySkill(root, version) {
277
+ async function installMemorySkill(root) {
260
278
  const sourceDir = resolveSkillSourceDir("project-memory");
261
279
  const parents = [".claude"];
262
280
  if ([".agents", ".codex", "AGENTS.md"].some((name) => existsSync2(path2.join(root, name)))) parents.push(".agents");
263
281
  const results = [];
264
282
  for (const parent of parents) {
265
- results.push(await installSkill({ name: "project-memory", skillsParentDir: path2.join(root, parent, "skills"), sourceDir, version }));
283
+ results.push(await installSkill({ name: "project-memory", skillsParentDir: path2.join(root, parent, "skills"), sourceDir }));
266
284
  }
267
285
  return results;
268
286
  }
269
287
  function object(value) {
270
288
  return value !== null && typeof value === "object" && !Array.isArray(value);
271
289
  }
272
- async function installMemoryHooks(root, version, agent, writeAgentsMd = false) {
290
+ function detectMemoryAgents(root) {
291
+ const selected = ["claude", "codex", "gemini"].filter((a) => existsSync2(path2.join(root, `.${a}`)));
292
+ return selected.length ? selected : ["claude"];
293
+ }
294
+ function hookCommand(agent) {
295
+ return `command -v nolto >/dev/null 2>&1 && nolto memory pull --hook ${agent} || true`;
296
+ }
297
+ function containsMemoryHook(start, agent) {
298
+ return start.some((group) => object(group) && Array.isArray(group.hooks) && group.hooks.some((h) => object(h) && h.command === hookCommand(agent)));
299
+ }
300
+ async function hasMemoryHook(root, agent) {
301
+ try {
302
+ const settings = JSON.parse(await readFile2(path2.join(root, `.${agent}`, agent === "codex" ? "hooks.json" : "settings.json"), "utf8"));
303
+ return object(settings) && object(settings.hooks) && Array.isArray(settings.hooks.SessionStart) && containsMemoryHook(settings.hooks.SessionStart, agent);
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+ function claudeMemoryDir(root, projectsDir) {
309
+ return path2.join(projectsDir, path2.resolve(root).replace(/[^a-zA-Z0-9]/g, "-"), "memory");
310
+ }
311
+ async function disableClaudeAutoMemory(root) {
312
+ const file = path2.join(root, ".claude", "settings.local.json");
313
+ let settings = {};
314
+ try {
315
+ settings = JSON.parse(await readFile2(file, "utf8"));
316
+ } catch (error) {
317
+ if (error.code !== "ENOENT") return "invalid";
318
+ }
319
+ if (!object(settings)) return "invalid";
320
+ if (settings.autoMemoryEnabled === false) return "already";
321
+ settings.autoMemoryEnabled = false;
322
+ await mkdir2(path2.dirname(file), { recursive: true });
323
+ await writeFile2(file, JSON.stringify(settings, null, 2) + "\n");
324
+ return "written";
325
+ }
326
+ async function installMemoryHooks(root, agent, writeAgentsMd = false) {
273
327
  const agents = ["claude", "codex", "gemini"];
274
328
  if (agent && agent !== "all" && !agents.includes(agent)) throw new CliError("--agent \u306F claude|codex|gemini|all", 2);
275
- let selected = agent && agent !== "all" ? [agent] : agents.filter((a) => existsSync2(path2.join(root, `.${a}`)));
276
- if (!selected.length) selected = ["claude"];
329
+ const selected = agent && agent !== "all" ? [agent] : detectMemoryAgents(root);
277
330
  const messages = [];
278
331
  for (const a of selected) {
279
332
  const file = path2.join(root, `.${a}`, a === "codex" ? "hooks.json" : "settings.json");
@@ -287,8 +340,8 @@ async function installMemoryHooks(root, version, agent, writeAgentsMd = false) {
287
340
  const hooks = settings.hooks ?? {};
288
341
  const start = hooks.SessionStart ?? [];
289
342
  if (!Array.isArray(start)) throw new CliError(`${file}: SessionStart \u306F\u914D\u5217\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002`, 2);
290
- const command = `command -v nolto >/dev/null 2>&1 && nolto memory pull --hook ${a} || true`;
291
- const present = start.some((group) => object(group) && Array.isArray(group.hooks) && group.hooks.some((h) => object(h) && h.command === command));
343
+ const command = hookCommand(a);
344
+ const present = containsMemoryHook(start, a);
292
345
  if (!present) {
293
346
  hooks.SessionStart = [...start, { hooks: [{ type: "command", command }] }];
294
347
  settings.hooks = hooks;
@@ -300,7 +353,7 @@ async function installMemoryHooks(root, version, agent, writeAgentsMd = false) {
300
353
  "Codex 0.157.0: hooks \u306F\u65E2\u5B9A\u3067\u6709\u52B9\u3002\u7121\u52B9\u306A\u3089 config.toml \u306E [features] \u306B hooks = true \u3092\u8A2D\u5B9A\u3057\u3001\u4FE1\u983C\u6E08\u307F repo \u3067 /hooks \u304B\u3089\u627F\u8A8D\u3059\u308B\u3002"
301
354
  );
302
355
  }
303
- for (const skill of await installMemorySkill(root, version)) messages.push(`skill project-memory: ${skill.action} ${path2.relative(root, skill.targetDir)}`);
356
+ for (const skill of await installMemorySkill(root)) messages.push(`skill project-memory: ${skill.action} ${path2.relative(root, skill.targetDir)}`);
304
357
  messages.push("AGENTS.md \u306B\u8DB3\u3059\u6307\u793A\u306F nolto memory instructions");
305
358
  if (writeAgentsMd) {
306
359
  const file = path2.join(root, "AGENTS.md");
@@ -324,6 +377,7 @@ ${MEMORY_INSTRUCTIONS}
324
377
  import { createRequire as createRequire3 } from "module";
325
378
  import { fileURLToPath as fileURLToPath4 } from "url";
326
379
  import path24 from "path";
380
+ import os5 from "os";
327
381
  import { CommanderError } from "commander";
328
382
 
329
383
  // src/config.ts
@@ -618,7 +672,7 @@ function createHttpClient(opts) {
618
672
  import { Command } from "commander";
619
673
 
620
674
  // src/commands/issue.ts
621
- import { readFile as readFile4, readdir, writeFile as writeFile4, rename, rm as rm2 } from "fs/promises";
675
+ import { readFile as readFile4, readdir as readdir2, writeFile as writeFile4, rename, rm as rm2 } from "fs/promises";
622
676
  import path4 from "path";
623
677
  import { randomUUID } from "crypto";
624
678
 
@@ -738,7 +792,7 @@ function checkKeys(value, allowed, at, errors) {
738
792
  function isValidPlanPath(value) {
739
793
  if (typeof value !== "string" || value.length === 0) return false;
740
794
  if (value.includes("\\") || value.startsWith("/") || /^[A-Za-z]:/.test(value)) return false;
741
- return /\.(md|markdown)$/i.test(value) && value.split("/").every((segment, index2) => segment !== "" && (!segment.startsWith(".") || index2 === 0 && segment === ".nolto"));
795
+ return /\.(md|markdown)$/i.test(value) && value.split("/").every((segment, index) => segment !== "" && (!segment.startsWith(".") || index === 0 && segment === ".nolto"));
742
796
  }
743
797
  function daysInMonth(year, month) {
744
798
  if (month === 2) {
@@ -1019,8 +1073,8 @@ function formatIssueList(rows, meta) {
1019
1073
  const subject = Array.from(singleLine(row.subject));
1020
1074
  return [row.key, row.status.name, row.priority, personLabel(row.assignee), subject.length > 60 ? `${subject.slice(0, 59).join("")}\u2026` : subject.join("")].map(singleLine);
1021
1075
  });
1022
- const widths = [0, 1, 2, 3].map((index2) => Math.max(0, ...values.map((row) => row[index2].length)));
1023
- const lines = values.map((row) => row.map((value, index2) => index2 < 4 ? value.padEnd(widths[index2]) : value).join(" "));
1076
+ const widths = [0, 1, 2, 3].map((index) => Math.max(0, ...values.map((row) => row[index].length)));
1077
+ const lines = values.map((row) => row.map((value, index) => index < 4 ? value.padEnd(widths[index]) : value).join(" "));
1024
1078
  return [...lines, `${rows.length} / ${meta.total} (page ${meta.page})`].join("\n");
1025
1079
  }
1026
1080
  function formatIssueView(bundle) {
@@ -1131,7 +1185,7 @@ async function attachRoadmap(deps, taskId, slug, key) {
1131
1185
  let entries;
1132
1186
  for (; ; ) {
1133
1187
  try {
1134
- entries = await readdir(path4.join(directory, ".nolto", "roadmaps"));
1188
+ entries = await readdir2(path4.join(directory, ".nolto", "roadmaps"));
1135
1189
  break;
1136
1190
  } catch (error) {
1137
1191
  if (error.code !== "ENOENT" || path4.dirname(directory) === directory) throw error;
@@ -1171,7 +1225,18 @@ function writeOptions(command, create) {
1171
1225
  return command;
1172
1226
  }
1173
1227
  function register(program, deps) {
1174
- const group = program.command("issue").description("List, view and manage project issues.");
1228
+ const group = program.command("issue").description("List, view and manage project issues.").addHelpText("after", `
1229
+ All commands accept global \`--project <id>\`, \`--json\`, \`--token <value>\` and \`--base-url <url>\`.
1230
+ 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.
1231
+
1232
+ | Exit | Meaning |
1233
+ |---|---|
1234
+ | 0 | Success |
1235
+ | 2 | Invalid input, recognized API 404, HTTP 422 (details shown), or local roadmap failure after creation |
1236
+ | 3 | HTTP 401/403; token_scope/token_project includes a token settings hint |
1237
+ | 4 | HTTP 402/429 (quota/rate limit). API token writes: 60/minute. On 429, wait Retry-After seconds before retrying. |
1238
+ | 5 | Network/generic HTTP errors, including a 404 without an API error string |
1239
+ `);
1175
1240
  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) => {
1176
1241
  const ctx = context(deps, command);
1177
1242
  const settings = flags.status || flags.type || flags.category ? await deps.http.get(`${ctx.root}/issue-settings`) : emptySettings;
@@ -1222,601 +1287,982 @@ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1222
1287
  });
1223
1288
  }
1224
1289
 
1225
- // src/watch-state.ts
1226
- import * as fs from "fs/promises";
1290
+ // src/memory-import.ts
1291
+ import { readFile as readFile7, readdir as readdir3 } from "fs/promises";
1292
+ import path8 from "path";
1293
+
1294
+ // src/memory-format.ts
1295
+ var oneLine = (value) => value.replace(/[\r\n\u0085\u2028\u2029]/g, " ");
1296
+ var shellArg = (value) => /^[A-Za-z0-9._/-]+$/.test(value) ? value : JSON.stringify(value);
1297
+ var memoryClient = (via) => via?.client || via?.tokenName || "Web";
1298
+ function parseMemory(text, importing = false) {
1299
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
1300
+ if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
1301
+ if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
1302
+ const end = lines.indexOf("---");
1303
+ if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
1304
+ const fields = {};
1305
+ let metadata = false;
1306
+ for (const line2 of lines.slice(0, end)) {
1307
+ const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
1308
+ if (!match) continue;
1309
+ const indent = match[1], key = match[2], raw = match[3];
1310
+ if (!indent) metadata = key === "metadata";
1311
+ if (indent && !(importing && metadata && key === "type")) continue;
1312
+ let value = raw.trim();
1313
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
1314
+ if (["name", "description", "type", "scope", "branch", "revision"].includes(key)) fields[key] = value;
1315
+ }
1316
+ const body = lines.slice(end + 1);
1317
+ if (body[0] === "") body.shift();
1318
+ return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
1319
+ }
1320
+ function formatMemory(entry) {
1321
+ const value = (s) => {
1322
+ const safe = oneLine(s);
1323
+ return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
1324
+ };
1325
+ return [
1326
+ "<!-- 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 -->",
1327
+ "---",
1328
+ `name: ${entry.name}`,
1329
+ `description: ${value(entry.description)}`,
1330
+ ...entry.type == null ? [] : [`type: ${entry.type}`],
1331
+ `scope: ${entry.scope}`,
1332
+ ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
1333
+ `revision: ${entry.revision}`,
1334
+ `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
1335
+ "---",
1336
+ "",
1337
+ entry.body
1338
+ ].join("\n");
1339
+ }
1340
+ function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
1341
+ if (scope !== "project" && scope !== "user" && scope !== "branch") {
1342
+ throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
1343
+ }
1344
+ return scope;
1345
+ }
1346
+ var count = (n) => n.toLocaleString("en-US");
1347
+ var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
1348
+ function validateDraft(draft) {
1349
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
1350
+ 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");
1351
+ }
1352
+ const description = draft.description.trim();
1353
+ 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");
1354
+ 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");
1355
+ 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");
1356
+ 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");
1357
+ if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
1358
+ 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");
1359
+ }
1360
+ }
1361
+ function parseRevision(value) {
1362
+ const revision = Number(value);
1363
+ 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);
1364
+ return revision;
1365
+ }
1366
+ function detectMemoryClient(env) {
1367
+ const agent = env.NOLTO_AGENT?.trim();
1368
+ if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
1369
+ if (env.CLAUDECODE === "1") return "Claude Code";
1370
+ if (env.GEMINI_CLI === "1") return "Gemini CLI";
1371
+ if (env.CODEX_THREAD_ID) return "Codex";
1372
+ return "CLI";
1373
+ }
1374
+
1375
+ // src/memory-cache.ts
1376
+ import { mkdir as mkdir4, readFile as readFile5, rename as rename2, rm as rm3, unlink, writeFile as writeFile5 } from "fs/promises";
1227
1377
  import { randomUUID as randomUUID2 } from "crypto";
1228
1378
  import path5 from "path";
1229
- import { z as z2 } from "zod";
1230
- var watchStateSchema = z2.object({
1231
- pid: z2.number().int().positive(),
1232
- version: z2.string().min(1),
1233
- startedAt: z2.string().datetime()
1234
- });
1235
- function getWatchStatePath(env) {
1236
- return path5.join(getConfigDir(env), "watch.json");
1379
+ function memoryDir(configPath, project) {
1380
+ 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);
1381
+ return path5.join(path5.dirname(configPath), "projects", project, "memory");
1237
1382
  }
1238
- async function readWatchState(filePath, io = fs) {
1383
+ function memoryEntryPath(entry) {
1384
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(entry.name)) throw new CliError("Invalid memory name in cache.", 2);
1385
+ if (entry.scope === "project" || entry.scope === "user") return `${entry.scope}/${entry.name}.md`;
1386
+ if (entry.scope !== "branch" || !entry.repoIdentity || !entry.branch) throw new CliError("Invalid memory scope in cache.", 2);
1387
+ 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);
1388
+ const repoDir = encodeURIComponent(entry.repoIdentity);
1389
+ if (Buffer.byteLength(repoDir) > 200) throw new CliError("Unsafe memory repo path.", 2);
1390
+ return `branch/${repoDir}/${entry.branch}/${entry.name}.md`;
1391
+ }
1392
+ function storableMemoryEntry(entry) {
1239
1393
  try {
1240
- const result = watchStateSchema.safeParse(JSON.parse(await io.readFile(filePath, "utf8")));
1241
- return result.success ? result.data : null;
1394
+ memoryEntryPath(entry);
1395
+ return true;
1242
1396
  } catch {
1243
- return null;
1397
+ return false;
1244
1398
  }
1245
1399
  }
1246
- async function writeWatchState(filePath, state, io = fs) {
1247
- await io.mkdir(path5.dirname(filePath), { recursive: true, mode: 448 });
1248
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1400
+ async function atomicMemoryFile(file, content) {
1401
+ await mkdir4(path5.dirname(file), { recursive: true, mode: 448 });
1402
+ const temp = `${file}.tmp-${randomUUID2()}`;
1249
1403
  try {
1250
- await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
1251
- await io.rename(tempPath, filePath);
1404
+ await writeFile5(temp, content, { mode: 292 });
1405
+ await unlink(file).catch((error) => {
1406
+ if (error.code !== "ENOENT") throw error;
1407
+ });
1408
+ await rename2(temp, file);
1409
+ } finally {
1410
+ await unlink(temp).catch(() => void 0);
1411
+ }
1412
+ }
1413
+ async function readMemoryCache(dir, project) {
1414
+ const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
1415
+ try {
1416
+ const state = JSON.parse(await readFile5(path5.join(dir, ".entries.json"), "utf8"));
1417
+ if (!Array.isArray(state.entries) || typeof state.scope !== "string" || typeof state.projectName !== "string") throw new Error("Invalid state");
1418
+ if (state.entries.some((e) => e == null || typeof e !== "object" || typeof e.id !== "string" || typeof e.name !== "string")) throw new Error("Invalid entry");
1419
+ let meta = empty.meta;
1420
+ try {
1421
+ meta = JSON.parse(await readFile5(path5.join(dir, ".meta.json"), "utf8"));
1422
+ } catch (error) {
1423
+ if (error.code !== "ENOENT") throw error;
1424
+ }
1425
+ if (!Number.isSafeInteger(meta.cursor) || meta.cursor < 0 || typeof meta.pulledAt !== "string") throw new Error("Invalid cursor");
1426
+ return { state, meta };
1252
1427
  } catch (error) {
1253
- await io.unlink(tempPath).catch(() => void 0);
1254
- throw error;
1428
+ if (error.code === "ENOENT") return empty;
1429
+ throw new CliError(`\u30E1\u30E2\u30EA\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u8AAD\u3081\u307E\u305B\u3093: ${String(error)}`, 2, "nolto memory pull");
1255
1430
  }
1256
1431
  }
1257
- async function removeWatchState(filePath, pid, io = fs) {
1258
- if ((await readWatchState(filePath, io))?.pid === pid) {
1259
- await io.unlink(filePath).catch(() => void 0);
1432
+ function mergeMemoryEntries(entries, updates) {
1433
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
1434
+ for (const entry of updates) {
1435
+ const old = byId.get(entry.id);
1436
+ if (!old || old.revision <= entry.revision) byId.set(entry.id, entry);
1260
1437
  }
1438
+ return [...byId.values()];
1261
1439
  }
1262
- function isAlive(pid, kill = process.kill) {
1263
- try {
1264
- kill(pid, 0);
1265
- return true;
1266
- } catch (error) {
1267
- if (error.code === "ESRCH") return false;
1268
- if (error.code === "EPERM") return true;
1269
- throw error;
1440
+ async function saveMemoryCache(dir, cache, previous, index, reset = false) {
1441
+ const unsafe = cache.state.entries.filter((e) => !storableMemoryEntry(e));
1442
+ if (reset) await rm3(dir, { recursive: true, force: true });
1443
+ const livePaths = new Set(cache.state.entries.filter((e) => !e.deleted && storableMemoryEntry(e)).map(memoryEntryPath));
1444
+ for (const entry of previous.filter(storableMemoryEntry)) {
1445
+ const relative = memoryEntryPath(entry);
1446
+ if (!livePaths.has(relative)) await rm3(path5.join(dir, relative), { force: true });
1447
+ }
1448
+ for (const entry of cache.state.entries) {
1449
+ if (!entry.deleted && storableMemoryEntry(entry)) await atomicMemoryFile(path5.join(dir, memoryEntryPath(entry)), formatMemory(entry));
1270
1450
  }
1451
+ await atomicMemoryFile(path5.join(dir, ".entries.json"), JSON.stringify(cache.state) + "\n");
1452
+ await atomicMemoryFile(path5.join(dir, "MEMORY.md"), index);
1453
+ await atomicMemoryFile(path5.join(dir, ".meta.json"), JSON.stringify(cache.meta) + "\n");
1454
+ return unsafe;
1271
1455
  }
1272
- async function staleWatchWarning(env, currentVersion, kill = process.kill) {
1273
- const state = await readWatchState(getWatchStatePath(env));
1274
- if (!state || state.version === currentVersion || !isAlive(state.pid, kill)) return null;
1275
- 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).`;
1456
+ function currentMemoryEntries(entries, context3, allBranches = false) {
1457
+ return entries.filter((e) => !e.deleted && storableMemoryEntry(e) && (e.scope !== "branch" || allBranches || context3.branch !== context3.defaultBranch && e.repoIdentity === context3.repoIdentity && e.branch === context3.branch));
1458
+ }
1459
+ var scopeOrder = ["project", "user", "branch"];
1460
+ function sortMemoryEntries(entries) {
1461
+ return entries.sort((a, b) => scopeOrder.indexOf(a.scope) - scopeOrder.indexOf(b.scope) || b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
1462
+ }
1463
+ function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
1464
+ const branch = context3.branch && context3.branch !== context3.defaultBranch ? context3.branch : null;
1465
+ const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3));
1466
+ const groups = ["project", "user", ...branch ? ["branch"] : []];
1467
+ 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)}`);
1468
+ let omitted = 0;
1469
+ const build = () => [
1470
+ `# 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)}` : ""})`,
1471
+ "\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",
1472
+ ...dir ? [`\u30AD\u30E3\u30C3\u30B7\u30E5: ${dir}`] : [],
1473
+ ...groups.flatMap((scope) => {
1474
+ const lines = entries.filter((e) => e.scope === scope).map((e) => `- ${e.name} \u2014 ${oneLine(e.description)}`);
1475
+ return lines.length ? [`## ${scope === "branch" ? `branch ${oneLine(branch)}` : scope}`, ...lines] : [];
1476
+ }),
1477
+ ...mergedLines,
1478
+ ...omitted ? [`\u6B8B\u308A ${omitted} \u4EF6: nolto memory list`] : []
1479
+ ];
1480
+ while (build().length > 200) {
1481
+ let project = -1;
1482
+ for (let i = entries.length - 1; i >= 0; i--) {
1483
+ if (entries[i].scope === "project") {
1484
+ project = i;
1485
+ break;
1486
+ }
1487
+ }
1488
+ if (entries.length) {
1489
+ entries.splice(project < 0 ? entries.length - 1 : project, 1);
1490
+ omitted++;
1491
+ } else {
1492
+ mergedLines.pop();
1493
+ omitted++;
1494
+ }
1495
+ }
1496
+ return build().join("\n") + "\n";
1276
1497
  }
1277
1498
 
1278
- // src/commands/init.ts
1279
- import readline2 from "readline/promises";
1280
- import { createRequire } from "module";
1281
- import { fileURLToPath as fileURLToPath2 } from "url";
1282
- import os3 from "os";
1283
- import path13 from "path";
1284
- import fs2 from "fs";
1285
-
1286
- // src/roadmap-bootstrap.ts
1287
- import { existsSync as existsSync3 } from "fs";
1288
- import { readFile as readFile6, realpath } from "fs/promises";
1289
- import path8 from "path";
1499
+ // src/memory-git.ts
1500
+ import { execFile as execFile2 } from "child_process";
1501
+ import { promisify } from "util";
1290
1502
 
1291
- // src/roadmap-cache.ts
1292
- import { mkdir as mkdir4, readdir as readdir2, readFile as readFile5, writeFile as writeFile5, rename as rename2, unlink } from "fs/promises";
1293
- import { randomUUID as randomUUID3 } from "crypto";
1503
+ // src/repo-identity.ts
1504
+ import { execFile } from "child_process";
1505
+ import { realpathSync } from "fs";
1294
1506
  import path7 from "path";
1295
1507
 
1296
- // src/sync-core.ts
1297
- import { createHash } from "crypto";
1298
- import path6 from "path";
1299
- function sha256Hex(content) {
1300
- return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1301
- }
1302
- function collectPlanRefs(roadmap) {
1303
- const seen = /* @__PURE__ */ new Set();
1304
- const refs = [];
1305
- for (const phase of roadmap.phases) {
1306
- if (phase.plan != null && !seen.has(phase.plan)) {
1307
- seen.add(phase.plan);
1308
- refs.push({ path: phase.plan, ownerId: phase.id });
1309
- }
1310
- for (const task of phase.tasks) {
1311
- if (task.plan != null && !seen.has(task.plan)) {
1312
- seen.add(task.plan);
1313
- refs.push({ path: task.plan, ownerId: task.id });
1314
- }
1315
- }
1316
- }
1317
- return refs;
1318
- }
1319
- async function loadValidRoadmap(filePath, readFile16) {
1320
- let raw;
1321
- try {
1322
- raw = await readFile16(filePath);
1323
- } catch {
1324
- throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1325
- }
1508
+ // src/machine-id.ts
1509
+ import { chmod, mkdir as mkdir5, readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
1510
+ import { randomUUID as randomUUID3 } from "crypto";
1511
+ import path6 from "path";
1512
+ var inFlightByConfigDir = /* @__PURE__ */ new Map();
1513
+ function parseMachineId(raw, file) {
1326
1514
  let parsed;
1327
1515
  try {
1328
1516
  parsed = JSON.parse(raw);
1329
1517
  } catch {
1330
- throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1518
+ throw new CliError(`Malformed JSON in ${file}. Remove the file to regenerate it.`, 2);
1331
1519
  }
1332
- const { errors } = validateRoadmap(parsed);
1333
- if (errors.length > 0) {
1334
- throw new CliError(
1335
- `${filePath} failed validation \u2014 not syncing:
1336
- ${errors.join("\n ")}`,
1337
- 2
1338
- );
1520
+ const id = parsed?.machineId;
1521
+ if (typeof id !== "string" || id.length === 0) {
1522
+ throw new CliError(`Invalid ${file}: missing machineId. Remove the file to regenerate it.`, 2);
1339
1523
  }
1340
- return parsed;
1524
+ return id;
1341
1525
  }
1342
- async function buildSyncBody(args) {
1343
- const planDocuments = [];
1344
- for (const ref of collectPlanRefs(args.roadmap)) {
1345
- if (!isValidPlanPath(ref.path)) {
1346
- args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1347
- continue;
1348
- }
1349
- try {
1350
- if (await args.deps.isIgnored?.(args.repoRoot, ref.path)) {
1351
- args.deps.warn(`plan path is git-ignored, skipping: ${ref.path}`);
1352
- continue;
1353
- }
1354
- } catch {
1355
- }
1356
- const root = path6.resolve(args.repoRoot);
1357
- const absolute = path6.resolve(root, ref.path);
1358
- if (absolute !== root && !absolute.startsWith(root + path6.sep)) {
1359
- args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1360
- continue;
1361
- }
1362
- if (!args.deps.fileExists(absolute)) {
1363
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1364
- continue;
1365
- }
1366
- if (args.deps.realpath !== void 0) {
1367
- let real;
1368
- let realRoot;
1369
- try {
1370
- real = await args.deps.realpath(absolute);
1371
- realRoot = await args.deps.realpath(root);
1372
- } catch {
1373
- args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1374
- continue;
1375
- }
1376
- if (real !== realRoot && !real.startsWith(realRoot + path6.sep)) {
1377
- args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1378
- continue;
1379
- }
1380
- if (!isValidPlanPath(path6.relative(realRoot, real).split(path6.sep).join("/"))) {
1381
- args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1382
- continue;
1383
- }
1526
+ async function loadOrCreate(configDir) {
1527
+ const file = path6.join(configDir, "machine.json");
1528
+ let raw = null;
1529
+ try {
1530
+ raw = await readFile6(file, "utf8");
1531
+ } catch (err) {
1532
+ const code = err.code;
1533
+ if (code !== "ENOENT") {
1534
+ throw new CliError(`Cannot read ${file}: ${String(err)}`, 2);
1384
1535
  }
1385
- const content = await args.deps.readFile(absolute);
1386
- planDocuments.push({
1387
- path: ref.path,
1388
- taskId: ref.ownerId,
1389
- content,
1390
- contentHash: sha256Hex(content)
1536
+ }
1537
+ if (raw !== null) {
1538
+ return parseMachineId(raw, file);
1539
+ }
1540
+ const machineId = randomUUID3();
1541
+ await mkdir5(configDir, { recursive: true, mode: 448 });
1542
+ try {
1543
+ await writeFile6(file, `${JSON.stringify({ machineId }, null, 2)}
1544
+ `, {
1545
+ flag: "wx",
1546
+ mode: 384
1391
1547
  });
1548
+ } catch (err) {
1549
+ if (err.code === "EEXIST") {
1550
+ return parseMachineId(await readFile6(file, "utf8"), file);
1551
+ }
1552
+ throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1392
1553
  }
1393
- return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1554
+ await chmod(file, 384);
1555
+ return machineId;
1394
1556
  }
1395
- async function runSync(args, deps) {
1396
- const body = await buildSyncBody({
1397
- roadmap: args.roadmap,
1398
- repoRoot: args.repoRoot,
1399
- repoIdentity: args.repoIdentity,
1400
- deps
1557
+ function loadOrCreateMachineId(configDir) {
1558
+ const key = path6.resolve(configDir);
1559
+ const existing = inFlightByConfigDir.get(key);
1560
+ if (existing !== void 0) return existing;
1561
+ const pending = loadOrCreate(key).finally(() => {
1562
+ if (inFlightByConfigDir.get(key) === pending) inFlightByConfigDir.delete(key);
1401
1563
  });
1402
- const response = await deps.http.put(
1403
- `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1404
- { ...body, baseRevision: args.baseRevision }
1405
- );
1406
- for (const warning of response.warnings ?? []) deps.warn(warning);
1407
- const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1408
- deps.log(
1409
- `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})` : ""}`
1410
- );
1411
- return response;
1564
+ inFlightByConfigDir.set(key, pending);
1565
+ return pending;
1412
1566
  }
1413
1567
 
1414
- // src/roadmap-cache.ts
1415
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1416
- var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1417
- function cacheDir(env, projectId) {
1418
- if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1419
- return path7.join(getConfigDir(env), "projects", projectId, "roadmaps");
1420
- }
1421
- function cachePaths(env, projectId, slug) {
1422
- if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1423
- const dir = cacheDir(env, projectId);
1424
- return { json: path7.join(dir, `${slug}.json`), meta: path7.join(dir, `${slug}.meta.json`) };
1568
+ // src/repo-identity.ts
1569
+ function defaultGetRemoteUrl(root) {
1570
+ return new Promise((resolve) => {
1571
+ execFile(
1572
+ "git",
1573
+ ["-C", root, "remote", "get-url", "origin"],
1574
+ { timeout: 5e3 },
1575
+ (err, stdout2) => {
1576
+ if (err) return resolve(null);
1577
+ const line2 = stdout2.split(/\r?\n/)[0]?.trim() ?? "";
1578
+ resolve(line2.length > 0 ? line2 : null);
1579
+ }
1580
+ );
1581
+ });
1425
1582
  }
1426
- async function listCachedSlugs(env, projectId) {
1583
+ async function resolveRepoIdentity(root, deps) {
1584
+ const remote = await deps.getRemoteUrl(root);
1585
+ const normalized = remote === null ? null : normalizeRemote(remote);
1586
+ if (normalized !== null) return { kind: "remote", value: normalized };
1587
+ const machineId = await deps.machineId();
1588
+ let canonicalRoot;
1427
1589
  try {
1428
- const entries = await readdir2(cacheDir(env, projectId), { withFileTypes: true });
1429
- return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
1430
- } catch (err) {
1431
- if (err.code === "ENOENT") return [];
1432
- throw err;
1590
+ canonicalRoot = realpathSync(root);
1591
+ } catch {
1592
+ canonicalRoot = path7.resolve(root);
1433
1593
  }
1594
+ return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1434
1595
  }
1435
- async function readCache(env, projectId, slug) {
1436
- const paths = cachePaths(env, projectId, slug);
1437
- let raw;
1596
+ function makeRepoIdentityResolver(deps) {
1597
+ return deps.repoIdentity ?? ((root) => resolveRepoIdentity(root, {
1598
+ getRemoteUrl: defaultGetRemoteUrl,
1599
+ machineId: () => loadOrCreateMachineId(getConfigDir(process.env))
1600
+ }));
1601
+ }
1602
+
1603
+ // src/memory-git.ts
1604
+ var runMemoryGit = async (args, root) => (await promisify(execFile2)("git", args, { cwd: root, timeout: 5e3 })).stdout.trim();
1605
+ async function memoryGitContext(root, deps) {
1606
+ const git = deps.memoryGit ?? runMemoryGit;
1607
+ const result = { repoIdentity: null, branch: null, defaultBranch: null };
1438
1608
  try {
1439
- raw = await readFile5(paths.json, "utf8");
1440
- } catch (err) {
1441
- if (err.code === "ENOENT") return null;
1442
- throw err;
1609
+ await git(["rev-parse", "--show-toplevel"], root);
1610
+ const identity = await makeRepoIdentityResolver(deps)(root);
1611
+ result.repoIdentity = `${identity.kind}:${identity.value}`;
1612
+ result.branch = await git(["symbolic-ref", "--quiet", "--short", "HEAD"], root).catch(() => null);
1613
+ const remote = await git(["symbolic-ref", "refs/remotes/origin/HEAD"], root).catch(() => "");
1614
+ if (remote.startsWith("refs/remotes/origin/")) result.defaultBranch = remote.slice("refs/remotes/origin/".length);
1615
+ else {
1616
+ for (const branch of ["main", "master"]) {
1617
+ try {
1618
+ await git(["show-ref", "--verify", `refs/heads/${branch}`], root);
1619
+ result.defaultBranch = branch;
1620
+ break;
1621
+ } catch {
1622
+ }
1623
+ }
1624
+ }
1625
+ } catch {
1443
1626
  }
1444
- let roadmap;
1627
+ return result;
1628
+ }
1629
+ async function mergedMemoryBranches(branches, context3, root, git, mine = /* @__PURE__ */ new Set()) {
1630
+ const merged = /* @__PURE__ */ new Set();
1631
+ if (!context3.defaultBranch || !context3.repoIdentity) return merged;
1632
+ const hasRef = async (ref) => {
1633
+ try {
1634
+ await git(["show-ref", "--verify", "--quiet", ref], root);
1635
+ return true;
1636
+ } catch (error) {
1637
+ if (error.code === 1) return false;
1638
+ throw error;
1639
+ }
1640
+ };
1641
+ let checkedOut, target, targetTip;
1445
1642
  try {
1446
- roadmap = JSON.parse(raw);
1643
+ 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)));
1644
+ target = await hasRef(`refs/heads/${context3.defaultBranch}`) ? `refs/heads/${context3.defaultBranch}` : `refs/remotes/origin/${context3.defaultBranch}`;
1645
+ targetTip = await git(["rev-parse", target], root);
1447
1646
  } catch {
1448
- throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
1647
+ return merged;
1449
1648
  }
1450
- const { errors } = validateRoadmap(roadmap);
1451
- if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1452
- let meta = null;
1453
- try {
1454
- const parsed = JSON.parse(await readFile5(paths.meta, "utf8"));
1455
- 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") {
1456
- throw new Error("Invalid cache metadata");
1457
- }
1458
- if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
1459
- throw new Error("Invalid currentTaskId");
1460
- }
1461
- if ("repoIdentity" in parsed && parsed.repoIdentity !== null && typeof parsed.repoIdentity !== "string") {
1462
- throw new Error("Invalid repoIdentity");
1463
- }
1464
- meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null, repoIdentity: parsed.repoIdentity ?? null };
1465
- } catch (err) {
1466
- if (err.code !== "ENOENT") {
1467
- throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
1649
+ for (const branch of branches) {
1650
+ if (branch === context3.defaultBranch || branch === context3.branch || checkedOut.has(branch)) continue;
1651
+ try {
1652
+ const local = `refs/heads/${branch}`;
1653
+ if (await hasRef(local)) {
1654
+ if (await git(["rev-parse", local], root) === targetTip) continue;
1655
+ await git(["merge-base", "--is-ancestor", local, target], root);
1656
+ merged.add(branch);
1657
+ } else if (mine.has(branch) && !await hasRef(`refs/remotes/origin/${branch}`)) merged.add(branch);
1658
+ } catch {
1468
1659
  }
1469
1660
  }
1470
- return { roadmap, meta, raw };
1471
- }
1472
- async function writeCache(env, projectId, slug, roadmap, meta) {
1473
- const paths = cachePaths(env, projectId, slug);
1474
- const raw = serializeRoadmap(roadmap);
1475
- const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
1476
- await mkdir4(cacheDir(env, projectId), { recursive: true, mode: 448 });
1477
- for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1478
- const temp = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1479
- try {
1480
- await writeFile5(temp, content, { mode: 384 });
1481
- await rename2(temp, filePath);
1482
- } finally {
1483
- await unlink(temp).catch(() => void 0);
1484
- }
1485
- }
1486
- }
1487
- function isDirty(entry) {
1488
- return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
1661
+ return merged;
1489
1662
  }
1490
1663
 
1491
- // src/roadmap-scaffold.ts
1492
- function slugifyProjectId(name) {
1493
- const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1494
- return slug.length > 0 ? slug : "project";
1664
+ // src/memory-import.ts
1665
+ function aiHeading(response) {
1666
+ const { entry, ai } = response;
1667
+ if (!ai || ai.action !== "merge" && ai.action !== "replace") return null;
1668
+ 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 ?? "")}`;
1495
1669
  }
1496
- function buildScaffold(projectName, repoBasename) {
1497
- return {
1498
- schemaVersion: 3,
1499
- project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
1500
- summary: "",
1501
- phases: []
1502
- };
1670
+ async function createMemoryContext(opts, recover = false) {
1671
+ const { projectId: project, root, git } = opts;
1672
+ const dir = memoryDir(opts.configPath, project);
1673
+ const cache = await readMemoryCache(dir, project).catch((error) => {
1674
+ if (!recover) throw error;
1675
+ return { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
1676
+ });
1677
+ return { project, dir, root, git, cache, api: `/api/projects/${project}/memory` };
1503
1678
  }
1504
-
1505
- // src/roadmap-bootstrap.ts
1506
- async function pullRoadmapCache(args) {
1507
- const { env, projectId, slug } = args;
1508
- const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
1509
- const validation = validateRoadmap(response.roadmap);
1510
- if (validation.errors.length > 0) {
1511
- throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
1512
- }
1513
- let existing;
1679
+ async function memoryIndexText(ctx, deps) {
1680
+ const entries = ctx.cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === ctx.git.repoIdentity);
1681
+ const branches = [...new Set(entries.map((e) => e.branch))];
1682
+ const userId = ctx.cache.state.userId;
1683
+ const mine = new Set(userId ? entries.filter((e) => e.updatedBy?.id === userId).map((e) => e.branch) : []);
1684
+ return memoryIndex(ctx.cache, ctx.git, await mergedMemoryBranches(branches, ctx.git, ctx.root, deps.memoryGit ?? runMemoryGit, mine), ctx.dir);
1685
+ }
1686
+ 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";
1687
+ async function updateCache(ctx, deps, entries, quiet = false) {
1688
+ const previous = ctx.cache.state.entries;
1514
1689
  try {
1515
- existing = await readCache(env, projectId, slug);
1516
- } catch (err) {
1517
- if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
1518
- existing = null;
1519
- }
1520
- if (existing && isDirty(existing) && !args.force) {
1521
- args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1690
+ ctx.cache.state.entries = mergeMemoryEntries(previous, entries);
1691
+ await saveMemoryCache(ctx.dir, ctx.cache, previous, await memoryIndexText(ctx, deps));
1692
+ return true;
1693
+ } catch {
1694
+ if (!quiet) process.stderr.write(cacheWarning);
1522
1695
  return false;
1523
1696
  }
1524
- const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
1525
- await writeCache(env, projectId, slug, response.roadmap, {
1526
- revision: response.revision,
1527
- pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
1528
- currentTaskId: response.currentTaskId,
1529
- repoIdentity: response.repoIdentity ?? null
1697
+ }
1698
+ function writtenEntries(ctx, response) {
1699
+ const tombstones = (response.affected ?? []).flatMap((a) => {
1700
+ const cached = a.deleted && a.entryId !== response.entry.id ? ctx.cache.state.entries.find((e) => e.id === a.entryId) : void 0;
1701
+ return cached ? [{ ...cached, deleted: true, revision: a.toRevision }] : [];
1530
1702
  });
1531
- args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
1532
- return true;
1703
+ return [response.entry, ...tombstones];
1533
1704
  }
1534
- async function ensureRoadmapCache(args) {
1535
- const { env, projectId } = args;
1536
- const identity = repoIdentityToString(args.repoIdentity);
1537
- const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1538
- const warn2 = (line2) => {
1539
- process.stderr.write(line2 + "\n");
1540
- };
1541
- const log = (line2) => args.log(`roadmap: ${line2}`);
1542
- if (list.roadmaps.length > 0) {
1543
- let skipped = false;
1544
- for (const { slug: slug2 } of list.roadmaps) {
1545
- if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
1705
+ async function scanMemoryDir(dir) {
1706
+ const ok = [], invalid = [];
1707
+ const seen = /* @__PURE__ */ new Map();
1708
+ 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))) {
1709
+ let original = file.name.slice(0, -3), name = original;
1710
+ try {
1711
+ const draft = parseMemory(await readFile7(path8.join(dir, file.name), "utf8"), true);
1712
+ original = draft.name || original;
1713
+ name = original.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+/, "").slice(0, 64);
1714
+ if (!name) throw new CliError(`name \u3092\u6B63\u898F\u5316\u3067\u304D\u307E\u305B\u3093: ${original}`, 2);
1715
+ validateDraft({ ...draft, name });
1716
+ const first = seen.get(name);
1717
+ if (first) throw new CliError(`import \u5185\u3067 name \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059(\u5148: ${first})\u3002`, 2);
1718
+ seen.set(name, file.name);
1719
+ ok.push({ file: file.name, name, original, draft: { ...draft, name } });
1720
+ } catch (error) {
1721
+ invalid.push({ file: file.name, name, original, status: "failed", message: error instanceof Error ? error.message : String(error) });
1546
1722
  }
1547
- if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1548
- if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1549
1723
  }
1550
- const basename = path8.basename(args.repoRoot);
1551
- const slug = args.slug ?? slugifyProjectId(basename);
1552
- const collision = list.roadmaps.find((row) => row.slug === slug);
1553
- if (collision) throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
1554
- let existing;
1555
- try {
1556
- existing = await readCache(env, projectId, slug);
1557
- } catch (err) {
1558
- if (!(err instanceof CliError)) throw err;
1559
- existing = null;
1724
+ return { ok, invalid };
1725
+ }
1726
+ function importResultLine(scope, result) {
1727
+ const { status, name, original, message } = result;
1728
+ return `${status} ${scope}/${name}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}`;
1729
+ }
1730
+ async function importMemoryFiles(opts) {
1731
+ const ctx = await createMemoryContext(opts, true);
1732
+ let imported = 0, skipped = 0, failed = 0, cached = true;
1733
+ const results = [];
1734
+ for (const { file, name, original, draft } of opts.targets) {
1735
+ let status, message, heading = null;
1736
+ try {
1737
+ const response = await opts.http.put(ctx.api, {
1738
+ scope: opts.scope,
1739
+ name,
1740
+ description: draft.description,
1741
+ body: draft.body,
1742
+ ...draft.type ? { type: draft.type } : {},
1743
+ allowNew: true,
1744
+ ...opts.ai ? {} : { aiSkip: true }
1745
+ }, { "X-Nolto-Client": detectMemoryClient(process.env) });
1746
+ cached = await updateCache(ctx, opts, writtenEntries(ctx, response), true) && cached;
1747
+ heading = aiHeading(response);
1748
+ imported++;
1749
+ status = "imported";
1750
+ } catch (error) {
1751
+ if (error instanceof CliError && error.serverError === "memory_exists") {
1752
+ skipped++;
1753
+ status = "skipped";
1754
+ if (error.body?.entry) cached = await updateCache(ctx, opts, [error.body.entry], true) && cached;
1755
+ } else {
1756
+ failed++;
1757
+ status = "failed";
1758
+ message = error instanceof Error ? error.message : String(error);
1759
+ }
1760
+ }
1761
+ const result = { file, name, original, status, ...message ? { message } : {} };
1762
+ results.push(result);
1763
+ opts.write(heading ? `${heading} (\u5143: ${oneLine(file)})` : importResultLine(opts.scope, result));
1560
1764
  }
1561
- if (existing && isDirty(existing)) {
1562
- warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1563
- throw new CliError("Roadmap has local changes that are not synced.", 4);
1765
+ return { imported, skipped, failed, results, cached };
1766
+ }
1767
+
1768
+ // src/commands/init.ts
1769
+ import { readFile as readFile11 } from "fs/promises";
1770
+
1771
+ // src/watch-state.ts
1772
+ import * as fs from "fs/promises";
1773
+ import { randomUUID as randomUUID4 } from "crypto";
1774
+ import path9 from "path";
1775
+ import { z as z2 } from "zod";
1776
+ var watchStateSchema = z2.object({
1777
+ pid: z2.number().int().positive(),
1778
+ version: z2.string().min(1),
1779
+ startedAt: z2.string().datetime()
1780
+ });
1781
+ function getWatchStatePath(env) {
1782
+ return path9.join(getConfigDir(env), "watch.json");
1783
+ }
1784
+ async function readWatchState(filePath, io = fs) {
1785
+ try {
1786
+ const result = watchStateSchema.safeParse(JSON.parse(await io.readFile(filePath, "utf8")));
1787
+ return result.success ? result.data : null;
1788
+ } catch {
1789
+ return null;
1564
1790
  }
1565
- const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
1566
- await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1567
- const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1568
- http: args.http,
1569
- readFile: (p) => readFile6(p, "utf8"),
1570
- realpath,
1571
- fileExists: existsSync3,
1572
- log: () => void 0,
1573
- warn: warn2
1574
- });
1575
- 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 });
1576
- log(`created ${slug} on server (rev ${response.revision})`);
1577
1791
  }
1578
- async function ensureProjectRepo(args) {
1579
- let repos;
1792
+ async function writeWatchState(filePath, state, io = fs) {
1793
+ await io.mkdir(path9.dirname(filePath), { recursive: true, mode: 448 });
1794
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID4()}`;
1580
1795
  try {
1581
- const project = await args.http.get(`/api/projects/${args.projectId}`);
1582
- repos = Array.isArray(project.repos) ? project.repos : [];
1796
+ await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
1797
+ await io.rename(tempPath, filePath);
1583
1798
  } catch (error) {
1584
- if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
1585
- process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
1586
- `);
1587
- return "unbound";
1799
+ await io.unlink(tempPath).catch(() => void 0);
1800
+ throw error;
1588
1801
  }
1589
- if (repos.length === 0) return "unbound";
1590
- const identity = repoIdentityToString(args.repoIdentity);
1591
- if (repos.some((repo) => repo.identity === identity)) return "bound";
1592
- 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";
1802
+ }
1803
+ async function removeWatchState(filePath, pid, io = fs) {
1804
+ if ((await readWatchState(filePath, io))?.pid === pid) {
1805
+ await io.unlink(filePath).catch(() => void 0);
1806
+ }
1807
+ }
1808
+ function isAlive(pid, kill = process.kill) {
1593
1809
  try {
1594
- await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
1810
+ kill(pid, 0);
1811
+ return true;
1595
1812
  } catch (error) {
1596
- if (error instanceof CliError) {
1597
- if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
1598
- if (error.status === 403) {
1599
- throw new CliError(
1600
- "Only the project owner can add a repository.",
1601
- 2,
1602
- "Ask the owner to run `nolto link --add` in this repository."
1603
- );
1604
- }
1605
- if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
1606
- }
1813
+ if (error.code === "ESRCH") return false;
1814
+ if (error.code === "EPERM") return true;
1607
1815
  throw error;
1608
1816
  }
1609
- args.log(`Added ${identity} to project.`);
1610
- return "added";
1817
+ }
1818
+ async function staleWatchWarning(env, currentVersion, kill = process.kill) {
1819
+ const state = await readWatchState(getWatchStatePath(env));
1820
+ if (!state || state.version === currentVersion || !isAlive(state.pid, kill)) return null;
1821
+ 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).`;
1611
1822
  }
1612
1823
 
1613
- // src/commands/link.ts
1614
- import readline from "readline/promises";
1615
- import os2 from "os";
1824
+ // src/commands/init.ts
1825
+ import readline2 from "readline/promises";
1826
+ import { createRequire } from "module";
1827
+ import { fileURLToPath as fileURLToPath2 } from "url";
1828
+ import os3 from "os";
1829
+ import path15 from "path";
1830
+ import fs2 from "fs";
1831
+
1832
+ // src/roadmap-bootstrap.ts
1833
+ import { existsSync as existsSync3 } from "fs";
1834
+ import { readFile as readFile9, realpath } from "fs/promises";
1616
1835
  import path12 from "path";
1617
- import { statSync as statSync2 } from "fs";
1618
1836
 
1619
- // src/registry.ts
1620
- import { readFile as readFile7, writeFile as writeFile6, mkdir as mkdir5, rename as rename3, unlink as unlink2 } from "fs/promises";
1621
- import { randomUUID as randomUUID4 } from "crypto";
1622
- import path9 from "path";
1623
- import { z as z3 } from "zod";
1624
- var registrySchema = z3.object({
1625
- schemaVersion: z3.literal(1),
1626
- repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
1627
- }).passthrough();
1628
- function getRegistryPath(env) {
1629
- return path9.join(getConfigDir(env), "registry.json");
1837
+ // src/roadmap-cache.ts
1838
+ import { mkdir as mkdir6, readdir as readdir4, readFile as readFile8, writeFile as writeFile7, rename as rename3, unlink as unlink2 } from "fs/promises";
1839
+ import { randomUUID as randomUUID5 } from "crypto";
1840
+ import path11 from "path";
1841
+
1842
+ // src/sync-core.ts
1843
+ import { createHash as createHash2 } from "crypto";
1844
+ import path10 from "path";
1845
+ function sha256Hex(content) {
1846
+ return "sha256:" + createHash2("sha256").update(content, "utf8").digest("hex");
1630
1847
  }
1631
- async function loadRegistry(filePath) {
1848
+ function collectPlanRefs(roadmap) {
1849
+ const seen = /* @__PURE__ */ new Set();
1850
+ const refs = [];
1851
+ for (const phase of roadmap.phases) {
1852
+ if (phase.plan != null && !seen.has(phase.plan)) {
1853
+ seen.add(phase.plan);
1854
+ refs.push({ path: phase.plan, ownerId: phase.id });
1855
+ }
1856
+ for (const task of phase.tasks) {
1857
+ if (task.plan != null && !seen.has(task.plan)) {
1858
+ seen.add(task.plan);
1859
+ refs.push({ path: task.plan, ownerId: task.id });
1860
+ }
1861
+ }
1862
+ }
1863
+ return refs;
1864
+ }
1865
+ async function loadValidRoadmap(filePath, readFile19) {
1632
1866
  let raw;
1633
1867
  try {
1634
- raw = await readFile7(filePath, "utf8");
1635
- } catch (err) {
1636
- const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1637
- if (code === "ENOENT") {
1638
- return { schemaVersion: 1, repos: [] };
1639
- }
1640
- throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
1868
+ raw = await readFile19(filePath);
1869
+ } catch {
1870
+ throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1641
1871
  }
1642
1872
  let parsed;
1643
1873
  try {
1644
1874
  parsed = JSON.parse(raw);
1645
1875
  } catch {
1646
- throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
1876
+ throw new CliError(`Malformed JSON in ${filePath}.`, 2);
1647
1877
  }
1648
- const result = registrySchema.safeParse(parsed);
1649
- if (!result.success) {
1650
- const issue = result.error.issues[0];
1651
- const fieldPath = issue?.path.join(".") ?? "";
1878
+ const { errors } = validateRoadmap(parsed);
1879
+ if (errors.length > 0) {
1652
1880
  throw new CliError(
1653
- `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
1654
- 2
1881
+ `${filePath} failed validation \u2014 not syncing:
1882
+ ${errors.join("\n ")}`,
1883
+ 2
1655
1884
  );
1656
1885
  }
1657
- return result.data;
1886
+ return parsed;
1658
1887
  }
1659
- async function addRepoToRegistry(filePath, entry) {
1660
- const registry = await loadRegistry(filePath);
1661
- const existing = registry.repos.find((repo) => repo.root === entry.root);
1662
- if (existing?.projectId === entry.projectId) {
1663
- return { added: false, updated: false, registry };
1888
+ async function buildSyncBody(args) {
1889
+ const planDocuments = [];
1890
+ for (const ref of collectPlanRefs(args.roadmap)) {
1891
+ if (!isValidPlanPath(ref.path)) {
1892
+ args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1893
+ continue;
1894
+ }
1895
+ try {
1896
+ if (await args.deps.isIgnored?.(args.repoRoot, ref.path)) {
1897
+ args.deps.warn(`plan path is git-ignored, skipping: ${ref.path}`);
1898
+ continue;
1899
+ }
1900
+ } catch {
1901
+ }
1902
+ const root = path10.resolve(args.repoRoot);
1903
+ const absolute = path10.resolve(root, ref.path);
1904
+ if (absolute !== root && !absolute.startsWith(root + path10.sep)) {
1905
+ args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1906
+ continue;
1907
+ }
1908
+ if (!args.deps.fileExists(absolute)) {
1909
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1910
+ continue;
1911
+ }
1912
+ if (args.deps.realpath !== void 0) {
1913
+ let real;
1914
+ let realRoot;
1915
+ try {
1916
+ real = await args.deps.realpath(absolute);
1917
+ realRoot = await args.deps.realpath(root);
1918
+ } catch {
1919
+ args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1920
+ continue;
1921
+ }
1922
+ if (real !== realRoot && !real.startsWith(realRoot + path10.sep)) {
1923
+ args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1924
+ continue;
1925
+ }
1926
+ if (!isValidPlanPath(path10.relative(realRoot, real).split(path10.sep).join("/"))) {
1927
+ args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1928
+ continue;
1929
+ }
1930
+ }
1931
+ const content = await args.deps.readFile(absolute);
1932
+ planDocuments.push({
1933
+ path: ref.path,
1934
+ taskId: ref.ownerId,
1935
+ content,
1936
+ contentHash: sha256Hex(content)
1937
+ });
1664
1938
  }
1665
- const updated = {
1666
- ...registry,
1667
- repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
1668
- };
1669
- await writeRegistry(filePath, updated);
1670
- return { added: !existing, updated: !!existing, registry: updated };
1939
+ return { roadmap: args.roadmap, planDocuments, repoIdentity: args.repoIdentity };
1671
1940
  }
1672
- async function writeRegistry(filePath, registry) {
1673
- await mkdir5(path9.dirname(filePath), { recursive: true, mode: 448 });
1674
- const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID4()}`;
1941
+ async function runSync(args, deps) {
1942
+ const body = await buildSyncBody({
1943
+ roadmap: args.roadmap,
1944
+ repoRoot: args.repoRoot,
1945
+ repoIdentity: args.repoIdentity,
1946
+ deps
1947
+ });
1948
+ const response = await deps.http.put(
1949
+ `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1950
+ { ...body, baseRevision: args.baseRevision }
1951
+ );
1952
+ for (const warning of response.warnings ?? []) deps.warn(warning);
1953
+ const stats = deriveTaskStats(response.roadmap ?? args.roadmap);
1954
+ deps.log(
1955
+ `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})` : ""}`
1956
+ );
1957
+ return response;
1958
+ }
1959
+
1960
+ // src/roadmap-cache.ts
1961
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1962
+ var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1963
+ function cacheDir(env, projectId) {
1964
+ if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1965
+ return path11.join(getConfigDir(env), "projects", projectId, "roadmaps");
1966
+ }
1967
+ function cachePaths(env, projectId, slug) {
1968
+ if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1969
+ const dir = cacheDir(env, projectId);
1970
+ return { json: path11.join(dir, `${slug}.json`), meta: path11.join(dir, `${slug}.meta.json`) };
1971
+ }
1972
+ async function listCachedSlugs(env, projectId) {
1675
1973
  try {
1676
- await writeFile6(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
1677
- await rename3(tempPath, filePath);
1974
+ const entries = await readdir4(cacheDir(env, projectId), { withFileTypes: true });
1975
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.name.endsWith(".meta.json")).map((entry) => entry.name.slice(0, -5)).sort();
1678
1976
  } catch (err) {
1679
- await unlink2(tempPath).catch(() => void 0);
1977
+ if (err.code === "ENOENT") return [];
1680
1978
  throw err;
1681
1979
  }
1682
1980
  }
1683
- async function removeRepoFromRegistry(filePath, root) {
1684
- const registry = await loadRegistry(filePath);
1685
- const repos = registry.repos.filter((repo) => repo.root !== root);
1686
- if (repos.length === registry.repos.length) return { removed: false, registry };
1687
- const updated = { ...registry, repos };
1688
- await writeRegistry(filePath, updated);
1689
- return { removed: true, registry: updated };
1690
- }
1691
-
1692
- // src/repo-identity.ts
1693
- import { execFile } from "child_process";
1694
- import { realpathSync } from "fs";
1695
- import path11 from "path";
1696
-
1697
- // src/machine-id.ts
1698
- import { chmod, mkdir as mkdir6, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
1699
- import { randomUUID as randomUUID5 } from "crypto";
1700
- import path10 from "path";
1701
- var inFlightByConfigDir = /* @__PURE__ */ new Map();
1702
- function parseMachineId(raw, file) {
1703
- let parsed;
1981
+ async function readCache(env, projectId, slug) {
1982
+ const paths = cachePaths(env, projectId, slug);
1983
+ let raw;
1704
1984
  try {
1705
- parsed = JSON.parse(raw);
1706
- } catch {
1707
- throw new CliError(`Malformed JSON in ${file}. Remove the file to regenerate it.`, 2);
1985
+ raw = await readFile8(paths.json, "utf8");
1986
+ } catch (err) {
1987
+ if (err.code === "ENOENT") return null;
1988
+ throw err;
1708
1989
  }
1709
- const id = parsed?.machineId;
1710
- if (typeof id !== "string" || id.length === 0) {
1711
- throw new CliError(`Invalid ${file}: missing machineId. Remove the file to regenerate it.`, 2);
1990
+ let roadmap;
1991
+ try {
1992
+ roadmap = JSON.parse(raw);
1993
+ } catch {
1994
+ throw new CliError(`Malformed JSON in ${paths.json}.`, 2);
1712
1995
  }
1713
- return id;
1714
- }
1715
- async function loadOrCreate(configDir) {
1716
- const file = path10.join(configDir, "machine.json");
1717
- let raw = null;
1996
+ const { errors } = validateRoadmap(roadmap);
1997
+ if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1998
+ let meta = null;
1718
1999
  try {
1719
- raw = await readFile8(file, "utf8");
2000
+ const parsed = JSON.parse(await readFile8(paths.meta, "utf8"));
2001
+ 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") {
2002
+ throw new Error("Invalid cache metadata");
2003
+ }
2004
+ if ("currentTaskId" in parsed && parsed.currentTaskId !== null && typeof parsed.currentTaskId !== "string") {
2005
+ throw new Error("Invalid currentTaskId");
2006
+ }
2007
+ if ("repoIdentity" in parsed && parsed.repoIdentity !== null && typeof parsed.repoIdentity !== "string") {
2008
+ throw new Error("Invalid repoIdentity");
2009
+ }
2010
+ meta = { ...parsed, currentTaskId: parsed.currentTaskId ?? null, repoIdentity: parsed.repoIdentity ?? null };
1720
2011
  } catch (err) {
1721
- const code = err.code;
1722
- if (code !== "ENOENT") {
1723
- throw new CliError(`Cannot read ${file}: ${String(err)}`, 2);
2012
+ if (err.code !== "ENOENT") {
2013
+ throw new CliError(`Invalid cache metadata at ${paths.meta}: ${String(err)}`, 2);
1724
2014
  }
1725
2015
  }
1726
- if (raw !== null) {
1727
- return parseMachineId(raw, file);
1728
- }
1729
- const machineId = randomUUID5();
1730
- await mkdir6(configDir, { recursive: true, mode: 448 });
1731
- try {
1732
- await writeFile7(file, `${JSON.stringify({ machineId }, null, 2)}
1733
- `, {
1734
- flag: "wx",
1735
- mode: 384
1736
- });
1737
- } catch (err) {
1738
- if (err.code === "EEXIST") {
1739
- return parseMachineId(await readFile8(file, "utf8"), file);
2016
+ return { roadmap, meta, raw };
2017
+ }
2018
+ async function writeCache(env, projectId, slug, roadmap, meta) {
2019
+ const paths = cachePaths(env, projectId, slug);
2020
+ const raw = serializeRoadmap(roadmap);
2021
+ const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
2022
+ await mkdir6(cacheDir(env, projectId), { recursive: true, mode: 448 });
2023
+ for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
2024
+ const temp = `${filePath}.tmp-${process.pid}-${randomUUID5()}`;
2025
+ try {
2026
+ await writeFile7(temp, content, { mode: 384 });
2027
+ await rename3(temp, filePath);
2028
+ } finally {
2029
+ await unlink2(temp).catch(() => void 0);
1740
2030
  }
1741
- throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1742
2031
  }
1743
- await chmod(file, 384);
1744
- return machineId;
1745
2032
  }
1746
- function loadOrCreateMachineId(configDir) {
1747
- const key = path10.resolve(configDir);
1748
- const existing = inFlightByConfigDir.get(key);
1749
- if (existing !== void 0) return existing;
1750
- const pending = loadOrCreate(key).finally(() => {
1751
- if (inFlightByConfigDir.get(key) === pending) inFlightByConfigDir.delete(key);
1752
- });
1753
- inFlightByConfigDir.set(key, pending);
1754
- return pending;
2033
+ function isDirty(entry) {
2034
+ return entry.meta === null || sha256Hex(entry.raw) !== entry.meta.contentHash;
1755
2035
  }
1756
2036
 
1757
- // src/repo-identity.ts
1758
- function defaultGetRemoteUrl(root) {
1759
- return new Promise((resolve) => {
1760
- execFile(
1761
- "git",
1762
- ["-C", root, "remote", "get-url", "origin"],
1763
- { timeout: 5e3 },
1764
- (err, stdout2) => {
1765
- if (err) return resolve(null);
1766
- const line2 = stdout2.split(/\r?\n/)[0]?.trim() ?? "";
1767
- resolve(line2.length > 0 ? line2 : null);
1768
- }
1769
- );
1770
- });
1771
- }
1772
- async function resolveRepoIdentity(root, deps) {
1773
- const remote = await deps.getRemoteUrl(root);
1774
- const normalized = remote === null ? null : normalizeRemote(remote);
1775
- if (normalized !== null) return { kind: "remote", value: normalized };
1776
- const machineId = await deps.machineId();
1777
- let canonicalRoot;
1778
- try {
1779
- canonicalRoot = realpathSync(root);
1780
- } catch {
1781
- canonicalRoot = path11.resolve(root);
1782
- }
1783
- return { kind: "local", value: `${machineId}:${canonicalRoot}` };
2037
+ // src/roadmap-scaffold.ts
2038
+ function slugifyProjectId(name) {
2039
+ const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
2040
+ return slug.length > 0 ? slug : "project";
1784
2041
  }
1785
- function makeRepoIdentityResolver(deps) {
1786
- return deps.repoIdentity ?? ((root) => resolveRepoIdentity(root, {
1787
- getRemoteUrl: defaultGetRemoteUrl,
1788
- machineId: () => loadOrCreateMachineId(getConfigDir(process.env))
1789
- }));
2042
+ function buildScaffold(projectName, repoBasename) {
2043
+ return {
2044
+ schemaVersion: 3,
2045
+ project: { id: slugifyProjectId(repoBasename), name: projectName, repository: repoBasename },
2046
+ summary: "",
2047
+ phases: []
2048
+ };
1790
2049
  }
1791
2050
 
1792
- // src/commands/link.ts
1793
- var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1794
- function resolveStartDir(env, cwd) {
1795
- const cpd = env["CLAUDE_PROJECT_DIR"];
1796
- return cpd != null && cpd.length > 0 ? cpd : cwd;
1797
- }
1798
- function dirHasGit(dir) {
2051
+ // src/roadmap-bootstrap.ts
2052
+ async function pullRoadmapCache(args) {
2053
+ const { env, projectId, slug } = args;
2054
+ const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
2055
+ const validation = validateRoadmap(response.roadmap);
2056
+ if (validation.errors.length > 0) {
2057
+ throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
2058
+ }
2059
+ let existing;
1799
2060
  try {
1800
- statSync2(path12.join(dir, ".git"));
1801
- return true;
1802
- } catch {
2061
+ existing = await readCache(env, projectId, slug);
2062
+ } catch (err) {
2063
+ if (!(err instanceof CliError) || !(args.force || args.recoverInvalid)) throw err;
2064
+ existing = null;
2065
+ }
2066
+ if (existing && isDirty(existing) && !args.force) {
2067
+ args.warn(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1803
2068
  return false;
1804
2069
  }
1805
- }
1806
- function findRepoRoot(startDir, hasGit = dirHasGit) {
2070
+ const unchanged = existing?.raw === serializeRoadmap(response.roadmap) && existing.meta?.revision === response.revision;
2071
+ await writeCache(env, projectId, slug, response.roadmap, {
2072
+ revision: response.revision,
2073
+ pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2074
+ currentTaskId: response.currentTaskId,
2075
+ repoIdentity: response.repoIdentity ?? null
2076
+ });
2077
+ args.log(unchanged ? `unchanged ${slug}` : `pulled ${slug} (rev ${response.revision})`);
2078
+ return true;
2079
+ }
2080
+ async function ensureRoadmapCache(args) {
2081
+ const { env, projectId } = args;
2082
+ const identity = repoIdentityToString(args.repoIdentity);
2083
+ const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
2084
+ const warn2 = (line2) => {
2085
+ process.stderr.write(line2 + "\n");
2086
+ };
2087
+ const log = (line2) => args.log(`roadmap: ${line2}`);
2088
+ if (list.roadmaps.length > 0) {
2089
+ let skipped = false;
2090
+ for (const { slug: slug2 } of list.roadmaps) {
2091
+ if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
2092
+ }
2093
+ if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
2094
+ if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
2095
+ }
2096
+ const basename = path12.basename(args.repoRoot);
2097
+ const slug = args.slug ?? slugifyProjectId(basename);
2098
+ const collision = list.roadmaps.find((row) => row.slug === slug);
2099
+ if (collision) throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
2100
+ let existing;
2101
+ try {
2102
+ existing = await readCache(env, projectId, slug);
2103
+ } catch (err) {
2104
+ if (!(err instanceof CliError)) throw err;
2105
+ existing = null;
2106
+ }
2107
+ if (existing && isDirty(existing)) {
2108
+ warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
2109
+ throw new CliError("Roadmap has local changes that are not synced.", 4);
2110
+ }
2111
+ const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
2112
+ await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
2113
+ const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
2114
+ http: args.http,
2115
+ readFile: (p) => readFile9(p, "utf8"),
2116
+ realpath,
2117
+ fileExists: existsSync3,
2118
+ log: () => void 0,
2119
+ warn: warn2
2120
+ });
2121
+ 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 });
2122
+ log(`created ${slug} on server (rev ${response.revision})`);
2123
+ }
2124
+ async function ensureProjectRepo(args) {
2125
+ let repos;
2126
+ try {
2127
+ const project = await args.http.get(`/api/projects/${args.projectId}`);
2128
+ repos = Array.isArray(project.repos) ? project.repos : [];
2129
+ } catch (error) {
2130
+ if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
2131
+ process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
2132
+ `);
2133
+ return "unbound";
2134
+ }
2135
+ if (repos.length === 0) return "unbound";
2136
+ const identity = repoIdentityToString(args.repoIdentity);
2137
+ if (repos.some((repo) => repo.identity === identity)) return "bound";
2138
+ 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";
2139
+ try {
2140
+ await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
2141
+ } catch (error) {
2142
+ if (error instanceof CliError) {
2143
+ if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
2144
+ if (error.status === 403) {
2145
+ throw new CliError(
2146
+ "Only the project owner can add a repository.",
2147
+ 2,
2148
+ "Ask the owner to run `nolto link --add` in this repository."
2149
+ );
2150
+ }
2151
+ if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
2152
+ }
2153
+ throw error;
2154
+ }
2155
+ args.log(`Added ${identity} to project.`);
2156
+ return "added";
2157
+ }
2158
+
2159
+ // src/commands/link.ts
2160
+ import readline from "readline/promises";
2161
+ import os2 from "os";
2162
+ import path14 from "path";
2163
+ import { statSync as statSync2 } from "fs";
2164
+
2165
+ // src/registry.ts
2166
+ import { readFile as readFile10, writeFile as writeFile8, mkdir as mkdir7, rename as rename4, unlink as unlink3 } from "fs/promises";
2167
+ import { randomUUID as randomUUID6 } from "crypto";
2168
+ import path13 from "path";
2169
+ import { z as z3 } from "zod";
2170
+ var registrySchema = z3.object({
2171
+ schemaVersion: z3.literal(1),
2172
+ repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
2173
+ }).passthrough();
2174
+ function getRegistryPath(env) {
2175
+ return path13.join(getConfigDir(env), "registry.json");
2176
+ }
2177
+ async function loadRegistry(filePath) {
2178
+ let raw;
2179
+ try {
2180
+ raw = await readFile10(filePath, "utf8");
2181
+ } catch (err) {
2182
+ const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
2183
+ if (code === "ENOENT") {
2184
+ return { schemaVersion: 1, repos: [] };
2185
+ }
2186
+ throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
2187
+ }
2188
+ let parsed;
2189
+ try {
2190
+ parsed = JSON.parse(raw);
2191
+ } catch {
2192
+ throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
2193
+ }
2194
+ const result = registrySchema.safeParse(parsed);
2195
+ if (!result.success) {
2196
+ const issue = result.error.issues[0];
2197
+ const fieldPath = issue?.path.join(".") ?? "";
2198
+ throw new CliError(
2199
+ `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
2200
+ 2
2201
+ );
2202
+ }
2203
+ return result.data;
2204
+ }
2205
+ async function addRepoToRegistry(filePath, entry) {
2206
+ const registry = await loadRegistry(filePath);
2207
+ const existing = registry.repos.find((repo) => repo.root === entry.root);
2208
+ if (existing?.projectId === entry.projectId) {
2209
+ return { added: false, updated: false, registry };
2210
+ }
2211
+ const updated = {
2212
+ ...registry,
2213
+ repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
2214
+ };
2215
+ await writeRegistry(filePath, updated);
2216
+ return { added: !existing, updated: !!existing, registry: updated };
2217
+ }
2218
+ async function writeRegistry(filePath, registry) {
2219
+ await mkdir7(path13.dirname(filePath), { recursive: true, mode: 448 });
2220
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID6()}`;
2221
+ try {
2222
+ await writeFile8(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
2223
+ await rename4(tempPath, filePath);
2224
+ } catch (err) {
2225
+ await unlink3(tempPath).catch(() => void 0);
2226
+ throw err;
2227
+ }
2228
+ }
2229
+ async function removeRepoFromRegistry(filePath, root) {
2230
+ const registry = await loadRegistry(filePath);
2231
+ const repos = registry.repos.filter((repo) => repo.root !== root);
2232
+ if (repos.length === registry.repos.length) return { removed: false, registry };
2233
+ const updated = { ...registry, repos };
2234
+ await writeRegistry(filePath, updated);
2235
+ return { removed: true, registry: updated };
2236
+ }
2237
+
2238
+ // src/commands/link.ts
2239
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2240
+ function resolveStartDir(env, cwd) {
2241
+ const cpd = env["CLAUDE_PROJECT_DIR"];
2242
+ return cpd != null && cpd.length > 0 ? cpd : cwd;
2243
+ }
2244
+ function dirHasGit(dir) {
2245
+ try {
2246
+ statSync2(path14.join(dir, ".git"));
2247
+ return true;
2248
+ } catch {
2249
+ return false;
2250
+ }
2251
+ }
2252
+ function findRepoRoot(startDir, hasGit = dirHasGit) {
1807
2253
  let current = startDir;
1808
2254
  while (true) {
1809
2255
  if (hasGit(current)) {
1810
2256
  return { root: current, foundGit: true };
1811
2257
  }
1812
- const parent = path12.dirname(current);
2258
+ const parent = path14.dirname(current);
1813
2259
  if (parent === current) break;
1814
2260
  current = parent;
1815
2261
  }
1816
2262
  return { root: startDir, foundGit: false };
1817
2263
  }
1818
2264
  function isHomeDirectory(dir, home = os2.homedir()) {
1819
- return path12.resolve(dir) === path12.resolve(home);
2265
+ return path14.resolve(dir) === path14.resolve(home);
1820
2266
  }
1821
2267
  async function handleShow(deps, projectBindingPath, mode2) {
1822
2268
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1915,10 +2361,10 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1915
2361
  }
1916
2362
  }
1917
2363
  async function handleUnlink(projectBindingPath, mode2) {
1918
- const { readFile: readFile16, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
2364
+ const { readFile: readFile19, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
1919
2365
  let existing = {};
1920
2366
  try {
1921
- const raw = await readFile16(projectBindingPath, "utf8");
2367
+ const raw = await readFile19(projectBindingPath, "utf8");
1922
2368
  const parsed = JSON.parse(raw);
1923
2369
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
1924
2370
  throw new CliError(
@@ -1962,7 +2408,7 @@ async function performLink(deps, projectId, mode2, slug, yes = false) {
1962
2408
  token: deps.settings.token,
1963
2409
  version: deps.version
1964
2410
  });
1965
- let projectName = path12.basename(root);
2411
+ let projectName = path14.basename(root);
1966
2412
  if (deps.settings.token != null) {
1967
2413
  try {
1968
2414
  const result = await http.get(
@@ -1990,7 +2436,7 @@ Proceeding anyway \u2014 verify the ID is correct.
1990
2436
  );
1991
2437
  }
1992
2438
  await writeRepoBinding(root, projectId);
1993
- const writtenPath = path12.join(root, "nolto.json");
2439
+ const writtenPath = path14.join(root, "nolto.json");
1994
2440
  let repoAdded = false;
1995
2441
  if (deps.settings.token == null) {
1996
2442
  process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
@@ -2174,13 +2620,13 @@ function invalidBindingError(projectBindingPath, error) {
2174
2620
  }
2175
2621
 
2176
2622
  // src/commands/init.ts
2177
- var __dirname2 = path13.dirname(fileURLToPath2(import.meta.url));
2623
+ var __dirname2 = path15.dirname(fileURLToPath2(import.meta.url));
2178
2624
  var _require = createRequire(import.meta.url);
2179
2625
  function getCliVersion() {
2180
2626
  const candidates = [
2181
- path13.resolve(__dirname2, "../package.json"),
2627
+ path15.resolve(__dirname2, "../package.json"),
2182
2628
  // bundled: dist/../package.json
2183
- path13.resolve(__dirname2, "../../package.json")
2629
+ path15.resolve(__dirname2, "../../package.json")
2184
2630
  // source: src/commands/../../package.json
2185
2631
  ];
2186
2632
  for (const pkgPath of candidates) {
@@ -2197,8 +2643,8 @@ function getCliVersion() {
2197
2643
  async function pickProject(rl, http, projects, promptText, baseUrl) {
2198
2644
  if (projects.length > 0) {
2199
2645
  process.stdout.write("\nProjects:\n");
2200
- projects.forEach((project, index2) => {
2201
- process.stdout.write(` (${index2 + 1}) ${project.name} \u2014 ${project.id}
2646
+ projects.forEach((project, index) => {
2647
+ process.stdout.write(` (${index + 1}) ${project.name} \u2014 ${project.id}
2202
2648
  `);
2203
2649
  });
2204
2650
  } else {
@@ -2218,16 +2664,16 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
2218
2664
  let organization = orgs[0];
2219
2665
  if (orgs.length > 1) {
2220
2666
  process.stdout.write("\nOrganizations:\n");
2221
- orgs.forEach((org, index3) => {
2222
- process.stdout.write(` (${index3 + 1}) ${org.name} \u2014 ${org.id}
2667
+ orgs.forEach((org, index2) => {
2668
+ process.stdout.write(` (${index2 + 1}) ${org.name} \u2014 ${org.id}
2223
2669
  `);
2224
2670
  });
2225
2671
  const choice = (await rl.question("Organization number: ")).trim();
2226
- const index2 = Number(choice);
2227
- if (!/^\d+$/.test(choice) || !Number.isSafeInteger(index2) || index2 < 1 || index2 > orgs.length) {
2672
+ const index = Number(choice);
2673
+ if (!/^\d+$/.test(choice) || !Number.isSafeInteger(index) || index < 1 || index > orgs.length) {
2228
2674
  throw new CliError("Invalid organization number.", 2);
2229
2675
  }
2230
- organization = orgs[index2 - 1];
2676
+ organization = orgs[index - 1];
2231
2677
  }
2232
2678
  const created = await http.post(
2233
2679
  "/api/projects",
@@ -2268,8 +2714,91 @@ async function selectRepoProject(rl, http, projects, defaultProjectId, baseUrl)
2268
2714
  baseUrl
2269
2715
  );
2270
2716
  }
2717
+ async function setupMemory(opts) {
2718
+ const { rl, root, projectId, http, deps, memory } = opts;
2719
+ if (memory === false) return;
2720
+ const agents = detectMemoryAgents(root);
2721
+ const scan = deps.claudeProjectsDir ? await scanMemoryDir(claudeMemoryDir(root, deps.claudeProjectsDir)).catch((error) => {
2722
+ if (error.code === "ENOENT") return { ok: [], invalid: [] };
2723
+ throw error;
2724
+ }) : { ok: [], invalid: [] };
2725
+ if (!scan.ok.length && !scan.invalid.length && (await Promise.all(agents.map((agent) => hasMemoryHook(root, agent)))).every(Boolean)) {
2726
+ process.stdout.write(`memory: \u8A2D\u5B9A\u6E08\u307F(hook ${agents.join(", ")})
2727
+ `);
2728
+ return;
2729
+ }
2730
+ if (memory !== true && (await rl.question("\u3053\u306E\u30EA\u30DD\u30B8\u30C8\u30EA\u306E\u30E1\u30E2\u30EA\u3092 Nolto \u3067\u7BA1\u7406\u3057\u307E\u3059\u304B? [Y/n] ")).trim().toLowerCase() === "n") {
2731
+ process.stdout.write("\u5F8C\u304B\u3089\u8A2D\u5B9A\u3059\u308B\u306B\u306F nolto memory hook install\n");
2732
+ return;
2733
+ }
2734
+ for (const message of await installMemoryHooks(root)) process.stdout.write(`memory: ${message}
2735
+ `);
2736
+ if (scan.invalid.length) {
2737
+ process.stdout.write(`\u53D6\u308A\u8FBC\u3081\u306A\u3044\u30E1\u30E2\u30EA ${scan.invalid.length} \u4EF6(\u672C\u6587\u3092\u5206\u3051\u308B\u304B\u8981\u70B9\u306B\u7D5E\u3063\u3066\u304B\u3089 nolto memory put \u3067\u767B\u9332\u3057\u3066\u304F\u3060\u3055\u3044):
2738
+ `);
2739
+ for (const invalid of scan.invalid) process.stdout.write(` - ${oneLine(invalid.file)} \u2014 ${oneLine(invalid.message)}
2740
+ `);
2741
+ }
2742
+ const ask = async (prompt) => memory === true && !process.stdin.isTTY ? "" : (await rl.question(prompt)).trim().toLowerCase();
2743
+ if (scan.ok.length) {
2744
+ const users = scan.ok.filter((target) => target.draft.type === "user").length;
2745
+ process.stdout.write(`Claude Code \u306E\u30E1\u30E2\u30EA\u304C ${scan.ok.length} \u4EF6\u3042\u308A\u307E\u3059(type user ${users} \u4EF6\u3001\u305D\u308C\u4EE5\u5916 ${scan.ok.length - users} \u4EF6)\u3002
2746
+ `);
2747
+ const choice = await ask("\u53D6\u308A\u8FBC\u307F\u307E\u3059\u304B? [a] type \u3067\u632F\u308A\u5206\u3051(user \u2192 user\u3001\u4ED6 \u2192 project) / [p] \u3059\u3079\u3066 project / [u] \u3059\u3079\u3066 user / [n] \u53D6\u308A\u8FBC\u307E\u306A\u3044 [a] ");
2748
+ if (choice !== "n") {
2749
+ const git = await memoryGitContext(root, deps);
2750
+ let imported = 0, skipped = 0, failed = 0, cached = true;
2751
+ for (const scope of ["project", "user"]) {
2752
+ const targets = scan.ok.filter((target) => (choice === "p" ? "project" : choice === "u" ? "user" : target.draft.type === "user" ? "user" : "project") === scope);
2753
+ if (!targets.length) continue;
2754
+ const result2 = await importMemoryFiles({
2755
+ http,
2756
+ projectId,
2757
+ configPath: deps.configPath,
2758
+ root,
2759
+ scope,
2760
+ targets,
2761
+ git,
2762
+ memoryGit: deps.memoryGit,
2763
+ write: (line2) => {
2764
+ process.stdout.write(line2 + "\n");
2765
+ }
2766
+ });
2767
+ imported += result2.imported;
2768
+ skipped += result2.skipped;
2769
+ failed += result2.failed;
2770
+ cached = result2.cached && cached;
2771
+ }
2772
+ process.stdout.write(`imported ${imported}, skipped ${skipped}, failed ${failed}
2773
+ `);
2774
+ if (!cached) process.stderr.write(cacheWarning);
2775
+ }
2776
+ }
2777
+ if (!agents.includes("claude")) return;
2778
+ const file = path15.join(root, ".claude", "settings.local.json");
2779
+ let settings = {};
2780
+ try {
2781
+ settings = JSON.parse(await readFile11(file, "utf8"));
2782
+ } catch (error) {
2783
+ if (error.code !== "ENOENT") {
2784
+ 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
2785
+ `);
2786
+ return;
2787
+ }
2788
+ }
2789
+ if (settings && typeof settings === "object" && !Array.isArray(settings) && "autoMemoryEnabled" in settings && settings.autoMemoryEnabled === false) {
2790
+ process.stdout.write("memory: Claude Code \u306E\u81EA\u52D5\u30E1\u30E2\u30EA\u505C\u6B62\u306F\u8A2D\u5B9A\u6E08\u307F\n");
2791
+ return;
2792
+ }
2793
+ if (await ask("Claude Code \u306E\u81EA\u52D5\u30E1\u30E2\u30EA\u3092\u6B62\u3081\u307E\u3059\u304B(Nolto \u3068\u306E\u4E8C\u91CD\u7BA1\u7406\u3092\u907F\u3051\u307E\u3059)? .claude/settings.local.json \u306B autoMemoryEnabled: false \u3092\u66F8\u304D\u307E\u3059 [Y/n] ") === "n") return;
2794
+ const result = await disableClaudeAutoMemory(root);
2795
+ if (result === "invalid") process.stderr.write(`Warning: ${file} \u304C\u4E0D\u6B63\u306A\u305F\u3081\u3001\u81EA\u52D5\u30E1\u30E2\u30EA\u306E\u8A2D\u5B9A\u3092\u7701\u7565\u3057\u307E\u3057\u305F\u3002
2796
+ `);
2797
+ 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"}
2798
+ `);
2799
+ }
2271
2800
  function register3(program, deps) {
2272
- program.command("init").description("Interactive setup: configure token, base URL, and default project.").option("--force", "Overwrite existing config without prompting").action(async (opts) => {
2801
+ 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) => {
2273
2802
  const configPath = deps.configPath;
2274
2803
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
2275
2804
  try {
@@ -2361,7 +2890,7 @@ Saved ${configPath}
2361
2890
  }
2362
2891
  if (isHomeDirectory(root)) {
2363
2892
  process.stderr.write(
2364
- `Refusing to set up your home directory as a repository root (found ${path13.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
2893
+ `Refusing to set up your home directory as a repository root (found ${path15.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
2365
2894
  `
2366
2895
  );
2367
2896
  return;
@@ -2393,7 +2922,7 @@ Saved ${configPath}
2393
2922
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
2394
2923
  );
2395
2924
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
2396
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path13.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2925
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path15.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2397
2926
  } else {
2398
2927
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2399
2928
  }
@@ -2407,7 +2936,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2407
2936
  process.stdout.write("Skipped repo setup.\n");
2408
2937
  return;
2409
2938
  }
2410
- const bindingPath = deps.repoBinding?.path ?? path13.join(root, "nolto.json");
2939
+ const bindingPath = deps.repoBinding?.path ?? path15.join(root, "nolto.json");
2411
2940
  if (keepExistingBinding) {
2412
2941
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
2413
2942
  `);
@@ -2419,32 +2948,30 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2419
2948
  );
2420
2949
  }
2421
2950
  await writeRepoBinding(root, repoProject.id);
2422
- process.stdout.write(`binding: wrote ${path13.join(root, "nolto.json")}
2951
+ process.stdout.write(`binding: wrote ${path15.join(root, "nolto.json")}
2423
2952
  `);
2424
2953
  }
2425
2954
  const sourceDir = resolveSkillSourceDir();
2426
- const version = getCliVersion();
2427
2955
  const claudeInstall = await installSkill({
2428
- skillsParentDir: path13.join(root, ".claude", "skills"),
2429
- sourceDir,
2430
- version
2956
+ skillsParentDir: path15.join(root, ".claude", "skills"),
2957
+ sourceDir
2431
2958
  });
2432
2959
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
2433
2960
  `);
2434
- const usesAgentsTooling = fs2.existsSync(path13.join(root, ".agents")) || fs2.existsSync(path13.join(root, ".codex")) || fs2.existsSync(path13.join(root, "AGENTS.md"));
2961
+ const usesAgentsTooling = fs2.existsSync(path15.join(root, ".agents")) || fs2.existsSync(path15.join(root, ".codex")) || fs2.existsSync(path15.join(root, "AGENTS.md"));
2435
2962
  if (usesAgentsTooling) {
2436
2963
  const agentsInstall = await installSkill({
2437
- skillsParentDir: path13.join(root, ".agents", "skills"),
2438
- sourceDir,
2439
- version
2964
+ skillsParentDir: path15.join(root, ".agents", "skills"),
2965
+ sourceDir
2440
2966
  });
2441
2967
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
2442
2968
  `);
2443
2969
  }
2444
- for (const memorySkill of await installMemorySkill(root, version)) {
2970
+ for (const memorySkill of await installMemorySkill(root)) {
2445
2971
  process.stdout.write(`skill (memory): ${memorySkill.action} ${memorySkill.targetDir}
2446
2972
  `);
2447
2973
  }
2974
+ await setupMemory({ rl, root, projectId: repoProject.id, http: repoHttp, deps, memory: opts.memory });
2448
2975
  const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2449
2976
  const repoResult = await ensureProjectRepo({
2450
2977
  http: repoHttp,
@@ -2714,13 +3241,13 @@ function register5(program, deps) {
2714
3241
  }
2715
3242
 
2716
3243
  // src/commands/sync.ts
2717
- import { execFile as execFile2 } from "child_process";
2718
- import { promisify } from "util";
2719
- import { readFile as readFile9, realpath as realpath2 } from "fs/promises";
3244
+ import { execFile as execFile3 } from "child_process";
3245
+ import { promisify as promisify2 } from "util";
3246
+ import { readFile as readFile12, realpath as realpath2 } from "fs/promises";
2720
3247
  import { existsSync as existsSync4 } from "fs";
2721
3248
 
2722
3249
  // src/roadmap-read.ts
2723
- import path14 from "path";
3250
+ import path16 from "path";
2724
3251
  async function resolveRoadmapReadContext(deps) {
2725
3252
  if (deps.settings.token == null) {
2726
3253
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
@@ -2730,7 +3257,7 @@ async function resolveRoadmapReadContext(deps) {
2730
3257
  if (!foundGit) {
2731
3258
  throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2732
3259
  }
2733
- const binding = await loadRepoBinding(path14.join(root, "nolto.json"));
3260
+ const binding = await loadRepoBinding(path16.join(root, "nolto.json"));
2734
3261
  const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2735
3262
  if (projectId == null) {
2736
3263
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
@@ -2760,12 +3287,12 @@ function buildGitLinksPayload(entries) {
2760
3287
  const keys = extractIssueKeys(entry.subject);
2761
3288
  const pr = extractPrNumber(entry.subject);
2762
3289
  const refs = [{ kind: "commit", ref: entry.ref }, ...pr ? [{ kind: "pr", ref: pr }] : []];
2763
- return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index2) => ({
3290
+ return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
2764
3291
  ...ref,
2765
3292
  title: entry.subject.slice(0, 500),
2766
3293
  author: entry.author.slice(0, 500),
2767
3294
  committedAt: entry.committedAt,
2768
- issueKeys: keys.slice(index2 * 20, (index2 + 1) * 20)
3295
+ issueKeys: keys.slice(index * 20, (index + 1) * 20)
2769
3296
  })));
2770
3297
  }) };
2771
3298
  }
@@ -2786,15 +3313,15 @@ async function collectGitLinks(root, exec) {
2786
3313
  }
2787
3314
 
2788
3315
  // src/sync-repo.ts
2789
- import path15 from "path";
2790
- import { readdir as readdir3 } from "fs/promises";
3316
+ import path17 from "path";
3317
+ import { readdir as readdir5 } from "fs/promises";
2791
3318
  function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2792
3319
  const planAbsPaths = /* @__PURE__ */ new Set();
2793
- const resolvedRoot = path15.resolve(root);
3320
+ const resolvedRoot = path17.resolve(root);
2794
3321
  for (const roadmap of roadmaps) {
2795
3322
  for (const ref of collectPlanRefs(roadmap)) {
2796
- const absolute = path15.resolve(resolvedRoot, ref.path);
2797
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path15.sep)) {
3323
+ const absolute = path17.resolve(resolvedRoot, ref.path);
3324
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path17.sep)) {
2798
3325
  warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2799
3326
  continue;
2800
3327
  }
@@ -2815,7 +3342,7 @@ async function syncRepo(args, io) {
2815
3342
  if (slugs.length === 0) {
2816
3343
  let legacyFiles = [];
2817
3344
  try {
2818
- legacyFiles = await readdir3(path15.join(args.root, ".nolto", "roadmaps"));
3345
+ legacyFiles = await readdir5(path17.join(args.root, ".nolto", "roadmaps"));
2819
3346
  } catch (err) {
2820
3347
  if (err.code !== "ENOENT") throw err;
2821
3348
  }
@@ -2922,11 +3449,11 @@ async function runSyncCommand(deps, opts = {}) {
2922
3449
  { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2923
3450
  {
2924
3451
  env: process.env,
2925
- readFile: (p) => readFile9(p, "utf8"),
3452
+ readFile: (p) => readFile12(p, "utf8"),
2926
3453
  realpath: (p) => realpath2(p),
2927
3454
  fileExists: (p) => existsSync4(p),
2928
3455
  repoIdentity: makeRepoIdentityResolver(deps),
2929
- exec: promisify(execFile2),
3456
+ exec: promisify2(execFile3),
2930
3457
  gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2931
3458
  http,
2932
3459
  log: (line2) => {
@@ -2936,10 +3463,8 @@ async function runSyncCommand(deps, opts = {}) {
2936
3463
  }
2937
3464
  );
2938
3465
  try {
2939
- const drifted = await checkSkillVersionDrift(root, deps.version);
2940
- if (drifted.length > 0) {
2941
- warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
2942
- }
3466
+ const drifted = await checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs });
3467
+ for (const warning of drifted) warn2(warning);
2943
3468
  } catch {
2944
3469
  }
2945
3470
  let registryAdded = false;
@@ -3135,11 +3660,15 @@ function register7(program, deps) {
3135
3660
  });
3136
3661
  }
3137
3662
 
3663
+ // src/commands/roadmap.ts
3664
+ import { readFile as readFile14 } from "fs/promises";
3665
+ import { existsSync as existsSync6 } from "fs";
3666
+
3138
3667
  // src/roadmap-commands.ts
3139
- import path16 from "path";
3668
+ import path18 from "path";
3140
3669
  import { existsSync as existsSync5 } from "fs";
3141
- import { readFile as readFile10, readdir as readdir4, writeFile as writeFile8, rename as rename4, unlink as unlink3, realpath as realpath3 } from "fs/promises";
3142
- import { randomUUID as randomUUID6 } from "crypto";
3670
+ import { readFile as readFile13, readdir as readdir6, writeFile as writeFile9, rename as rename5, unlink as unlink4, realpath as realpath3 } from "fs/promises";
3671
+ import { randomUUID as randomUUID7 } from "crypto";
3143
3672
  import readline4 from "readline/promises";
3144
3673
 
3145
3674
  // src/commands/pull.ts
@@ -3207,7 +3736,7 @@ async function selectRoadmap(deps, requestedSlug) {
3207
3736
  }
3208
3737
  async function roadmapPath(deps, slug) {
3209
3738
  const { paths } = await selectRoadmap(deps, slug);
3210
- printResult(path16.resolve(paths.json), deps.output.mode);
3739
+ printResult(path18.resolve(paths.json), deps.output.mode);
3211
3740
  }
3212
3741
  async function roadmapStatus(deps, slug, fresh = false) {
3213
3742
  const selected = await selectRoadmap(deps, slug);
@@ -3236,7 +3765,7 @@ async function roadmapValidate(deps, slug) {
3236
3765
  const { paths } = await selectRoadmap(deps, slug);
3237
3766
  let parsed;
3238
3767
  try {
3239
- parsed = JSON.parse(await readFile10(paths.json, "utf8"));
3768
+ parsed = JSON.parse(await readFile13(paths.json, "utf8"));
3240
3769
  } catch {
3241
3770
  throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
3242
3771
  }
@@ -3252,12 +3781,12 @@ async function roadmapSummary(deps, slug, text) {
3252
3781
  const selected = await selectRoadmap(deps, slug);
3253
3782
  const entry = await readCache(process.env, selected.projectId, selected.slug);
3254
3783
  entry.roadmap.summary = text;
3255
- const temp = `${selected.paths.json}.tmp-${randomUUID6()}`;
3784
+ const temp = `${selected.paths.json}.tmp-${randomUUID7()}`;
3256
3785
  try {
3257
- await writeFile8(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3258
- await rename4(temp, selected.paths.json);
3786
+ await writeFile9(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3787
+ await rename5(temp, selected.paths.json);
3259
3788
  } finally {
3260
- await unlink3(temp).catch(() => void 0);
3789
+ await unlink4(temp).catch(() => void 0);
3261
3790
  }
3262
3791
  await runSyncCommand(deps, { slug: selected.slug });
3263
3792
  }
@@ -3286,8 +3815,8 @@ async function roadmapTask(deps, taskId, slug, body) {
3286
3815
  const selected = await selectRoadmap(deps, slug);
3287
3816
  if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
3288
3817
  if (body.plan !== void 0) {
3289
- const absolute = path16.resolve(selected.root, body.plan);
3290
- if (!isValidPlanPath(body.plan) || !absolute.startsWith(path16.resolve(selected.root) + path16.sep)) {
3818
+ const absolute = path18.resolve(selected.root, body.plan);
3819
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path18.resolve(selected.root) + path18.sep)) {
3291
3820
  throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
3292
3821
  }
3293
3822
  if (!existsSync5(absolute)) warn(`WARN plan file not found at ${absolute}`);
@@ -3309,10 +3838,10 @@ async function roadmapEvents(deps, slug, opts) {
3309
3838
  }
3310
3839
  async function roadmapMigrate(deps, yes = false) {
3311
3840
  const { root, projectId } = await resolveRoadmapReadContext(deps);
3312
- const dir = path16.join(root, ".nolto", "roadmaps");
3841
+ const dir = path18.join(root, ".nolto", "roadmaps");
3313
3842
  let files;
3314
3843
  try {
3315
- files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
3844
+ files = (await readdir6(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
3316
3845
  } catch (error) {
3317
3846
  if (error.code !== "ENOENT") throw error;
3318
3847
  files = [];
@@ -3325,7 +3854,7 @@ async function roadmapMigrate(deps, yes = false) {
3325
3854
  for (const file of files) {
3326
3855
  const slug = file.slice(0, -5);
3327
3856
  cachePaths(process.env, projectId, slug);
3328
- const roadmap = await loadValidRoadmap(path16.join(dir, file), (p) => readFile10(p, "utf8"));
3857
+ const roadmap = await loadValidRoadmap(path18.join(dir, file), (p) => readFile13(p, "utf8"));
3329
3858
  roadmap.schemaVersion = 3;
3330
3859
  delete roadmap.updatedAt;
3331
3860
  delete roadmap.currentTaskId;
@@ -3357,7 +3886,7 @@ async function roadmapMigrate(deps, yes = false) {
3357
3886
  if (!unchanged) {
3358
3887
  const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
3359
3888
  http: deps.http,
3360
- readFile: (p) => readFile10(p, "utf8"),
3889
+ readFile: (p) => readFile13(p, "utf8"),
3361
3890
  realpath: realpath3,
3362
3891
  fileExists: existsSync5,
3363
3892
  log: () => void 0,
@@ -3375,7 +3904,7 @@ async function roadmapMigrate(deps, yes = false) {
3375
3904
  const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3376
3905
  let attributes = "";
3377
3906
  try {
3378
- attributes = await readFile10(path16.join(root, ".gitattributes"), "utf8");
3907
+ attributes = await readFile13(path18.join(root, ".gitattributes"), "utf8");
3379
3908
  } catch (error) {
3380
3909
  if (error.code !== "ENOENT") throw error;
3381
3910
  }
@@ -3394,6 +3923,11 @@ async function roadmapMigrate(deps, yes = false) {
3394
3923
  // src/commands/roadmap.ts
3395
3924
  function register9(program, deps) {
3396
3925
  const roadmap = program.command("roadmap").description("Read and update server roadmaps through the local cache.");
3926
+ roadmap.command("schema").description("Print the roadmap schema reference").action(async () => {
3927
+ const bundled = new URL("./roadmap-schema-reference.md", import.meta.url);
3928
+ const source = new URL("../roadmap-schema-reference.md", import.meta.url);
3929
+ process.stdout.write(await readFile14(existsSync6(bundled) ? bundled : source, "utf8"));
3930
+ });
3397
3931
  roadmap.command("path [slug]").description("Print the cached roadmap path").action((slug) => roadmapPath(deps, slug));
3398
3932
  roadmap.command("pull [slug]").description("Pull one roadmap, or all when slug is omitted").option("--all", "Pull all roadmaps (default without a slug)").option("--force", "Overwrite unsynced local changes").action((slug, opts) => runPull(deps, { ...opts, slug }));
3399
3933
  roadmap.command("sync [slug]").description("Push one roadmap, or all when slug is omitted").option("--no-git-links", "Skip commit / PR issue links").action((slug, opts) => runSyncCommand(deps, { ...opts, slug }).then(() => void 0));
@@ -3421,15 +3955,15 @@ function register9(program, deps) {
3421
3955
  }
3422
3956
 
3423
3957
  // src/commands/watch.ts
3424
- import { execFile as execFile3 } from "child_process";
3425
- import { promisify as promisify2 } from "util";
3426
- import { readFile as readFile11, realpath as realpath4 } from "fs/promises";
3427
- import { existsSync as existsSync6, mkdirSync } from "fs";
3428
- import path19 from "path";
3958
+ import { execFile as execFile4 } from "child_process";
3959
+ import { promisify as promisify3 } from "util";
3960
+ import { readFile as readFile15, realpath as realpath4 } from "fs/promises";
3961
+ import { existsSync as existsSync7, mkdirSync } from "fs";
3962
+ import path21 from "path";
3429
3963
  import chokidar from "chokidar";
3430
3964
 
3431
3965
  // src/watch-core.ts
3432
- import path17 from "path";
3966
+ import path19 from "path";
3433
3967
  var WatchSet = class {
3434
3968
  constructor(deps) {
3435
3969
  this.deps = deps;
@@ -3478,7 +4012,7 @@ async function reloadRoots(deps) {
3478
4012
  continue;
3479
4013
  }
3480
4014
  try {
3481
- const projectId = repo.projectId ?? (await loadRepoBinding(path17.join(repo.root, "nolto.json")))?.projectId;
4015
+ const projectId = repo.projectId ?? (await loadRepoBinding(path19.join(repo.root, "nolto.json")))?.projectId;
3482
4016
  if (projectId) repos.push({ root: repo.root, projectId });
3483
4017
  else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3484
4018
  } catch (err) {
@@ -3549,7 +4083,7 @@ var RepoWatch = class {
3549
4083
  };
3550
4084
 
3551
4085
  // src/service-install.ts
3552
- import path18 from "path";
4086
+ import path20 from "path";
3553
4087
  import os4 from "os";
3554
4088
  function buildUnitFile(args) {
3555
4089
  return [
@@ -3569,8 +4103,8 @@ function buildUnitFile(args) {
3569
4103
  }
3570
4104
  function getUnitPath(env) {
3571
4105
  const xdg = env["XDG_CONFIG_HOME"];
3572
- const base = xdg != null && xdg.length > 0 ? xdg : path18.join(os4.homedir(), ".config");
3573
- return path18.join(base, "systemd", "user", "nolto-watch.service");
4106
+ const base = xdg != null && xdg.length > 0 ? xdg : path20.join(os4.homedir(), ".config");
4107
+ return path20.join(base, "systemd", "user", "nolto-watch.service");
3574
4108
  }
3575
4109
  async function installServiceWith(deps) {
3576
4110
  if (deps.platform !== "linux") {
@@ -3581,7 +4115,7 @@ async function installServiceWith(deps) {
3581
4115
  );
3582
4116
  }
3583
4117
  const unitPath = getUnitPath(deps.env);
3584
- await deps.mkdir(path18.dirname(unitPath));
4118
+ await deps.mkdir(path20.dirname(unitPath));
3585
4119
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
3586
4120
  deps.log(`Wrote ${unitPath}`);
3587
4121
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -3603,7 +4137,7 @@ async function installService() {
3603
4137
  platform: process.platform,
3604
4138
  env: process.env,
3605
4139
  nodePath: process.execPath,
3606
- scriptPath: path18.resolve(process.argv[1] ?? ""),
4140
+ scriptPath: path20.resolve(process.argv[1] ?? ""),
3607
4141
  writeFile: (p, content) => writeFile12(p, content, "utf8"),
3608
4142
  mkdir: async (p) => {
3609
4143
  await mkdir9(p, { recursive: true });
@@ -3728,7 +4262,7 @@ function register10(program, deps) {
3728
4262
  const registryPath = getRegistryPath(process.env);
3729
4263
  const roots = await reloadRoots({
3730
4264
  load: () => loadRegistry(registryPath),
3731
- exists: existsSync6,
4265
+ exists: existsSync7,
3732
4266
  warn: (line2) => {
3733
4267
  process.stderr.write(`Warning: ${line2}
3734
4268
  `);
@@ -3745,7 +4279,7 @@ function register10(program, deps) {
3745
4279
  const startRepo = ({ root, projectId }) => {
3746
4280
  const roadmapsPath = cacheDir(process.env, projectId);
3747
4281
  const warn2 = (line2) => {
3748
- process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path19.basename(root)}] ${line2}
4282
+ process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path21.basename(root)}] ${line2}
3749
4283
  `);
3750
4284
  };
3751
4285
  mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
@@ -3755,14 +4289,14 @@ function register10(program, deps) {
3755
4289
  { root, projectId, onlyDirty },
3756
4290
  {
3757
4291
  env: process.env,
3758
- readFile: (p) => readFile11(p, "utf8"),
4292
+ readFile: (p) => readFile15(p, "utf8"),
3759
4293
  realpath: (p) => realpath4(p),
3760
- fileExists: (p) => existsSync6(p),
4294
+ fileExists: (p) => existsSync7(p),
3761
4295
  repoIdentity: makeRepoIdentityResolver(deps),
3762
- exec: promisify2(execFile3),
4296
+ exec: promisify3(execFile4),
3763
4297
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3764
4298
  http,
3765
- log: (line2) => process.stdout.write(`[${path19.basename(root)}] ${line2}
4299
+ log: (line2) => process.stdout.write(`[${path21.basename(root)}] ${line2}
3766
4300
  `),
3767
4301
  warn: warn2
3768
4302
  }
@@ -3775,13 +4309,11 @@ function register10(program, deps) {
3775
4309
  warn: (line2) => process.stderr.write(line2 + "\n")
3776
4310
  });
3777
4311
  watcher.on("all", (_event, filePath) => {
3778
- if (path19.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
4312
+ if (path21.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3779
4313
  repoWatch.handleEvent(filePath);
3780
4314
  });
3781
- void checkSkillVersionDrift(root, deps.version).then((drifted) => {
3782
- if (drifted.length > 0) {
3783
- warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
3784
- }
4315
+ void checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs }).then((drifted) => {
4316
+ for (const warning of drifted) warn2(warning);
3785
4317
  }).catch(() => {
3786
4318
  });
3787
4319
  void repoWatch.flush();
@@ -3806,7 +4338,7 @@ function register10(program, deps) {
3806
4338
  registryReloadTimer = null;
3807
4339
  void reloadRoots({
3808
4340
  load: () => loadRegistry(registryPath),
3809
- exists: (root) => existsSync6(root),
4341
+ exists: (root) => existsSync7(root),
3810
4342
  warn: (line2) => process.stderr.write(`Warning: ${line2}
3811
4343
  `)
3812
4344
  }).then(async (newRoots) => {
@@ -3843,7 +4375,7 @@ function register10(program, deps) {
3843
4375
  version: running ? state.version : null,
3844
4376
  startedAt: running ? state.startedAt : null,
3845
4377
  stale: running && state.version !== deps.version,
3846
- service: existsSync6(getUnitPath(process.env)) ? "installed" : "not-installed"
4378
+ service: existsSync7(getUnitPath(process.env)) ? "installed" : "not-installed"
3847
4379
  };
3848
4380
  printResult(deps.output.mode === "json" ? result : `${running ? "running" : "not running"}
3849
4381
  service: ${result.service}
@@ -3855,14 +4387,14 @@ stale: ${result.stale}`, deps.output.mode);
3855
4387
  watch.command("stop").description("Stop watch without disabling the installed service.").action(async () => {
3856
4388
  const statePath = getWatchStatePath(process.env);
3857
4389
  const state = await readWatchState(statePath);
3858
- const service = existsSync6(getUnitPath(process.env));
4390
+ const service = existsSync7(getUnitPath(process.env));
3859
4391
  let via = null;
3860
4392
  if (service) {
3861
4393
  await stopServiceWith({
3862
4394
  platform: process.platform,
3863
4395
  exec: async (cmd) => {
3864
4396
  try {
3865
- await promisify2(execFile3)(cmd[0], cmd.slice(1));
4397
+ await promisify3(execFile4)(cmd[0], cmd.slice(1));
3866
4398
  return { code: 0, stderr: "" };
3867
4399
  } catch (error) {
3868
4400
  const e = error;
@@ -3893,11 +4425,11 @@ stale: ${result.stale}`, deps.output.mode);
3893
4425
  });
3894
4426
  watch.command("list").description("List repositories in the watch registry.").action(async () => {
3895
4427
  const registry = await loadRegistry(getRegistryPath(process.env));
3896
- const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync6(repo.root) }));
4428
+ const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync7(repo.root) }));
3897
4429
  printResult(deps.output.mode === "json" ? { repos } : repos.map((repo) => `${repo.root} ${repo.projectId ?? "\u2014"}${repo.exists ? "" : " (missing)"}`).join("\n"), deps.output.mode);
3898
4430
  });
3899
4431
  watch.command("remove [root]").description("Remove a repository from the watch registry.").action(async (arg) => {
3900
- const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path19.resolve(arg);
4432
+ const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path21.resolve(arg);
3901
4433
  const { removed } = await removeRepoFromRegistry(getRegistryPath(process.env), root);
3902
4434
  if (!removed) throw new CliError(`${root} is not in the watch registry.`, 2, "Run `nolto watch list` to see registered repositories.");
3903
4435
  printResult(deps.output.mode === "json" ? { removed: true, root } : `Removed ${root} from the watch registry.`, deps.output.mode);
@@ -3905,18 +4437,18 @@ stale: ${result.stale}`, deps.output.mode);
3905
4437
  }
3906
4438
 
3907
4439
  // src/update-cli.ts
3908
- import { execFile as execFile4 } from "child_process";
3909
- import { existsSync as existsSync7 } from "fs";
4440
+ import { execFile as execFile5 } from "child_process";
4441
+ import { existsSync as existsSync8 } from "fs";
3910
4442
  import { realpath as realpath5 } from "fs/promises";
3911
4443
  import { createRequire as createRequire2 } from "module";
3912
- import path21 from "path";
4444
+ import path23 from "path";
3913
4445
  import { fileURLToPath as fileURLToPath3 } from "url";
3914
- import { promisify as promisify3 } from "util";
4446
+ import { promisify as promisify4 } from "util";
3915
4447
 
3916
4448
  // src/update-notifier.ts
3917
- import { readFile as readFile12, writeFile as writeFile9, mkdir as mkdir7 } from "fs/promises";
4449
+ import { readFile as readFile16, writeFile as writeFile10, mkdir as mkdir8 } from "fs/promises";
3918
4450
  import https from "https";
3919
- import path20 from "path";
4451
+ import path22 from "path";
3920
4452
  var PACKAGE = "@nolto/cli";
3921
4453
  var CACHE_FILE = "update-check.json";
3922
4454
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -3974,9 +4506,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3974
4506
  });
3975
4507
  }
3976
4508
  async function writeUpdateCache(cachePath, now, latest2) {
3977
- await mkdir7(path20.dirname(cachePath), { recursive: true });
4509
+ await mkdir8(path22.dirname(cachePath), { recursive: true });
3978
4510
  const payload = { checkedAt: now, latest: latest2 };
3979
- await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
4511
+ await writeFile10(cachePath, JSON.stringify(payload), { mode: 384 });
3980
4512
  }
3981
4513
  async function refreshCache(cachePath, now, fetchLatest) {
3982
4514
  const latest2 = await fetchLatest();
@@ -3985,10 +4517,10 @@ async function refreshCache(cachePath, now, fetchLatest) {
3985
4517
  }
3986
4518
  async function checkForUpdate(opts) {
3987
4519
  if (isDisabled(opts.env)) return null;
3988
- const cachePath = path20.join(opts.configDir, CACHE_FILE);
4520
+ const cachePath = path22.join(opts.configDir, CACHE_FILE);
3989
4521
  let cache = {};
3990
4522
  try {
3991
- cache = JSON.parse(await readFile12(cachePath, "utf8"));
4523
+ cache = JSON.parse(await readFile16(cachePath, "utf8"));
3992
4524
  } catch {
3993
4525
  }
3994
4526
  if (typeof cache.checkedAt !== "number" || opts.now - cache.checkedAt > CACHE_TTL_MS) {
@@ -4093,7 +4625,7 @@ async function updateCliWith(deps) {
4093
4625
  }
4094
4626
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
4095
4627
  await deps.writeCache(
4096
- path21.join(deps.configDir, UPDATE_CACHE_FILE),
4628
+ path23.join(deps.configDir, UPDATE_CACHE_FILE),
4097
4629
  deps.now,
4098
4630
  latest2
4099
4631
  ).catch(() => void 0);
@@ -4124,17 +4656,17 @@ async function updateCliWith(deps) {
4124
4656
  };
4125
4657
  }
4126
4658
  function getCurrentVersion() {
4127
- const dirname = path21.dirname(fileURLToPath3(import.meta.url));
4659
+ const dirname = path23.dirname(fileURLToPath3(import.meta.url));
4128
4660
  const require3 = createRequire2(import.meta.url);
4129
4661
  try {
4130
- const pkg = require3(path21.resolve(dirname, "../package.json"));
4662
+ const pkg = require3(path23.resolve(dirname, "../package.json"));
4131
4663
  return pkg.version ?? "0.0.0";
4132
4664
  } catch {
4133
4665
  return "0.0.0";
4134
4666
  }
4135
4667
  }
4136
4668
  async function updateCli(opts = {}) {
4137
- const execFileAsync = promisify3(execFile4);
4669
+ const execFileAsync = promisify4(execFile5);
4138
4670
  const scriptPath = await realpath5(process.argv[1] ?? "");
4139
4671
  return updateCliWith({
4140
4672
  currentVersion: getCurrentVersion(),
@@ -4159,7 +4691,7 @@ async function updateCli(opts = {}) {
4159
4691
  realpath: realpath5,
4160
4692
  fetchLatest: () => fetchLatestFromRegistry(UPDATE_REQUEST_TIMEOUT_MS, UPDATE_FETCH_OPTIONS),
4161
4693
  writeCache: writeUpdateCache,
4162
- unitExists: existsSync7,
4694
+ unitExists: existsSync8,
4163
4695
  log: opts.quiet === true ? () => void 0 : (line2) => process.stdout.write(line2 + "\n"),
4164
4696
  warn: (line2) => process.stderr.write("Warning: " + line2 + "\n")
4165
4697
  });
@@ -4177,7 +4709,7 @@ function register11(program, deps) {
4177
4709
  }
4178
4710
 
4179
4711
  // src/commands/merge-file.ts
4180
- import { readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
4712
+ import { readFile as readFile17, writeFile as writeFile11 } from "fs/promises";
4181
4713
 
4182
4714
  // src/roadmap-merge.ts
4183
4715
  import { isDeepStrictEqual } from "util";
@@ -4269,7 +4801,7 @@ function mergeTask(args) {
4269
4801
  const dependsOn = [
4270
4802
  ...args.ours.dependsOn ?? [],
4271
4803
  ...args.theirs.dependsOn ?? []
4272
- ].filter((id, index2, values) => values.indexOf(id) === index2);
4804
+ ].filter((id, index, values) => values.indexOf(id) === index);
4273
4805
  if (dependsOn.length > 0) merged.dependsOn = dependsOn;
4274
4806
  const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
4275
4807
  if (issues.length > 0) merged.issues = issues;
@@ -4283,456 +4815,180 @@ function shouldKeep(base, ours, theirs) {
4283
4815
  return true;
4284
4816
  }
4285
4817
  function orderTasks(args) {
4286
- const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
4287
- const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
4288
- const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
4289
- let nearestCommon = null;
4290
- let insertAfter = null;
4291
- for (const task of theirsPhase?.tasks ?? []) {
4292
- if (!args.taskIds.has(task.id)) continue;
4293
- if (args.oursLocations.has(task.id)) {
4294
- if (ordered.includes(task.id)) {
4295
- nearestCommon = task.id;
4296
- insertAfter = task.id;
4297
- }
4298
- continue;
4299
- }
4300
- if (nearestCommon === null || insertAfter === null) {
4301
- ordered.push(task.id);
4302
- continue;
4303
- }
4304
- const index2 = ordered.indexOf(insertAfter);
4305
- ordered.splice(index2 + 1, 0, task.id);
4306
- insertAfter = task.id;
4307
- }
4308
- return ordered;
4309
- }
4310
- function mergeRoadmaps(args) {
4311
- const newer = Date.parse(args.theirs.updatedAt ?? "") > Date.parse(args.ours.updatedAt ?? "") ? "theirs" : "ours";
4312
- const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
4313
- const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
4314
- const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
4315
- const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
4316
- const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
4317
- const baseLocations = taskLocations(args.base);
4318
- const oursLocations = taskLocations(args.ours);
4319
- const theirsLocations = taskLocations(args.theirs);
4320
- const keptTasks = /* @__PURE__ */ new Map();
4321
- const targetPhaseByTask = /* @__PURE__ */ new Map();
4322
- const taskIds = /* @__PURE__ */ new Set([
4323
- ...baseLocations.keys(),
4324
- ...oursLocations.keys(),
4325
- ...theirsLocations.keys()
4326
- ]);
4327
- for (const taskId of taskIds) {
4328
- const baseLocation = baseLocations.get(taskId);
4329
- const oursLocation = oursLocations.get(taskId);
4330
- const theirsLocation = theirsLocations.get(taskId);
4331
- if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
4332
- const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
4333
- base: baseLocation?.task,
4334
- ours: oursLocation.task,
4335
- theirs: theirsLocation.task,
4336
- newer
4337
- }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
4338
- keptTasks.set(taskId, task);
4339
- targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
4340
- }
4341
- const keptPhaseIds = /* @__PURE__ */ new Set();
4342
- const allPhaseIds = /* @__PURE__ */ new Set([
4343
- ...basePhases.keys(),
4344
- ...oursPhases.keys(),
4345
- ...theirsPhases.keys()
4346
- ]);
4347
- for (const phaseId of allPhaseIds) {
4348
- if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
4349
- keptPhaseIds.add(phaseId);
4350
- }
4351
- }
4352
- const phaseOrder = [
4353
- ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
4354
- ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
4355
- ];
4356
- const phases = phaseOrder.map((phaseId) => {
4357
- const base = basePhases.get(phaseId);
4358
- const ours = oursPhases.get(phaseId);
4359
- const theirs = theirsPhases.get(phaseId);
4360
- const source = ours ?? theirs;
4361
- const title = ours !== void 0 && theirs !== void 0 ? chooseField({
4362
- baseExists: base !== void 0,
4363
- base: base?.title,
4364
- ours: ours.title,
4365
- theirs: theirs.title,
4366
- newer
4367
- }) : source.title;
4368
- const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
4369
- baseExists: base !== void 0,
4370
- base: base?.plan,
4371
- ours: ours.plan,
4372
- theirs: theirs.plan,
4373
- newer
4374
- }) : source.plan;
4375
- const phaseTaskIds = new Set(
4376
- [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
4377
- );
4378
- const tasks = orderTasks({
4379
- phaseId,
4380
- taskIds: phaseTaskIds,
4381
- ours: args.ours,
4382
- theirs: args.theirs,
4383
- oursLocations
4384
- }).map((taskId) => keptTasks.get(taskId));
4385
- const phase = { id: phaseId, title, status: "todo", tasks };
4386
- if (plan !== void 0) phase.plan = plan;
4387
- phase.status = derivePhaseStatus(phase);
4388
- return phase;
4389
- });
4390
- const mergedTasks = new Map(
4391
- phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
4392
- );
4393
- const validCurrentTask = (roadmap) => {
4394
- const id = roadmap.currentTaskId ?? null;
4395
- return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
4396
- };
4397
- const merged = {
4398
- schemaVersion: newerRoadmap.updatedAt === void 0 ? 3 : 2,
4399
- project: { ...newerRoadmap.project },
4400
- updatedAt: newerRoadmap.updatedAt,
4401
- currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
4402
- summary: newerRoadmap.summary,
4403
- phases
4404
- };
4405
- const validation = validateRoadmap(merged);
4406
- if (validation.errors.length > 0) {
4407
- throw new CliError(
4408
- `Merged roadmap failed validation:
4409
- ${validation.errors.join("\n ")}`,
4410
- 1
4411
- );
4412
- }
4413
- return merged;
4414
- }
4415
-
4416
- // src/commands/merge-file.ts
4417
- async function readRoadmap(filePath) {
4418
- let parsed;
4419
- try {
4420
- parsed = JSON.parse(await readFile13(filePath, "utf8"));
4421
- } catch (err) {
4422
- const message = err instanceof SyntaxError ? "malformed JSON" : String(err);
4423
- throw new CliError(`${filePath}: ${message}`, 1);
4424
- }
4425
- const validation = validateRoadmap(parsed);
4426
- if (validation.errors.length > 0) {
4427
- throw new CliError(
4428
- `${filePath} failed validation:
4429
- ${validation.errors.join("\n ")}`,
4430
- 1
4431
- );
4432
- }
4433
- return parsed;
4434
- }
4435
- function register12(program) {
4436
- program.command("merge-file <ours> <theirs>").description(
4437
- 'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
4438
- ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
4439
- process.stderr.write("Warning: merge-file is deprecated and will be removed; roadmaps are no longer stored in git.\n");
4440
- const ours = await readRoadmap(oursPath);
4441
- const theirs = await readRoadmap(theirsPath);
4442
- const base = opts.base == null ? null : await readRoadmap(opts.base);
4443
- const merged = mergeRoadmaps({ base, ours, theirs });
4444
- await writeFile10(
4445
- opts.output ?? oursPath,
4446
- JSON.stringify(merged, null, 2) + "\n",
4447
- "utf8"
4448
- );
4449
- const taskCount = merged.phases.reduce((total, phase) => total + phase.tasks.length, 0);
4450
- process.stderr.write(`merged roadmap (${taskCount} tasks)
4451
- `);
4452
- process.exitCode = 0;
4453
- });
4454
- }
4455
-
4456
- // src/commands/memory.ts
4457
- import { readFile as readFile15, readdir as readdir5 } from "fs/promises";
4458
- import path23 from "path";
4459
-
4460
- // src/memory-format.ts
4461
- var oneLine = (value) => value.replace(/[\r\n\u0085\u2028\u2029]/g, " ");
4462
- var shellArg = (value) => /^[A-Za-z0-9._/-]+$/.test(value) ? value : JSON.stringify(value);
4463
- var memoryClient = (via) => via?.client || via?.tokenName || "Web";
4464
- function parseMemory(text, importing = false) {
4465
- const lines = text.replace(/\r\n/g, "\n").split("\n");
4466
- if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
4467
- if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
4468
- const end = lines.indexOf("---");
4469
- if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
4470
- const fields = {};
4471
- let metadata = false;
4472
- for (const line2 of lines.slice(0, end)) {
4473
- const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
4474
- if (!match) continue;
4475
- const indent = match[1], key = match[2], raw = match[3];
4476
- if (!indent) metadata = key === "metadata";
4477
- if (indent && !(importing && metadata && key === "type")) continue;
4478
- let value = raw.trim();
4479
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
4480
- if (["name", "description", "type", "scope", "branch", "revision"].includes(key)) fields[key] = value;
4481
- }
4482
- const body = lines.slice(end + 1);
4483
- if (body[0] === "") body.shift();
4484
- return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
4485
- }
4486
- function formatMemory(entry) {
4487
- const value = (s) => {
4488
- const safe = oneLine(s);
4489
- return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
4490
- };
4491
- return [
4492
- "<!-- 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 -->",
4493
- "---",
4494
- `name: ${entry.name}`,
4495
- `description: ${value(entry.description)}`,
4496
- ...entry.type == null ? [] : [`type: ${entry.type}`],
4497
- `scope: ${entry.scope}`,
4498
- ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
4499
- `revision: ${entry.revision}`,
4500
- `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
4501
- "---",
4502
- "",
4503
- entry.body
4504
- ].join("\n");
4505
- }
4506
- function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
4507
- if (scope !== "project" && scope !== "user" && scope !== "branch") {
4508
- throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
4509
- }
4510
- return scope;
4511
- }
4512
- var count = (n) => n.toLocaleString("en-US");
4513
- var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
4514
- function validateDraft(draft) {
4515
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
4516
- 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");
4517
- }
4518
- const description = draft.description.trim();
4519
- 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");
4520
- 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");
4521
- 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");
4522
- 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");
4523
- if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
4524
- 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");
4525
- }
4526
- }
4527
- function parseRevision(value) {
4528
- const revision = Number(value);
4529
- 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);
4530
- return revision;
4531
- }
4532
- function detectMemoryClient(env) {
4533
- const agent = env.NOLTO_AGENT?.trim();
4534
- if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
4535
- if (env.CLAUDECODE === "1") return "Claude Code";
4536
- if (env.GEMINI_CLI === "1") return "Gemini CLI";
4537
- if (env.CODEX_THREAD_ID) return "Codex";
4538
- return "CLI";
4539
- }
4540
-
4541
- // src/memory-cache.ts
4542
- import { mkdir as mkdir8, readFile as readFile14, rename as rename5, rm as rm3, unlink as unlink4, writeFile as writeFile11 } from "fs/promises";
4543
- import { randomUUID as randomUUID7 } from "crypto";
4544
- import path22 from "path";
4545
- function memoryDir(configPath, project) {
4546
- 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);
4547
- return path22.join(path22.dirname(configPath), "projects", project, "memory");
4548
- }
4549
- function memoryEntryPath(entry) {
4550
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(entry.name)) throw new CliError("Invalid memory name in cache.", 2);
4551
- if (entry.scope === "project" || entry.scope === "user") return `${entry.scope}/${entry.name}.md`;
4552
- if (entry.scope !== "branch" || !entry.repoIdentity || !entry.branch) throw new CliError("Invalid memory scope in cache.", 2);
4553
- 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);
4554
- const repoDir = encodeURIComponent(entry.repoIdentity);
4555
- if (Buffer.byteLength(repoDir) > 200) throw new CliError("Unsafe memory repo path.", 2);
4556
- return `branch/${repoDir}/${entry.branch}/${entry.name}.md`;
4557
- }
4558
- function storableMemoryEntry(entry) {
4559
- try {
4560
- memoryEntryPath(entry);
4561
- return true;
4562
- } catch {
4563
- return false;
4564
- }
4565
- }
4566
- async function atomicMemoryFile(file, content) {
4567
- await mkdir8(path22.dirname(file), { recursive: true, mode: 448 });
4568
- const temp = `${file}.tmp-${randomUUID7()}`;
4569
- try {
4570
- await writeFile11(temp, content, { mode: 292 });
4571
- await unlink4(file).catch((error) => {
4572
- if (error.code !== "ENOENT") throw error;
4573
- });
4574
- await rename5(temp, file);
4575
- } finally {
4576
- await unlink4(temp).catch(() => void 0);
4577
- }
4578
- }
4579
- async function readMemoryCache(dir, project) {
4580
- const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
4581
- try {
4582
- const state = JSON.parse(await readFile14(path22.join(dir, ".entries.json"), "utf8"));
4583
- if (!Array.isArray(state.entries) || typeof state.scope !== "string" || typeof state.projectName !== "string") throw new Error("Invalid state");
4584
- if (state.entries.some((e) => e == null || typeof e !== "object" || typeof e.id !== "string" || typeof e.name !== "string")) throw new Error("Invalid entry");
4585
- let meta = empty.meta;
4586
- try {
4587
- meta = JSON.parse(await readFile14(path22.join(dir, ".meta.json"), "utf8"));
4588
- } catch (error) {
4589
- if (error.code !== "ENOENT") throw error;
4590
- }
4591
- if (!Number.isSafeInteger(meta.cursor) || meta.cursor < 0 || typeof meta.pulledAt !== "string") throw new Error("Invalid cursor");
4592
- return { state, meta };
4593
- } catch (error) {
4594
- if (error.code === "ENOENT") return empty;
4595
- throw new CliError(`\u30E1\u30E2\u30EA\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u8AAD\u3081\u307E\u305B\u3093: ${String(error)}`, 2, "nolto memory pull");
4596
- }
4597
- }
4598
- function mergeMemoryEntries(entries, updates) {
4599
- const byId = new Map(entries.map((entry) => [entry.id, entry]));
4600
- for (const entry of updates) {
4601
- const old = byId.get(entry.id);
4602
- if (!old || old.revision <= entry.revision) byId.set(entry.id, entry);
4603
- }
4604
- return [...byId.values()];
4605
- }
4606
- async function saveMemoryCache(dir, cache, previous, index2, reset = false) {
4607
- const unsafe = cache.state.entries.filter((e) => !storableMemoryEntry(e));
4608
- if (reset) await rm3(dir, { recursive: true, force: true });
4609
- const livePaths = new Set(cache.state.entries.filter((e) => !e.deleted && storableMemoryEntry(e)).map(memoryEntryPath));
4610
- for (const entry of previous.filter(storableMemoryEntry)) {
4611
- const relative = memoryEntryPath(entry);
4612
- if (!livePaths.has(relative)) await rm3(path22.join(dir, relative), { force: true });
4613
- }
4614
- for (const entry of cache.state.entries) {
4615
- if (!entry.deleted && storableMemoryEntry(entry)) await atomicMemoryFile(path22.join(dir, memoryEntryPath(entry)), formatMemory(entry));
4616
- }
4617
- await atomicMemoryFile(path22.join(dir, ".entries.json"), JSON.stringify(cache.state) + "\n");
4618
- await atomicMemoryFile(path22.join(dir, "MEMORY.md"), index2);
4619
- await atomicMemoryFile(path22.join(dir, ".meta.json"), JSON.stringify(cache.meta) + "\n");
4620
- return unsafe;
4621
- }
4622
- function currentMemoryEntries(entries, context3, allBranches = false) {
4623
- return entries.filter((e) => !e.deleted && storableMemoryEntry(e) && (e.scope !== "branch" || allBranches || context3.branch !== context3.defaultBranch && e.repoIdentity === context3.repoIdentity && e.branch === context3.branch));
4624
- }
4625
- var scopeOrder = ["project", "user", "branch"];
4626
- function sortMemoryEntries(entries) {
4627
- return entries.sort((a, b) => scopeOrder.indexOf(a.scope) - scopeOrder.indexOf(b.scope) || b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
4628
- }
4629
- function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
4630
- const branch = context3.branch && context3.branch !== context3.defaultBranch ? context3.branch : null;
4631
- const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3));
4632
- const groups = ["project", "user", ...branch ? ["branch"] : []];
4633
- 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)}`);
4634
- let omitted = 0;
4635
- const build = () => [
4636
- `# 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)}` : ""})`,
4637
- "\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",
4638
- ...dir ? [`\u30AD\u30E3\u30C3\u30B7\u30E5: ${dir}`] : [],
4639
- ...groups.flatMap((scope) => {
4640
- const lines = entries.filter((e) => e.scope === scope).map((e) => `- ${e.name} \u2014 ${oneLine(e.description)}`);
4641
- return lines.length ? [`## ${scope === "branch" ? `branch ${oneLine(branch)}` : scope}`, ...lines] : [];
4642
- }),
4643
- ...mergedLines,
4644
- ...omitted ? [`\u6B8B\u308A ${omitted} \u4EF6: nolto memory list`] : []
4645
- ];
4646
- while (build().length > 200) {
4647
- let project = -1;
4648
- for (let i = entries.length - 1; i >= 0; i--) {
4649
- if (entries[i].scope === "project") {
4650
- project = i;
4651
- break;
4818
+ const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
4819
+ const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
4820
+ const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
4821
+ let nearestCommon = null;
4822
+ let insertAfter = null;
4823
+ for (const task of theirsPhase?.tasks ?? []) {
4824
+ if (!args.taskIds.has(task.id)) continue;
4825
+ if (args.oursLocations.has(task.id)) {
4826
+ if (ordered.includes(task.id)) {
4827
+ nearestCommon = task.id;
4828
+ insertAfter = task.id;
4652
4829
  }
4830
+ continue;
4653
4831
  }
4654
- if (entries.length) {
4655
- entries.splice(project < 0 ? entries.length - 1 : project, 1);
4656
- omitted++;
4657
- } else {
4658
- mergedLines.pop();
4659
- omitted++;
4832
+ if (nearestCommon === null || insertAfter === null) {
4833
+ ordered.push(task.id);
4834
+ continue;
4660
4835
  }
4836
+ const index = ordered.indexOf(insertAfter);
4837
+ ordered.splice(index + 1, 0, task.id);
4838
+ insertAfter = task.id;
4661
4839
  }
4662
- return build().join("\n") + "\n";
4840
+ return ordered;
4663
4841
  }
4664
-
4665
- // src/memory-git.ts
4666
- import { execFile as execFile5 } from "child_process";
4667
- import { promisify as promisify4 } from "util";
4668
- var runMemoryGit = async (args, root) => (await promisify4(execFile5)("git", args, { cwd: root, timeout: 5e3 })).stdout.trim();
4669
- async function memoryGitContext(root, deps) {
4670
- const git = deps.memoryGit ?? runMemoryGit;
4671
- const result = { repoIdentity: null, branch: null, defaultBranch: null };
4672
- try {
4673
- await git(["rev-parse", "--show-toplevel"], root);
4674
- const identity = await makeRepoIdentityResolver(deps)(root);
4675
- result.repoIdentity = `${identity.kind}:${identity.value}`;
4676
- result.branch = await git(["symbolic-ref", "--quiet", "--short", "HEAD"], root).catch(() => null);
4677
- const remote = await git(["symbolic-ref", "refs/remotes/origin/HEAD"], root).catch(() => "");
4678
- if (remote.startsWith("refs/remotes/origin/")) result.defaultBranch = remote.slice("refs/remotes/origin/".length);
4679
- else {
4680
- for (const branch of ["main", "master"]) {
4681
- try {
4682
- await git(["show-ref", "--verify", `refs/heads/${branch}`], root);
4683
- result.defaultBranch = branch;
4684
- break;
4685
- } catch {
4686
- }
4687
- }
4688
- }
4689
- } catch {
4842
+ function mergeRoadmaps(args) {
4843
+ const newer = Date.parse(args.theirs.updatedAt ?? "") > Date.parse(args.ours.updatedAt ?? "") ? "theirs" : "ours";
4844
+ const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
4845
+ const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
4846
+ const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
4847
+ const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
4848
+ const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
4849
+ const baseLocations = taskLocations(args.base);
4850
+ const oursLocations = taskLocations(args.ours);
4851
+ const theirsLocations = taskLocations(args.theirs);
4852
+ const keptTasks = /* @__PURE__ */ new Map();
4853
+ const targetPhaseByTask = /* @__PURE__ */ new Map();
4854
+ const taskIds = /* @__PURE__ */ new Set([
4855
+ ...baseLocations.keys(),
4856
+ ...oursLocations.keys(),
4857
+ ...theirsLocations.keys()
4858
+ ]);
4859
+ for (const taskId of taskIds) {
4860
+ const baseLocation = baseLocations.get(taskId);
4861
+ const oursLocation = oursLocations.get(taskId);
4862
+ const theirsLocation = theirsLocations.get(taskId);
4863
+ if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
4864
+ const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
4865
+ base: baseLocation?.task,
4866
+ ours: oursLocation.task,
4867
+ theirs: theirsLocation.task,
4868
+ newer
4869
+ }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
4870
+ keptTasks.set(taskId, task);
4871
+ targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
4690
4872
  }
4691
- return result;
4692
- }
4693
- async function mergedMemoryBranches(branches, context3, root, git, mine = /* @__PURE__ */ new Set()) {
4694
- const merged = /* @__PURE__ */ new Set();
4695
- if (!context3.defaultBranch || !context3.repoIdentity) return merged;
4696
- const hasRef = async (ref) => {
4697
- try {
4698
- await git(["show-ref", "--verify", "--quiet", ref], root);
4699
- return true;
4700
- } catch (error) {
4701
- if (error.code === 1) return false;
4702
- throw error;
4873
+ const keptPhaseIds = /* @__PURE__ */ new Set();
4874
+ const allPhaseIds = /* @__PURE__ */ new Set([
4875
+ ...basePhases.keys(),
4876
+ ...oursPhases.keys(),
4877
+ ...theirsPhases.keys()
4878
+ ]);
4879
+ for (const phaseId of allPhaseIds) {
4880
+ if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
4881
+ keptPhaseIds.add(phaseId);
4703
4882
  }
4883
+ }
4884
+ const phaseOrder = [
4885
+ ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
4886
+ ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
4887
+ ];
4888
+ const phases = phaseOrder.map((phaseId) => {
4889
+ const base = basePhases.get(phaseId);
4890
+ const ours = oursPhases.get(phaseId);
4891
+ const theirs = theirsPhases.get(phaseId);
4892
+ const source = ours ?? theirs;
4893
+ const title = ours !== void 0 && theirs !== void 0 ? chooseField({
4894
+ baseExists: base !== void 0,
4895
+ base: base?.title,
4896
+ ours: ours.title,
4897
+ theirs: theirs.title,
4898
+ newer
4899
+ }) : source.title;
4900
+ const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
4901
+ baseExists: base !== void 0,
4902
+ base: base?.plan,
4903
+ ours: ours.plan,
4904
+ theirs: theirs.plan,
4905
+ newer
4906
+ }) : source.plan;
4907
+ const phaseTaskIds = new Set(
4908
+ [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
4909
+ );
4910
+ const tasks = orderTasks({
4911
+ phaseId,
4912
+ taskIds: phaseTaskIds,
4913
+ ours: args.ours,
4914
+ theirs: args.theirs,
4915
+ oursLocations
4916
+ }).map((taskId) => keptTasks.get(taskId));
4917
+ const phase = { id: phaseId, title, status: "todo", tasks };
4918
+ if (plan !== void 0) phase.plan = plan;
4919
+ phase.status = derivePhaseStatus(phase);
4920
+ return phase;
4921
+ });
4922
+ const mergedTasks = new Map(
4923
+ phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
4924
+ );
4925
+ const validCurrentTask = (roadmap) => {
4926
+ const id = roadmap.currentTaskId ?? null;
4927
+ return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
4704
4928
  };
4705
- let checkedOut, target, targetTip;
4929
+ const merged = {
4930
+ schemaVersion: newerRoadmap.updatedAt === void 0 ? 3 : 2,
4931
+ project: { ...newerRoadmap.project },
4932
+ updatedAt: newerRoadmap.updatedAt,
4933
+ currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
4934
+ summary: newerRoadmap.summary,
4935
+ phases
4936
+ };
4937
+ const validation = validateRoadmap(merged);
4938
+ if (validation.errors.length > 0) {
4939
+ throw new CliError(
4940
+ `Merged roadmap failed validation:
4941
+ ${validation.errors.join("\n ")}`,
4942
+ 1
4943
+ );
4944
+ }
4945
+ return merged;
4946
+ }
4947
+
4948
+ // src/commands/merge-file.ts
4949
+ async function readRoadmap(filePath) {
4950
+ let parsed;
4706
4951
  try {
4707
- 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)));
4708
- target = await hasRef(`refs/heads/${context3.defaultBranch}`) ? `refs/heads/${context3.defaultBranch}` : `refs/remotes/origin/${context3.defaultBranch}`;
4709
- targetTip = await git(["rev-parse", target], root);
4710
- } catch {
4711
- return merged;
4952
+ parsed = JSON.parse(await readFile17(filePath, "utf8"));
4953
+ } catch (err) {
4954
+ const message = err instanceof SyntaxError ? "malformed JSON" : String(err);
4955
+ throw new CliError(`${filePath}: ${message}`, 1);
4712
4956
  }
4713
- for (const branch of branches) {
4714
- if (branch === context3.defaultBranch || branch === context3.branch || checkedOut.has(branch)) continue;
4715
- try {
4716
- const local = `refs/heads/${branch}`;
4717
- if (await hasRef(local)) {
4718
- if (await git(["rev-parse", local], root) === targetTip) continue;
4719
- await git(["merge-base", "--is-ancestor", local, target], root);
4720
- merged.add(branch);
4721
- } else if (mine.has(branch) && !await hasRef(`refs/remotes/origin/${branch}`)) merged.add(branch);
4722
- } catch {
4723
- }
4957
+ const validation = validateRoadmap(parsed);
4958
+ if (validation.errors.length > 0) {
4959
+ throw new CliError(
4960
+ `${filePath} failed validation:
4961
+ ${validation.errors.join("\n ")}`,
4962
+ 1
4963
+ );
4724
4964
  }
4725
- return merged;
4965
+ return parsed;
4966
+ }
4967
+ function register12(program) {
4968
+ program.command("merge-file <ours> <theirs>").description(
4969
+ 'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
4970
+ ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
4971
+ process.stderr.write("Warning: merge-file is deprecated and will be removed; roadmaps are no longer stored in git.\n");
4972
+ const ours = await readRoadmap(oursPath);
4973
+ const theirs = await readRoadmap(theirsPath);
4974
+ const base = opts.base == null ? null : await readRoadmap(opts.base);
4975
+ const merged = mergeRoadmaps({ base, ours, theirs });
4976
+ await writeFile11(
4977
+ opts.output ?? oursPath,
4978
+ JSON.stringify(merged, null, 2) + "\n",
4979
+ "utf8"
4980
+ );
4981
+ const taskCount = merged.phases.reduce((total, phase) => total + phase.tasks.length, 0);
4982
+ process.stderr.write(`merged roadmap (${taskCount} tasks)
4983
+ `);
4984
+ process.exitCode = 0;
4985
+ });
4726
4986
  }
4727
4987
 
4728
4988
  // src/commands/memory.ts
4989
+ import { readFile as readFile18 } from "fs/promises";
4729
4990
  var aiSkipReasons = { timeout: "\u6642\u9593\u5207\u308C", limit: "\u4ECA\u65E5\u306E\u4E0A\u9650", size: "\u672C\u6587\u304C\u9577\u3044", invalid: "\u7D50\u679C\u304C\u4E0D\u6B63", stale: "\u540C\u6642\u306B\u66F4\u65B0\u304C\u3042\u3063\u305F", unavailable: "AI \u3092\u4F7F\u3048\u306A\u3044" };
4730
4991
  var aiSkippedLine = (reason) => `AI \u6574\u7406\u306A\u3057(${aiSkipReasons[reason] ?? oneLine(reason)})`;
4731
- function aiHeading(response) {
4732
- const { entry, ai } = response;
4733
- if (!ai || ai.action !== "merge" && ai.action !== "replace") return null;
4734
- 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 ?? "")}`;
4735
- }
4736
4992
  var pullHint = "nolto memory pull \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044";
4737
4993
  var scopeHint = "--scope project|user|branch";
4738
4994
  async function context2(deps, recover = false) {
@@ -4741,19 +4997,7 @@ async function context2(deps, recover = false) {
4741
4997
  const project = deps.settings.defaultProjectId ?? binding?.projectId;
4742
4998
  if (!project) throw new CliError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u304C\u672A\u8A2D\u5B9A\u3067\u3059\u3002", 2, "nolto link \u307E\u305F\u306F --project <id>");
4743
4999
  const root = findRepoRoot(resolveStartDir(process.env, process.cwd())).root;
4744
- const dir = memoryDir(deps.configPath, project);
4745
- const cache = await readMemoryCache(dir, project).catch((error) => {
4746
- if (!recover) throw error;
4747
- return { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
4748
- });
4749
- return { project, dir, root, git: await memoryGitContext(root, deps), cache, api: `/api/projects/${project}/memory` };
4750
- }
4751
- async function index(ctx, deps) {
4752
- const entries = ctx.cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === ctx.git.repoIdentity);
4753
- const branches = [...new Set(entries.map((e) => e.branch))];
4754
- const userId = ctx.cache.state.userId;
4755
- const mine = new Set(userId ? entries.filter((e) => e.updatedBy?.id === userId).map((e) => e.branch) : []);
4756
- return memoryIndex(ctx.cache, ctx.git, await mergedMemoryBranches(branches, ctx.git, ctx.root, deps.memoryGit ?? runMemoryGit, mine), ctx.dir);
5000
+ return createMemoryContext({ projectId: project, configPath: deps.configPath, root, git: await memoryGitContext(root, deps) }, recover);
4757
5001
  }
4758
5002
  function headers() {
4759
5003
  return { "X-Nolto-Client": detectMemoryClient(process.env) };
@@ -4819,25 +5063,6 @@ async function apiCall(deps, ctx, call, op = "read", name = "<name>") {
4819
5063
  throw new CliError(error.message, error.exitCode, hint, error.status, code, body, detail);
4820
5064
  }
4821
5065
  }
4822
- 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";
4823
- async function updateCache(ctx, deps, entries, quiet = false) {
4824
- const previous = ctx.cache.state.entries;
4825
- try {
4826
- ctx.cache.state.entries = mergeMemoryEntries(previous, entries);
4827
- await saveMemoryCache(ctx.dir, ctx.cache, previous, await index(ctx, deps));
4828
- return true;
4829
- } catch {
4830
- if (!quiet) process.stderr.write(cacheWarning);
4831
- return false;
4832
- }
4833
- }
4834
- function writtenEntries(ctx, response) {
4835
- const tombstones = (response.affected ?? []).flatMap((a) => {
4836
- const cached = a.deleted && a.entryId !== response.entry.id ? ctx.cache.state.entries.find((e) => e.id === a.entryId) : void 0;
4837
- return cached ? [{ ...cached, deleted: true, revision: a.toRevision }] : [];
4838
- });
4839
- return [response.entry, ...tombstones];
4840
- }
4841
5066
  function printWrite(deps, ctx, action, response, isNew = false) {
4842
5067
  if (deps.output.mode === "json") {
4843
5068
  printResult(response, "json");
@@ -4891,7 +5116,7 @@ async function pull2(deps, opts) {
4891
5116
  const projectName = projects?.projects?.find((p) => p.id === ctx.project)?.name ?? ctx.cache.state.projectName;
4892
5117
  const userId = typeof profile?.profile?.id === "string" ? profile.profile.id : ctx.cache.state.userId;
4893
5118
  const next = { ...ctx, cache: { state: { entries, scope, projectName, ...userId ? { userId } : {} }, meta: { cursor, pulledAt: (/* @__PURE__ */ new Date()).toISOString() } } };
4894
- const text = await index(next, deps);
5119
+ const text = await memoryIndexText(next, deps);
4895
5120
  const unsafe = await saveMemoryCache(ctx.dir, next.cache, previous, text, reset);
4896
5121
  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(", ")}
4897
5122
  `);
@@ -4904,7 +5129,7 @@ async function pull2(deps, opts) {
4904
5129
  try {
4905
5130
  const age = Math.max(0, Math.floor((Date.now() - Date.parse(ctx.cache.meta.pulledAt)) / 6e4));
4906
5131
  text = `(\u6700\u7D42\u540C\u671F ${Number.isFinite(age) ? age : "\u4E0D\u660E"} \u5206\u524D\u3002\u4ECA\u56DE\u306F\u540C\u671F\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F)
4907
- ${await index(ctx, deps)}`;
5132
+ ${await memoryIndexText(ctx, deps)}`;
4908
5133
  } catch {
4909
5134
  }
4910
5135
  }
@@ -4912,7 +5137,7 @@ ${await index(ctx, deps)}`;
4912
5137
  }
4913
5138
  }
4914
5139
  async function inputText(file) {
4915
- if (file !== "-") return readFile15(file, "utf8");
5140
+ if (file !== "-") return readFile18(file, "utf8");
4916
5141
  let text = "";
4917
5142
  process.stdin.setEncoding("utf8");
4918
5143
  for await (const chunk of process.stdin) text += chunk;
@@ -4923,7 +5148,7 @@ function register13(program, deps) {
4923
5148
  memory.command("pull").option("--hook [agent]", "SessionStart output; always exit 0").option("--scope <csv>").action((opts) => pull2(deps, opts));
4924
5149
  memory.command("context").action(async () => {
4925
5150
  const ctx = await context2(deps);
4926
- process.stdout.write(ctx.cache.meta.pulledAt || ctx.cache.state.entries.length ? await index(ctx, deps) : pullHint + "\n");
5151
+ process.stdout.write(ctx.cache.meta.pulledAt || ctx.cache.state.entries.length ? await memoryIndexText(ctx, deps) : pullHint + "\n");
4927
5152
  });
4928
5153
  memory.command("instructions").action(() => {
4929
5154
  process.stdout.write(MEMORY_INSTRUCTIONS + "\n");
@@ -5002,48 +5227,35 @@ function register13(program, deps) {
5002
5227
  });
5003
5228
  memory.command("hook").command("install").option("--agent <agent>").option("--write-agents-md").action(async (opts) => {
5004
5229
  const { root } = findRepoRoot(resolveStartDir(process.env, process.cwd()));
5005
- const messages = await installMemoryHooks(root, deps.version, opts.agent, opts.writeAgentsMd);
5230
+ const messages = await installMemoryHooks(root, opts.agent, opts.writeAgentsMd);
5006
5231
  printResult(deps.output.mode === "json" ? { messages } : messages.join("\n"), deps.output.mode);
5007
5232
  });
5008
5233
  memory.command("import <dir>").description("Import memory files. AI cleanup is off by default (--ai to use it).").requiredOption("--scope <scope>").option("--ai", "use AI cleanup (Pro+)").action(async (dir, opts) => {
5009
5234
  const scope = parseScope(opts.scope, "--scope project|user");
5010
5235
  if (scope === "branch") throw new CliError("branch \u30B9\u30B3\u30FC\u30D7\u3078\u306E import \u306F\u3067\u304D\u307E\u305B\u3093\u3002", 2, "--scope project|user");
5011
5236
  const ctx = await context2(deps, true);
5012
- let imported = 0, skipped = 0, failed = 0, cached = true;
5013
- const results = [];
5014
- const seen = /* @__PURE__ */ new Map();
5015
- 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))) {
5016
- let original = file.name.slice(0, -3), name = original;
5017
- let status, message, heading = null;
5018
- try {
5019
- const draft = parseMemory(await readFile15(path23.join(dir, file.name), "utf8"), true);
5020
- original = draft.name || original;
5021
- name = original.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+/, "").slice(0, 64);
5022
- if (!name) throw new CliError(`name \u3092\u6B63\u898F\u5316\u3067\u304D\u307E\u305B\u3093: ${original}`, 2);
5023
- validateDraft({ ...draft, name });
5024
- const first = seen.get(name);
5025
- if (first) throw new CliError(`import \u5185\u3067 name \u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059(\u5148: ${first})\u3002`, 2);
5026
- seen.set(name, file.name);
5027
- const response = await deps.http.put(ctx.api, { scope, name, description: draft.description, body: draft.body, ...draft.type ? { type: draft.type } : {}, allowNew: true, ...opts.ai ? {} : { aiSkip: true } }, headers());
5028
- cached = await updateCache(ctx, deps, writtenEntries(ctx, response), true) && cached;
5029
- heading = aiHeading(response);
5030
- imported++;
5031
- status = "imported";
5032
- } catch (error) {
5033
- if (error instanceof CliError && error.serverError === "memory_exists") {
5034
- skipped++;
5035
- status = "skipped";
5036
- if (error.body?.entry) cached = await updateCache(ctx, deps, [error.body.entry], true) && cached;
5037
- } else {
5038
- failed++;
5039
- status = "failed";
5040
- message = error instanceof Error ? error.message : String(error);
5041
- }
5237
+ const scan = await scanMemoryDir(dir);
5238
+ const lines = /* @__PURE__ */ new Map();
5239
+ let position = 0;
5240
+ const result = await importMemoryFiles({
5241
+ http: deps.http,
5242
+ projectId: ctx.project,
5243
+ configPath: deps.configPath,
5244
+ root: ctx.root,
5245
+ scope,
5246
+ targets: scan.ok,
5247
+ ai: opts.ai,
5248
+ git: ctx.git,
5249
+ memoryGit: deps.memoryGit,
5250
+ write: (line2) => {
5251
+ lines.set(scan.ok[position++].file, line2);
5042
5252
  }
5043
- results.push({ file: file.name, name, original, status, ...message ? { message } : {} });
5044
- if (deps.output.mode !== "json") process.stdout.write(heading ? `${heading} (\u5143: ${oneLine(file.name)})
5045
- ` : `${status} ${scope}/${name}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}
5046
- `);
5253
+ });
5254
+ const { imported, skipped, cached } = result;
5255
+ const failed = result.failed + scan.invalid.length;
5256
+ const results = [...result.results, ...scan.invalid].sort((a, b) => a.file.localeCompare(b.file));
5257
+ if (deps.output.mode !== "json") {
5258
+ for (const item of results) process.stdout.write((lines.get(item.file) ?? importResultLine(scope, item)) + "\n");
5047
5259
  }
5048
5260
  const skippedNames = results.filter((r) => r.status === "skipped").map((r) => `${scope}/${String(r.name)}`);
5049
5261
  if (deps.output.mode !== "json" && skippedNames.length) process.stdout.write(`skipped (\u540C\u540D\u3042\u308A\u3002\u7D71\u5408\u3059\u308B\u306A\u3089 nolto memory show <name> --fresh): ${skippedNames.join(", ")}
@@ -5148,6 +5360,11 @@ async function main() {
5148
5360
  output: { mode },
5149
5361
  version,
5150
5362
  configPath,
5363
+ claudeProjectsDir: path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "projects"),
5364
+ homeSkillDirs: [
5365
+ path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "skills"),
5366
+ path24.join(os5.homedir(), ".agents", "skills")
5367
+ ],
5151
5368
  repoBinding
5152
5369
  });
5153
5370
  await program.parseAsync(process.argv);