@nolto/cli 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,27 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/index.ts
4
- import { createRequire as createRequire3 } from "module";
5
- import { fileURLToPath as fileURLToPath4 } from "url";
6
- import path21 from "path";
7
- import { CommanderError } from "commander";
8
-
9
- // src/config.ts
10
- import { readFile, writeFile, mkdir, stat } from "fs/promises";
11
- import { statSync } from "fs";
12
- import os from "os";
13
- import path from "path";
14
- import { z } from "zod";
3
+ // src/memory-hooks.ts
4
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
5
+ import { existsSync as existsSync2 } from "fs";
6
+ import path2 from "path";
15
7
 
16
8
  // src/errors.ts
17
9
  var CliError = class extends Error {
18
- constructor(message, exitCode, hint, status, serverError, body) {
10
+ constructor(message, exitCode, hint, status, serverError, body, detail) {
19
11
  super(message);
20
12
  this.exitCode = exitCode;
21
13
  this.hint = hint;
22
14
  this.status = status;
23
15
  this.serverError = serverError;
24
16
  this.body = body;
17
+ this.detail = detail;
25
18
  this.name = "CliError";
26
19
  }
27
20
  exitCode;
@@ -29,8 +22,12 @@ var CliError = class extends Error {
29
22
  status;
30
23
  serverError;
31
24
  body;
25
+ detail;
32
26
  };
33
27
  function mapHttpStatusToCliError(status, opts = {}) {
28
+ if (opts.serverError?.startsWith("memory_") || status === 400 && opts.serverError === "invalid_input") {
29
+ return new CliError(opts.serverMessage ?? opts.serverError, 2, void 0, status, opts.serverError, opts.body);
30
+ }
34
31
  if (status === 401) {
35
32
  const detail = opts.wwwAuthenticate ? ` (${opts.wwwAuthenticate})` : "";
36
33
  return new CliError(
@@ -148,22 +145,194 @@ function mapHttpStatusToCliError(status, opts = {}) {
148
145
  const reason = opts.serverMessage ?? opts.serverError;
149
146
  return new CliError(reason ? `Server returned HTTP ${status}: ${reason}` : `Server returned HTTP ${status}`, 5, void 0, status, opts.serverError, opts.body);
150
147
  }
148
+ var NETWORK_ERROR_CODES = [
149
+ "ECONNREFUSED",
150
+ "ENOTFOUND",
151
+ "EAI_AGAIN",
152
+ "ETIMEDOUT",
153
+ "ECONNRESET",
154
+ "ENETUNREACH",
155
+ "EHOSTUNREACH",
156
+ "EPERM",
157
+ "EACCES",
158
+ "UND_ERR_CONNECT_TIMEOUT"
159
+ ];
151
160
  function isNetworkError(err) {
152
161
  if (!(err instanceof Error)) {
153
162
  return false;
154
163
  }
155
- const cause = err.cause;
156
- const causeCode = cause != null && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
157
- const networkCodes = ["ECONNREFUSED", "ENOTFOUND", "ETIMEDOUT", "EAI_AGAIN"];
158
- if (networkCodes.some((c) => causeCode === c)) {
159
- return true;
164
+ const codes = /* @__PURE__ */ new Set();
165
+ const collect = (value, depth) => {
166
+ if (value == null || typeof value !== "object" || depth > 3) return;
167
+ const record = value;
168
+ if (typeof record.code === "string") codes.add(record.code);
169
+ collect(record.cause, depth + 1);
170
+ if (Array.isArray(record.errors)) for (const inner of record.errors) collect(inner, depth + 1);
171
+ };
172
+ collect(err, 0);
173
+ return [...codes].some((code) => NETWORK_ERROR_CODES.includes(code));
174
+ }
175
+
176
+ // src/skill-install.ts
177
+ import { cp, mkdir, readFile, writeFile, rm } from "fs/promises";
178
+ import { existsSync } from "fs";
179
+ import path from "path";
180
+ import { fileURLToPath } from "url";
181
+ var __dirname = path.dirname(fileURLToPath(import.meta.url));
182
+ function resolveSkillSourceDir(name = "roadmap-progress") {
183
+ const candidates = [
184
+ path.resolve(__dirname, `skill/${name}`),
185
+ // bundled: dist/skill/...
186
+ path.resolve(__dirname, `../../../skills/${name}`)
187
+ // source: <repo>/skills/...
188
+ ];
189
+ for (const candidate of candidates) {
190
+ if (existsSync(path.join(candidate, "SKILL.md"))) return candidate;
160
191
  }
161
- if (err.message.includes("fetch failed") || err.message.includes("ECONNREFUSED") || err.message.includes("ENOTFOUND")) {
162
- return true;
192
+ throw new Error(`Bundled ${name} skill not found. Reinstall @nolto/cli.`);
193
+ }
194
+ 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;
209
+ }
210
+ if (installed !== cliVersion) drifted.push({ dir, installed });
163
211
  }
164
- return false;
212
+ return drifted;
213
+ }
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.`;
218
+ }
219
+ async function installSkill(args) {
220
+ const targetDir = path.join(args.skillsParentDir, args.name ?? "roadmap-progress");
221
+ const markerPath = path.join(targetDir, VERSION_MARKER);
222
+ const dirExists = existsSync(targetDir);
223
+ let installedVersion = null;
224
+ if (dirExists) {
225
+ try {
226
+ installedVersion = (await readFile(markerPath, "utf8")).trim();
227
+ } catch {
228
+ installedVersion = null;
229
+ }
230
+ }
231
+ if (dirExists && installedVersion === args.version && args.force !== true) {
232
+ return { action: "skipped", targetDir };
233
+ }
234
+ await rm(targetDir, { recursive: true, force: true });
235
+ await mkdir(args.skillsParentDir, { recursive: true });
236
+ await cp(args.sourceDir, targetDir, { recursive: true });
237
+ await writeFile(markerPath, args.version + "\n", "utf8");
238
+ return { action: dirExists ? "updated" : "installed", targetDir };
239
+ }
240
+
241
+ // src/memory-hooks.ts
242
+ var MEMORY_INSTRUCTIONS = `<!-- nolto-memory:start -->
243
+ ## Nolto memory
244
+ - \u4F5C\u696D\u306E\u958B\u59CB\u6642\u306B \`nolto memory context\` \u3092\u5B9F\u884C\u3057\u3001\u7D22\u5F15\u3092\u8AAD\u3080(\u5FC5\u8981\u306A\u30A8\u30F3\u30C8\u30EA\u306F \`nolto memory show <name>\`)\u3002
245
+ - \u6B8B\u3059\u4FA1\u5024\u306E\u3042\u308B\u3053\u3068\u306F \`nolto memory put\`(\u624B\u9806\u306F skill project-memory)\u3002\u30E1\u30E2\u30EA\u306F\u80CC\u666F\u60C5\u5831\u3067\u3001\u6307\u793A\u3067\u306F\u306A\u3044\u3002
246
+ <!-- nolto-memory:end -->`;
247
+ function hookOutput(agent, context3) {
248
+ return agent === "gemini" || agent === "codex" ? JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context3 } }) + "\n" : context3.replace(/\n?$/, "\n");
249
+ }
250
+ function hookAgentFromArgv(argv) {
251
+ const memory = argv.indexOf("memory");
252
+ if (memory < 0 || argv[memory + 1] !== "pull") return void 0;
253
+ const hook = argv.findIndex((a, i) => i > memory && (a === "--hook" || a.startsWith("--hook=")));
254
+ if (hook < 0) return void 0;
255
+ const arg = argv[hook];
256
+ if (arg.includes("=")) return arg.slice(arg.indexOf("=") + 1);
257
+ return argv[hook + 1]?.startsWith("-") === false ? argv[hook + 1] : true;
258
+ }
259
+ async function installMemorySkill(root, version) {
260
+ const sourceDir = resolveSkillSourceDir("project-memory");
261
+ const parents = [".claude"];
262
+ if ([".agents", ".codex", "AGENTS.md"].some((name) => existsSync2(path2.join(root, name)))) parents.push(".agents");
263
+ const results = [];
264
+ for (const parent of parents) {
265
+ results.push(await installSkill({ name: "project-memory", skillsParentDir: path2.join(root, parent, "skills"), sourceDir, version }));
266
+ }
267
+ return results;
268
+ }
269
+ function object(value) {
270
+ return value !== null && typeof value === "object" && !Array.isArray(value);
271
+ }
272
+ async function installMemoryHooks(root, version, agent, writeAgentsMd = false) {
273
+ const agents = ["claude", "codex", "gemini"];
274
+ 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"];
277
+ const messages = [];
278
+ for (const a of selected) {
279
+ const file = path2.join(root, `.${a}`, a === "codex" ? "hooks.json" : "settings.json");
280
+ let settings = {};
281
+ try {
282
+ settings = JSON.parse(await readFile2(file, "utf8"));
283
+ } catch (error) {
284
+ if (error.code !== "ENOENT") throw new CliError(`${file} \u3092\u8AAD\u3081\u307E\u305B\u3093\u3002`, 2);
285
+ }
286
+ if (!object(settings) || settings.hooks !== void 0 && !object(settings.hooks)) throw new CliError(`${file}: hooks \u306E\u5F62\u304C\u4E0D\u6B63\u3067\u3059\u3002`, 2);
287
+ const hooks = settings.hooks ?? {};
288
+ const start = hooks.SessionStart ?? [];
289
+ 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));
292
+ if (!present) {
293
+ hooks.SessionStart = [...start, { hooks: [{ type: "command", command }] }];
294
+ settings.hooks = hooks;
295
+ await mkdir2(path2.dirname(file), { recursive: true });
296
+ await writeFile2(file, JSON.stringify(settings, null, 2) + "\n");
297
+ }
298
+ messages.push(`hook ${a}: ${present ? "\u8A2D\u5B9A\u6E08\u307F" : "\u8FFD\u52A0"}`);
299
+ if (a === "codex") messages.push(
300
+ "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
+ );
302
+ }
303
+ for (const skill of await installMemorySkill(root, version)) messages.push(`skill project-memory: ${skill.action} ${path2.relative(root, skill.targetDir)}`);
304
+ messages.push("AGENTS.md \u306B\u8DB3\u3059\u6307\u793A\u306F nolto memory instructions");
305
+ if (writeAgentsMd) {
306
+ const file = path2.join(root, "AGENTS.md");
307
+ try {
308
+ const old = await readFile2(file, "utf8");
309
+ const block = /<!-- nolto-memory:start -->[\s\S]*?<!-- nolto-memory:end -->/g;
310
+ const next = block.test(old) ? old.replace(block, () => MEMORY_INSTRUCTIONS) : `${old.replace(/\n?$/, "\n")}
311
+ ${MEMORY_INSTRUCTIONS}
312
+ `;
313
+ if (old !== next) await writeFile2(file, next);
314
+ messages.push(old !== next ? "AGENTS.md \u3092\u66F4\u65B0\u3057\u305F" : "AGENTS.md \u306F\u6700\u65B0");
315
+ } catch (error) {
316
+ if (error.code !== "ENOENT") throw error;
317
+ messages.push("AGENTS.md \u304C\u7121\u3044\u305F\u3081\u6307\u793A\u306E\u8FFD\u52A0\u3092\u7701\u7565\u3057\u305F");
318
+ }
319
+ }
320
+ return messages;
165
321
  }
166
322
 
323
+ // src/index.ts
324
+ import { createRequire as createRequire3 } from "module";
325
+ import { fileURLToPath as fileURLToPath4 } from "url";
326
+ import path24 from "path";
327
+ import { CommanderError } from "commander";
328
+
329
+ // src/config.ts
330
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3, stat } from "fs/promises";
331
+ import { statSync } from "fs";
332
+ import os from "os";
333
+ import path3 from "path";
334
+ import { z } from "zod";
335
+
167
336
  // src/constants.ts
168
337
  var DOCUMENT_MAX_BYTES = 2 * 1024 * 1024;
169
338
  var DEFAULT_BASE_URL = "https://nolto.app";
