@nolto/cli 0.18.0 → 0.19.1

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,988 @@ ${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"}`,
1881
+ `${filePath} failed validation \u2014 not syncing:
1882
+ ${errors.join("\n ")}`,
1654
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) {
1807
- let current = startDir;
1808
- while (true) {
1809
- if (hasGit(current)) {
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) {
2100
+ if (args.slug === void 0) {
2101
+ log(`skipped \u2014 "${slug}" is another repository's roadmap (${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <name>\` to create one for this repository.`);
2102
+ return;
2103
+ }
2104
+ 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);
2105
+ }
2106
+ let existing;
2107
+ try {
2108
+ existing = await readCache(env, projectId, slug);
2109
+ } catch (err) {
2110
+ if (!(err instanceof CliError)) throw err;
2111
+ existing = null;
2112
+ }
2113
+ if (existing && isDirty(existing)) {
2114
+ warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
2115
+ throw new CliError("Roadmap has local changes that are not synced.", 4);
2116
+ }
2117
+ const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
2118
+ await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
2119
+ const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
2120
+ http: args.http,
2121
+ readFile: (p) => readFile9(p, "utf8"),
2122
+ realpath,
2123
+ fileExists: existsSync3,
2124
+ log: () => void 0,
2125
+ warn: warn2
2126
+ });
2127
+ 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 });
2128
+ log(`created ${slug} on server (rev ${response.revision})`);
2129
+ }
2130
+ async function ensureProjectRepo(args) {
2131
+ let repos;
2132
+ try {
2133
+ const project = await args.http.get(`/api/projects/${args.projectId}`);
2134
+ repos = Array.isArray(project.repos) ? project.repos : [];
2135
+ } catch (error) {
2136
+ if (error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
2137
+ process.stderr.write(`Warning: could not check project repositories: ${error instanceof Error ? error.message : String(error)}
2138
+ `);
2139
+ return "unbound";
2140
+ }
2141
+ if (repos.length === 0) return "unbound";
2142
+ const identity = repoIdentityToString(args.repoIdentity);
2143
+ if (repos.some((repo) => repo.identity === identity)) return "bound";
2144
+ 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";
2145
+ try {
2146
+ await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
2147
+ } catch (error) {
2148
+ if (error instanceof CliError) {
2149
+ if (error.status === 409 && error.serverError === "repo_already_bound_to_this") return "bound";
2150
+ if (error.status === 403) {
2151
+ throw new CliError(
2152
+ "Only the project owner can add a repository.",
2153
+ 2,
2154
+ "Ask the owner to run `nolto link --add` in this repository."
2155
+ );
2156
+ }
2157
+ if (error.status === 402) process.stderr.write("binding and skill are kept; retry after upgrading.\n");
2158
+ }
2159
+ throw error;
2160
+ }
2161
+ args.log(`Added ${identity} to project.`);
2162
+ return "added";
2163
+ }
2164
+
2165
+ // src/commands/link.ts
2166
+ import readline from "readline/promises";
2167
+ import os2 from "os";
2168
+ import path14 from "path";
2169
+ import { statSync as statSync2 } from "fs";
2170
+
2171
+ // src/registry.ts
2172
+ import { readFile as readFile10, writeFile as writeFile8, mkdir as mkdir7, rename as rename4, unlink as unlink3 } from "fs/promises";
2173
+ import { randomUUID as randomUUID6 } from "crypto";
2174
+ import path13 from "path";
2175
+ import { z as z3 } from "zod";
2176
+ var registrySchema = z3.object({
2177
+ schemaVersion: z3.literal(1),
2178
+ repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
2179
+ }).passthrough();
2180
+ function getRegistryPath(env) {
2181
+ return path13.join(getConfigDir(env), "registry.json");
2182
+ }
2183
+ async function loadRegistry(filePath) {
2184
+ let raw;
2185
+ try {
2186
+ raw = await readFile10(filePath, "utf8");
2187
+ } catch (err) {
2188
+ const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
2189
+ if (code === "ENOENT") {
2190
+ return { schemaVersion: 1, repos: [] };
2191
+ }
2192
+ throw new CliError(`Cannot read registry: ${filePath}: ${String(err)}`, 2);
2193
+ }
2194
+ let parsed;
2195
+ try {
2196
+ parsed = JSON.parse(raw);
2197
+ } catch {
2198
+ throw new CliError(`Malformed JSON in ${filePath}. Fix or remove the file.`, 2);
2199
+ }
2200
+ const result = registrySchema.safeParse(parsed);
2201
+ if (!result.success) {
2202
+ const issue = result.error.issues[0];
2203
+ const fieldPath = issue?.path.join(".") ?? "";
2204
+ throw new CliError(
2205
+ `Invalid registry at ${filePath}: ${fieldPath.length > 0 ? `field "${fieldPath}" \u2014 ` : ""}${issue?.message ?? "validation failed"}`,
2206
+ 2
2207
+ );
2208
+ }
2209
+ return result.data;
2210
+ }
2211
+ async function addRepoToRegistry(filePath, entry) {
2212
+ const registry = await loadRegistry(filePath);
2213
+ const existing = registry.repos.find((repo) => repo.root === entry.root);
2214
+ if (existing?.projectId === entry.projectId) {
2215
+ return { added: false, updated: false, registry };
2216
+ }
2217
+ const updated = {
2218
+ ...registry,
2219
+ repos: existing ? registry.repos.map((repo) => repo.root === entry.root ? { ...repo, projectId: entry.projectId } : repo) : [...registry.repos, entry]
2220
+ };
2221
+ await writeRegistry(filePath, updated);
2222
+ return { added: !existing, updated: !!existing, registry: updated };
2223
+ }
2224
+ async function writeRegistry(filePath, registry) {
2225
+ await mkdir7(path13.dirname(filePath), { recursive: true, mode: 448 });
2226
+ const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID6()}`;
2227
+ try {
2228
+ await writeFile8(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
2229
+ await rename4(tempPath, filePath);
2230
+ } catch (err) {
2231
+ await unlink3(tempPath).catch(() => void 0);
2232
+ throw err;
2233
+ }
2234
+ }
2235
+ async function removeRepoFromRegistry(filePath, root) {
2236
+ const registry = await loadRegistry(filePath);
2237
+ const repos = registry.repos.filter((repo) => repo.root !== root);
2238
+ if (repos.length === registry.repos.length) return { removed: false, registry };
2239
+ const updated = { ...registry, repos };
2240
+ await writeRegistry(filePath, updated);
2241
+ return { removed: true, registry: updated };
2242
+ }
2243
+
2244
+ // src/commands/link.ts
2245
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2246
+ function resolveStartDir(env, cwd) {
2247
+ const cpd = env["CLAUDE_PROJECT_DIR"];
2248
+ return cpd != null && cpd.length > 0 ? cpd : cwd;
2249
+ }
2250
+ function dirHasGit(dir) {
2251
+ try {
2252
+ statSync2(path14.join(dir, ".git"));
2253
+ return true;
2254
+ } catch {
2255
+ return false;
2256
+ }
2257
+ }
2258
+ function findRepoRoot(startDir, hasGit = dirHasGit) {
2259
+ let current = startDir;
2260
+ while (true) {
2261
+ if (hasGit(current)) {
1810
2262
  return { root: current, foundGit: true };
1811
2263
  }
1812
- const parent = path12.dirname(current);
2264
+ const parent = path14.dirname(current);
1813
2265
  if (parent === current) break;
1814
2266
  current = parent;
1815
2267
  }
1816
2268
  return { root: startDir, foundGit: false };
1817
2269
  }
1818
2270
  function isHomeDirectory(dir, home = os2.homedir()) {
1819
- return path12.resolve(dir) === path12.resolve(home);
2271
+ return path14.resolve(dir) === path14.resolve(home);
1820
2272
  }
1821
2273
  async function handleShow(deps, projectBindingPath, mode2) {
1822
2274
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1915,10 +2367,10 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1915
2367
  }
1916
2368
  }
1917
2369
  async function handleUnlink(projectBindingPath, mode2) {
1918
- const { readFile: readFile16, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
2370
+ const { readFile: readFile19, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
1919
2371
  let existing = {};
1920
2372
  try {
1921
- const raw = await readFile16(projectBindingPath, "utf8");
2373
+ const raw = await readFile19(projectBindingPath, "utf8");
1922
2374
  const parsed = JSON.parse(raw);
1923
2375
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
1924
2376
  throw new CliError(
@@ -1962,7 +2414,7 @@ async function performLink(deps, projectId, mode2, slug, yes = false) {
1962
2414
  token: deps.settings.token,
1963
2415
  version: deps.version
1964
2416
  });
1965
- let projectName = path12.basename(root);
2417
+ let projectName = path14.basename(root);
1966
2418
  if (deps.settings.token != null) {
1967
2419
  try {
1968
2420
  const result = await http.get(
@@ -1990,7 +2442,7 @@ Proceeding anyway \u2014 verify the ID is correct.
1990
2442
  );
1991
2443
  }
1992
2444
  await writeRepoBinding(root, projectId);
1993
- const writtenPath = path12.join(root, "nolto.json");
2445
+ const writtenPath = path14.join(root, "nolto.json");
1994
2446
  let repoAdded = false;
1995
2447
  if (deps.settings.token == null) {
1996
2448
  process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
@@ -2174,13 +2626,13 @@ function invalidBindingError(projectBindingPath, error) {
2174
2626
  }
2175
2627
 
2176
2628
  // src/commands/init.ts
2177
- var __dirname2 = path13.dirname(fileURLToPath2(import.meta.url));
2629
+ var __dirname2 = path15.dirname(fileURLToPath2(import.meta.url));
2178
2630
  var _require = createRequire(import.meta.url);
2179
2631
  function getCliVersion() {
2180
2632
  const candidates = [
2181
- path13.resolve(__dirname2, "../package.json"),
2633
+ path15.resolve(__dirname2, "../package.json"),
2182
2634
  // bundled: dist/../package.json
2183
- path13.resolve(__dirname2, "../../package.json")
2635
+ path15.resolve(__dirname2, "../../package.json")
2184
2636
  // source: src/commands/../../package.json
2185
2637
  ];
2186
2638
  for (const pkgPath of candidates) {
@@ -2197,8 +2649,8 @@ function getCliVersion() {
2197
2649
  async function pickProject(rl, http, projects, promptText, baseUrl) {
2198
2650
  if (projects.length > 0) {
2199
2651
  process.stdout.write("\nProjects:\n");
2200
- projects.forEach((project, index2) => {
2201
- process.stdout.write(` (${index2 + 1}) ${project.name} \u2014 ${project.id}
2652
+ projects.forEach((project, index) => {
2653
+ process.stdout.write(` (${index + 1}) ${project.name} \u2014 ${project.id}
2202
2654
  `);
2203
2655
  });
2204
2656
  } else {
@@ -2218,16 +2670,16 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
2218
2670
  let organization = orgs[0];
2219
2671
  if (orgs.length > 1) {
2220
2672
  process.stdout.write("\nOrganizations:\n");
2221
- orgs.forEach((org, index3) => {
2222
- process.stdout.write(` (${index3 + 1}) ${org.name} \u2014 ${org.id}
2673
+ orgs.forEach((org, index2) => {
2674
+ process.stdout.write(` (${index2 + 1}) ${org.name} \u2014 ${org.id}
2223
2675
  `);
2224
2676
  });
2225
2677
  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) {
2678
+ const index = Number(choice);
2679
+ if (!/^\d+$/.test(choice) || !Number.isSafeInteger(index) || index < 1 || index > orgs.length) {
2228
2680
  throw new CliError("Invalid organization number.", 2);
2229
2681
  }
2230
- organization = orgs[index2 - 1];
2682
+ organization = orgs[index - 1];
2231
2683
  }
2232
2684
  const created = await http.post(
2233
2685
  "/api/projects",
@@ -2268,8 +2720,91 @@ async function selectRepoProject(rl, http, projects, defaultProjectId, baseUrl)
2268
2720
  baseUrl
2269
2721
  );
2270
2722
  }
2723
+ async function setupMemory(opts) {
2724
+ const { rl, root, projectId, http, deps, memory } = opts;
2725
+ if (memory === false) return;
2726
+ const agents = detectMemoryAgents(root);
2727
+ const scan = deps.claudeProjectsDir ? await scanMemoryDir(claudeMemoryDir(root, deps.claudeProjectsDir)).catch((error) => {
2728
+ if (error.code === "ENOENT") return { ok: [], invalid: [] };
2729
+ throw error;
2730
+ }) : { ok: [], invalid: [] };
2731
+ if (!scan.ok.length && !scan.invalid.length && (await Promise.all(agents.map((agent) => hasMemoryHook(root, agent)))).every(Boolean)) {
2732
+ process.stdout.write(`memory: \u8A2D\u5B9A\u6E08\u307F(hook ${agents.join(", ")})
2733
+ `);
2734
+ return;
2735
+ }
2736
+ 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") {
2737
+ process.stdout.write("\u5F8C\u304B\u3089\u8A2D\u5B9A\u3059\u308B\u306B\u306F nolto memory hook install\n");
2738
+ return;
2739
+ }
2740
+ for (const message of await installMemoryHooks(root)) process.stdout.write(`memory: ${message}
2741
+ `);
2742
+ if (scan.invalid.length) {
2743
+ 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):
2744
+ `);
2745
+ for (const invalid of scan.invalid) process.stdout.write(` - ${oneLine(invalid.file)} \u2014 ${oneLine(invalid.message)}
2746
+ `);
2747
+ }
2748
+ const ask = async (prompt) => memory === true && !process.stdin.isTTY ? "" : (await rl.question(prompt)).trim().toLowerCase();
2749
+ if (scan.ok.length) {
2750
+ const users = scan.ok.filter((target) => target.draft.type === "user").length;
2751
+ 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
2752
+ `);
2753
+ 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] ");
2754
+ if (choice !== "n") {
2755
+ const git = await memoryGitContext(root, deps);
2756
+ let imported = 0, skipped = 0, failed = 0, cached = true;
2757
+ for (const scope of ["project", "user"]) {
2758
+ const targets = scan.ok.filter((target) => (choice === "p" ? "project" : choice === "u" ? "user" : target.draft.type === "user" ? "user" : "project") === scope);
2759
+ if (!targets.length) continue;
2760
+ const result2 = await importMemoryFiles({
2761
+ http,
2762
+ projectId,
2763
+ configPath: deps.configPath,
2764
+ root,
2765
+ scope,
2766
+ targets,
2767
+ git,
2768
+ memoryGit: deps.memoryGit,
2769
+ write: (line2) => {
2770
+ process.stdout.write(line2 + "\n");
2771
+ }
2772
+ });
2773
+ imported += result2.imported;
2774
+ skipped += result2.skipped;
2775
+ failed += result2.failed;
2776
+ cached = result2.cached && cached;
2777
+ }
2778
+ process.stdout.write(`imported ${imported}, skipped ${skipped}, failed ${failed}
2779
+ `);
2780
+ if (!cached) process.stderr.write(cacheWarning);
2781
+ }
2782
+ }
2783
+ if (!agents.includes("claude")) return;
2784
+ const file = path15.join(root, ".claude", "settings.local.json");
2785
+ let settings = {};
2786
+ try {
2787
+ settings = JSON.parse(await readFile11(file, "utf8"));
2788
+ } catch (error) {
2789
+ if (error.code !== "ENOENT") {
2790
+ 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
2791
+ `);
2792
+ return;
2793
+ }
2794
+ }
2795
+ if (settings && typeof settings === "object" && !Array.isArray(settings) && "autoMemoryEnabled" in settings && settings.autoMemoryEnabled === false) {
2796
+ process.stdout.write("memory: Claude Code \u306E\u81EA\u52D5\u30E1\u30E2\u30EA\u505C\u6B62\u306F\u8A2D\u5B9A\u6E08\u307F\n");
2797
+ return;
2798
+ }
2799
+ 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;
2800
+ const result = await disableClaudeAutoMemory(root);
2801
+ 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
2802
+ `);
2803
+ 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"}
2804
+ `);
2805
+ }
2271
2806
  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) => {
2807
+ 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
2808
  const configPath = deps.configPath;
2274
2809
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
2275
2810
  try {
@@ -2361,7 +2896,7 @@ Saved ${configPath}
2361
2896
  }
2362
2897
  if (isHomeDirectory(root)) {
2363
2898
  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.
2899
+ `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
2900
  `
2366
2901
  );
2367
2902
  return;
@@ -2393,7 +2928,7 @@ Saved ${configPath}
2393
2928
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
2394
2929
  );