@@ -182,7 +351,7 @@ var repoBindingSchema = z.object({
182
351
  async function loadRepoBinding(filePath) {
183
352
  let raw;
184
353
  try {
185
- raw = await readFile(filePath, "utf8");
354
+ raw = await readFile3(filePath, "utf8");
186
355
  } catch (err) {
187
356
  const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
188
357
  if (code === "ENOENT") {
@@ -210,13 +379,13 @@ async function loadRepoBinding(filePath) {
210
379
  function findNoltoJsonSync(startDir) {
211
380
  let current = startDir;
212
381
  while (true) {
213
- const candidate = path.join(current, "nolto.json");
382
+ const candidate = path3.join(current, "nolto.json");
214
383
  try {
215
384
  statSync(candidate);
216
385
  return candidate;
217
386
  } catch {
218
387
  }
219
- const parent = path.dirname(current);
388
+ const parent = path3.dirname(current);
220
389
  if (parent === current) break;
221
390
  current = parent;
222
391
  }
@@ -230,7 +399,7 @@ function findRepoBindingFile(args) {
230
399
  async function mergeJsonFile(filePath, patch) {
231
400
  let existing = {};
232
401
  try {
233
- const raw = await readFile(filePath, "utf8");
402
+ const raw = await readFile3(filePath, "utf8");
234
403
  const parsed = JSON.parse(raw);
235
404
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
236
405
  throw new CliError(
@@ -247,20 +416,20 @@ async function mergeJsonFile(filePath, patch) {
247
416
  }
248
417
  const merged = { ...existing, ...patch };
249
418
  const { chmod: chmod2 } = await import("fs/promises");
250
- await writeFile(filePath, JSON.stringify(merged, null, 2) + "\n", { mode: 420 });
419
+ await writeFile3(filePath, JSON.stringify(merged, null, 2) + "\n", { mode: 420 });
251
420
  await chmod2(filePath, 420);
252
421
  }
253
422
  async function writeRepoBinding(root, projectId) {
254
- await mergeJsonFile(path.join(root, "nolto.json"), { projectId });
423
+ await mergeJsonFile(path3.join(root, "nolto.json"), { projectId });
255
424
  }
256
425
  function getConfigDir(env) {
257
426
  if (env["NOLTO_HOME"]) return env["NOLTO_HOME"];
258
427
  const xdg = env["XDG_CONFIG_HOME"];
259
- const base = xdg != null && xdg.length > 0 ? xdg : path.join(os.homedir(), ".config");
260
- return path.join(base, "nolto");
428
+ const base = xdg != null && xdg.length > 0 ? xdg : path3.join(os.homedir(), ".config");
429
+ return path3.join(base, "nolto");
261
430
  }
262
431
  function getConfigPath(env) {
263
- return path.join(getConfigDir(env), "config.json");
432
+ return path3.join(getConfigDir(env), "config.json");
264
433
  }
265
434
  async function loadConfigFile(filePath) {
266
435
  try {
@@ -278,7 +447,7 @@ async function loadConfigFile(filePath) {
278
447
  }
279
448
  let raw;
280
449
  try {
281
- raw = await readFile(filePath, "utf8");
450
+ raw = await readFile3(filePath, "utf8");
282
451
  } catch (err) {
283
452
  throw new CliError(`Cannot read config file: ${filePath}: ${String(err)}`, 2);
284
453
  }
@@ -304,8 +473,8 @@ async function loadConfigFile(filePath) {
304
473
  return result.data;
305
474
  }
306
475
  async function saveConfigFile(filePath, value) {
307
- await mkdir(path.dirname(filePath), { recursive: true, mode: 448 });
308
- await writeFile(filePath, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
476
+ await mkdir3(path3.dirname(filePath), { recursive: true, mode: 448 });
477
+ await writeFile3(filePath, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
309
478
  }
310
479
  function resolveProjectId(args) {
311
480
  const { flagProject, envProject, repoBinding, fileProjectId } = args;
@@ -372,32 +541,42 @@ function maskToken(token) {
372
541
  function createHttpClient(opts) {
373
542
  const { baseUrl, version, token } = opts;
374
543
  const base = baseUrl.replace(/\/+$/, "");
375
- async function request(method, path22, body) {
376
- if (!path22.startsWith("/api/")) {
377
- throw new CliError(`HTTP client path must start with /api/, got: ${path22}`, 2);
544
+ async function request(method, path25, body, extraHeaders, signal) {
545
+ if (!path25.startsWith("/api/")) {
546
+ throw new CliError(`HTTP client path must start with /api/, got: ${path25}`, 2);
378
547
  }
379
- const url = `${base}${path22}`;
380
- const headers = {
548
+ const url = `${base}${path25}`;
549
+ const headers2 = {
550
+ ...extraHeaders,
381
551
  "Content-Type": "application/json",
382
552
  "User-Agent": `${CLI_USER_AGENT_NAME}/${version}`
383
553
  };
384
554
  if (token) {
385
- headers["Authorization"] = `Bearer ${token}`;
555
+ headers2["Authorization"] = `Bearer ${token}`;
386
556
  }
387
557
  let response;
388
558
  try {
389
559
  response = await fetch(url, {
390
560
  method,
391
- headers,
392
- body: body === void 0 ? void 0 : JSON.stringify(body)
561
+ headers: headers2,
562
+ body: body === void 0 ? void 0 : JSON.stringify(body),
563
+ ...signal ? { signal } : {}
393
564
  });
394
565
  } catch (err) {
395
566
  if (isNetworkError(err)) {
396
567
  throw new CliError(
397
568
  `Network error contacting ${base}: ${err instanceof Error ? err.message : String(err)}`,
398
- 5
569
+ 5,
570
+ "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u306B\u51FA\u3089\u308C\u306A\u3044\u74B0\u5883(Codex \u306E sandbox \u306A\u3069)\u3002sandbox \u306E\u5916\u3067\u5B9F\u884C\u3059\u308B\u627F\u8A8D\u3092\u6C42\u3081\u308B",
571
+ void 0,
572
+ "network_unavailable"
399
573
  );
400
574
  }
575
+ if (err instanceof TypeError && err.message === "fetch failed") {
576
+ const cause = err.cause;
577
+ const code = typeof cause?.code === "string" ? ` (${cause.code})` : "";
578
+ throw new CliError(`Network error contacting ${base}: fetch failed${code}`, 5);
579
+ }
401
580
  throw err;
402
581
  }
403
582
  if (!response.ok) {
@@ -427,11 +606,11 @@ function createHttpClient(opts) {
427
606
  return response.json();
428
607
  }
429
608
  return {
430
- get: (p) => request("GET", p),
431
- post: (p, b) => request("POST", p, b),
432
- patch: (p, b) => request("PATCH", p, b),
433
- delete: (p) => request("DELETE", p),
434
- put: (p, b) => request("PUT", p, b)
609
+ get: (p, signal) => request("GET", p, void 0, void 0, signal),
610
+ post: (p, b, h) => request("POST", p, b, h),
611
+ patch: (p, b, h) => request("PATCH", p, b, h),
612
+ delete: (p, h) => request("DELETE", p, void 0, h),
613
+ put: (p, b, h) => request("PUT", p, b, h)
435
614
  };
436
615
  }
437
616
 
@@ -439,8 +618,8 @@ function createHttpClient(opts) {
439
618
  import { Command } from "commander";
440
619
 
441
620
  // src/commands/issue.ts
442
- import { readFile as readFile2, readdir, writeFile as writeFile2, rename, rm } from "fs/promises";
443
- import path2 from "path";
621
+ import { readFile as readFile4, readdir, writeFile as writeFile4, rename, rm as rm2 } from "fs/promises";
622
+ import path4 from "path";
444
623
  import { randomUUID } from "crypto";
445
624
 
446
625
  // src/output.ts
@@ -457,6 +636,11 @@ function printError(err, mode2) {
457
636
  const envelope = {
458
637
  error: {
459
638
  message: err.message,
639
+ ...err.serverError ? { code: err.serverError } : {},
640
+ ...err.body?.["entry"] ? { entry: err.body["entry"] } : {},
641
+ ...err.body?.["candidates"] ? { candidates: err.body["candidates"] } : {},
642
+ ...err.body?.["conflicts"] ? { conflicts: err.body["conflicts"] } : {},
643
+ ...err.body && "aiSkipped" in err.body ? { aiSkipped: err.body["aiSkipped"] } : {},
460
644
  exitCode: err.exitCode,
461
645
  ...err.status != null ? { status: err.status } : {},
462
646
  ...err.hint != null ? { hint: err.hint } : {}
@@ -464,8 +648,10 @@ function printError(err, mode2) {
464
648
  };
465
649
  process.stderr.write(JSON.stringify(envelope, null, 2) + "\n");
466
650
  } else {
467
- process.stderr.write(`Error: ${err.message}
651
+ const code = err.serverError && !err.message.startsWith(err.serverError) ? `${err.serverError}: ` : "";
652
+ process.stderr.write(`Error: ${code}${err.message}
468
653
  `);
654
+ if (err.detail) process.stderr.write(err.detail.replace(/\n?$/, "\n"));
469
655
  if (err.hint != null) {
470
656
  process.stderr.write(`Hint: ${err.hint}
471
657
  `);
@@ -518,12 +704,12 @@ function normalizeRemote(raw) {
518
704
  const firstSlash = s.indexOf("/");
519
705
  if (firstSlash <= 0) return null;
520
706
  let host = s.slice(0, firstSlash).toLowerCase();
521
- let path22 = s.slice(firstSlash + 1);
707
+ let path25 = s.slice(firstSlash + 1);
522
708
  if (hadScheme) host = host.replace(/:\d+$/, "");
523
- path22 = path22.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
524
- if (path22.length === 0) return null;
525
- if (HOSTED_LOWERCASE_PATH.has(host)) path22 = path22.toLowerCase();
526
- return `${host}/${path22}`;
709
+ path25 = path25.replace(/\/+/g, "/").replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
710
+ if (path25.length === 0) return null;
711
+ if (HOSTED_LOWERCASE_PATH.has(host)) path25 = path25.toLowerCase();
712
+ return `${host}/${path25}`;
527
713
  }
528
714
  function repoIdentityToString(id) {
529
715
  return `${id.kind}:${id.value}`;
@@ -552,7 +738,7 @@ function checkKeys(value, allowed, at, errors) {
552
738
  function isValidPlanPath(value) {
553
739
  if (typeof value !== "string" || value.length === 0) return false;
554
740
  if (value.includes("\\") || value.startsWith("/") || /^[A-Za-z]:/.test(value)) return false;
555
- return /\.(md|markdown)$/i.test(value) && value.split("/").every((segment, index) => segment !== "" && (!segment.startsWith(".") || index === 0 && segment === ".nolto"));
741
+ return /\.(md|markdown)$/i.test(value) && value.split("/").every((segment, index2) => segment !== "" && (!segment.startsWith(".") || index2 === 0 && segment === ".nolto"));
556
742
  }
557
743
  function daysInMonth(year, month) {
558
744
  if (month === 2) {
@@ -833,8 +1019,8 @@ function formatIssueList(rows, meta) {
833
1019
  const subject = Array.from(singleLine(row.subject));
834
1020
  return [row.key, row.status.name, row.priority, personLabel(row.assignee), subject.length > 60 ? `${subject.slice(0, 59).join("")}\u2026` : subject.join("")].map(singleLine);
835
1021
  });
836
- const widths = [0, 1, 2, 3].map((index) => Math.max(0, ...values.map((row) => row[index].length)));
837
- const lines = values.map((row) => row.map((value, index) => index < 4 ? value.padEnd(widths[index]) : value).join(" "));
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(" "));
838
1024
  return [...lines, `${rows.length} / ${meta.total} (page ${meta.page})`].join("\n");
839
1025
  }
840
1026
  function formatIssueView(bundle) {
@@ -889,7 +1075,7 @@ async function bodyText(body, file) {
889
1075
  if (body !== void 0 && file !== void 0) throw new CliError("Use either --body/-m or --body-file, not both.", 2);
890
1076
  if (file === void 0) return body;
891
1077
  try {
892
- if (file !== "-") return await readFile2(file, "utf8");
1078
+ if (file !== "-") return await readFile4(file, "utf8");
893
1079
  const chunks = [];
894
1080
  for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
895
1081
  return Buffer.concat(chunks).toString("utf8");
@@ -938,32 +1124,32 @@ function localTimestamp() {
938
1124
  return `${new Date(date.getTime() + minutes * 6e4).toISOString().slice(0, -1)}${minutes >= 0 ? "+" : "-"}${pad(Math.trunc(minutes / 60))}:${pad(minutes % 60)}`;
939
1125
  }
940
1126
  async function attachRoadmap(deps, taskId, slug, key) {
941
- let directory = path2.dirname(deps.repoBinding?.path ?? deps.projectBindingPath ?? path2.join(process.cwd(), "nolto.json"));
1127
+ let directory = path4.dirname(deps.repoBinding?.path ?? deps.projectBindingPath ?? path4.join(process.cwd(), "nolto.json"));
942
1128
  let file = "";
943
1129
  try {
944
1130
  if (slug !== void 0 && !/^[a-z0-9][a-z0-9._-]*$/.test(slug)) throw new Error("Invalid --roadmap slug.");
945
1131
  let entries;
946
1132
  for (; ; ) {
947
1133
  try {
948
- entries = await readdir(path2.join(directory, ".nolto", "roadmaps"));
1134
+ entries = await readdir(path4.join(directory, ".nolto", "roadmaps"));
949
1135
  break;
950
1136
  } catch (error) {
951
- if (error.code !== "ENOENT" || path2.dirname(directory) === directory) throw error;
952
- directory = path2.dirname(directory);
1137
+ if (error.code !== "ENOENT" || path4.dirname(directory) === directory) throw error;
1138
+ directory = path4.dirname(directory);
953
1139
  }
954
1140
  }
955
1141
  const names = entries.filter((name) => name.endsWith(".json")).sort();
956
1142
  if (slug === void 0 && names.length !== 1) throw new Error(`Choose --roadmap <slug>. Candidates: ${names.map((name) => name.slice(0, -5)).join(", ") || "(none)"}`);
957
- file = path2.join(directory, ".nolto", "roadmaps", slug === void 0 ? names[0] : `${slug}.json`);
958
- const result = addIssueToRoadmapTask(JSON.parse(await readFile2(file, "utf8")), taskId, key, localTimestamp());
1143
+ file = path4.join(directory, ".nolto", "roadmaps", slug === void 0 ? names[0] : `${slug}.json`);
1144
+ const result = addIssueToRoadmapTask(JSON.parse(await readFile4(file, "utf8")), taskId, key, localTimestamp());
959
1145
  if ("error" in result) throw new Error(`${result.error} in ${file}`);
960
1146
  if (result.changed) {
961
1147
  const temp = `${file}.${randomUUID()}.tmp`;
962
1148
  try {
963
- await writeFile2(temp, JSON.stringify(result.roadmap, null, 2) + "\n", { flag: "wx" });
1149
+ await writeFile4(temp, JSON.stringify(result.roadmap, null, 2) + "\n", { flag: "wx" });
964
1150
  await rename(temp, file);
965
1151
  } finally {
966
- await rm(temp, { force: true });
1152
+ await rm2(temp, { force: true });
967
1153
  }
968
1154
  }
969
1155
  process.stderr.write("Run `nolto sync` to link it on Nolto.\n");
@@ -1039,7 +1225,7 @@ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
1039
1225
  // src/watch-state.ts
1040
1226
  import * as fs from "fs/promises";
1041
1227
  import { randomUUID as randomUUID2 } from "crypto";
1042
- import path3 from "path";
1228
+ import path5 from "path";
1043
1229
  import { z as z2 } from "zod";
1044
1230
  var watchStateSchema = z2.object({
1045
1231
  pid: z2.number().int().positive(),
@@ -1047,7 +1233,7 @@ var watchStateSchema = z2.object({
1047
1233
  startedAt: z2.string().datetime()
1048
1234
  });
1049
1235
  function getWatchStatePath(env) {
1050
- return path3.join(getConfigDir(env), "watch.json");
1236
+ return path5.join(getConfigDir(env), "watch.json");
1051
1237
  }
1052
1238
  async function readWatchState(filePath, io = fs) {
1053
1239
  try {
@@ -1058,7 +1244,7 @@ async function readWatchState(filePath, io = fs) {
1058
1244
  }
1059
1245
  }
1060
1246
  async function writeWatchState(filePath, state, io = fs) {
1061
- await io.mkdir(path3.dirname(filePath), { recursive: true, mode: 448 });
1247
+ await io.mkdir(path5.dirname(filePath), { recursive: true, mode: 448 });
1062
1248
  const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID2()}`;
1063
1249
  try {
1064
1250
  await io.writeFile(tempPath, JSON.stringify(state, null, 2) + "\n", { encoding: "utf8", mode: 384 });
@@ -1094,22 +1280,22 @@ import readline2 from "readline/promises";
1094
1280
  import { createRequire } from "module";
1095
1281
  import { fileURLToPath as fileURLToPath2 } from "url";
1096
1282
  import os3 from "os";
1097
- import path12 from "path";
1283
+ import path13 from "path";
1098
1284
  import fs2 from "fs";
1099
1285
 
1100
1286
  // src/roadmap-bootstrap.ts
1101
- import { existsSync } from "fs";
1102
- import { readFile as readFile4, realpath } from "fs/promises";
1103
- import path6 from "path";
1287
+ import { existsSync as existsSync3 } from "fs";
1288
+ import { readFile as readFile6, realpath } from "fs/promises";
1289
+ import path8 from "path";
1104
1290
 
1105
1291
  // src/roadmap-cache.ts
1106
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, writeFile as writeFile3, rename as rename2, unlink } from "fs/promises";
1292
+ import { mkdir as mkdir4, readdir as readdir2, readFile as readFile5, writeFile as writeFile5, rename as rename2, unlink } from "fs/promises";
1107
1293
  import { randomUUID as randomUUID3 } from "crypto";
1108
- import path5 from "path";
1294
+ import path7 from "path";
1109
1295
 
1110
1296
  // src/sync-core.ts
1111
1297
  import { createHash } from "crypto";
1112
- import path4 from "path";
1298
+ import path6 from "path";
1113
1299
  function sha256Hex(content) {
1114
1300
  return "sha256:" + createHash("sha256").update(content, "utf8").digest("hex");
1115
1301
  }
@@ -1130,10 +1316,10 @@ function collectPlanRefs(roadmap) {
1130
1316
  }
1131
1317
  return refs;
1132
1318
  }
1133
- async function loadValidRoadmap(filePath, readFile13) {
1319
+ async function loadValidRoadmap(filePath, readFile16) {
1134
1320
  let raw;
1135
1321
  try {
1136
- raw = await readFile13(filePath);
1322
+ raw = await readFile16(filePath);
1137
1323
  } catch {
1138
1324
  throw new CliError(`No roadmap found at ${filePath}. Run \`nolto init\` first.`, 2);
1139
1325
  }
@@ -1167,9 +1353,9 @@ async function buildSyncBody(args) {
1167
1353
  }
1168
1354
  } catch {
1169
1355
  }
1170
- const root = path4.resolve(args.repoRoot);
1171
- const absolute = path4.resolve(root, ref.path);
1172
- if (absolute !== root && !absolute.startsWith(root + path4.sep)) {
1356
+ const root = path6.resolve(args.repoRoot);
1357
+ const absolute = path6.resolve(root, ref.path);
1358
+ if (absolute !== root && !absolute.startsWith(root + path6.sep)) {
1173
1359
  args.deps.warn(`plan path outside repository root, skipping: ${ref.path}`);
1174
1360
  continue;
1175
1361
  }
@@ -1187,11 +1373,11 @@ async function buildSyncBody(args) {
1187
1373
  args.deps.warn(`plan file not found, skipping: ${ref.path}`);
1188
1374
  continue;
1189
1375
  }
1190
- if (real !== realRoot && !real.startsWith(realRoot + path4.sep)) {
1376
+ if (real !== realRoot && !real.startsWith(realRoot + path6.sep)) {
1191
1377
  args.deps.warn(`symlink escapes repository root, skipping: ${ref.path}`);
1192
1378
  continue;
1193
1379
  }
1194
- if (!isValidPlanPath(path4.relative(realRoot, real).split(path4.sep).join("/"))) {
1380
+ if (!isValidPlanPath(path6.relative(realRoot, real).split(path6.sep).join("/"))) {
1195
1381
  args.deps.warn(`plan path not allowed (markdown only, no dot segments), skipping: ${ref.path}`);
1196
1382
  continue;
1197
1383
  }
@@ -1230,12 +1416,12 @@ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1230
1416
  var ROADMAP_SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
1231
1417
  function cacheDir(env, projectId) {
1232
1418
  if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1233
- return path5.join(getConfigDir(env), "projects", projectId, "roadmaps");
1419
+ return path7.join(getConfigDir(env), "projects", projectId, "roadmaps");
1234
1420
  }
1235
1421
  function cachePaths(env, projectId, slug) {
1236
1422
  if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1237
1423
  const dir = cacheDir(env, projectId);
1238
- return { json: path5.join(dir, `${slug}.json`), meta: path5.join(dir, `${slug}.meta.json`) };
1424
+ return { json: path7.join(dir, `${slug}.json`), meta: path7.join(dir, `${slug}.meta.json`) };
1239
1425
  }
1240
1426
  async function listCachedSlugs(env, projectId) {
1241
1427
  try {
@@ -1250,7 +1436,7 @@ async function readCache(env, projectId, slug) {
1250
1436
  const paths = cachePaths(env, projectId, slug);
1251
1437
  let raw;
1252
1438
  try {
1253
- raw = await readFile3(paths.json, "utf8");
1439
+ raw = await readFile5(paths.json, "utf8");
1254
1440
  } catch (err) {
1255
1441
  if (err.code === "ENOENT") return null;
1256
1442
  throw err;
@@ -1265,7 +1451,7 @@ async function readCache(env, projectId, slug) {
1265
1451
  if (errors.length) throw new CliError(`${paths.json} failed validation: ${errors.join("; ")}`, 2);
1266
1452
  let meta = null;
1267
1453
  try {
1268
- const parsed = JSON.parse(await readFile3(paths.meta, "utf8"));
1454
+ const parsed = JSON.parse(await readFile5(paths.meta, "utf8"));
1269
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") {
1270
1456
  throw new Error("Invalid cache metadata");
1271
1457
  }
@@ -1287,11 +1473,11 @@ async function writeCache(env, projectId, slug, roadmap, meta) {
1287
1473
  const paths = cachePaths(env, projectId, slug);
1288
1474
  const raw = serializeRoadmap(roadmap);
1289
1475
  const metadata = { ...meta, currentTaskId: meta.currentTaskId ?? null, repoIdentity: meta.repoIdentity ?? null, contentHash: sha256Hex(raw) };
1290
- await mkdir2(cacheDir(env, projectId), { recursive: true, mode: 448 });
1476
+ await mkdir4(cacheDir(env, projectId), { recursive: true, mode: 448 });
1291
1477
  for (const [filePath, content] of [[paths.json, raw], [paths.meta, JSON.stringify(metadata, null, 2) + "\n"]]) {
1292
1478
  const temp = `${filePath}.tmp-${process.pid}-${randomUUID3()}`;
1293
1479
  try {
1294
- await writeFile3(temp, content, { mode: 384 });
1480
+ await writeFile5(temp, content, { mode: 384 });
1295
1481
  await rename2(temp, filePath);
1296
1482
  } finally {
1297
1483
  await unlink(temp).catch(() => void 0);
@@ -1349,10 +1535,10 @@ async function ensureRoadmapCache(args) {
1349
1535
  const { env, projectId } = args;
1350
1536
  const identity = repoIdentityToString(args.repoIdentity);
1351
1537
  const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1352
- const warn2 = (line) => {
1353
- process.stderr.write(line + "\n");
1538
+ const warn2 = (line2) => {
1539
+ process.stderr.write(line2 + "\n");
1354
1540
  };
1355
- const log = (line) => args.log(`roadmap: ${line}`);
1541
+ const log = (line2) => args.log(`roadmap: ${line2}`);
1356
1542
  if (list.roadmaps.length > 0) {
1357
1543
  let skipped = false;
1358
1544
  for (const { slug: slug2 } of list.roadmaps) {
@@ -1361,7 +1547,7 @@ async function ensureRoadmapCache(args) {
1361
1547
  if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1362
1548
  if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1363
1549
  }
1364
- const basename = path6.basename(args.repoRoot);
1550
+ const basename = path8.basename(args.repoRoot);
1365
1551
  const slug = args.slug ?? slugifyProjectId(basename);
1366
1552
  const collision = list.roadmaps.find((row) => row.slug === slug);
1367
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);
@@ -1380,9 +1566,9 @@ async function ensureRoadmapCache(args) {
1380
1566
  await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1381
1567
  const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1382
1568
  http: args.http,
1383
- readFile: (p) => readFile4(p, "utf8"),
1569
+ readFile: (p) => readFile6(p, "utf8"),
1384
1570
  realpath,
1385
- fileExists: existsSync,
1571
+ fileExists: existsSync3,
1386
1572
  log: () => void 0,
1387
1573
  warn: warn2
1388
1574
  });
@@ -1427,25 +1613,25 @@ async function ensureProjectRepo(args) {
1427
1613
  // src/commands/link.ts
1428
1614
  import readline from "readline/promises";
1429
1615
  import os2 from "os";
1430
- import path10 from "path";
1616
+ import path12 from "path";
1431
1617
  import { statSync as statSync2 } from "fs";
1432
1618
 
1433
1619
  // src/registry.ts
1434
- import { readFile as readFile5, writeFile as writeFile4, mkdir as mkdir3, rename as rename3, unlink as unlink2 } from "fs/promises";
1620
+ import { readFile as readFile7, writeFile as writeFile6, mkdir as mkdir5, rename as rename3, unlink as unlink2 } from "fs/promises";
1435
1621
  import { randomUUID as randomUUID4 } from "crypto";
1436
- import path7 from "path";
1622
+ import path9 from "path";
1437
1623
  import { z as z3 } from "zod";
1438
1624
  var registrySchema = z3.object({
1439
1625
  schemaVersion: z3.literal(1),
1440
1626
  repos: z3.array(z3.object({ root: z3.string().min(1), projectId: z3.string().uuid().optional() }).passthrough())
1441
1627
  }).passthrough();
1442
1628
  function getRegistryPath(env) {
1443
- return path7.join(getConfigDir(env), "registry.json");
1629
+ return path9.join(getConfigDir(env), "registry.json");
1444
1630
  }
1445
1631
  async function loadRegistry(filePath) {
1446
1632
  let raw;
1447
1633
  try {
1448
- raw = await readFile5(filePath, "utf8");
1634
+ raw = await readFile7(filePath, "utf8");
1449
1635
  } catch (err) {
1450
1636
  const code = err != null && typeof err === "object" && "code" in err ? err.code : "";
1451
1637
  if (code === "ENOENT") {
@@ -1484,10 +1670,10 @@ async function addRepoToRegistry(filePath, entry) {
1484
1670
  return { added: !existing, updated: !!existing, registry: updated };
1485
1671
  }
1486
1672
  async function writeRegistry(filePath, registry) {
1487
- await mkdir3(path7.dirname(filePath), { recursive: true, mode: 448 });
1673
+ await mkdir5(path9.dirname(filePath), { recursive: true, mode: 448 });
1488
1674
  const tempPath = `${filePath}.tmp-${process.pid}-${randomUUID4()}`;
1489
1675
  try {
1490
- await writeFile4(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
1676
+ await writeFile6(tempPath, JSON.stringify(registry, null, 2) + "\n", "utf8");
1491
1677
  await rename3(tempPath, filePath);
1492
1678
  } catch (err) {
1493
1679
  await unlink2(tempPath).catch(() => void 0);
@@ -1506,12 +1692,12 @@ async function removeRepoFromRegistry(filePath, root) {
1506
1692
  // src/repo-identity.ts
1507
1693
  import { execFile } from "child_process";
1508
1694
  import { realpathSync } from "fs";
1509
- import path9 from "path";
1695
+ import path11 from "path";
1510
1696
 
1511
1697
  // src/machine-id.ts
1512
- import { chmod, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5 } from "fs/promises";
1698
+ import { chmod, mkdir as mkdir6, readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
1513
1699
  import { randomUUID as randomUUID5 } from "crypto";
1514
- import path8 from "path";
1700
+ import path10 from "path";
1515
1701
  var inFlightByConfigDir = /* @__PURE__ */ new Map();
1516
1702
  function parseMachineId(raw, file) {
1517
1703
  let parsed;
@@ -1527,10 +1713,10 @@ function parseMachineId(raw, file) {
1527
1713
  return id;
1528
1714
  }
1529
1715
  async function loadOrCreate(configDir) {
1530
- const file = path8.join(configDir, "machine.json");
1716
+ const file = path10.join(configDir, "machine.json");
1531
1717
  let raw = null;
1532
1718
  try {
1533
- raw = await readFile6(file, "utf8");
1719
+ raw = await readFile8(file, "utf8");
1534
1720
  } catch (err) {
1535
1721
  const code = err.code;
1536
1722
  if (code !== "ENOENT") {
@@ -1541,16 +1727,16 @@ async function loadOrCreate(configDir) {
1541
1727
  return parseMachineId(raw, file);
1542
1728
  }
1543
1729
  const machineId = randomUUID5();
1544
- await mkdir4(configDir, { recursive: true, mode: 448 });
1730
+ await mkdir6(configDir, { recursive: true, mode: 448 });
1545
1731
  try {
1546
- await writeFile5(file, `${JSON.stringify({ machineId }, null, 2)}
1732
+ await writeFile7(file, `${JSON.stringify({ machineId }, null, 2)}
1547
1733
  `, {
1548
1734
  flag: "wx",
1549
1735
  mode: 384
1550
1736
  });
1551
1737
  } catch (err) {
1552
1738
  if (err.code === "EEXIST") {
1553
- return parseMachineId(await readFile6(file, "utf8"), file);
1739
+ return parseMachineId(await readFile8(file, "utf8"), file);
1554
1740
  }
1555
1741
  throw new CliError(`Cannot write ${file}: ${String(err)}`, 2);
1556
1742
  }
@@ -1558,7 +1744,7 @@ async function loadOrCreate(configDir) {
1558
1744
  return machineId;
1559
1745
  }
1560
1746
  function loadOrCreateMachineId(configDir) {
1561
- const key = path8.resolve(configDir);
1747
+ const key = path10.resolve(configDir);
1562
1748
  const existing = inFlightByConfigDir.get(key);
1563
1749
  if (existing !== void 0) return existing;
1564
1750
  const pending = loadOrCreate(key).finally(() => {
@@ -1577,8 +1763,8 @@ function defaultGetRemoteUrl(root) {
1577
1763
  { timeout: 5e3 },
1578
1764
  (err, stdout2) => {
1579
1765
  if (err) return resolve(null);
1580
- const line = stdout2.split(/\r?\n/)[0]?.trim() ?? "";
1581
- resolve(line.length > 0 ? line : null);
1766
+ const line2 = stdout2.split(/\r?\n/)[0]?.trim() ?? "";
1767
+ resolve(line2.length > 0 ? line2 : null);
1582
1768
  }
1583
1769
  );
1584
1770
  });
@@ -1592,7 +1778,7 @@ async function resolveRepoIdentity(root, deps) {
1592
1778
  try {
1593
1779
  canonicalRoot = realpathSync(root);
1594
1780
  } catch {
1595
- canonicalRoot = path9.resolve(root);
1781
+ canonicalRoot = path11.resolve(root);
1596
1782
  }
1597
1783
  return { kind: "local", value: `${machineId}:${canonicalRoot}` };
1598
1784
  }
@@ -1611,7 +1797,7 @@ function resolveStartDir(env, cwd) {
1611
1797
  }
1612
1798
  function dirHasGit(dir) {
1613
1799
  try {
1614
- statSync2(path10.join(dir, ".git"));
1800
+ statSync2(path12.join(dir, ".git"));
1615
1801
  return true;
1616
1802
  } catch {
1617
1803
  return false;
@@ -1623,14 +1809,14 @@ function findRepoRoot(startDir, hasGit = dirHasGit) {
1623
1809
  if (hasGit(current)) {
1624
1810
  return { root: current, foundGit: true };
1625
1811
  }
1626
- const parent = path10.dirname(current);
1812
+ const parent = path12.dirname(current);
1627
1813
  if (parent === current) break;
1628
1814
  current = parent;
1629
1815
  }
1630
1816
  return { root: startDir, foundGit: false };
1631
1817
  }
1632
1818
  function isHomeDirectory(dir, home = os2.homedir()) {
1633
- return path10.resolve(dir) === path10.resolve(home);
1819
+ return path12.resolve(dir) === path12.resolve(home);
1634
1820
  }
1635
1821
  async function handleShow(deps, projectBindingPath, mode2) {
1636
1822
  const startDir = resolveStartDir(process.env, process.cwd());
@@ -1729,10 +1915,10 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1729
1915
  }
1730
1916
  }
1731
1917
  async function handleUnlink(projectBindingPath, mode2) {
1732
- const { readFile: readFile13, writeFile: writeFile10, chmod: chmod2 } = await import("fs/promises");
1918
+ const { readFile: readFile16, writeFile: writeFile12, chmod: chmod2 } = await import("fs/promises");
1733
1919
  let existing = {};
1734
1920
  try {
1735
- const raw = await readFile13(projectBindingPath, "utf8");
1921
+ const raw = await readFile16(projectBindingPath, "utf8");
1736
1922
  const parsed = JSON.parse(raw);
1737
1923
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
1738
1924
  throw new CliError(
@@ -1747,7 +1933,7 @@ async function handleUnlink(projectBindingPath, mode2) {
1747
1933
  }
1748
1934
  const { projectId: _removed, ...rest } = existing;
1749
1935
  void _removed;
1750
- await writeFile10(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1936
+ await writeFile12(projectBindingPath, JSON.stringify(rest, null, 2) + "\n", { mode: 420 });
1751
1937
  await chmod2(projectBindingPath, 420);
1752
1938
  if (mode2 === "json") {
1753
1939
  printResult({ unlinked: true, projectBindingPath }, mode2);
@@ -1776,7 +1962,7 @@ async function performLink(deps, projectId, mode2, slug, yes = false) {
1776
1962
  token: deps.settings.token,
1777
1963
  version: deps.version
1778
1964
  });
1779
- let projectName = path10.basename(root);
1965
+ let projectName = path12.basename(root);
1780
1966
  if (deps.settings.token != null) {
1781
1967
  try {
1782
1968
  const result = await http.get(
@@ -1804,7 +1990,7 @@ Proceeding anyway \u2014 verify the ID is correct.
1804
1990
  );
1805
1991
  }
1806
1992
  await writeRepoBinding(root, projectId);
1807
- const writtenPath = path10.join(root, "nolto.json");
1993
+ const writtenPath = path12.join(root, "nolto.json");
1808
1994
  let repoAdded = false;
1809
1995
  if (deps.settings.token == null) {
1810
1996
  process.stderr.write("Warning: roadmap cache not initialized (no token); run nolto pull after nolto login\n");
@@ -1825,8 +2011,8 @@ Proceeding anyway \u2014 verify the ID is correct.
1825
2011
  rl.close();
1826
2012
  }
1827
2013
  },
1828
- log: (line) => {
1829
- if (mode2 !== "json") process.stdout.write(line + "\n");
2014
+ log: (line2) => {
2015
+ if (mode2 !== "json") process.stdout.write(line2 + "\n");
1830
2016
  }
1831
2017
  });
1832
2018
  if (result === "declined") {
@@ -1842,8 +2028,8 @@ Proceeding anyway \u2014 verify the ID is correct.
1842
2028
  repoRoot: root,
1843
2029
  slug,
1844
2030
  repoIdentity,
1845
- log: (line) => {
1846
- if (mode2 !== "json") process.stdout.write(line + "\n");
2031
+ log: (line2) => {
2032
+ if (mode2 !== "json") process.stdout.write(line2 + "\n");
1847
2033
  }
1848
2034
  });
1849
2035
  }
@@ -1987,79 +2173,14 @@ function invalidBindingError(projectBindingPath, error) {
1987
2173
  );
1988
2174
  }
1989
2175
 
1990
- // src/skill-install.ts
1991
- import { cp, mkdir as mkdir5, readFile as readFile7, writeFile as writeFile6, rm as rm2 } from "fs/promises";
1992
- import { existsSync as existsSync2 } from "fs";
1993
- import path11 from "path";
1994
- import { fileURLToPath } from "url";
1995
- var __dirname = path11.dirname(fileURLToPath(import.meta.url));
1996
- function resolveSkillSourceDir() {
1997
- const candidates = [
1998
- path11.resolve(__dirname, "skill/roadmap-progress"),
1999
- // bundled: dist/skill/...
2000
- path11.resolve(__dirname, "../../../skills/roadmap-progress")
2001
- // source: <repo>/skills/...
2002
- ];
2003
- for (const candidate of candidates) {
2004
- if (existsSync2(path11.join(candidate, "SKILL.md"))) return candidate;
2005
- }
2006
- throw new Error("Bundled roadmap-progress skill not found. Reinstall @nolto/cli.");
2007
- }
2008
- var VERSION_MARKER = ".nolto-skill-version";
2009
- async function checkSkillVersionDrift(repoRoot, cliVersion) {
2010
- const skillDirs = [
2011
- path11.join(repoRoot, ".claude", "skills", "roadmap-progress"),
2012
- path11.join(repoRoot, ".agents", "skills", "roadmap-progress")
2013
- ];
2014
- const drifted = [];
2015
- for (const dir of skillDirs) {
2016
- if (!existsSync2(dir)) continue;
2017
- let installed;
2018
- try {
2019
- const marker = (await readFile7(path11.join(dir, VERSION_MARKER), "utf8")).trim();
2020
- installed = marker.length > 0 ? marker : null;
2021
- } catch {
2022
- installed = null;
2023
- }
2024
- if (installed !== cliVersion) drifted.push({ dir, installed });
2025
- }
2026
- return drifted;
2027
- }
2028
- function formatSkillVersionDriftWarning(repoRoot, cliVersion, drifted) {
2029
- const dirs = drifted.map(({ dir }) => path11.relative(repoRoot, dir).split(path11.sep).join("/")).join(", ");
2030
- const installed = [...new Set(drifted.map((entry) => entry.installed ?? "unknown"))].join(", ");
2031
- return `roadmap-progress skill is outdated in ${dirs} (installed ${installed}, CLI ${cliVersion}). Run \`nolto init\` in this repo to update it.`;
2032
- }
2033
- async function installSkill(args) {
2034
- const targetDir = path11.join(args.skillsParentDir, "roadmap-progress");
2035
- const markerPath = path11.join(targetDir, VERSION_MARKER);
2036
- const dirExists = existsSync2(targetDir);
2037
- let installedVersion = null;
2038
- if (dirExists) {
2039
- try {
2040
- installedVersion = (await readFile7(markerPath, "utf8")).trim();
2041
- } catch {
2042
- installedVersion = null;
2043
- }
2044
- }
2045
- if (dirExists && installedVersion === args.version && args.force !== true) {
2046
- return { action: "skipped", targetDir };
2047
- }
2048
- await rm2(targetDir, { recursive: true, force: true });
2049
- await mkdir5(args.skillsParentDir, { recursive: true });
2050
- await cp(args.sourceDir, targetDir, { recursive: true });
2051
- await writeFile6(markerPath, args.version + "\n", "utf8");
2052
- return { action: dirExists ? "updated" : "installed", targetDir };
2053
- }
2054
-
2055
2176
  // src/commands/init.ts
2056
- var __dirname2 = path12.dirname(fileURLToPath2(import.meta.url));
2177
+ var __dirname2 = path13.dirname(fileURLToPath2(import.meta.url));
2057
2178
  var _require = createRequire(import.meta.url);
2058
2179
  function getCliVersion() {
2059
2180
  const candidates = [
2060
- path12.resolve(__dirname2, "../package.json"),
2181
+ path13.resolve(__dirname2, "../package.json"),
2061
2182
  // bundled: dist/../package.json
2062
- path12.resolve(__dirname2, "../../package.json")
2183
+ path13.resolve(__dirname2, "../../package.json")
2063
2184
  // source: src/commands/../../package.json
2064
2185
  ];
2065
2186
  for (const pkgPath of candidates) {
@@ -2076,8 +2197,8 @@ function getCliVersion() {
2076
2197
  async function pickProject(rl, http, projects, promptText, baseUrl) {
2077
2198
  if (projects.length > 0) {
2078
2199
  process.stdout.write("\nProjects:\n");
2079
- projects.forEach((project, index) => {
2080
- process.stdout.write(` (${index + 1}) ${project.name} \u2014 ${project.id}
2200
+ projects.forEach((project, index2) => {
2201
+ process.stdout.write(` (${index2 + 1}) ${project.name} \u2014 ${project.id}
2081
2202
  `);
2082
2203
  });
2083
2204
  } else {
@@ -2097,16 +2218,16 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
2097
2218
  let organization = orgs[0];
2098
2219
  if (orgs.length > 1) {
2099
2220
  process.stdout.write("\nOrganizations:\n");
2100
- orgs.forEach((org, index2) => {
2101
- process.stdout.write(` (${index2 + 1}) ${org.name} \u2014 ${org.id}
2221
+ orgs.forEach((org, index3) => {
2222
+ process.stdout.write(` (${index3 + 1}) ${org.name} \u2014 ${org.id}
2102
2223
  `);
2103
2224
  });
2104
2225
  const choice = (await rl.question("Organization number: ")).trim();
2105
- const index = Number(choice);
2106
- if (!/^\d+$/.test(choice) || !Number.isSafeInteger(index) || index < 1 || index > orgs.length) {
2226
+ const index2 = Number(choice);
2227
+ if (!/^\d+$/.test(choice) || !Number.isSafeInteger(index2) || index2 < 1 || index2 > orgs.length) {
2107
2228
  throw new CliError("Invalid organization number.", 2);
2108
2229
  }
2109
- organization = orgs[index - 1];
2230
+ organization = orgs[index2 - 1];
2110
2231
  }
2111
2232
  const created = await http.post(
2112
2233
  "/api/projects",
@@ -2240,7 +2361,7 @@ Saved ${configPath}
2240
2361
  }
2241
2362
  if (isHomeDirectory(root)) {
2242
2363
  process.stderr.write(
2243
- `Refusing to set up your home directory as a repository root (found ${path12.join(os3.homedir(), ".git")}). Run nolto init inside a project repository.
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.
2244
2365
  `
2245
2366
  );
2246
2367
  return;
@@ -2272,7 +2393,7 @@ Saved ${configPath}
2272
2393
  boundProject != null ? "Keep this binding? [Y/n] " : "Keep this binding? [y/N] "
2273
2394
  );
2274
2395
  keepExistingBinding = boundProject != null ? keep.trim().toLowerCase() !== "n" : keep.trim().toLowerCase() === "y";
2275
- repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path12.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2396
+ repoProject = keepExistingBinding ? boundProject ?? { id: existingBinding.projectId, name: path13.basename(root) } : await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2276
2397
  } else {
2277
2398
  repoProject = await selectRepoProject(rl, repoHttp, projects, defaultProjectId, baseUrl);
2278
2399
  }
@@ -2286,7 +2407,7 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2286
2407
  process.stdout.write("Skipped repo setup.\n");
2287
2408
  return;
2288
2409
  }
2289
- const bindingPath = deps.repoBinding?.path ?? path12.join(root, "nolto.json");
2410
+ const bindingPath = deps.repoBinding?.path ?? path13.join(root, "nolto.json");
2290
2411
  if (keepExistingBinding) {
2291
2412
  process.stdout.write(`binding: kept ${bindingPath} (${repoProject.id})
2292
2413
  `);
@@ -2298,26 +2419,30 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2298
2419
  );
2299
2420
  }
2300
2421
  await writeRepoBinding(root, repoProject.id);
2301
- process.stdout.write(`binding: wrote ${path12.join(root, "nolto.json")}
2422
+ process.stdout.write(`binding: wrote ${path13.join(root, "nolto.json")}
2302
2423
  `);
2303
2424
  }
2304
2425
  const sourceDir = resolveSkillSourceDir();
2305
2426
  const version = getCliVersion();
2306
2427
  const claudeInstall = await installSkill({
2307
- skillsParentDir: path12.join(root, ".claude", "skills"),
2428
+ skillsParentDir: path13.join(root, ".claude", "skills"),
2308
2429
  sourceDir,
2309
2430
  version
2310
2431
  });
2311
2432
  process.stdout.write(`skill (claude): ${claudeInstall.action} ${claudeInstall.targetDir}
2312
2433
  `);
2313
- const usesAgentsTooling = fs2.existsSync(path12.join(root, ".agents")) || fs2.existsSync(path12.join(root, ".codex")) || fs2.existsSync(path12.join(root, "AGENTS.md"));
2434
+ const usesAgentsTooling = fs2.existsSync(path13.join(root, ".agents")) || fs2.existsSync(path13.join(root, ".codex")) || fs2.existsSync(path13.join(root, "AGENTS.md"));
2314
2435
  if (usesAgentsTooling) {
2315
2436
  const agentsInstall = await installSkill({
2316
- skillsParentDir: path12.join(root, ".agents", "skills"),
2437
+ skillsParentDir: path13.join(root, ".agents", "skills"),
2317
2438
  sourceDir,
2318
2439
  version
2319
2440
  });
2320
2441
  process.stdout.write(`skill (agents): ${agentsInstall.action} ${agentsInstall.targetDir}
2442
+ `);
2443
+ }
2444
+ for (const memorySkill of await installMemorySkill(root, version)) {
2445
+ process.stdout.write(`skill (memory): ${memorySkill.action} ${memorySkill.targetDir}
2321
2446
  `);
2322
2447
  }
2323
2448
  const repoIdentity = await makeRepoIdentityResolver(deps)(root);
@@ -2329,8 +2454,8 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2329
2454
  const answer = (await rl.question(question)).trim().toLowerCase();
2330
2455
  return answer === "" || answer === "y" || answer === "yes";
2331
2456
  },
2332
- log: (line) => {
2333
- process.stdout.write(line + "\n");
2457
+ log: (line2) => {
2458
+ process.stdout.write(line2 + "\n");
2334
2459
  }
2335
2460
  });
2336
2461
  if (repoResult === "declined") {
@@ -2344,8 +2469,8 @@ Set up this repository (${root}) for roadmap sync? [Y/n] `);
2344
2469
  projectName: repoProject.name,
2345
2470
  repoRoot: root,
2346
2471
  repoIdentity,
2347
- log: (line) => {
2348
- process.stdout.write(line + "\n");
2472
+ log: (line2) => {
2473
+ process.stdout.write(line2 + "\n");
2349
2474
  }
2350
2475
  });
2351
2476
  const registryResult = await addRepoToRegistry(getRegistryPath(process.env), { root, projectId: repoProject.id });
@@ -2591,11 +2716,11 @@ function register5(program, deps) {
2591
2716
  // src/commands/sync.ts
2592
2717
  import { execFile as execFile2 } from "child_process";
2593
2718
  import { promisify } from "util";
2594
- import { readFile as readFile8, realpath as realpath2 } from "fs/promises";
2595
- import { existsSync as existsSync3 } from "fs";
2719
+ import { readFile as readFile9, realpath as realpath2 } from "fs/promises";
2720
+ import { existsSync as existsSync4 } from "fs";
2596
2721
 
2597
2722
  // src/roadmap-read.ts
2598
- import path13 from "path";
2723
+ import path14 from "path";
2599
2724
  async function resolveRoadmapReadContext(deps) {
2600
2725
  if (deps.settings.token == null) {
2601
2726
  throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
@@ -2605,7 +2730,7 @@ async function resolveRoadmapReadContext(deps) {
2605
2730
  if (!foundGit) {
2606
2731
  throw new CliError("No git repository found. Run inside a repo set up with `nolto init`.", 2);
2607
2732
  }
2608
- const binding = await loadRepoBinding(path13.join(root, "nolto.json"));
2733
+ const binding = await loadRepoBinding(path14.join(root, "nolto.json"));
2609
2734
  const projectId = binding?.projectId ?? deps.settings.defaultProjectId;
2610
2735
  if (projectId == null) {
2611
2736
  throw new CliError("No project binding. Run `nolto init` or `nolto link <projectId>`.", 2);
@@ -2615,8 +2740,8 @@ async function resolveRoadmapReadContext(deps) {
2615
2740
 
2616
2741
  // src/git-links.ts
2617
2742
  function parseGitLog(raw) {
2618
- return raw.split("\n").filter((line) => line.length > 0).map((line) => {
2619
- const fields = line.replace(/\r$/, "").split("");
2743
+ return raw.split("\n").filter((line2) => line2.length > 0).map((line2) => {
2744
+ const fields = line2.replace(/\r$/, "").split("");
2620
2745
  const [ref, subject, author, committedAt] = fields;
2621
2746
  if (fields.length !== 4 || !ref || !/^[0-9a-f]{40}$/.test(ref) || subject === void 0 || author === void 0 || !committedAt || !Number.isFinite(Date.parse(committedAt))) {
2622
2747
  throw new Error("Malformed git log entry");
@@ -2635,12 +2760,12 @@ function buildGitLinksPayload(entries) {
2635
2760
  const keys = extractIssueKeys(entry.subject);
2636
2761
  const pr = extractPrNumber(entry.subject);
2637
2762
  const refs = [{ kind: "commit", ref: entry.ref }, ...pr ? [{ kind: "pr", ref: pr }] : []];
2638
- return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index) => ({
2763
+ return refs.flatMap((ref) => Array.from({ length: Math.ceil(keys.length / 20) }, (_, index2) => ({
2639
2764
  ...ref,
2640
2765
  title: entry.subject.slice(0, 500),
2641
2766
  author: entry.author.slice(0, 500),
2642
2767
  committedAt: entry.committedAt,
2643
- issueKeys: keys.slice(index * 20, (index + 1) * 20)
2768
+ issueKeys: keys.slice(index2 * 20, (index2 + 1) * 20)
2644
2769
  })));
2645
2770
  }) };
2646
2771
  }
@@ -2661,15 +2786,15 @@ async function collectGitLinks(root, exec) {
2661
2786
  }
2662
2787
 
2663
2788
  // src/sync-repo.ts
2664
- import path14 from "path";
2789
+ import path15 from "path";
2665
2790
  import { readdir as readdir3 } from "fs/promises";
2666
2791
  function collectContainedPlanAbsPaths(roadmaps, root, warn2) {
2667
2792
  const planAbsPaths = /* @__PURE__ */ new Set();
2668
- const resolvedRoot = path14.resolve(root);
2793
+ const resolvedRoot = path15.resolve(root);
2669
2794
  for (const roadmap of roadmaps) {
2670
2795
  for (const ref of collectPlanRefs(roadmap)) {
2671
- const absolute = path14.resolve(resolvedRoot, ref.path);
2672
- if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path14.sep)) {
2796
+ const absolute = path15.resolve(resolvedRoot, ref.path);
2797
+ if (absolute !== resolvedRoot && !absolute.startsWith(resolvedRoot + path15.sep)) {
2673
2798
  warn2(`chokidar target outside repo, skipping: ${ref.path}`);
2674
2799
  continue;
2675
2800
  }
@@ -2690,7 +2815,7 @@ async function syncRepo(args, io) {
2690
2815
  if (slugs.length === 0) {
2691
2816
  let legacyFiles = [];
2692
2817
  try {
2693
- legacyFiles = await readdir3(path14.join(args.root, ".nolto", "roadmaps"));
2818
+ legacyFiles = await readdir3(path15.join(args.root, ".nolto", "roadmaps"));
2694
2819
  } catch (err) {
2695
2820
  if (err.code !== "ENOENT") throw err;
2696
2821
  }
@@ -2790,22 +2915,22 @@ function register6(program, deps) {
2790
2915
  async function runSyncCommand(deps, opts = {}) {
2791
2916
  const { root, projectId } = await resolveRoadmapReadContext(deps);
2792
2917
  const http = deps.http;
2793
- const warn2 = (line) => {
2794
- process.stderr.write((line.startsWith(" ") ? "" : "Warning: ") + line + "\n");
2918
+ const warn2 = (line2) => {
2919
+ process.stderr.write((line2.startsWith(" ") ? "" : "Warning: ") + line2 + "\n");
2795
2920
  };
2796
2921
  const response = await syncRepo(
2797
2922
  { root, projectId, slugs: opts.slug === void 0 ? void 0 : [opts.slug] },
2798
2923
  {
2799
2924
  env: process.env,
2800
- readFile: (p) => readFile8(p, "utf8"),
2925
+ readFile: (p) => readFile9(p, "utf8"),
2801
2926
  realpath: (p) => realpath2(p),
2802
- fileExists: (p) => existsSync3(p),
2927
+ fileExists: (p) => existsSync4(p),
2803
2928
  repoIdentity: makeRepoIdentityResolver(deps),
2804
2929
  exec: promisify(execFile2),
2805
2930
  gitLinks: (opts.gitLinks ?? true) && process.env.NOLTO_GIT_LINKS !== "0",
2806
2931
  http,
2807
- log: (line) => {
2808
- if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
2932
+ log: (line2) => {
2933
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
2809
2934
  },
2810
2935
  warn: warn2
2811
2936
  }
@@ -3011,9 +3136,9 @@ function register7(program, deps) {
3011
3136
  }
3012
3137
 
3013
3138
  // src/roadmap-commands.ts
3014
- import path15 from "path";
3015
- import { existsSync as existsSync4 } from "fs";
3016
- import { readFile as readFile9, readdir as readdir4, writeFile as writeFile7, rename as rename4, unlink as unlink3, realpath as realpath3 } from "fs/promises";
3139
+ import path16 from "path";
3140
+ 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";
3017
3142
  import { randomUUID as randomUUID6 } from "crypto";
3018
3143
  import readline4 from "readline/promises";
3019
3144
 
@@ -3040,12 +3165,12 @@ async function runPull(deps, opts = {}) {
3040
3165
  projectId,
3041
3166
  slug,
3042
3167
  force: opts.force,
3043
- log: (line) => {
3044
- messages.push(line);
3045
- if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line + "\n");
3168
+ log: (line2) => {
3169
+ messages.push(line2);
3170
+ if (!opts.quiet && deps.output.mode !== "json") process.stdout.write(line2 + "\n");
3046
3171
  },
3047
- warn: (line) => {
3048
- process.stderr.write(line + "\n");
3172
+ warn: (line2) => {
3173
+ process.stderr.write(line2 + "\n");
3049
3174
  }
3050
3175
  })) skipped = true;
3051
3176
  }
@@ -3054,8 +3179,8 @@ async function runPull(deps, opts = {}) {
3054
3179
  }
3055
3180
 
3056
3181
  // src/roadmap-commands.ts
3057
- var warn = (line) => {
3058
- process.stderr.write(line + "\n");
3182
+ var warn = (line2) => {
3183
+ process.stderr.write(line2 + "\n");
3059
3184
  };
3060
3185
  async function pull(deps, projectId, slug) {
3061
3186
  if (!await pullRoadmapCache({ env: process.env, http: deps.http, projectId, slug, log: () => void 0, warn })) {
@@ -3063,26 +3188,26 @@ async function pull(deps, projectId, slug) {
3063
3188
  }
3064
3189
  }
3065
3190
  async function selectRoadmap(deps, requestedSlug) {
3066
- const context2 = await resolveRoadmapReadContext(deps);
3191
+ const context3 = await resolveRoadmapReadContext(deps);
3067
3192
  let slug = requestedSlug;
3068
3193
  if (slug === void 0) {
3069
- let slugs = await listCachedSlugs(process.env, context2.projectId);
3194
+ let slugs = await listCachedSlugs(process.env, context3.projectId);
3070
3195
  if (slugs.length === 0) {
3071
3196
  await runPull(deps, { quiet: true });
3072
- slugs = await listCachedSlugs(process.env, context2.projectId);
3197
+ slugs = await listCachedSlugs(process.env, context3.projectId);
3073
3198
  }
3074
3199
  if (slugs.length !== 1) {
3075
3200
  throw new CliError(slugs.length === 0 ? "No roadmap found. Run `nolto init`." : `Multiple roadmaps found (${slugs.join(", ")}); specify a slug (task commands: --slug <slug>).`, 2);
3076
3201
  }
3077
3202
  slug = slugs[0];
3078
3203
  }
3079
- const paths = cachePaths(process.env, context2.projectId, slug);
3080
- if (!existsSync4(paths.json)) await pull(deps, context2.projectId, slug);
3081
- return { ...context2, slug, paths };
3204
+ const paths = cachePaths(process.env, context3.projectId, slug);
3205
+ if (!existsSync5(paths.json)) await pull(deps, context3.projectId, slug);
3206
+ return { ...context3, slug, paths };
3082
3207
  }
3083
3208
  async function roadmapPath(deps, slug) {
3084
3209
  const { paths } = await selectRoadmap(deps, slug);
3085
- printResult(path15.resolve(paths.json), deps.output.mode);
3210
+ printResult(path16.resolve(paths.json), deps.output.mode);
3086
3211
  }
3087
3212
  async function roadmapStatus(deps, slug, fresh = false) {
3088
3213
  const selected = await selectRoadmap(deps, slug);
@@ -3111,7 +3236,7 @@ async function roadmapValidate(deps, slug) {
3111
3236
  const { paths } = await selectRoadmap(deps, slug);
3112
3237
  let parsed;
3113
3238
  try {
3114
- parsed = JSON.parse(await readFile9(paths.json, "utf8"));
3239
+ parsed = JSON.parse(await readFile10(paths.json, "utf8"));
3115
3240
  } catch {
3116
3241
  throw new CliError(`ERROR Malformed JSON in ${paths.json}.`, 1);
3117
3242
  }
@@ -3129,7 +3254,7 @@ async function roadmapSummary(deps, slug, text) {
3129
3254
  entry.roadmap.summary = text;
3130
3255
  const temp = `${selected.paths.json}.tmp-${randomUUID6()}`;
3131
3256
  try {
3132
- await writeFile7(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3257
+ await writeFile8(temp, serializeRoadmap(entry.roadmap), { mode: 384 });
3133
3258
  await rename4(temp, selected.paths.json);
3134
3259
  } finally {
3135
3260
  await unlink3(temp).catch(() => void 0);
@@ -3161,11 +3286,11 @@ async function roadmapTask(deps, taskId, slug, body) {
3161
3286
  const selected = await selectRoadmap(deps, slug);
3162
3287
  if (body.status === "blocked" && !body.note?.trim()) throw new CliError("block requires a non-empty --note.", 2);
3163
3288
  if (body.plan !== void 0) {
3164
- const absolute = path15.resolve(selected.root, body.plan);
3165
- if (!isValidPlanPath(body.plan) || !absolute.startsWith(path15.resolve(selected.root) + path15.sep)) {
3289
+ const absolute = path16.resolve(selected.root, body.plan);
3290
+ if (!isValidPlanPath(body.plan) || !absolute.startsWith(path16.resolve(selected.root) + path16.sep)) {
3166
3291
  throw new CliError("plan must be a repository-relative path without . or .. segments.", 2);
3167
3292
  }
3168
- if (!existsSync4(absolute)) warn(`WARN plan file not found at ${absolute}`);
3293
+ if (!existsSync5(absolute)) warn(`WARN plan file not found at ${absolute}`);
3169
3294
  }
3170
3295
  const response = await patchTask({ ...selected, env: process.env, http: deps.http, taskId, body });
3171
3296
  if (body.plan !== void 0) await runSyncCommand(deps, { slug: selected.slug, quiet: true });
@@ -3184,7 +3309,7 @@ async function roadmapEvents(deps, slug, opts) {
3184
3309
  }
3185
3310
  async function roadmapMigrate(deps, yes = false) {
3186
3311
  const { root, projectId } = await resolveRoadmapReadContext(deps);
3187
- const dir = path15.join(root, ".nolto", "roadmaps");
3312
+ const dir = path16.join(root, ".nolto", "roadmaps");
3188
3313
  let files;
3189
3314
  try {
3190
3315
  files = (await readdir4(dir, { withFileTypes: true })).filter((file) => file.isFile() && file.name.endsWith(".json")).map((file) => file.name).sort();
@@ -3200,7 +3325,7 @@ async function roadmapMigrate(deps, yes = false) {
3200
3325
  for (const file of files) {
3201
3326
  const slug = file.slice(0, -5);
3202
3327
  cachePaths(process.env, projectId, slug);
3203
- const roadmap = await loadValidRoadmap(path15.join(dir, file), (p) => readFile9(p, "utf8"));
3328
+ const roadmap = await loadValidRoadmap(path16.join(dir, file), (p) => readFile10(p, "utf8"));
3204
3329
  roadmap.schemaVersion = 3;
3205
3330
  delete roadmap.updatedAt;
3206
3331
  delete roadmap.currentTaskId;
@@ -3232,9 +3357,9 @@ async function roadmapMigrate(deps, yes = false) {
3232
3357
  if (!unchanged) {
3233
3358
  const response = await runSync({ repoRoot: root, projectId, slug, roadmap, baseRevision: revision, repoIdentity: await makeRepoIdentityResolver(deps)(root) }, {
3234
3359
  http: deps.http,
3235
- readFile: (p) => readFile9(p, "utf8"),
3360
+ readFile: (p) => readFile10(p, "utf8"),
3236
3361
  realpath: realpath3,
3237
- fileExists: existsSync4,
3362
+ fileExists: existsSync5,
3238
3363
  log: () => void 0,
3239
3364
  warn
3240
3365
  });
@@ -3250,11 +3375,11 @@ async function roadmapMigrate(deps, yes = false) {
3250
3375
  const nextSteps = ["Next steps (run yourself):", " git rm -r .nolto/roadmaps"];
3251
3376
  let attributes = "";
3252
3377
  try {
3253
- attributes = await readFile9(path15.join(root, ".gitattributes"), "utf8");
3378
+ attributes = await readFile10(path16.join(root, ".gitattributes"), "utf8");
3254
3379
  } catch (error) {
3255
3380
  if (error.code !== "ENOENT") throw error;
3256
3381
  }
3257
- if (attributes.split(/\r?\n/).some((line) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line))) {
3382
+ if (attributes.split(/\r?\n/).some((line2) => /^\s*\.nolto\/roadmaps\/\*\.json\s+.*\bmerge=nolto-roadmap(?:\s|$)/.test(line2))) {
3258
3383
  nextSteps.push(' # remove the ".nolto/roadmaps/*.json merge=nolto-roadmap" line from .gitattributes');
3259
3384
  }
3260
3385
  nextSteps.push(" git config --unset-all merge.nolto-roadmap.name; git config --unset-all merge.nolto-roadmap.driver");
@@ -3298,13 +3423,13 @@ function register9(program, deps) {
3298
3423
  // src/commands/watch.ts
3299
3424
  import { execFile as execFile3 } from "child_process";
3300
3425
  import { promisify as promisify2 } from "util";
3301
- import { readFile as readFile10, realpath as realpath4 } from "fs/promises";
3302
- import { existsSync as existsSync5, mkdirSync } from "fs";
3303
- import path18 from "path";
3426
+ import { readFile as readFile11, realpath as realpath4 } from "fs/promises";
3427
+ import { existsSync as existsSync6, mkdirSync } from "fs";
3428
+ import path19 from "path";
3304
3429
  import chokidar from "chokidar";
3305
3430
 
3306
3431
  // src/watch-core.ts
3307
- import path16 from "path";
3432
+ import path17 from "path";
3308
3433
  var WatchSet = class {
3309
3434
  constructor(deps) {
3310
3435
  this.deps = deps;
@@ -3353,7 +3478,7 @@ async function reloadRoots(deps) {
3353
3478
  continue;
3354
3479
  }
3355
3480
  try {
3356
- const projectId = repo.projectId ?? (await loadRepoBinding(path16.join(repo.root, "nolto.json")))?.projectId;
3481
+ const projectId = repo.projectId ?? (await loadRepoBinding(path17.join(repo.root, "nolto.json")))?.projectId;
3357
3482
  if (projectId) repos.push({ root: repo.root, projectId });
3358
3483
  else deps.warn(`registered repo has no project binding, skipping: ${repo.root}`);
3359
3484
  } catch (err) {
@@ -3424,7 +3549,7 @@ var RepoWatch = class {
3424
3549
  };
3425
3550
 
3426
3551
  // src/service-install.ts
3427
- import path17 from "path";
3552
+ import path18 from "path";
3428
3553
  import os4 from "os";
3429
3554
  function buildUnitFile(args) {
3430
3555
  return [
@@ -3444,8 +3569,8 @@ function buildUnitFile(args) {
3444
3569
  }
3445
3570
  function getUnitPath(env) {
3446
3571
  const xdg = env["XDG_CONFIG_HOME"];
3447
- const base = xdg != null && xdg.length > 0 ? xdg : path17.join(os4.homedir(), ".config");
3448
- return path17.join(base, "systemd", "user", "nolto-watch.service");
3572
+ const base = xdg != null && xdg.length > 0 ? xdg : path18.join(os4.homedir(), ".config");
3573
+ return path18.join(base, "systemd", "user", "nolto-watch.service");
3449
3574
  }
3450
3575
  async function installServiceWith(deps) {
3451
3576
  if (deps.platform !== "linux") {
@@ -3456,7 +3581,7 @@ async function installServiceWith(deps) {
3456
3581
  );
3457
3582
  }
3458
3583
  const unitPath = getUnitPath(deps.env);
3459
- await deps.mkdir(path17.dirname(unitPath));
3584
+ await deps.mkdir(path18.dirname(unitPath));
3460
3585
  await deps.writeFile(unitPath, buildUnitFile({ nodePath: deps.nodePath, scriptPath: deps.scriptPath }));
3461
3586
  deps.log(`Wrote ${unitPath}`);
3462
3587
  const reload = await deps.exec(["systemctl", "--user", "daemon-reload"]);
@@ -3470,18 +3595,18 @@ async function installServiceWith(deps) {
3470
3595
  deps.log("Service nolto-watch enabled and started. Logs: journalctl --user -u nolto-watch -f");
3471
3596
  }
3472
3597
  async function installService() {
3473
- const { writeFile: writeFile10, mkdir: mkdir7 } = await import("fs/promises");
3474
- const { execFile: execFile5 } = await import("child_process");
3475
- const { promisify: promisify4 } = await import("util");
3476
- const execFileAsync = promisify4(execFile5);
3598
+ const { writeFile: writeFile12, mkdir: mkdir9 } = await import("fs/promises");
3599
+ const { execFile: execFile6 } = await import("child_process");
3600
+ const { promisify: promisify5 } = await import("util");
3601
+ const execFileAsync = promisify5(execFile6);
3477
3602
  await installServiceWith({
3478
3603
  platform: process.platform,
3479
3604
  env: process.env,
3480
3605
  nodePath: process.execPath,
3481
- scriptPath: path17.resolve(process.argv[1] ?? ""),
3482
- writeFile: (p, content) => writeFile10(p, content, "utf8"),
3606
+ scriptPath: path18.resolve(process.argv[1] ?? ""),
3607
+ writeFile: (p, content) => writeFile12(p, content, "utf8"),
3483
3608
  mkdir: async (p) => {
3484
- await mkdir7(p, { recursive: true });
3609
+ await mkdir9(p, { recursive: true });
3485
3610
  },
3486
3611
  exec: async (cmd) => {
3487
3612
  try {
@@ -3492,8 +3617,8 @@ async function installService() {
3492
3617
  return { code: e.code ?? 1, stderr: e.stderr ?? String(err) };
3493
3618
  }
3494
3619
  },
3495
- log: (line) => process.stdout.write(line + "\n"),
3496
- warn: (line) => process.stderr.write("Warning: " + line + "\n")
3620
+ log: (line2) => process.stdout.write(line2 + "\n"),
3621
+ warn: (line2) => process.stderr.write("Warning: " + line2 + "\n")
3497
3622
  });
3498
3623
  }
3499
3624
  async function uninstallServiceWith(deps) {
@@ -3535,14 +3660,14 @@ async function uninstallServiceWith(deps) {
3535
3660
  deps.log("Service nolto-watch stopped, disabled, and removed.");
3536
3661
  }
3537
3662
  async function uninstallService() {
3538
- const { unlink: unlink4 } = await import("fs/promises");
3539
- const { execFile: execFile5 } = await import("child_process");
3540
- const { promisify: promisify4 } = await import("util");
3541
- const execFileAsync = promisify4(execFile5);
3663
+ const { unlink: unlink5 } = await import("fs/promises");
3664
+ const { execFile: execFile6 } = await import("child_process");
3665
+ const { promisify: promisify5 } = await import("util");
3666
+ const execFileAsync = promisify5(execFile6);
3542
3667
  await uninstallServiceWith({
3543
3668
  platform: process.platform,
3544
3669
  env: process.env,
3545
- unlink: unlink4,
3670
+ unlink: unlink5,
3546
3671
  exec: async (cmd) => {
3547
3672
  try {
3548
3673
  await execFileAsync(cmd[0], cmd.slice(1));
@@ -3552,8 +3677,8 @@ async function uninstallService() {
3552
3677
  return { code: e.code ?? 1, stderr: e.stderr ?? String(err) };
3553
3678
  }
3554
3679
  },
3555
- log: (line) => process.stdout.write(line + "\n"),
3556
- warn: (line) => process.stderr.write("Warning: " + line + "\n")
3680
+ log: (line2) => process.stdout.write(line2 + "\n"),
3681
+ warn: (line2) => process.stderr.write("Warning: " + line2 + "\n")
3557
3682
  });
3558
3683
  }
3559
3684
  async function stopServiceWith(deps) {
@@ -3603,9 +3728,9 @@ function register10(program, deps) {
3603
3728
  const registryPath = getRegistryPath(process.env);
3604
3729
  const roots = await reloadRoots({
3605
3730
  load: () => loadRegistry(registryPath),
3606
- exists: existsSync5,
3607
- warn: (line) => {
3608
- process.stderr.write(`Warning: ${line}
3731
+ exists: existsSync6,
3732
+ warn: (line2) => {
3733
+ process.stderr.write(`Warning: ${line2}
3609
3734
  `);
3610
3735
  }
3611
3736
  });
@@ -3619,8 +3744,8 @@ function register10(program, deps) {
3619
3744
  });
3620
3745
  const startRepo = ({ root, projectId }) => {
3621
3746
  const roadmapsPath = cacheDir(process.env, projectId);
3622
- const warn2 = (line) => {
3623
- process.stderr.write(line.startsWith(" ") ? line + "\n" : `Warning: [${path18.basename(root)}] ${line}
3747
+ const warn2 = (line2) => {
3748
+ process.stderr.write(line2.startsWith(" ") ? line2 + "\n" : `Warning: [${path19.basename(root)}] ${line2}
3624
3749
  `);
3625
3750
  };
3626
3751
  mkdirSync(roadmapsPath, { recursive: true, mode: 448 });
@@ -3630,14 +3755,14 @@ function register10(program, deps) {
3630
3755
  { root, projectId, onlyDirty },
3631
3756
  {
3632
3757
  env: process.env,
3633
- readFile: (p) => readFile10(p, "utf8"),
3758
+ readFile: (p) => readFile11(p, "utf8"),
3634
3759
  realpath: (p) => realpath4(p),
3635
- fileExists: (p) => existsSync5(p),
3760
+ fileExists: (p) => existsSync6(p),
3636
3761
  repoIdentity: makeRepoIdentityResolver(deps),
3637
3762
  exec: promisify2(execFile3),
3638
3763
  gitLinks: process.env.NOLTO_GIT_LINKS !== "0",
3639
3764
  http,
3640
- log: (line) => process.stdout.write(`[${path18.basename(root)}] ${line}
3765
+ log: (line2) => process.stdout.write(`[${path19.basename(root)}] ${line2}
3641
3766
  `),
3642
3767
  warn: warn2
3643
3768
  }
@@ -3646,11 +3771,11 @@ function register10(program, deps) {
3646
3771
  debounceMs,
3647
3772
  setTimeoutFn: (fn, ms) => setTimeout(fn, ms),
3648
3773
  clearTimeoutFn: (t) => clearTimeout(t),
3649
- log: (line) => process.stdout.write(line + "\n"),
3650
- warn: (line) => process.stderr.write(line + "\n")
3774
+ log: (line2) => process.stdout.write(line2 + "\n"),
3775
+ warn: (line2) => process.stderr.write(line2 + "\n")
3651
3776
  });
3652
3777
  watcher.on("all", (_event, filePath) => {
3653
- if (path18.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3778
+ if (path19.dirname(filePath) === roadmapsPath && !filePath.endsWith(".json")) return;
3654
3779
  repoWatch.handleEvent(filePath);
3655
3780
  });
3656
3781
  void checkSkillVersionDrift(root, deps.version).then((drifted) => {
@@ -3664,7 +3789,7 @@ function register10(program, deps) {
3664
3789
  };
3665
3790
  const watchSet = new WatchSet({
3666
3791
  start: startRepo,
3667
- log: (line) => process.stdout.write(line + "\n")
3792
+ log: (line2) => process.stdout.write(line2 + "\n")
3668
3793
  });
3669
3794
  await watchSet.reconcile(roots);
3670
3795
  try {
@@ -3681,8 +3806,8 @@ function register10(program, deps) {
3681
3806
  registryReloadTimer = null;
3682
3807
  void reloadRoots({
3683
3808
  load: () => loadRegistry(registryPath),
3684
- exists: (root) => existsSync5(root),
3685
- warn: (line) => process.stderr.write(`Warning: ${line}
3809
+ exists: (root) => existsSync6(root),
3810
+ warn: (line2) => process.stderr.write(`Warning: ${line2}
3686
3811
  `)
3687
3812
  }).then(async (newRoots) => {
3688
3813
  if (newRoots == null) return;
@@ -3718,7 +3843,7 @@ function register10(program, deps) {
3718
3843
  version: running ? state.version : null,
3719
3844
  startedAt: running ? state.startedAt : null,
3720
3845
  stale: running && state.version !== deps.version,
3721
- service: existsSync5(getUnitPath(process.env)) ? "installed" : "not-installed"
3846
+ service: existsSync6(getUnitPath(process.env)) ? "installed" : "not-installed"
3722
3847
  };
3723
3848
  printResult(deps.output.mode === "json" ? result : `${running ? "running" : "not running"}
3724
3849
  service: ${result.service}
@@ -3730,7 +3855,7 @@ stale: ${result.stale}`, deps.output.mode);
3730
3855
  watch.command("stop").description("Stop watch without disabling the installed service.").action(async () => {
3731
3856
  const statePath = getWatchStatePath(process.env);
3732
3857
  const state = await readWatchState(statePath);
3733
- const service = existsSync5(getUnitPath(process.env));
3858
+ const service = existsSync6(getUnitPath(process.env));
3734
3859
  let via = null;
3735
3860
  if (service) {
3736
3861
  await stopServiceWith({
@@ -3768,11 +3893,11 @@ stale: ${result.stale}`, deps.output.mode);
3768
3893
  });
3769
3894
  watch.command("list").description("List repositories in the watch registry.").action(async () => {
3770
3895
  const registry = await loadRegistry(getRegistryPath(process.env));
3771
- const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync5(repo.root) }));
3896
+ const repos = registry.repos.map((repo) => ({ root: repo.root, projectId: repo.projectId ?? null, exists: existsSync6(repo.root) }));
3772
3897
  printResult(deps.output.mode === "json" ? { repos } : repos.map((repo) => `${repo.root} ${repo.projectId ?? "\u2014"}${repo.exists ? "" : " (missing)"}`).join("\n"), deps.output.mode);
3773
3898
  });
3774
3899
  watch.command("remove [root]").description("Remove a repository from the watch registry.").action(async (arg) => {
3775
- const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path18.resolve(arg);
3900
+ const root = arg === void 0 ? findRepoRoot(resolveStartDir(process.env, process.cwd())).root : path19.resolve(arg);
3776
3901
  const { removed } = await removeRepoFromRegistry(getRegistryPath(process.env), root);
3777
3902
  if (!removed) throw new CliError(`${root} is not in the watch registry.`, 2, "Run `nolto watch list` to see registered repositories.");
3778
3903
  printResult(deps.output.mode === "json" ? { removed: true, root } : `Removed ${root} from the watch registry.`, deps.output.mode);
@@ -3781,17 +3906,17 @@ stale: ${result.stale}`, deps.output.mode);
3781
3906
 
3782
3907
  // src/update-cli.ts
3783
3908
  import { execFile as execFile4 } from "child_process";
3784
- import { existsSync as existsSync6 } from "fs";
3909
+ import { existsSync as existsSync7 } from "fs";
3785
3910
  import { realpath as realpath5 } from "fs/promises";
3786
3911
  import { createRequire as createRequire2 } from "module";
3787
- import path20 from "path";
3912
+ import path21 from "path";
3788
3913
  import { fileURLToPath as fileURLToPath3 } from "url";
3789
3914
  import { promisify as promisify3 } from "util";
3790
3915
 
3791
3916
  // src/update-notifier.ts
3792
- import { readFile as readFile11, writeFile as writeFile8, mkdir as mkdir6 } from "fs/promises";
3917
+ import { readFile as readFile12, writeFile as writeFile9, mkdir as mkdir7 } from "fs/promises";
3793
3918
  import https from "https";
3794
- import path19 from "path";
3919
+ import path20 from "path";
3795
3920
  var PACKAGE = "@nolto/cli";
3796
3921
  var CACHE_FILE = "update-check.json";
3797
3922
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -3849,9 +3974,9 @@ function fetchLatestFromRegistry(timeoutMs = REQUEST_TIMEOUT_MS, opts = {}) {
3849
3974
  });
3850
3975
  }
3851
3976
  async function writeUpdateCache(cachePath, now, latest2) {
3852
- await mkdir6(path19.dirname(cachePath), { recursive: true });
3977
+ await mkdir7(path20.dirname(cachePath), { recursive: true });
3853
3978
  const payload = { checkedAt: now, latest: latest2 };
3854
- await writeFile8(cachePath, JSON.stringify(payload), { mode: 384 });
3979
+ await writeFile9(cachePath, JSON.stringify(payload), { mode: 384 });
3855
3980
  }
3856
3981
  async function refreshCache(cachePath, now, fetchLatest) {
3857
3982
  const latest2 = await fetchLatest();
@@ -3860,10 +3985,10 @@ async function refreshCache(cachePath, now, fetchLatest) {
3860
3985
  }
3861
3986
  async function checkForUpdate(opts) {
3862
3987
  if (isDisabled(opts.env)) return null;
3863
- const cachePath = path19.join(opts.configDir, CACHE_FILE);
3988
+ const cachePath = path20.join(opts.configDir, CACHE_FILE);
3864
3989
  let cache = {};
3865
3990
  try {
3866
- cache = JSON.parse(await readFile11(cachePath, "utf8"));
3991
+ cache = JSON.parse(await readFile12(cachePath, "utf8"));
3867
3992
  } catch {
3868
3993
  }
3869
3994
  if (typeof cache.checkedAt !== "number" || opts.now - cache.checkedAt > CACHE_TTL_MS) {
@@ -3968,7 +4093,7 @@ async function updateCliWith(deps) {
3968
4093
  }
3969
4094
  deps.log(`Updated ${PACKAGE2} ${deps.currentVersion} \u2192 ${latest2}.`);
3970
4095
  await deps.writeCache(
3971
- path20.join(deps.configDir, UPDATE_CACHE_FILE),
4096
+ path21.join(deps.configDir, UPDATE_CACHE_FILE),
3972
4097
  deps.now,
3973
4098
  latest2
3974
4099
  ).catch(() => void 0);
@@ -3999,10 +4124,10 @@ async function updateCliWith(deps) {
3999
4124
  };
4000
4125
  }
4001
4126
  function getCurrentVersion() {
4002
- const dirname = path20.dirname(fileURLToPath3(import.meta.url));
4127
+ const dirname = path21.dirname(fileURLToPath3(import.meta.url));
4003
4128
  const require3 = createRequire2(import.meta.url);
4004
4129
  try {
4005
- const pkg = require3(path20.resolve(dirname, "../package.json"));
4130
+ const pkg = require3(path21.resolve(dirname, "../package.json"));
4006
4131
  return pkg.version ?? "0.0.0";
4007
4132
  } catch {
4008
4133
  return "0.0.0";
@@ -4034,9 +4159,9 @@ async function updateCli(opts = {}) {
4034
4159
  realpath: realpath5,
4035
4160
  fetchLatest: () => fetchLatestFromRegistry(UPDATE_REQUEST_TIMEOUT_MS, UPDATE_FETCH_OPTIONS),
4036
4161
  writeCache: writeUpdateCache,
4037
- unitExists: existsSync6,
4038
- log: opts.quiet === true ? () => void 0 : (line) => process.stdout.write(line + "\n"),
4039
- warn: (line) => process.stderr.write("Warning: " + line + "\n")
4162
+ unitExists: existsSync7,
4163
+ log: opts.quiet === true ? () => void 0 : (line2) => process.stdout.write(line2 + "\n"),
4164
+ warn: (line2) => process.stderr.write("Warning: " + line2 + "\n")
4040
4165
  });
4041
4166
  }
4042
4167
 
@@ -4052,7 +4177,7 @@ function register11(program, deps) {
4052
4177
  }
4053
4178
 
4054
4179
  // src/commands/merge-file.ts
4055
- import { readFile as readFile12, writeFile as writeFile9 } from "fs/promises";
4180
+ import { readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
4056
4181
 
4057
4182
  // src/roadmap-merge.ts
4058
4183
  import { isDeepStrictEqual } from "util";
@@ -4144,7 +4269,7 @@ function mergeTask(args) {
4144
4269
  const dependsOn = [
4145
4270
  ...args.ours.dependsOn ?? [],
4146
4271
  ...args.theirs.dependsOn ?? []
4147
- ].filter((id, index, values) => values.indexOf(id) === index);
4272
+ ].filter((id, index2, values) => values.indexOf(id) === index2);
4148
4273
  if (dependsOn.length > 0) merged.dependsOn = dependsOn;
4149
4274
  const issues = [.../* @__PURE__ */ new Set([...args.ours.issues ?? [], ...args.theirs.issues ?? []])];
4150
4275
  if (issues.length > 0) merged.issues = issues;
@@ -4176,8 +4301,8 @@ function orderTasks(args) {
4176
4301
  ordered.push(task.id);
4177
4302
  continue;
4178
4303
  }
4179
- const index = ordered.indexOf(insertAfter);
4180
- ordered.splice(index + 1, 0, task.id);
4304
+ const index2 = ordered.indexOf(insertAfter);
4305
+ ordered.splice(index2 + 1, 0, task.id);
4181
4306
  insertAfter = task.id;
4182
4307
  }
4183
4308
  return ordered;
@@ -4292,7 +4417,7 @@ function mergeRoadmaps(args) {
4292
4417
  async function readRoadmap(filePath) {
4293
4418
  let parsed;
4294
4419
  try {
4295
- parsed = JSON.parse(await readFile12(filePath, "utf8"));
4420
+ parsed = JSON.parse(await readFile13(filePath, "utf8"));
4296
4421
  } catch (err) {
4297
4422
  const message = err instanceof SyntaxError ? "malformed JSON" : String(err);
4298
4423
  throw new CliError(`${filePath}: ${message}`, 1);
@@ -4316,7 +4441,7 @@ function register12(program) {
4316
4441
  const theirs = await readRoadmap(theirsPath);
4317
4442
  const base = opts.base == null ? null : await readRoadmap(opts.base);
4318
4443
  const merged = mergeRoadmaps({ base, ours, theirs });
4319
- await writeFile9(
4444
+ await writeFile10(
4320
4445
  opts.output ?? oursPath,
4321
4446
  JSON.stringify(merged, null, 2) + "\n",
4322
4447
  "utf8"
@@ -4328,6 +4453,607 @@ function register12(program) {
4328
4453
  });
4329
4454
  }
4330
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;
4652
+ }
4653
+ }
4654
+ if (entries.length) {
4655
+ entries.splice(project < 0 ? entries.length - 1 : project, 1);
4656
+ omitted++;
4657
+ } else {
4658
+ mergedLines.pop();
4659
+ omitted++;
4660
+ }
4661
+ }
4662
+ return build().join("\n") + "\n";
4663
+ }
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 {
4690
+ }
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;
4703
+ }
4704
+ };
4705
+ let checkedOut, target, targetTip;
4706
+ 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;
4712
+ }
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
+ }
4724
+ }
4725
+ return merged;
4726
+ }
4727
+
4728
+ // src/commands/memory.ts
4729
+ 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
+ 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
+ var pullHint = "nolto memory pull \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044";
4737
+ var scopeHint = "--scope project|user|branch";
4738
+ async function context2(deps, recover = false) {
4739
+ const bindingPath = deps.repoBinding?.path ?? deps.projectBindingPath;
4740
+ const binding = deps.repoBinding?.binding ?? (bindingPath ? await loadRepoBinding(bindingPath) : null);
4741
+ const project = deps.settings.defaultProjectId ?? binding?.projectId;
4742
+ 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
+ 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);
4757
+ }
4758
+ function headers() {
4759
+ return { "X-Nolto-Client": detectMemoryClient(process.env) };
4760
+ }
4761
+ function line(entry) {
4762
+ return `${entry.scope}/${entry.name} r${entry.revision} \u2014 ${oneLine(entry.description)}`;
4763
+ }
4764
+ function resolveEntry(ctx, name, target, deleted = false) {
4765
+ if (target.scope) parseScope(target.scope, scopeHint);
4766
+ if (target.branch !== void 0 && target.scope && target.scope !== "branch") throw new CliError("--branch \u306F --scope branch \u3068\u3060\u3051\u7D44\u307F\u5408\u308F\u305B\u3089\u308C\u307E\u3059\u3002", 2, "--scope \u3092\u5916\u3059\u304B --scope branch \u306B\u3059\u308B");
4767
+ const scope = target.branch !== void 0 ? "branch" : target.scope;
4768
+ const branch = target.branch ?? ctx.git.branch;
4769
+ const named = ctx.cache.state.entries.filter((e) => e.name === name && (!scope || e.scope === scope));
4770
+ const inRepo = (e) => e.scope !== "branch" || e.repoIdentity === ctx.git.repoIdentity;
4771
+ const candidates = named.filter((e) => inRepo(e) && (e.scope !== "branch" || e.branch === branch) && (deleted || !e.deleted));
4772
+ if (candidates.length > 1) throw new CliError(`\u30E1\u30E2\u30EA ${name} \u306F\u66D6\u6627\u3067\u3059: ${candidates.map((e) => `${e.scope}/${e.name}`).join(", ")}`, 2, "--scope \u3092\u4ED8\u3051\u308B");
4773
+ if (candidates.length) return candidates[0];
4774
+ const others = [...new Set(named.filter((e) => e.scope === "branch" && inRepo(e) && e.branch !== branch && !e.deleted).map((e) => e.branch))];
4775
+ if (others.length) {
4776
+ throw new CliError(`\u30E1\u30E2\u30EA ${name} \u306F\u4ECA\u306E\u30D6\u30E9\u30F3\u30C1\u306B\u3042\u308A\u307E\u305B\u3093\u3002\u307B\u304B\u306E\u30D6\u30E9\u30F3\u30C1: ${others.map(oneLine).join(", ")}`, 2, `--branch ${shellArg(others[0])} \u3092\u4ED8\u3051\u308B`);
4777
+ }
4778
+ if (!deleted && named.some((e) => inRepo(e) && e.deleted)) {
4779
+ throw new CliError(`\u30E1\u30E2\u30EA ${name} \u306F\u524A\u9664\u6E08\u307F\u3067\u3059\u3002`, 2, `\u5C65\u6B74\u306F nolto memory log ${name}\u3001\u623B\u3059\u306A\u3089 nolto memory revert ${name} <revision>`);
4780
+ }
4781
+ throw new CliError(`\u30E1\u30E2\u30EA ${name} \u304C\u30AD\u30E3\u30C3\u30B7\u30E5\u306B\u3042\u308A\u307E\u305B\u3093\u3002`, 2, "nolto memory pull");
4782
+ }
4783
+ async function apiCall(deps, ctx, call, op = "read", name = "<name>") {
4784
+ try {
4785
+ return await call();
4786
+ } catch (error) {
4787
+ if (!(error instanceof CliError)) throw error;
4788
+ const code = error.serverError;
4789
+ let hint = error.hint;
4790
+ const body = error.body;
4791
+ const latest2 = body?.entry;
4792
+ if (latest2 && (code === "memory_exists" || code === "memory_conflict")) await updateCache(ctx, deps, [latest2], true);
4793
+ let detail;
4794
+ if (code === "memory_similar") {
4795
+ hint = "nolto memory show <name> \u3067\u8AAD\u307F\u3001\u540C\u3058\u8A71\u306A\u3089 frontmatter \u306B revision \u3092\u8DB3\u3057\u3066\u305D\u306E name \u3067 put\u3002\u5225\u306E\u8A71\u306A\u3089 --new";
4796
+ const lines = typeof body?.aiSkipped === "string" ? [aiSkippedLine(body.aiSkipped)] : [];
4797
+ if (Array.isArray(body?.candidates)) {
4798
+ lines.push(...body.candidates.map((candidate) => `${candidate.scope}/${candidate.name} r${candidate.revision} (${candidate.score.toFixed(2)}) \u2014 ${oneLine(candidate.description)}`));
4799
+ }
4800
+ if (lines.length) detail = lines.join("\n");
4801
+ } else if (code === "memory_exists" && Array.isArray(body?.conflicts)) {
4802
+ const conflicts = body.conflicts;
4803
+ await updateCache(ctx, deps, conflicts.flatMap((c) => [c.branchEntry, c.projectEntry]), true);
4804
+ detail = conflicts.map((c) => `project/${c.name} r${c.projectEntry.revision} \u2190 branch/${c.name} r${c.branchEntry.revision}`).join("\n");
4805
+ const branch = shellArg(conflicts[0]?.branchEntry.branch ?? "<branch>");
4806
+ const n = conflicts.length === 1 ? conflicts[0].name : "<name>";
4807
+ hint = `\u4E21\u65B9\u3092\u8AAD\u3080: nolto memory show ${n} --scope branch --branch ${branch} \u3068 nolto memory show ${n} --scope project\u3002project \u5074\u306B\u7D71\u5408\u3057\u3066 put \u2192 nolto memory promote --branch ${branch} --discard ${n}\u3002\u6B8B\u308A\u306F\u305D\u306E\u3042\u3068 promote`;
4808
+ } else if (code === "memory_not_found" && op === "put") {
4809
+ hint = `\u524A\u9664\u6E08\u307F\u304B\u3001\u898B\u3064\u304B\u3089\u306A\u3044\u3002revision \u884C\u3092\u6D88\u3057\u3066\u65B0\u898F\u3067 put \u3059\u308B\u304B\u3001nolto memory log ${name} \u3067\u5C65\u6B74\u3092\u898B\u3066 revert`;
4810
+ } else if (code === "memory_conflict" && latest2 && (op === "rm" || op === "revert")) {
4811
+ hint = "\u6700\u65B0\u306E\u5185\u5BB9\u3092\u78BA\u8A8D\u3057\u3001\u540C\u3058\u30B3\u30DE\u30F3\u30C9\u3092\u518D\u5B9F\u884C(\u30AD\u30E3\u30C3\u30B7\u30E5\u306F\u66F4\u65B0\u6E08\u307F)";
4812
+ detail = formatMemory(latest2);
4813
+ } else if (code === "memory_exists") {
4814
+ hint = `nolto memory show ${latest2 ? `${latest2.name} --scope ${latest2.scope}` : "<name>"} --fresh > \u4E0B\u66F8\u304D.md \u3067\u4ECA\u306E\u5185\u5BB9\u3068 revision \u3092\u53D6\u308A\u3001\u7D71\u5408\u3057\u3066 put`;
4815
+ } else if (code === "memory_conflict" && latest2) {
4816
+ hint = `\u5185\u5BB9\u3092\u7D71\u5408\u3057\u3001revision \u3092 ${latest2.revision} \u306B\u3057\u3066 put \u3057\u76F4\u3059`;
4817
+ detail = formatMemory(latest2);
4818
+ } else if (code === "repo_unbound") hint = "nolto link --add \u3067\u3053\u306E repo \u3092\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306B\u7D10\u4ED8\u3051\u308B";
4819
+ throw new CliError(error.message, error.exitCode, hint, error.status, code, body, detail);
4820
+ }
4821
+ }
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
+ function printWrite(deps, ctx, action, response, isNew = false) {
4842
+ if (deps.output.mode === "json") {
4843
+ printResult(response, "json");
4844
+ return;
4845
+ }
4846
+ const { entry } = response;
4847
+ const lines = [aiHeading(response) ?? `${action} ${entry.scope}/${entry.name} r${entry.revision}${isNew ? " (\u65B0\u898F)" : ""}`];
4848
+ if (response.aiSkipped) lines.push(aiSkippedLine(response.aiSkipped));
4849
+ const affected = response.affected ?? [];
4850
+ for (const a of affected) lines.push(`- ${a.scope}/${a.name} r${a.fromRevision} \u2192 ${a.deleted ? `\u524A\u9664 (r${a.toRevision})` : `r${a.toRevision}`}`);
4851
+ const reverts = affected.filter((a) => a.fromRevision >= 1).map((a) => {
4852
+ const shared = ctx.cache.state.entries.some((e) => e.name === a.name && e.id !== a.entryId && e.scope !== a.scope);
4853
+ return `nolto memory revert ${shellArg(a.name)} ${a.fromRevision}${shared ? ` --scope ${a.scope}` : ""}`;
4854
+ });
4855
+ if (reverts.length) lines.push(`\u623B\u3059: ${reverts.join(" / ")}`);
4856
+ for (const warning of response.warnings ?? []) lines.push(`\u6CE8\u610F: ${typeof warning === "string" ? oneLine(warning) : JSON.stringify(warning)}`);
4857
+ process.stdout.write(lines.join("\n") + "\n");
4858
+ }
4859
+ async function pull2(deps, opts) {
4860
+ let ctx;
4861
+ const signal = opts.hook ? AbortSignal.timeout(8e3) : void 0;
4862
+ try {
4863
+ const explicitProject = deps.settings.source?.project === "flag" || deps.settings.source?.project === "env";
4864
+ if (opts.hook && !explicitProject && !(deps.repoBinding?.path ?? deps.projectBindingPath)) {
4865
+ process.stdout.write(hookOutput(opts.hook, "nolto link \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"));
4866
+ return;
4867
+ }
4868
+ if (opts.hook && !deps.settings.token) {
4869
+ process.stdout.write(hookOutput(opts.hook, "nolto login \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"));
4870
+ return;
4871
+ }
4872
+ ctx = await context2(deps, true);
4873
+ if (opts.hook && typeof opts.hook === "string" && !["claude", "codex", "gemini"].includes(opts.hook)) throw new CliError("Unknown hook agent", 2);
4874
+ const scope = opts.scope ? [...new Set(opts.scope.split(",").map((s) => parseScope(s.trim(), scopeHint)))].sort().join(",") : "";
4875
+ const previous = ctx.cache.state.entries;
4876
+ const reset = ctx.cache.meta.cursor === 0 || ctx.cache.state.scope !== scope;
4877
+ let cursor = reset ? 0 : ctx.cache.meta.cursor;
4878
+ let entries = reset ? [] : previous;
4879
+ while (true) {
4880
+ const query = new URLSearchParams({ since: String(cursor), ...scope ? { scope } : {} });
4881
+ const page = await apiCall(deps, ctx, () => deps.http.get(`${ctx.api}?${query}`, signal));
4882
+ if (!Array.isArray(page.entries) || !Number.isSafeInteger(page.cursor) || page.cursor < cursor || page.hasMore && page.cursor === cursor) throw new CliError("Invalid memory cursor response", 5);
4883
+ entries = mergeMemoryEntries(entries, page.entries);
4884
+ cursor = page.cursor;
4885
+ if (!page.hasMore) break;
4886
+ }
4887
+ const [projects, profile] = await Promise.all([
4888
+ deps.http.get("/api/projects", signal).catch(() => null),
4889
+ deps.http.get("/api/me/profile", signal).catch(() => null)
4890
+ ]);
4891
+ const projectName = projects?.projects?.find((p) => p.id === ctx.project)?.name ?? ctx.cache.state.projectName;
4892
+ const userId = typeof profile?.profile?.id === "string" ? profile.profile.id : ctx.cache.state.userId;
4893
+ const next = { ...ctx, cache: { state: { entries, scope, projectName, ...userId ? { userId } : {} }, meta: { cursor, pulledAt: (/* @__PURE__ */ new Date()).toISOString() } } };
4894
+ const text = await index(next, deps);
4895
+ const unsafe = await saveMemoryCache(ctx.dir, next.cache, previous, text, reset);
4896
+ 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
+ `);
4898
+ if (opts.hook) process.stdout.write(hookOutput(opts.hook, text));
4899
+ else printResult(deps.output.mode === "json" ? { cursor, entries: entries.filter((e) => !e.deleted).length } : `pulled memory (${entries.filter((e) => !e.deleted).length} \u4EF6)`, deps.output.mode);
4900
+ } catch (error) {
4901
+ if (!opts.hook) throw error;
4902
+ let text = pullHint;
4903
+ if (ctx?.cache.meta.pulledAt) {
4904
+ try {
4905
+ const age = Math.max(0, Math.floor((Date.now() - Date.parse(ctx.cache.meta.pulledAt)) / 6e4));
4906
+ 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)}`;
4908
+ } catch {
4909
+ }
4910
+ }
4911
+ process.stdout.write(hookOutput(opts.hook, text));
4912
+ }
4913
+ }
4914
+ async function inputText(file) {
4915
+ if (file !== "-") return readFile15(file, "utf8");
4916
+ let text = "";
4917
+ process.stdin.setEncoding("utf8");
4918
+ for await (const chunk of process.stdin) text += chunk;
4919
+ return text;
4920
+ }
4921
+ function register13(program, deps) {
4922
+ const memory = program.command("memory").description("Read and write project memory.");
4923
+ memory.command("pull").option("--hook [agent]", "SessionStart output; always exit 0").option("--scope <csv>").action((opts) => pull2(deps, opts));
4924
+ memory.command("context").action(async () => {
4925
+ const ctx = await context2(deps);
4926
+ process.stdout.write(ctx.cache.meta.pulledAt || ctx.cache.state.entries.length ? await index(ctx, deps) : pullHint + "\n");
4927
+ });
4928
+ memory.command("instructions").action(() => {
4929
+ process.stdout.write(MEMORY_INSTRUCTIONS + "\n");
4930
+ });
4931
+ memory.command("list").option("--scope <scope>").option("--all-branches").action(async (opts) => {
4932
+ const ctx = await context2(deps);
4933
+ if (opts.scope) parseScope(opts.scope, scopeHint);
4934
+ const entries = sortMemoryEntries(currentMemoryEntries(ctx.cache.state.entries, ctx.git, opts.allBranches).filter((e) => !opts.scope || e.scope === opts.scope));
4935
+ printResult(deps.output.mode === "json" ? entries : entries.map((e) => line(e) + (opts.allBranches && e.scope === "branch" ? ` [${e.repoIdentity} ${e.branch}]` : "")).join("\n"), deps.output.mode);
4936
+ });
4937
+ memory.command("show <name>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").option("--fresh").action(async (name, opts) => {
4938
+ const ctx = await context2(deps);
4939
+ let entry = resolveEntry(ctx, name, opts);
4940
+ if (opts.fresh) {
4941
+ entry = await apiCall(deps, ctx, () => deps.http.get(`${ctx.api}/${encodeURIComponent(entry.id)}`));
4942
+ await updateCache(ctx, deps, [entry]);
4943
+ }
4944
+ if (deps.output.mode === "json") printResult(entry, "json");
4945
+ else process.stdout.write(formatMemory(entry));
4946
+ });
4947
+ memory.command("put <file>").option("--new").option("--no-ai", "skip AI cleanup (Pro+)").action(async (file, opts) => {
4948
+ const draft = parseMemory(await inputText(file));
4949
+ const scope = parseScope(draft.scope);
4950
+ validateDraft(draft);
4951
+ const ctx = await context2(deps, true);
4952
+ if (scope === "branch" && (!ctx.git.branch || !ctx.git.repoIdentity || ctx.git.branch === ctx.git.defaultBranch || ["main", "master"].includes(ctx.git.branch) && !ctx.git.defaultBranch)) throw new CliError("branch \u30B9\u30B3\u30FC\u30D7\u306F\u4F5C\u696D\u30D6\u30E9\u30F3\u30C1\u3067\u3060\u3051\u4F7F\u3048\u307E\u3059\u3002", 2, "\u4F5C\u696D\u30D6\u30E9\u30F3\u30C1\u306B\u5207\u308A\u66FF\u3048\u308B(git switch -c <branch>)\u304B\u3001scope \u3092 project / user \u306B\u3059\u308B");
4953
+ if (scope === "branch" && draft.branch !== void 0 && draft.branch !== ctx.git.branch) throw new CliError(`branch ${draft.branch} \u304C\u4ECA\u306E\u30D6\u30E9\u30F3\u30C1 ${ctx.git.branch} \u3068\u7570\u306A\u308A\u307E\u3059\u3002`, 2, `frontmatter \u306E branch \u3092\u6D88\u3059\u304B ${ctx.git.branch} \u306B\u3059\u308B`);
4954
+ const response = await apiCall(deps, ctx, () => deps.http.put(ctx.api, {
4955
+ scope,
4956
+ name: draft.name,
4957
+ description: draft.description,
4958
+ body: draft.body,
4959
+ ...draft.type ? { type: draft.type } : {},
4960
+ ...draft.revision !== void 0 ? { baseRevision: parseRevision(draft.revision) } : {},
4961
+ ...opts.new ? { allowNew: true } : {},
4962
+ ...opts.ai === false ? { aiSkip: true } : {},
4963
+ ...scope === "branch" ? { repoIdentity: ctx.git.repoIdentity, branch: ctx.git.branch } : {}
4964
+ }, headers()), "put", draft.name);
4965
+ await updateCache(ctx, deps, writtenEntries(ctx, response));
4966
+ printWrite(deps, ctx, "put", response, draft.revision === void 0);
4967
+ });
4968
+ memory.command("rm <name>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (name, opts) => {
4969
+ const ctx = await context2(deps);
4970
+ const entry = resolveEntry(ctx, name, opts);
4971
+ const response = await apiCall(deps, ctx, () => deps.http.delete(`${ctx.api}/${encodeURIComponent(entry.id)}?baseRevision=${entry.revision}`, headers()), "rm", name);
4972
+ await updateCache(ctx, deps, writtenEntries(ctx, response));
4973
+ printWrite(deps, ctx, "rm", response);
4974
+ });
4975
+ memory.command("revert <name> <revision>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (name, revision, opts) => {
4976
+ const ctx = await context2(deps);
4977
+ const entry = resolveEntry(ctx, name, opts, true);
4978
+ const response = await apiCall(deps, ctx, () => deps.http.post(`${ctx.api}/${encodeURIComponent(entry.id)}/revert`, { revision: parseRevision(revision), baseRevision: entry.revision }, headers()), "revert", name);
4979
+ await updateCache(ctx, deps, writtenEntries(ctx, response));
4980
+ printWrite(deps, ctx, "revert", response);
4981
+ });
4982
+ memory.command("log <name>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (name, opts) => {
4983
+ const ctx = await context2(deps);
4984
+ const entry = resolveEntry(ctx, name, opts, true);
4985
+ const names = new Map(ctx.cache.state.entries.flatMap((e) => e.updatedBy?.name ? [[e.updatedBy.id, e.updatedBy.name]] : []));
4986
+ const response = await apiCall(deps, ctx, () => deps.http.get(`${ctx.api}/${encodeURIComponent(entry.id)}/revisions`));
4987
+ printResult(deps.output.mode === "json" ? response : response.revisions.map((r) => `r${r.revision} ${r.source}${r.revertOf ? ` \u2190 r${r.revertOf}` : r.fromBranch ? ` \u2190 ${oneLine(r.fromBranch)}` : ""} ${r.createdAt} ${r.actorUserId ? oneLine(names.get(r.actorUserId) ?? r.actorUserId) : "\u4E0D\u660E"} (${oneLine(memoryClient(r.via))})${r.aiReason ? ` \u2014 ${oneLine(r.aiReason)}` : ""}`).join("\n"), deps.output.mode);
4988
+ });
4989
+ memory.command("promote [names...]").requiredOption("--branch <branch>").option("--all").option("--discard").action(async (names, opts) => {
4990
+ if (opts.all && names.length) throw new CliError("--all \u3068 name \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002", 2);
4991
+ const ctx = await context2(deps);
4992
+ if (!ctx.git.repoIdentity) throw new CliError("repo \u3092\u8B58\u5225\u3067\u304D\u307E\u305B\u3093\u3002", 2);
4993
+ const selected = ctx.cache.state.entries.filter((e) => !e.deleted && e.scope === "branch" && e.repoIdentity === ctx.git.repoIdentity && e.branch === opts.branch && (!names.length || names.includes(e.name)));
4994
+ if (!opts.all && !names.length) {
4995
+ printResult(deps.output.mode === "json" ? selected : selected.length ? selected.map(line).join("\n") : `branch ${opts.branch} \u306E\u30E1\u30E2\u30EA\u306F\u30AD\u30E3\u30C3\u30B7\u30E5\u306B\u3042\u308A\u307E\u305B\u3093(nolto memory pull \u3067\u66F4\u65B0)`, deps.output.mode);
4996
+ return;
4997
+ }
4998
+ const response = await apiCall(deps, ctx, () => deps.http.post(`${ctx.api}/promote`, { repoIdentity: ctx.git.repoIdentity, branch: opts.branch, ...names.length ? { names } : {}, ...opts.discard ? { discard: true } : {} }, headers()), "promote");
4999
+ const retired = selected.map((e) => ({ ...e, deleted: true }));
5000
+ await updateCache(ctx, deps, [...retired, ...response.promoted, ...response.discarded]);
5001
+ printResult(deps.output.mode === "json" ? response : [...response.promoted.map((e) => `promote ${line(e)}`), ...response.discarded.map((e) => `discard ${line(e)}`)].join("\n"), deps.output.mode);
5002
+ });
5003
+ memory.command("hook").command("install").option("--agent <agent>").option("--write-agents-md").action(async (opts) => {
5004
+ const { root } = findRepoRoot(resolveStartDir(process.env, process.cwd()));
5005
+ const messages = await installMemoryHooks(root, deps.version, opts.agent, opts.writeAgentsMd);
5006
+ printResult(deps.output.mode === "json" ? { messages } : messages.join("\n"), deps.output.mode);
5007
+ });
5008
+ 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
+ const scope = parseScope(opts.scope, "--scope project|user");
5010
+ 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
+ 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
+ }
5042
+ }
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
+ `);
5047
+ }
5048
+ const skippedNames = results.filter((r) => r.status === "skipped").map((r) => `${scope}/${String(r.name)}`);
5049
+ 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(", ")}
5050
+ `);
5051
+ printResult(deps.output.mode === "json" ? { imported, skipped, failed, results } : `imported ${imported}, skipped ${skipped}, failed ${failed}`, deps.output.mode);
5052
+ if (!cached) process.stderr.write(cacheWarning);
5053
+ if (failed) process.exitCode = 2;
5054
+ });
5055
+ }
5056
+
4331
5057
  // src/program.ts
4332
5058
  function stripCommanderErrorPrefix(msg) {
4333
5059
  return msg.startsWith("error: ") ? msg.slice("error: ".length) : msg;
@@ -4336,6 +5062,7 @@ function buildProgram(deps) {
4336
5062
  const writeErr = (_msg) => {
4337
5063
  };
4338
5064
  const program = new Command("nolto").version(deps.version, "-V, --version", "Print version number").exitOverride().configureOutput({ writeErr }).description("Nolto CLI \u2014 sync repository roadmaps with Nolto.").option("--token <value>", "API token (overrides env/file)").option("--base-url <url>", "Nolto base URL (default: https://nolto.app)").option("--project <projectId>", "Default project ID").option("--json", "Output as JSON");
5065
+ register13(program, deps);
4339
5066
  register(program, deps);
4340
5067
  register3(program, deps);
4341
5068
  register4(program, deps);
@@ -4352,6 +5079,7 @@ function buildProgram(deps) {
4352
5079
  program.help();
4353
5080
  });
4354
5081
  program.hook("preAction", (_thisCommand, actionCommand) => {
5082
+ if (actionCommand.parent?.name() === "memory" && actionCommand.name() === "pull" && actionCommand.opts().hook) return;
4355
5083
  const bindingError = deps.repoBinding?.error;
4356
5084
  const bindingExemptCommands = ["init", "link", "update", "merge-file"];
4357
5085
  if (bindingError != null && !(actionCommand.parent === program && bindingExemptCommands.includes(actionCommand.name()))) {
@@ -4362,11 +5090,11 @@ function buildProgram(deps) {
4362
5090
  }
4363
5091
 
4364
5092
  // src/index.ts
4365
- var __dirname3 = path21.dirname(fileURLToPath4(import.meta.url));
5093
+ var __dirname3 = path24.dirname(fileURLToPath4(import.meta.url));
4366
5094
  var require2 = createRequire3(import.meta.url);
4367
5095
  function getVersion() {
4368
5096
  try {
4369
- const pkgPath = path21.resolve(__dirname3, "../package.json");
5097
+ const pkgPath = path24.resolve(__dirname3, "../package.json");
4370
5098
  const pkg = require2(pkgPath);
4371
5099
  return pkg.version ?? "0.0.0";
4372
5100
  } catch {
@@ -4374,6 +5102,8 @@ function getVersion() {
4374
5102
  }
4375
5103
  }
4376
5104
  var mode = "human";
5105
+ var memoryHook = hookAgentFromArgv(process.argv.slice(2));
5106
+ if (memoryHook) process.stderr.write = (() => true);
4377
5107
  async function main() {
4378
5108
  const argv = process.argv.slice(2);
4379
5109
  const flagToken = extractFlag(argv, "--token");
@@ -4381,22 +5111,12 @@ async function main() {
4381
5111
  const flagProject = extractFlag(argv, "--project");
4382
5112
  mode = argv.includes("--json") ? "json" : "human";
4383
5113
  const configPath = getConfigPath(process.env);
4384
- const configFile = await loadConfigFile(configPath).catch((err) => {
4385
- if (err instanceof CliError) {
4386
- printError(err, mode);
4387
- process.exitCode = err.exitCode;
4388
- process.exit();
4389
- }
4390
- throw err;
4391
- });
5114
+ const configFile = await loadConfigFile(configPath);
4392
5115
  if (flagBaseUrl != null) {
4393
5116
  try {
4394
5117
  new URL(flagBaseUrl);
4395
5118
  } catch {
4396
- const err = new CliError(`Invalid base URL: ${flagBaseUrl}`, 2);
4397
- printError(err, mode);
4398
- process.exitCode = 2;
4399
- process.exit();
5119
+ throw new CliError(`Invalid base URL: ${flagBaseUrl}`, 2);
4400
5120
  }
4401
5121
  }
4402
5122
  const projectBindingPath = findRepoBindingFile({ env: process.env, cwd: process.cwd() });
@@ -4431,7 +5151,7 @@ async function main() {
4431
5151
  repoBinding
4432
5152
  });
4433
5153
  await program.parseAsync(process.argv);
4434
- await notifyUpdate({ current: version, env: process.env, isJson: mode === "json", now: Date.now() });
5154
+ if (!memoryHook) await notifyUpdate({ current: version, env: process.env, isJson: mode === "json", now: Date.now() });
4435
5155
  }
4436
5156
  function extractFlag(argv, name) {
4437
5157
  const idx = argv.indexOf(name);
@@ -4441,6 +5161,11 @@ function extractFlag(argv, name) {
4441
5161
  return void 0;
4442
5162
  }
4443
5163
  main().catch((err) => {
5164
+ if (memoryHook) {
5165
+ process.stdout.write(hookOutput(memoryHook, "nolto memory pull \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"));
5166
+ process.exitCode = 0;
5167
+ return;
5168
+ }
4444
5169
  if (err instanceof CommanderError) {
4445
5170
  if (err.exitCode === 0) {
4446
5171
  process.exit(0);