2395
2930
  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);
2931
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path15.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2397
2932
  } else {
2398
2933
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2399
2934
  }
@@ -2407,7 +2942,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2407
2942
  process.stdout.write("Skipped repo setup.\n");
2408
2943
  return;
2409
2944
  }
2410
- const bindingPath = deps.repoBinding?.path ?? path13.join(root, "nolto.json");
2945
+ const bindingPath = deps.repoBinding?.path ?? path15.join(root, "nolto.json");
2411
2946
  if (keepExistingBinding) {
2412
2947
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
2413
2948
  `);
@@ -2419,32 +2954,30 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2419
2954
  );
2420
2955
  }
2421
2956
  await writeRepoBinding(root, repoProject.id);
2422
- process.stdout.write(`binding: wrote ${path13.join(root, "nolto.json")}
2957
+ process.stdout.write(`binding: wrote ${path15.join(root, "nolto.json")}
2423
2958
  `);
2424
2959
  }
2425
2960
  const sourceDir = resolveSkillSourceDir();
2426
- const version = getCliVersion();
2427
2961
  const claudeInstall = await installSkill({
2428
- skillsParentDir: path13.join(root, ".claude", "skills"),
2429
- sourceDir,
2430
- version
2962
+ skillsParentDir: path15.join(root, ".claude", "skills"),
2963
+ sourceDir
2431
2964
  });
2432
2965
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
2433
2966
  `);
2434
- const usesAgentsTooling = fs2.existsSync(path13.join(root, ".agents")) || fs2.existsSync(path13.join(root, ".codex")) || fs2.existsSync(path13.join(root, "AGENTS.md"));
2967
+ const usesAgentsTooling = fs2.existsSync(path15.join(root, ".agents")) || fs2.existsSync(path15.join(root, ".codex")) || fs2.existsSync(path15.join(root, "AGENTS.md"));
2435
2968
  if (usesAgentsTooling) {
2436
2969
  const agentsInstall = await installSkill({
2437
- skillsParentDir: path13.join(root, ".agents", "skills"),
2438
- sourceDir,
2439
- version
2970
+ skillsParentDir: path15.join(root, ".agents", "skills"),
2971
+ sourceDir
2440
2972
  });
2441
2973
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
2442
2974
  `);
2443
2975
  }
2444
- for (const memorySkill of await installMemorySkill(root, version)) {
2976
+ for (const memorySkill of await installMemorySkill(root)) {
2445
2977
  process.stdout.write(`skill (memory): ${memorySkill.action} ${memorySkill.targetDir}
2446
2978
  `);
2447
2979
  }
2980
+ await setupMemory({ rl, root, projectId: repoProject.id, http: repoHttp, deps, memory: opts.memory });
2448
2981
  const repoIdentity = await makeRepoIdentityResolver(deps)(root);
2449
2982
  const repoResult = await ensureProjectRepo({
2450
2983
  http: repoHttp,
@@ -2714,13 +3247,13 @@ function register5(program, deps) {
2714
3247
  }
2715
3248
 
2716
3249
  // 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";
3250
+ import { execFile as execFile3 } from "child_process";
3251
+ import { promisify as promisify2 } from "util";
3252
+ import { readFile as readFile12, realpath as realpath2 } from "fs/promises";
2720
3253
  import { existsSync as existsSync4 } from "fs";
2721
3254
 
2722
3255
  // src/roadmap-read.ts
2723
- import path14 from "path";
3256
+ import path16 from "path";
2724
3257
  async function resolveRoadmapReadContext(deps) {
2725
3258
  if (deps.settings.token == null) {
2726
3259
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
@@ -2730,7 +3263,7 @@ async function resolveRoadmapReadContext(deps) {
2730
3263
  if (!foundGit) {
2731
3264
  throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2732
3265
  }
2733
- const binding = await loadRepoBinding(path14.join(root, "nolto.json"));
3266
+ const binding = await loadRepoBinding(path16.join(root, "nolto.json"));
2734
3267
  const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2735
3268
  if (projectId == null) {
2736
3269
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
@@ -2760,12 +3293,12 @@ function buildGitLinksPayload(entries) {
2760
3293
  const keys = extractIssueKeys(entry.subject);
2761
3294
  const pr = extractPrNumber(entry.subject);
2762
3295
  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) => ({
3296
+ return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
2764
3297
  ...ref,
2765
3298
  title: entry.subject.slice(0, 500),
2766
3299
  author: entry.author.slice(0, 500),
2767
3300
  committedAt: entry.committedAt,
2768
- issueKeys: keys.slice(index2 * 20, (index2 + 1) * 20)
3301
+ issueKeys: keys.slice(index * 20, (index + 1) * 20)
2769
3302
  })));
2770
3303
  }) };
2771
3304
  }
@@ -2786,15 +3319,15 @@ async function collectGitLinks(root, exec) {
2786
3319
  }
2787
3320
 
2788
3321
  // src/sync-repo.ts
2789
- import path15 from "path";
2790
- import { readdir as readdir3 } from "fs/promises";
3322
+ import path17 from "path";
3323
+ import { readdir as readdir5 } from "fs/promises";
2791
3324
  function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2792
3325
  const planAbsPaths = /* @__PURE__ */ new Set();
2793
- const resolvedRoot = path15.resolve(root);
3326
+ const resolvedRoot = path17.resolve(root);
2794
3327
  for (const roadmap of roadmaps) {
2795
3328
  for (const ref of collectPlanRefs(roadmap)) {
2796
- const absolute = path15.resolve(resolvedRoot, ref.path);
2797
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path15.sep)) {
3329
+ const absolute = path17.resolve(resolvedRoot, ref.path);
3330
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path17.sep)) {
2798
3331
  warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2799
3332
  continue;
2800
3333
  }
@@ -2815,7 +3348,7 @@ async function syncRepo(args, io) {
2815
3348
  if (slugs.length === 0) {
2816
3349
  let legacyFiles = [];
2817
3350
  try {
2818
- legacyFiles = await readdir3(path15.join(args.root, ".nolto", "roadmaps"));
3351
+ legacyFiles = await readdir5(path17.join(args.root, ".nolto", "roadmaps"));
2819
3352
  } catch (err) {
2820
3353
  if (err.code !== "ENOENT") throw err;
2821
3354
  }
@@ -2922,11 +3455,11 @@ async function runSyncCommand(deps, opts = {}) {
2922
3455
  { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2923
3456
  {
2924
3457
  env: process.env,
2925
- readFile: (p) => readFile9(p, "utf8"),
3458
+ readFile: (p) => readFile12(p, "utf8"),
2926
3459
  realpath: (p) => realpath2(p),
2927
3460
  fileExists: (p) => existsSync4(p),
2928
3461
  repoIdentity: makeRepoIdentityResolver(deps),
2929
- exec: promisify(execFile2),
3462
+ exec: promisify2(execFile3),
2930
3463
  gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2931
3464
  http,
2932
3465
  log: (line2) => {
@@ -2936,10 +3469,8 @@ async function runSyncCommand(deps, opts = {}) {
2936
3469
  }
2937
3470
  );
2938
3471
  try {
2939
- const drifted = await checkSkillVersionDrift(root, deps.version);
2940
- if (drifted.length > 0) {
2941
- warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
2942
- }
3472
+ const drifted = await checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs });
3473
+ for (const warning of drifted) warn2(warning);
2943
3474
  } catch {
2944
3475
  }
2945
3476
  let registryAdded = false;
@@ -3135,11 +3666,15 @@ function register7(program, deps) {
3135
3666
  });
3136
3667
  }
3137
3668
 
3669
+ // src/commands/roadmap.ts
3670
+ import { readFile as readFile14 } from "fs/promises";
3671
+ import { existsSync as existsSync6 } from "fs";
3672
+
3138
3673
  // src/roadmap-commands.ts
3139
- import path16 from "path";
3674
+ import path18 from "path";
3140
3675
  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";
3676
+ import { readFile as readFile13, readdir as readdir6, writeFile as writeFile9, rename as rename5, unlink as unlink4, realpath as realpath3 } from "fs/promises";
3677
+ import { randomUUID as randomUUID7 } from "crypto";
3143
3678
  import readline4 from "readline/promises";
3144
3679
 
3145
3680
  // src/commands/pull.ts
@@ -3207,7 +3742,7 @@ async function selectRoadmap(deps, requestedSlug) {
3207
3742
  }
3208
3743
  async function roadmapPath(deps, slug) {
3209
3744
  const { paths } = await selectRoadmap(deps, slug);
3210
- printResult(path16.resolve(paths.json), deps.output.mode);
3745
+ printResult(path18.resolve(paths.json), deps.output.mode);
3211
3746
  }
3212
3747
  async function roadmapStatus(deps, slug, fresh = false) {
3213
3748
  const selected = await selectRoadmap(deps, slug);
@@ -3236,7 +3771,7 @@ async function roadmapValidate(deps, slug) {
3236
3771
  const { paths } = await selectRoadmap(deps, slug);
3237
3772
  let parsed;
3238
3773
  try {
3239
- parsed = JSON.parse(await readFile10(paths.json, "utf8"));
3774
+ parsed = JSON.parse(await readFile13(paths.json, "utf8"));
3240
3775
  } catch {
3241
3776
  throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
3242
3777
  }
@@ -3252,12 +3787,12 @@ async function roadmapSummary(deps, slug, text) {
3252
3787
  const selected = await selectRoadmap(deps, slug);
3253
3788
  const entry = await readCache(process.env, selected.projectId, selected.slug);
3254
3789
  entry.roadmap.summary = text;
3255
- const temp = `${selected.paths.json}.tmp-${randomUUID6()}`;
3790
+ const temp = `${selected.paths.json}.tmp-${randomUUID7()}`;
3256
3791
  try {
3257
- await writeFile8(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3258
- await rename4(temp, selected.paths.json);
3792
+ await writeFile9(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3793
+ await rename5(temp, selected.paths.json);
3259
3794
  } finally {
3260
- await unlink3(temp).catch(() => void 0);
3795
+ await unlink4(temp).catch(() => void 0);
3261
3796
  }
3262
3797
  await runSyncCommand(deps, { slug: selected.slug });
3263
3798
  }
@@ -3286,8 +3821,8 @@ async function roadmapTask(deps, taskId, slug, body) {
3286
3821
  const selected = await selectRoadmap(deps, slug);
3287
3822
  if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
3288
3823
  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)) {
3824
+ const absolute = path18.resolve(selected.root, body.plan);
3825
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path18.resolve(selected.root) + path18.sep)) {
3291
3826
  throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
3292
3827
  }
3293
3828
  if (!existsSync5(absolute)) warn(`WARN plan file not found at ${absolute}`);
@@ -3309,10 +3844,10 @@ async function roadmapEvents(deps, slug, opts) {
3309
3844
  }
3310
3845
  async function roadmapMigrate(deps, yes = false) {
3311
3846
  const { root, projectId } = await resolveRoadmapReadContext(deps);
3312
- const dir = path16.join(root, ".nolto", "roadmaps");
3847
+ const dir = path18.join(root, ".nolto", "roadmaps");
3313
3848
  let files;
3314
3849
  try {
3315
- files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
3850
+ files = (await readdir6(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
3316
3851
  } catch (error) {
3317
3852
  if (error.code !== "ENOENT") throw error;
3318
3853
  files = [];
@@ -3325,7 +3860,7 @@ async function roadmapMigrate(deps, yes = false) {
3325
3860
  for (const file of files) {
3326
3861
  const slug = file.slice(0, -5);
3327
3862
  cachePaths(process.env, projectId, slug);
3328
- const roadmap = await loadValidRoadmap(path16.join(dir, file), (p) => readFile10(p, "utf8"));
3863
+ const roadmap = await loadValidRoadmap(path18.join(dir, file), (p) => readFile13(p, "utf8"));
3329
3864
  roadmap.schemaVersion = 3;
3330
3865
  delete roadmap.updatedAt;
3331
3866
  delete roadmap.currentTaskId;
@@ -3357,7 +3892,7 @@ async function roadmapMigrate(deps, yes = false) {
3357
3892
  if (!unchanged) {
3358
3893
  const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
3359
3894
  http: deps.http,
3360
- readFile: (p) => readFile10(p, "utf8"),
3895
+ readFile: (p) => readFile13(p, "utf8"),
3361
3896
  realpath: realpath3,
3362
3897
  fileExists: existsSync5,
3363
3898
  log: () => void 0,
@@ -3375,7 +3910,7 @@ async function roadmapMigrate(deps, yes = false) {
3375
3910
  const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3376
3911
  let attributes = "";
3377
3912
  try {
3378
- attributes = await readFile10(path16.join(root, ".gitattributes"), "utf8");
3913
+ attributes = await readFile13(path18.join(root, ".gitattributes"), "utf8");
3379
3914
  } catch (error) {
3380
3915
  if (error.code !== "ENOENT") throw error;
3381
3916
  }
@@ -3394,6 +3929,11 @@ async function roadmapMigrate(deps, yes = false) {
3394
3929
  // src/commands/roadmap.ts
3395
3930
  function register9(program, deps) {
3396
3931
  const roadmap = program.command("roadmap").description("Read and update server roadmaps through the local cache.");
3932
+ roadmap.command("schema").description("Print the roadmap schema reference").action(async () => {
3933
+ const bundled = new URL("./roadmap-schema-reference.md", import.meta.url);
3934
+ const source = new URL("../roadmap-schema-reference.md", import.meta.url);
3935
+ process.stdout.write(await readFile14(existsSync6(bundled) ? bundled : source, "utf8"));
3936
+ });
3397
3937
  roadmap.command("path [slug]").description("Print the cached roadmap path").action((slug) => roadmapPath(deps, slug));
3398
3938
  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
3939
  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 +3961,15 @@ function register9(program, deps) {
3421
3961
  }
3422
3962
 
3423
3963
  // 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";
3964
+ import { execFile as execFile4 } from "child_process";
3965
+ import { promisify as promisify3 } from "util";
3966
+ import { readFile as readFile15, realpath as realpath4 } from "fs/promises";
3967
+ import { existsSync as existsSync7, mkdirSync } from "fs";
3968
+ import path21 from "path";
3429
3969
  import chokidar from "chokidar";
3430
3970
 
3431
3971
  // src/watch-core.ts
3432
- import path17 from "path";
3972
+ import path19 from "path";
3433
3973
  var WatchSet = class {
3434
3974
  constructor(deps) {
3435
3975
  this.deps = deps;
@@ -3478,7 +4018,7 @@ async function reloadRoots(deps) {
3478
4018
  continue;
3479
4019
  }
3480
4020
  try {
3481
- const projectId = repo.projectId ?? (await loadRepoBinding(path17.join(repo.root, "nolto.json")))?.projectId;
4021
+ const projectId = repo.projectId ?? (await loadRepoBinding(path19.join(repo.root, "nolto.json")))?.projectId;
3482
4022
  if (projectId) repos.push({ root: repo.root, projectId });
3483
4023
  else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3484
4024
  } catch (err) {
@@ -3549,7 +4089,7 @@ var RepoWatch = class {
3549
4089
  };
3550
4090
 
3551
4091
  // src/service-install.ts
3552
- import path18 from "path";
4092
+ import path20 from "path";
3553
4093
  import os4 from "os";
3554
4094
  function buildUnitFile(args) {
3555
4095
  return [
@@ -3569,8 +4109,8 @@ function buildUnitFile(args) {
3569
4109
  }
3570
4110
  function getUnitPath(env) {
3571
4111
  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");
4112
+ const base = xdg != null && xdg.length > 0 ? xdg : path20.join(os4.homedir(), ".config");
4113
+ return path20.join(base, "systemd", "user", "nolto-watch.service");
3574
4114
  }
3575
4115
  async function installServiceWith(deps) {
3576
4116
  if (deps.platform !== "linux") {
@@ -3581,7 +4121,7 @@ async function installServiceWith(deps) {
3581
4121
  );
3582
4122
  }
3583
4123
  const unitPath = getUnitPath(deps.env);
3584
- await deps.mkdir(path18.dirname(unitPath));
4124
+ await deps.mkdir(path20.dirname(unitPath));
3585
4125
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
3586
4126
  deps.log(`Wrote ${unitPath}`);
3587
4127
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -3603,7 +4143,7 @@ async function installService() {
3603
4143
  platform: process.platform,
3604
4144
  env: process.env,
3605
4145
  nodePath: process.execPath,
3606
- scriptPath: path18.resolve(process.argv[1] ?? ""),
4146
+ scriptPath: path20.resolve(process.argv[1] ?? ""),
3607
4147
  writeFile: (p, content) => writeFile12(p, content, "utf8"),
3608
4148
  mkdir: async (p) => {
3609
4149
  await mkdir9(p, { recursive: true });
@@ -3728,7 +4268,7 @@ function register10(program, deps) {
3728
4268
  const registryPath = getRegistryPath(process.env);
3729
4269
  const roots = await reloadRoots({
3730
4270
  load: () => loadRegistry(registryPath),
3731
- exists: existsSync6,
4271
+ exists: existsSync7,
3732
4272
  warn: (line2) => {
3733
4273
  process.stderr.write(`Warning: ${line2}
3734
4274
  `);
@@ -3745,7 +4285,7 @@ function register10(program, deps) {
3745
4285
  const startRepo = ({ root, projectId }) => {
3746
4286
  const roadmapsPath = cacheDir(process.env, projectId);
3747
4287
  const warn2 = (line2) => {
3748
- process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path19.basename(root)}] ${line2}
4288
+ process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path21.basename(root)}] ${line2}
3749
4289
  `);
3750
4290
  };
3751
4291
  mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
@@ -3755,14 +4295,14 @@ function register10(program, deps) {
3755
4295
  { root, projectId, onlyDirty },
3756
4296
  {
3757
4297
  env: process.env,
3758
- readFile: (p) => readFile11(p, "utf8"),
4298
+ readFile: (p) => readFile15(p, "utf8"),
3759
4299
  realpath: (p) => realpath4(p),
3760
- fileExists: (p) => existsSync6(p),
4300
+ fileExists: (p) => existsSync7(p),
3761
4301
  repoIdentity: makeRepoIdentityResolver(deps),
3762
- exec: promisify2(execFile3),
4302
+ exec: promisify3(execFile4),
3763
4303
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3764
4304
  http,
3765
- log: (line2) => process.stdout.write(`[${path19.basename(root)}] ${line2}
4305
+ log: (line2) => process.stdout.write(`[${path21.basename(root)}] ${line2}
3766
4306
  `),
3767
4307
  warn: warn2
3768
4308
  }
@@ -3775,13 +4315,11 @@ function register10(program, deps) {
3775
4315
  warn: (line2) => process.stderr.write(line2 + "\n")
3776
4316
  });
3777
4317
  watcher.on("all", (_event, filePath) => {
3778
- if (path19.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
4318
+ if (path21.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3779
4319
  repoWatch.handleEvent(filePath);
3780
4320
  });
3781
- void checkSkillVersionDrift(root, deps.version).then((drifted) => {
3782
- if (drifted.length > 0) {
3783
- warn2(formatSkillVersionDriftWarning(root, deps.version, drifted));
3784
- }
4321
+ void checkSkillDrift(root, { homeSkillDirs: deps.homeSkillDirs }).then((drifted) => {
4322
+ for (const warning of drifted) warn2(warning);
3785
4323
  }).catch(() => {
3786
4324
  });
3787
4325
  void repoWatch.flush();
@@ -3806,7 +4344,7 @@ function register10(program, deps) {
3806
4344
  registryReloadTimer = null;
3807
4345
  void reloadRoots({
3808
4346
  load: () => loadRegistry(registryPath),
3809
- exists: (root) => existsSync6(root),
4347
+ exists: (root) => existsSync7(root),
3810
4348
  warn: (line2) => process.stderr.write(`Warning: ${line2}
3811
4349
  `)
3812
4350
  }).then(async (newRoots) => {
@@ -3843,7 +4381,7 @@ function register10(program, deps) {
3843
4381
  version: running ? state.version : null,
3844
4382
  startedAt: running ? state.startedAt : null,
3845
4383
  stale: running && state.version !== deps.version,
3846
- service: existsSync6(getUnitPath(process.env)) ? "installed" : "not-installed"
4384
+ service: existsSync7(getUnitPath(process.env)) ? "installed" : "not-installed"
3847
4385
  };
3848
4386
  printResult(deps.output.mode === "json" ? result : `${running ? "running" : "not running"}
3849
4387
  service: ${result.service}
@@ -3855,14 +4393,14 @@ stale: ${result.stale}`, deps.output.mode);
3855
4393
  watch.command("stop").description("Stop watch without disabling the installed service.").action(async () => {
3856
4394
  const statePath = getWatchStatePath(process.env);
3857
4395
  const state = await readWatchState(statePath);
3858
- const service = existsSync6(getUnitPath(process.env));
4396
+ const service = existsSync7(getUnitPath(process.env));
3859
4397
  let via = null;
3860
4398
  if (service) {
3861
4399
  await stopServiceWith({
3862
4400
  platform: process.platform,
3863
4401
  exec: async (cmd) => {
3864
4402
  try {
3865
- await promisify2(execFile3)(cmd[0], cmd.slice(1));
4403
+ await promisify3(execFile4)(cmd[0], cmd.slice(1));
3866
4404
  return { code: 0, stderr: "" };
3867
4405
  } catch (error) {
3868
4406
  const e = error;
@@ -3893,11 +4431,11 @@ stale: ${result.stale}`, deps.output.mode);
3893
4431
  });
3894
4432
  watch.command("list").description("List repositories in the watch registry.").action(async () => {
3895
4433
  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) }));
4434
+ const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync7(repo.root) }));
3897
4435
  printResult(deps.output.mode === "json" ? { repos } : repos.map((repo) => `${repo.root} ${repo.projectId ?? "\u2014"}${repo.exists ? "" : " (missing)"}`).join("\n"), deps.output.mode);
3898
4436
  });
3899
4437
  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);
4438
+ const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path21.resolve(arg);
3901
4439
  const { removed } = await removeRepoFromRegistry(getRegistryPath(process.env), root);
3902
4440
  if (!removed) throw new CliError(`${root} is not in the watch registry.`, 2, "Run `nolto watch list` to see registered repositories.");
3903
4441
  printResult(deps.output.mode === "json" ? { removed: true, root } : `Removed ${root} from the watch registry.`, deps.output.mode);
@@ -3905,18 +4443,18 @@ stale: ${result.stale}`, deps.output.mode);
3905
4443
  }
3906
4444
 
3907
4445
  // src/update-cli.ts
3908
- import { execFile as execFile4 } from "child_process";
3909
- import { existsSync as existsSync7 } from "fs";
4446
+ import { execFile as execFile5 } from "child_process";
4447
+ import { existsSync as existsSync8 } from "fs";
3910
4448
  import { realpath as realpath5 } from "fs/promises";
3911
4449
  import { createRequire as createRequire2 } from "module";
3912
- import path21 from "path";
4450
+ import path23 from "path";
3913
4451
  import { fileURLToPath as fileURLToPath3 } from "url";
3914
- import { promisify as promisify3 } from "util";
4452
+ import { promisify as promisify4 } from "util";
3915
4453
 
3916
4454
  // src/update-notifier.ts
3917
- import { readFile as readFile12, writeFile as writeFile9, mkdir as mkdir7 } from "fs/promises";
4455
+ import { readFile as readFile16, writeFile as writeFile10, mkdir as mkdir8 } from "fs/promises";
3918
4456
  import https from "https";
3919
- import path20 from "path";
4457
+ import path22 from "path";
3920
4458
  var PACKAGE = "@nolto/cli";
3921
4459
  var CACHE_FILE = "update-check.json";
3922
4460
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -3974,9 +4512,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3974
4512
  });
3975
4513
  }
3976
4514
  async function writeUpdateCache(cachePath, now, latest2) {
3977
- await mkdir7(path20.dirname(cachePath), { recursive: true });
4515
+ await mkdir8(path22.dirname(cachePath), { recursive: true });
3978
4516
  const payload = { checkedAt: now, latest: latest2 };
3979
- await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
4517
+ await writeFile10(cachePath, JSON.stringify(payload), { mode: 384 });
3980
4518
  }
3981
4519
  async function refreshCache(cachePath, now, fetchLatest) {
3982
4520
  const latest2 = await fetchLatest();
@@ -3985,10 +4523,10 @@ async function refreshCache(cachePath, now, fetchLatest) {
3985
4523
  }
3986
4524
  async function checkForUpdate(opts) {
3987
4525
  if (isDisabled(opts.env)) return null;
3988
- const cachePath = path20.join(opts.configDir, CACHE_FILE);
4526
+ const cachePath = path22.join(opts.configDir, CACHE_FILE);
3989
4527
  let cache = {};
3990
4528
  try {
3991
- cache = JSON.parse(await readFile12(cachePath, "utf8"));
4529
+ cache = JSON.parse(await readFile16(cachePath, "utf8"));
3992
4530
  } catch {
3993
4531
  }
3994
4532
  if (typeof cache.checkedAt !== "number" || opts.now - cache.checkedAt > CACHE_TTL_MS) {
@@ -4093,7 +4631,7 @@ async function updateCliWith(deps) {
4093
4631
  }
4094
4632
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
4095
4633
  await deps.writeCache(
4096
- path21.join(deps.configDir, UPDATE_CACHE_FILE),
4634
+ path23.join(deps.configDir, UPDATE_CACHE_FILE),
4097
4635
  deps.now,
4098
4636
  latest2
4099
4637
  ).catch(() => void 0);
@@ -4124,17 +4662,17 @@ async function updateCliWith(deps) {
4124
4662
  };
4125
4663
  }
4126
4664
  function getCurrentVersion() {
4127
- const dirname = path21.dirname(fileURLToPath3(import.meta.url));
4665
+ const dirname = path23.dirname(fileURLToPath3(import.meta.url));
4128
4666
  const require3 = createRequire2(import.meta.url);
4129
4667
  try {
4130
- const pkg = require3(path21.resolve(dirname, "../package.json"));
4668
+ const pkg = require3(path23.resolve(dirname, "../package.json"));
4131
4669
  return pkg.version ?? "0.0.0";
4132
4670
  } catch {
4133
4671
  return "0.0.0";
4134
4672
  }
4135
4673
  }
4136
4674
  async function updateCli(opts = {}) {
4137
- const execFileAsync = promisify3(execFile4);
4675
+ const execFileAsync = promisify4(execFile5);
4138
4676
  const scriptPath = await realpath5(process.argv[1] ?? "");
4139
4677
  return updateCliWith({
4140
4678
  currentVersion: getCurrentVersion(),
@@ -4159,7 +4697,7 @@ async function updateCli(opts = {}) {
4159
4697
  realpath: realpath5,
4160
4698
  fetchLatest: () => fetchLatestFromRegistry(UPDATE_REQUEST_TIMEOUT_MS, UPDATE_FETCH_OPTIONS),
4161
4699
  writeCache: writeUpdateCache,
4162
- unitExists: existsSync7,
4700
+ unitExists: existsSync8,
4163
4701
  log: opts.quiet === true ? () => void 0 : (line2) => process.stdout.write(line2 + "\n"),
4164
4702
  warn: (line2) => process.stderr.write("Warning: " + line2 + "\n")
4165
4703
  });
@@ -4177,7 +4715,7 @@ function register11(program, deps) {
4177
4715
  }
4178
4716
 
4179
4717
  // src/commands/merge-file.ts
4180
- import { readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
4718
+ import { readFile as readFile17, writeFile as writeFile11 } from "fs/promises";
4181
4719
 
4182
4720
  // src/roadmap-merge.ts
4183
4721
  import { isDeepStrictEqual } from "util";
@@ -4269,7 +4807,7 @@ function mergeTask(args) {
4269
4807
  const dependsOn = [
4270
4808
  ...args.ours.dependsOn ?? [],
4271
4809
  ...args.theirs.dependsOn ?? []
4272
- ].filter((id, index2, values) => values.indexOf(id) === index2);
4810
+ ].filter((id, index, values) => values.indexOf(id) === index);
4273
4811
  if (dependsOn.length > 0) merged.dependsOn = dependsOn;
4274
4812
  const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
4275
4813
  if (issues.length > 0) merged.issues = issues;
@@ -4283,456 +4821,180 @@ function shouldKeep(base, ours, theirs) {
4283
4821
  return true;
4284
4822
  }
4285
4823
  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;
4824
+ const oursPhase = args.ours.phases.find((phase) => phase.id === args.phaseId);
4825
+ const theirsPhase = args.theirs.phases.find((phase) => phase.id === args.phaseId);
4826
+ const ordered = (oursPhase?.tasks ?? []).map((task) => task.id).filter((id) => args.taskIds.has(id));
4827
+ let nearestCommon = null;
4828
+ let insertAfter = null;
4829
+ for (const task of theirsPhase?.tasks ?? []) {
4830
+ if (!args.taskIds.has(task.id)) continue;
4831
+ if (args.oursLocations.has(task.id)) {
4832
+ if (ordered.includes(task.id)) {
4833
+ nearestCommon = task.id;
4834
+ insertAfter = task.id;
4652
4835
  }
4836
+ continue;
4653
4837
  }
4654
- if (entries.length) {
4655
- entries.splice(project < 0 ? entries.length - 1 : project, 1);
4656
- omitted++;
4657
- } else {
4658
- mergedLines.pop();
4659
- omitted++;
4838
+ if (nearestCommon === null || insertAfter === null) {
4839
+ ordered.push(task.id);
4840
+ continue;
4660
4841
  }
4842
+ const index = ordered.indexOf(insertAfter);
4843
+ ordered.splice(index + 1, 0, task.id);
4844
+ insertAfter = task.id;
4661
4845
  }
4662
- return build().join("\n") + "\n";
4846
+ return ordered;
4663
4847
  }
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 {
4848
+ function mergeRoadmaps(args) {
4849
+ const newer = Date.parse(args.theirs.updatedAt ?? "") > Date.parse(args.ours.updatedAt ?? "") ? "theirs" : "ours";
4850
+ const newerRoadmap = newer === "ours" ? args.ours : args.theirs;
4851
+ const olderRoadmap = newer === "ours" ? args.theirs : args.ours;
4852
+ const basePhases = new Map((args.base?.phases ?? []).map((phase) => [phase.id, phase]));
4853
+ const oursPhases = new Map(args.ours.phases.map((phase) => [phase.id, phase]));
4854
+ const theirsPhases = new Map(args.theirs.phases.map((phase) => [phase.id, phase]));
4855
+ const baseLocations = taskLocations(args.base);
4856
+ const oursLocations = taskLocations(args.ours);
4857
+ const theirsLocations = taskLocations(args.theirs);
4858
+ const keptTasks = /* @__PURE__ */ new Map();
4859
+ const targetPhaseByTask = /* @__PURE__ */ new Map();
4860
+ const taskIds = /* @__PURE__ */ new Set([
4861
+ ...baseLocations.keys(),
4862
+ ...oursLocations.keys(),
4863
+ ...theirsLocations.keys()
4864
+ ]);
4865
+ for (const taskId of taskIds) {
4866
+ const baseLocation = baseLocations.get(taskId);
4867
+ const oursLocation = oursLocations.get(taskId);
4868
+ const theirsLocation = theirsLocations.get(taskId);
4869
+ if (!shouldKeep(baseLocation, oursLocation, theirsLocation)) continue;
4870
+ const task = oursLocation !== void 0 && theirsLocation !== void 0 ? mergeTask({
4871
+ base: baseLocation?.task,
4872
+ ours: oursLocation.task,
4873
+ theirs: theirsLocation.task,
4874
+ newer
4875
+ }) : cloneSingleTask((oursLocation ?? theirsLocation).task);
4876
+ keptTasks.set(taskId, task);
4877
+ targetPhaseByTask.set(taskId, (oursLocation ?? theirsLocation).phaseId);
4690
4878
  }
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;
4879
+ const keptPhaseIds = /* @__PURE__ */ new Set();
4880
+ const allPhaseIds = /* @__PURE__ */ new Set([
4881
+ ...basePhases.keys(),
4882
+ ...oursPhases.keys(),
4883
+ ...theirsPhases.keys()
4884
+ ]);
4885
+ for (const phaseId of allPhaseIds) {
4886
+ if (shouldKeep(basePhases.get(phaseId), oursPhases.get(phaseId), theirsPhases.get(phaseId))) {
4887
+ keptPhaseIds.add(phaseId);
4703
4888
  }
4889
+ }
4890
+ const phaseOrder = [
4891
+ ...args.ours.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id)),
4892
+ ...args.theirs.phases.map((phase) => phase.id).filter((id) => keptPhaseIds.has(id) && !oursPhases.has(id))
4893
+ ];
4894
+ const phases = phaseOrder.map((phaseId) => {
4895
+ const base = basePhases.get(phaseId);
4896
+ const ours = oursPhases.get(phaseId);
4897
+ const theirs = theirsPhases.get(phaseId);
4898
+ const source = ours ?? theirs;
4899
+ const title = ours !== void 0 && theirs !== void 0 ? chooseField({
4900
+ baseExists: base !== void 0,
4901
+ base: base?.title,
4902
+ ours: ours.title,
4903
+ theirs: theirs.title,
4904
+ newer
4905
+ }) : source.title;
4906
+ const plan = ours !== void 0 && theirs !== void 0 ? chooseField({
4907
+ baseExists: base !== void 0,
4908
+ base: base?.plan,
4909
+ ours: ours.plan,
4910
+ theirs: theirs.plan,
4911
+ newer
4912
+ }) : source.plan;
4913
+ const phaseTaskIds = new Set(
4914
+ [...keptTasks.keys()].filter((taskId) => targetPhaseByTask.get(taskId) === phaseId)
4915
+ );
4916
+ const tasks = orderTasks({
4917
+ phaseId,
4918
+ taskIds: phaseTaskIds,
4919
+ ours: args.ours,
4920
+ theirs: args.theirs,
4921
+ oursLocations
4922
+ }).map((taskId) => keptTasks.get(taskId));
4923
+ const phase = { id: phaseId, title, status: "todo", tasks };
4924
+ if (plan !== void 0) phase.plan = plan;
4925
+ phase.status = derivePhaseStatus(phase);
4926
+ return phase;
4927
+ });
4928
+ const mergedTasks = new Map(
4929
+ phases.flatMap((phase) => phase.tasks.map((task) => [task.id, task]))
4930
+ );
4931
+ const validCurrentTask = (roadmap) => {
4932
+ const id = roadmap.currentTaskId ?? null;
4933
+ return id != null && mergedTasks.get(id)?.status === "in-progress" ? id : null;
4704
4934
  };
4705
- let checkedOut, target, targetTip;
4935
+ const merged = {
4936
+ schemaVersion: newerRoadmap.updatedAt === void 0 ? 3 : 2,
4937
+ project: { ...newerRoadmap.project },
4938
+ updatedAt: newerRoadmap.updatedAt,
4939
+ currentTaskId: validCurrentTask(newerRoadmap) ?? validCurrentTask(olderRoadmap),
4940
+ summary: newerRoadmap.summary,
4941
+ phases
4942
+ };
4943
+ const validation = validateRoadmap(merged);
4944
+ if (validation.errors.length > 0) {
4945
+ throw new CliError(
4946
+ `Merged roadmap failed validation:
4947
+ ${validation.errors.join("\n ")}`,
4948
+ 1
4949
+ );
4950
+ }
4951
+ return merged;
4952
+ }
4953
+
4954
+ // src/commands/merge-file.ts
4955
+ async function readRoadmap(filePath) {
4956
+ let parsed;
4706
4957
  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;
4958
+ parsed = JSON.parse(await readFile17(filePath, "utf8"));
4959
+ } catch (err) {
4960
+ const message = err instanceof SyntaxError ? "malformed JSON" : String(err);
4961
+ throw new CliError(`${filePath}: ${message}`, 1);
4712
4962
  }
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
- }
4963
+ const validation = validateRoadmap(parsed);
4964
+ if (validation.errors.length > 0) {
4965
+ throw new CliError(
4966
+ `${filePath} failed validation:
4967
+ ${validation.errors.join("\n ")}`,
4968
+ 1
4969
+ );
4724
4970
  }
4725
- return merged;
4971
+ return parsed;
4972
+ }
4973
+ function register12(program) {
4974
+ program.command("merge-file <ours> <theirs>").description(
4975
+ 'Structurally merge roadmap files for Git.\ngit config merge.nolto-roadmap.driver "nolto merge-file %A %B --base %O"'
4976
+ ).option("--base <path>", "Common ancestor roadmap file").option("--output <path>", "Write the result here (defaults to <ours>)").action(async (oursPath, theirsPath, opts) => {
4977
+ process.stderr.write("Warning: merge-file is deprecated and will be removed; roadmaps are no longer stored in git.\n");
4978
+ const ours = await readRoadmap(oursPath);
4979
+ const theirs = await readRoadmap(theirsPath);
4980
+ const base = opts.base == null ? null : await readRoadmap(opts.base);
4981
+ const merged = mergeRoadmaps({ base, ours, theirs });
4982
+ await writeFile11(
4983
+ opts.output ?? oursPath,
4984
+ JSON.stringify(merged, null, 2) + "\n",
4985
+ "utf8"
4986
+ );
4987
+ const taskCount = merged.phases.reduce((total, phase) => total + phase.tasks.length, 0);
4988
+ process.stderr.write(`merged roadmap (${taskCount} tasks)
4989
+ `);
4990
+ process.exitCode = 0;
4991
+ });
4726
4992
  }
4727
4993
 
4728
4994
  // src/commands/memory.ts
4995
+ import { readFile as readFile18 } from "fs/promises";
4729
4996
  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
4997
  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
4998
  var pullHint = "nolto memory pull \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044";
4737
4999
  var scopeHint = "--scope project|user|branch";
4738
5000
  async function context2(deps, recover = false) {
@@ -4741,19 +5003,7 @@ async function context2(deps, recover = false) {
4741
5003
  const project = deps.settings.defaultProjectId ?? binding?.projectId;
4742
5004
  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
5005
  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);
5006
+ return createMemoryContext({ projectId: project, configPath: deps.configPath, root, git: await memoryGitContext(root, deps) }, recover);
4757
5007
  }
4758
5008
  function headers() {
4759
5009
  return { "X-Nolto-Client": detectMemoryClient(process.env) };
@@ -4819,25 +5069,6 @@ async function apiCall(deps, ctx, call, op = "read", name = "<name>") {
4819
5069
  throw new CliError(error.message, error.exitCode, hint, error.status, code, body, detail);
4820
5070
  }
4821
5071
  }
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
5072
  function printWrite(deps, ctx, action, response, isNew = false) {
4842
5073
  if (deps.output.mode === "json") {
4843
5074
  printResult(response, "json");
@@ -4891,7 +5122,7 @@ async function pull2(deps, opts) {
4891
5122
  const projectName = projects?.projects?.find((p) => p.id === ctx.project)?.name ?? ctx.cache.state.projectName;
4892
5123
  const userId = typeof profile?.profile?.id === "string" ? profile.profile.id : ctx.cache.state.userId;
4893
5124
  const next = { ...ctx, cache: { state: { entries, scope, projectName, ...userId ? { userId } : {} }, meta: { cursor, pulledAt: (/* @__PURE__ */ new Date()).toISOString() } } };
4894
- const text = await index(next, deps);
5125
+ const text = await memoryIndexText(next, deps);
4895
5126
  const unsafe = await saveMemoryCache(ctx.dir, next.cache, previous, text, reset);
4896
5127
  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
5128
  `);
@@ -4904,7 +5135,7 @@ async function pull2(deps, opts) {
4904
5135
  try {
4905
5136
  const age = Math.max(0, Math.floor((Date.now() - Date.parse(ctx.cache.meta.pulledAt)) / 6e4));
4906
5137
  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)}`;
5138
+ ${await memoryIndexText(ctx, deps)}`;
4908
5139
  } catch {
4909
5140
  }
4910
5141
  }
@@ -4912,7 +5143,7 @@ ${await index(ctx, deps)}`;
4912
5143
  }
4913
5144
  }
4914
5145
  async function inputText(file) {
4915
- if (file !== "-") return readFile15(file, "utf8");
5146
+ if (file !== "-") return readFile18(file, "utf8");
4916
5147
  let text = "";
4917
5148
  process.stdin.setEncoding("utf8");
4918
5149
  for await (const chunk of process.stdin) text += chunk;
@@ -4923,7 +5154,7 @@ function register13(program, deps) {
4923
5154
  memory.command("pull").option("--hook [agent]", "SessionStart output; always exit 0").option("--scope <csv>").action((opts) => pull2(deps, opts));
4924
5155
  memory.command("context").action(async () => {
4925
5156
  const ctx = await context2(deps);
4926
- process.stdout.write(ctx.cache.meta.pulledAt || ctx.cache.state.entries.length ? await index(ctx, deps) : pullHint + "\n");
5157
+ process.stdout.write(ctx.cache.meta.pulledAt || ctx.cache.state.entries.length ? await memoryIndexText(ctx, deps) : pullHint + "\n");
4927
5158
  });
4928
5159
  memory.command("instructions").action(() => {
4929
5160
  process.stdout.write(MEMORY_INSTRUCTIONS + "\n");
@@ -5002,48 +5233,35 @@ function register13(program, deps) {
5002
5233
  });
5003
5234
  memory.command("hook").command("install").option("--agent <agent>").option("--write-agents-md").action(async (opts) => {
5004
5235
  const { root } = findRepoRoot(resolveStartDir(process.env, process.cwd()));
5005
- const messages = await installMemoryHooks(root, deps.version, opts.agent, opts.writeAgentsMd);
5236
+ const messages = await installMemoryHooks(root, opts.agent, opts.writeAgentsMd);
5006
5237
  printResult(deps.output.mode === "json" ? { messages } : messages.join("\n"), deps.output.mode);
5007
5238
  });
5008
5239
  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
5240
  const scope = parseScope(opts.scope, "--scope project|user");
5010
5241
  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
5242
  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
- }
5243
+ const scan = await scanMemoryDir(dir);
5244
+ const lines = /* @__PURE__ */ new Map();
5245
+ let position = 0;
5246
+ const result = await importMemoryFiles({
5247
+ http: deps.http,
5248
+ projectId: ctx.project,
5249
+ configPath: deps.configPath,
5250
+ root: ctx.root,
5251
+ scope,
5252
+ targets: scan.ok,
5253
+ ai: opts.ai,
5254
+ git: ctx.git,
5255
+ memoryGit: deps.memoryGit,
5256
+ write: (line2) => {
5257
+ lines.set(scan.ok[position++].file, line2);
5042
5258
  }
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
- `);
5259
+ });
5260
+ const { imported, skipped, cached } = result;
5261
+ const failed = result.failed + scan.invalid.length;
5262
+ const results = [...result.results, ...scan.invalid].sort((a, b) => a.file.localeCompare(b.file));
5263
+ if (deps.output.mode !== "json") {
5264
+ for (const item of results) process.stdout.write((lines.get(item.file) ?? importResultLine(scope, item)) + "\n");
5047
5265
  }
5048
5266
  const skippedNames = results.filter((r) => r.status === "skipped").map((r) => `${scope}/${String(r.name)}`);
5049
5267
  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 +5366,11 @@ async function main() {
5148
5366
  output: { mode },
5149
5367
  version,
5150
5368
  configPath,
5369
+ claudeProjectsDir: path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "projects"),
5370
+ homeSkillDirs: [
5371
+ path24.join(process.env.CLAUDE_CONFIG_DIR ?? path24.join(os5.homedir(), ".claude"), "skills"),
5372
+ path24.join(os5.homedir(), ".agents", "skills")
5373
+ ],
5151
5374
  repoBinding
5152
5375
  });
5153
5376
  await program.parseAsync(process.argv);