@nolto/cli 0.21.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -117,6 +117,9 @@ function mapHttpStatusToCliError(status, opts = {}) {
117
117
  if (status === 404 && opts.serverError) {
118
118
  return new CliError(opts.serverError, 2, void 0, status, opts.serverError, opts.body);
119
119
  }
120
+ if (status === 422 && opts.serverError === "secret_detected") {
121
+ return new CliError(opts.serverMessage ?? opts.serverError, 2, void 0, status, opts.serverError, opts.body);
122
+ }
120
123
  if (status === 422) {
121
124
  const details = Array.isArray(opts.details) ? opts.details.map((detail) => typeof detail === "string" ? detail : JSON.stringify(detail)).join("\n") : "";
122
125
  return new CliError([opts.serverError ?? opts.serverMessage ?? "Validation failed", details].filter(Boolean).join("\n"), 2, void 0, status, opts.serverError, opts.body);
@@ -686,6 +689,133 @@ function createHttpClient(opts) {
686
689
  // src/program.ts
687
690
  import { Command } from "commander";
688
691
 
692
+ // src/memory-format.ts
693
+ var oneLine = (value) => value.replace(new RegExp("\\p{Cs}", "gu"), "\uFFFD").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/gu, " ").replace(new RegExp("(?![\\u200c\\u200d])\\p{Cf}|[\\u{e0100}-\\u{e01ef}\\u3164\\u115f\\u1160\\uffa0]", "gu"), "");
694
+ var commandArg = (value, placeholder) => {
695
+ const safe = oneLine(value);
696
+ return /^[A-Za-z0-9._/][A-Za-z0-9._/-]*$/.test(safe) ? safe : placeholder;
697
+ };
698
+ var shellArg = (value) => {
699
+ const safe = oneLine(value);
700
+ return /^[A-Za-z0-9._/][A-Za-z0-9._/-]*$/.test(safe) ? safe : "'" + safe.replace(/'/g, "'\\''") + "'";
701
+ };
702
+ var memoryClient = (via) => via?.client || via?.tokenName || "Web";
703
+ function parseMemory(text, importing = false) {
704
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
705
+ if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
706
+ if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
707
+ const end = lines.indexOf("---");
708
+ if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
709
+ const fields = {};
710
+ let metadata = false;
711
+ for (const line2 of lines.slice(0, end)) {
712
+ const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
713
+ if (!match) continue;
714
+ const indent = match[1], key = match[2], raw = match[3];
715
+ if (!indent) metadata = key === "metadata";
716
+ if (indent && !(importing && metadata && key === "type")) continue;
717
+ if (importing && ["expires", "ttl", "until"].includes(key)) continue;
718
+ let value = raw.trim();
719
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
720
+ if (["name", "description", "type", "scope", "branch", "revision", "expires", "ttl", "until"].includes(key)) fields[key] = value;
721
+ }
722
+ const body = lines.slice(end + 1);
723
+ if (body[0] === "") body.shift();
724
+ return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
725
+ }
726
+ function cleanupReason(reason) {
727
+ let text;
728
+ switch (reason.code) {
729
+ case "expired":
730
+ text = `\u671F\u9650\u5207\u308C(${reason.expiresOn ?? ""} \u307E\u3067)`;
731
+ break;
732
+ case "issue_closed":
733
+ text = `${reason.until ?? ""} \u304C\u5B8C\u4E86`;
734
+ break;
735
+ case "task_done":
736
+ text = `task ${reason.until ?? ""} \u304C\u5B8C\u4E86`;
737
+ break;
738
+ case "ref_missing":
739
+ text = `${reason.until ?? ""} \u304C\u898B\u3064\u304B\u3089\u306A\u3044`;
740
+ break;
741
+ case "superseded":
742
+ text = `\u65B0\u3057\u3044\u518D\u958B\u30DD\u30A4\u30F3\u30C8\u3042\u308A(${reason.newer ?? ""})`;
743
+ break;
744
+ default:
745
+ text = reason.code;
746
+ }
747
+ const chars = Array.from(oneLine(text));
748
+ return chars.length > 200 ? chars.slice(0, 199).join("") + "\u2026" : chars.join("");
749
+ }
750
+ function ttlExpires(ttl, today) {
751
+ const date = new Date(today.getTime());
752
+ date.setDate(date.getDate() + Number(ttl.slice(0, -1)));
753
+ return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
754
+ }
755
+ function formatMemory(entry, cleanup, scoped = false) {
756
+ const value = (s) => {
757
+ const safe = oneLine(s);
758
+ return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
759
+ };
760
+ return [
761
+ `<!-- ${cleanup ? `\u6574\u7406\u5019\u88DC: ${cleanupReason(cleanup)}\u3002\u6D88\u3059\u306A\u3089 nolto memory rm ${commandArg(entry.name, "<name>")}${scoped && ["project", "user", "branch"].includes(entry.scope) ? ` --scope ${entry.scope}` : ""}\u3002` : ""}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 -->`,
762
+ "---",
763
+ `name: ${oneLine(entry.name)}`,
764
+ `description: ${value(entry.description)}`,
765
+ ...entry.type == null ? [] : [`type: ${entry.type}`],
766
+ `scope: ${entry.scope}`,
767
+ ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
768
+ ...entry.expiresOn ? [`expires: ${value(entry.expiresOn)}`] : [],
769
+ ...entry.until ? [`until: ${value(entry.until)}`] : [],
770
+ `revision: ${entry.revision}`,
771
+ `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
772
+ "---",
773
+ "",
774
+ entry.body
775
+ ].join("\n");
776
+ }
777
+ function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
778
+ if (scope !== "project" && scope !== "user" && scope !== "branch") {
779
+ throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
780
+ }
781
+ return scope;
782
+ }
783
+ var count = (n) => n.toLocaleString("en-US");
784
+ var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
785
+ function validateDraft(draft) {
786
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
787
+ 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");
788
+ }
789
+ const description = draft.description.trim();
790
+ 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");
791
+ 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");
792
+ 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");
793
+ 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");
794
+ if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
795
+ 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");
796
+ }
797
+ if (draft.expires !== void 0 && draft.ttl !== void 0) throw invalidInput("expires \u3068 ttl \u306F\u4E21\u65B9\u66F8\u3051\u307E\u305B\u3093\u3002", "expires \u304B ttl \u306E\u3069\u3061\u3089\u304B\u3092\u66F8\u304F");
798
+ if (draft.expires !== void 0) {
799
+ const parsed = /* @__PURE__ */ new Date(`${draft.expires}T00:00:00Z`);
800
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(draft.expires) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== draft.expires) throw invalidInput("expires \u304C\u4E0D\u6B63\u3067\u3059\u3002", "expires \u306F YYYY-MM-DD \u306E\u5B9F\u5728\u3059\u308B\u65E5\u4ED8\u3067\u66F8\u304F");
801
+ }
802
+ if (draft.ttl !== void 0 && (!/^([1-9][0-9]{0,2})d$/.test(draft.ttl) || Number(draft.ttl.slice(0, -1)) > 365)) throw invalidInput("ttl \u304C\u4E0D\u6B63\u3067\u3059\u3002", "ttl \u306F 7d \u306E\u3088\u3046\u306B\u65E5\u6570\u3067\u66F8\u304F(1\u301C365)");
803
+ if (draft.until !== void 0 && draft.until.length > 200) throw invalidInput("until \u304C 200 \u5B57\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002", "until \u306F 200 \u5B57\u307E\u3067");
804
+ }
805
+ function parseRevision(value) {
806
+ const revision = Number(value);
807
+ 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);
808
+ return revision;
809
+ }
810
+ function detectMemoryClient(env) {
811
+ const agent = env.NOLTO_AGENT?.trim();
812
+ if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
813
+ if (env.CLAUDECODE === "1") return "Claude Code";
814
+ if (env.GEMINI_CLI === "1") return "Gemini CLI";
815
+ if (env.CODEX_THREAD_ID) return "Codex";
816
+ return "CLI";
817
+ }
818
+
689
819
  // src/commands/issue.ts
690
820
  import { readFile as readFile10 } from "fs/promises";
691
821
 
@@ -708,6 +838,14 @@ function printError(err, mode2) {
708
838
  ...err.body?.["candidates"] ? { candidates: err.body["candidates"] } : {},
709
839
  ...err.body?.["conflicts"] ? { conflicts: err.body["conflicts"] } : {},
710
840
  ...err.body && "aiSkipped" in err.body ? { aiSkipped: err.body["aiSkipped"] } : {},
841
+ ...Array.isArray(err.body?.["findings"]) ? { findings: err.body["findings"].flatMap((item) => {
842
+ if (!item || typeof item !== "object") return [];
843
+ const { field, rule, line: line2 } = item;
844
+ if (typeof field !== "string" || typeof rule !== "string") return [];
845
+ return [{ field, rule, ...typeof line2 === "number" ? { line: line2 } : {} }];
846
+ }) } : {},
847
+ ...err.body && "references" in err.body ? { references: err.body["references"] } : {},
848
+ ...err.body && "total" in err.body ? { total: err.body["total"] } : {},
711
849
  exitCode: err.exitCode,
712
850
  ...err.status != null ? { status: err.status } : {},
713
851
  ...err.hint != null ? { hint: err.hint } : {}
@@ -1142,6 +1280,22 @@ function buildListQuery(flags, settings) {
1142
1280
  var personLabel = (person) => person?.name ?? person?.email ?? "\u2014";
1143
1281
  var singleLine = (value) => (value ?? "").replace(/[\r\n\t\u2028\u2029]/g, " ");
1144
1282
  var stripControl = (value, multiline = false) => multiline ? (value ?? "").replace(new RegExp("\\p{Cc}", "gu"), (c) => c === "\n" || c === " " ? c : "") : singleLine(value).replace(new RegExp("\\p{Cc}", "gu"), "");
1283
+ var stripFormatControl = (value) => value.replace(new RegExp("\\p{Cf}", "gu"), (c) => c === "\u200C" || c === "\u200D" ? c : "");
1284
+ var stripTerminal = (value) => stripFormatControl(stripControl(value));
1285
+ function formatInternalReferences(body) {
1286
+ const references = Array.isArray(body.references) ? body.references : [];
1287
+ const rows = [];
1288
+ for (const ref of references) {
1289
+ if (!ref || typeof ref !== "object" || Array.isArray(ref) || typeof ref.label !== "string") continue;
1290
+ const label = Array.from(stripTerminal(ref.label));
1291
+ rows.push(`- ${label.length > 200 ? `${label.slice(0, 199).join("")}\u2026` : label.join("")}`);
1292
+ }
1293
+ const total = typeof body.total === "number" && Number.isSafeInteger(body.total) && body.total >= 0 ? body.total : references.length;
1294
+ const lines = rows.slice(0, 20);
1295
+ const remaining = total - lines.length;
1296
+ if (remaining > 0) lines.push(`\u2026\u307B\u304B ${remaining} \u4EF6(\u4E00\u89A7\u306B\u306F\u51FA\u3066\u3044\u307E\u305B\u3093\u3002\u672C\u6587\u3092\u898B\u3066\u78BA\u304B\u3081\u308B)`);
1297
+ return { message: `\u304A\u5BA2\u3055\u307E\u306B\u306F\u958B\u3051\u306A\u3044\u53C2\u7167\u304C\u3042\u308A\u307E\u3059(${total} \u4EF6)\u3002`, detail: lines.join("\n") };
1298
+ }
1145
1299
  var formatTimestamp = (value) => value.replace("T", " ").replace(/\.\d+/, "").replace(/([+-]\d{2})$/, "$1:00").replace(/Z$/, "+00:00");
1146
1300
  function formatIssueList(rows, meta) {
1147
1301
  const values = rows.map((row) => {
@@ -1316,7 +1470,7 @@ async function runSync(args, deps) {
1316
1470
  deps
1317
1471
  });
1318
1472
  const response = await deps.http.put(
1319
- `/api/projects/${args.projectId}/roadmaps/${args.slug}`,
1473
+ `/api/projects/${args.projectId}/roadmaps/${encodeURIComponent(args.slug)}`,
1320
1474
  { ...body, baseRevision: args.baseRevision }
1321
1475
  );
1322
1476
  for (const warning of response.warnings ?? []) deps.warn(warning);
@@ -1334,8 +1488,14 @@ function cacheDir(env, projectId) {
1334
1488
  if (!UUID_RE.test(projectId)) throw new CliError(`Invalid project id "${projectId}".`, 2);
1335
1489
  return path6.join(getConfigDir(env), "projects", projectId, "roadmaps");
1336
1490
  }
1491
+ function isCacheableSlug(slug) {
1492
+ return ROADMAP_SLUG_PATTERN.test(slug) && !slug.endsWith(".meta");
1493
+ }
1494
+ function assertCacheableSlug(slug) {
1495
+ if (!isCacheableSlug(slug)) throw new CliError(`Invalid roadmap slug "${stripTerminal(slug)}".`, 2);
1496
+ }
1337
1497
  function cachePaths(env, projectId, slug) {
1338
- if (!ROADMAP_SLUG_PATTERN.test(slug)) throw new CliError(`Invalid roadmap slug "${slug}".`, 2);
1498
+ assertCacheableSlug(slug);
1339
1499
  const dir = cacheDir(env, projectId);
1340
1500
  return { json: path6.join(dir, `${slug}.json`), meta: path6.join(dir, `${slug}.meta.json`) };
1341
1501
  }
@@ -1411,7 +1571,7 @@ import path7 from "path";
1411
1571
 
1412
1572
  // src/roadmap-scaffold.ts
1413
1573
  function slugifyProjectId(name) {
1414
- const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "");
1574
+ const slug = name.toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[-_.]+$/, "").replace(/\.meta$/, "-meta");
1415
1575
  return slug.length > 0 ? slug : "project";
1416
1576
  }
1417
1577
  function buildScaffold(projectName, repoBasename) {
@@ -1424,12 +1584,14 @@ function buildScaffold(projectName, repoBasename) {
1424
1584
  }
1425
1585
 
1426
1586
  // src/roadmap-bootstrap.ts
1587
+ var uncacheableSlugWarning = (slug) => `Warning: skipped roadmap "${stripTerminal(slug)}" \u2014 its slug cannot be cached locally.`;
1427
1588
  async function pullRoadmapCache(args) {
1428
1589
  const { env, projectId, slug } = args;
1590
+ assertCacheableSlug(slug);
1429
1591
  const response = await args.http.get(`/api/projects/${projectId}/roadmaps/${encodeURIComponent(slug)}`);
1430
1592
  const validation = validateRoadmap(response.roadmap);
1431
1593
  if (validation.errors.length > 0) {
1432
- throw new CliError(`Server roadmap "${slug}" failed validation: ${validation.errors.join("; ")}`, 5);
1594
+ throw new CliError(`Server roadmap "${slug}" failed validation: ${stripTerminal(validation.errors.join("; "))}`, 5);
1433
1595
  }
1434
1596
  let existing;
1435
1597
  try {
@@ -1454,42 +1616,49 @@ async function pullRoadmapCache(args) {
1454
1616
  }
1455
1617
  async function ensureRoadmapCache(args) {
1456
1618
  const { env, projectId } = args;
1619
+ const basename = path7.basename(args.repoRoot);
1620
+ const slug = args.slug ?? slugifyProjectId(basename);
1621
+ assertCacheableSlug(slug);
1457
1622
  const identity = repoIdentityToString(args.repoIdentity);
1458
1623
  const list = await args.http.get(`/api/projects/${projectId}/roadmaps`);
1459
1624
  const warn2 = (line2) => {
1460
1625
  process.stderr.write(line2 + "\n");
1461
1626
  };
1462
1627
  const log = (line2) => args.log(`roadmap: ${line2}`);
1463
- if (list.roadmaps.length > 0) {
1628
+ const roadmaps = list.roadmaps.filter((row) => {
1629
+ if (isCacheableSlug(row.slug)) return true;
1630
+ warn2(uncacheableSlugWarning(row.slug));
1631
+ return false;
1632
+ });
1633
+ const mine = roadmaps.filter((row) => row.repoIdentity == null || row.repoIdentity === identity);
1634
+ if (roadmaps.length > 0) {
1464
1635
  let skipped = false;
1465
- for (const { slug: slug2 } of list.roadmaps) {
1466
- if (!await pullRoadmapCache({ ...args, slug: slug2, warn: warn2, log, recoverInvalid: true })) skipped = true;
1636
+ for (const row of roadmaps) {
1637
+ if (!await pullRoadmapCache({ ...args, slug: row.slug, warn: warn2, log, recoverInvalid: true })) skipped = true;
1467
1638
  }
1468
1639
  if (skipped) throw new CliError("Some roadmaps have local changes that are not synced.", 4);
1469
- if (list.roadmaps.some((row) => row.repoIdentity == null || row.repoIdentity === identity)) return;
1640
+ if (args.slug === void 0 ? mine.length > 0 : mine.some((row) => row.slug === args.slug)) return;
1470
1641
  }
1471
- const basename = path7.basename(args.repoRoot);
1472
- const slug = args.slug ?? slugifyProjectId(basename);
1473
- const collision = list.roadmaps.find((row) => row.slug === slug);
1642
+ const collision = roadmaps.find((row) => row.slug === slug);
1474
1643
  if (collision) {
1475
1644
  if (args.slug === void 0) {
1476
- log(`skipped \u2014 "${slug}" is another repository's roadmap (${collision.repoIdentity ?? "unknown"}). Run \`nolto link --slug <name>\` to create one for this repository.`);
1645
+ log(`skipped \u2014 "${slug}" is another repository's roadmap (${stripTerminal(collision.repoIdentity ?? "unknown")}). Run \`nolto link --slug <name>\` to create one for this repository.`);
1477
1646
  return;
1478
1647
  }
1479
- 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);
1648
+ throw new CliError(`Roadmap slug "${slug}" already exists in this project (repo: ${stripTerminal(collision.repoIdentity ?? "unknown")}). Run \`nolto link --slug <other-slug>\` to name this repository's roadmap.`, 2);
1480
1649
  }
1481
- let existing;
1482
- try {
1483
- existing = await readCache(env, projectId, slug);
1484
- } catch (err) {
1485
- if (!(err instanceof CliError)) throw err;
1486
- existing = null;
1650
+ const existing = await readCache(env, projectId, slug);
1651
+ if (existing?.meta && (existing.meta.revision > 0 || existing.meta.repoIdentity != null && existing.meta.repoIdentity !== identity)) {
1652
+ throw new CliError(`Local cache for "${slug}" belongs to a roadmap that is no longer on the server (${cachePaths(env, projectId, slug).json}). Remove it or choose another slug with \`nolto link --slug\`.`, 2);
1487
1653
  }
1488
1654
  if (existing && isDirty(existing)) {
1489
1655
  warn2(`Warning: ${slug} has local changes that are not synced; use --force to overwrite or run nolto sync first`);
1490
1656
  throw new CliError("Roadmap has local changes that are not synced.", 4);
1491
1657
  }
1492
- const roadmap = existing?.roadmap ?? buildScaffold(args.projectName, basename);
1658
+ const second = mine.length > 0;
1659
+ const scaffold = buildScaffold(second ? slug : args.projectName, basename);
1660
+ if (second) scaffold.project.id = slug;
1661
+ const roadmap = existing?.roadmap ?? scaffold;
1493
1662
  await writeCache(env, projectId, slug, roadmap, { repoIdentity: identity, revision: 0, pulledAt: (/* @__PURE__ */ new Date()).toISOString() });
1494
1663
  const response = await runSync({ ...args, slug, roadmap, baseRevision: 0 }, {
1495
1664
  http: args.http,
@@ -1516,7 +1685,7 @@ async function ensureProjectRepo(args) {
1516
1685
  if (repos.length === 0) return "unbound";
1517
1686
  const identity = repoIdentityToString(args.repoIdentity);
1518
1687
  if (repos.some((repo) => repo.identity === identity)) return "bound";
1519
- if (!await args.confirm(`Project is bound to ${repos.map((repo) => repo.identity).join(", ")}. Add this repository (${identity}) to the project? [Y/n] `)) return "declined";
1688
+ if (!await args.confirm(`Project is bound to ${repos.map((repo) => stripTerminal(repo.identity)).join(", ")}. Add this repository (${identity}) to the project? [Y/n] `)) return "declined";
1520
1689
  try {
1521
1690
  await args.http.post(`/api/projects/${args.projectId}/repos`, { repoIdentity: args.repoIdentity });
1522
1691
  } catch (error) {
@@ -1809,9 +1978,9 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1809
1978
  }
1810
1979
  const repoIdentity = await makeRepoIdentityResolver(deps)(root);
1811
1980
  if (mode2 !== "json") {
1812
- process.stdout.write(`Project : ${project.name} (${project.id})
1981
+ process.stdout.write(`Project : ${stripTerminal(project.name)} (${project.id})
1813
1982
  `);
1814
- process.stdout.write(`Bound to : ${project.repoIdentity ?? "not bound"}
1983
+ process.stdout.write(`Bound to : ${stripTerminal(project.repoIdentity ?? "not bound")}
1815
1984
  `);
1816
1985
  process.stdout.write(`Rebind to : ${repoIdentity.kind}:${repoIdentity.value}
1817
1986
  `);
@@ -1826,7 +1995,7 @@ async function handleRebind(deps, projectId, root, mode2, yes) {
1826
1995
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1827
1996
  let confirmed = false;
1828
1997
  try {
1829
- const answer = await rl.question(`Rebind "${project.name}" to this repository? [y/N] `);
1998
+ const answer = await rl.question(`Rebind "${stripTerminal(project.name)}" to this repository? [y/N] `);
1830
1999
  confirmed = answer.trim().toLowerCase() === "y";
1831
2000
  } finally {
1832
2001
  rl.close();
@@ -2003,7 +2172,7 @@ Commit nolto.json to share the binding with your team.
2003
2172
  function register(program, deps) {
2004
2173
  const cmd = program.command("link [projectId]").description(
2005
2174
  "Bind this repository to a Nolto project.\nWrites nolto.json at the repo root. Commit it to share the binding with your team.\n\nExamples:\n nolto link <uuid> Write / update nolto.json\n nolto link --show Show the current binding\n nolto link --rebind Rebind the project to this repository\n nolto link --list List project repositories\n nolto link --add Add this repository to the project\n nolto link --remove <identity-or-id> Remove a project repository\n nolto link --unlink Remove the projectId from nolto.json"
2006
- ).option("--slug <slug>", "Name this repository's roadmap").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").option("--show", "Show the current repo binding (path + projectId + source)").option("--rebind", "Rebind the project to this repository (owner only, once per 7 days)").option("-y, --yes", "Skip repository addition, rebind, and removal confirmation prompts").option("--unlink", "Remove the projectId key from nolto.json");
2175
+ ).option("--slug <slug>", "Name this repository's roadmap (creates another one if the name is new)").option("--list", "List project repositories").option("--add", "Add this repository to the project").option("--label <text>", "Label the added repository").option("--remove <identity-or-id>", "Remove a project repository").option("--show", "Show the current repo binding (path + projectId + source)").option("--rebind", "Rebind the project to this repository (owner only, once per 7 days)").option("-y, --yes", "Skip repository addition, rebind, and removal confirmation prompts").option("--unlink", "Remove the projectId key from nolto.json");
2007
2176
  cmd.action(async (projectId) => {
2008
2177
  const { output } = deps;
2009
2178
  const projectBindingPath = deps.repoBinding?.path ?? deps.projectBindingPath ?? null;
@@ -2024,6 +2193,7 @@ function register(program, deps) {
2024
2193
  return;
2025
2194
  }
2026
2195
  const opts = cmd.opts();
2196
+ if (opts["slug"] !== void 0) assertCacheableSlug(opts["slug"]);
2027
2197
  if (opts["list"] || opts["add"] || opts["remove"] !== void 0 || opts["slug"] !== void 0) {
2028
2198
  if (projectId == null) {
2029
2199
  if (bindingError != null) throw invalidBindingError(projectBindingPath, bindingError);
@@ -2046,7 +2216,7 @@ function register(program, deps) {
2046
2216
  const { repos } = await deps.http.get(`/api/projects/${projectId}`);
2047
2217
  if (opts["list"]) {
2048
2218
  if (mode2 === "json") printResult({ repos }, mode2);
2049
- else for (const repo2 of repos) printResult(`${repo2.identity}${repo2.label ? ` (${repo2.label})` : ""} ${repo2.boundAt} ${repo2.id}`, mode2);
2219
+ else for (const repo2 of repos) printResult(`${stripTerminal(repo2.identity)}${repo2.label ? ` (${stripTerminal(repo2.label)})` : ""} ${stripTerminal(repo2.boundAt)} ${stripTerminal(repo2.id)}`, mode2);
2050
2220
  return;
2051
2221
  }
2052
2222
  const input = opts["remove"];
@@ -2058,7 +2228,7 @@ function register(program, deps) {
2058
2228
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2059
2229
  let confirmed = false;
2060
2230
  try {
2061
- const answer = await rl.question(`Remove "${repo.identity}" from project ${projectId}? [y/N] `);
2231
+ const answer = await rl.question(`Remove "${stripTerminal(repo.identity)}" from project ${projectId}? [y/N] `);
2062
2232
  confirmed = answer.trim().toLowerCase() === "y";
2063
2233
  } finally {
2064
2234
  rl.close();
@@ -2069,7 +2239,7 @@ function register(program, deps) {
2069
2239
  }
2070
2240
  }
2071
2241
  await deps.http.delete(`/api/projects/${projectId}/repos/${repo.id}`);
2072
- printResult(mode2 === "json" ? { removed: true, projectId, repoId: repo.id } : `Removed ${repo.identity} from project ${projectId}.`, mode2);
2242
+ printResult(mode2 === "json" ? { removed: true, projectId, repoId: repo.id } : `Removed ${stripTerminal(repo.identity)} from project ${projectId}.`, mode2);
2073
2243
  return;
2074
2244
  }
2075
2245
  }
@@ -2129,13 +2299,18 @@ function register2(program, deps) {
2129
2299
  }
2130
2300
  async function runPull(deps, opts = {}) {
2131
2301
  const messages = [];
2302
+ if (opts.slug != null) assertCacheableSlug(opts.slug);
2132
2303
  const { projectId } = await resolveRoadmapReadContext(deps);
2133
2304
  const list = await deps.http.get(`/api/projects/${projectId}/roadmaps`);
2134
2305
  const serverBySlug = new Map(list.roadmaps.map((roadmap) => [roadmap.slug, roadmap]));
2135
2306
  if (opts.slug != null && !serverBySlug.has(opts.slug)) {
2136
2307
  throw new CliError(`Roadmap "${opts.slug}" was not found on the server.`, 2);
2137
2308
  }
2138
- const slugs = opts.slug == null ? [...serverBySlug.keys()] : [opts.slug];
2309
+ const slugs = opts.slug == null ? [...serverBySlug.keys()].filter((slug) => {
2310
+ if (isCacheableSlug(slug)) return true;
2311
+ process.stderr.write(uncacheableSlugWarning(slug) + "\n");
2312
+ return false;
2313
+ }) : [opts.slug];
2139
2314
  let skipped = false;
2140
2315
  for (const slug of slugs) {
2141
2316
  if (!await pullRoadmapCache({
@@ -2254,7 +2429,7 @@ async function syncRepo(args, io) {
2254
2429
  const entry = await readCache(io.env, projectId, slug);
2255
2430
  if (!entry) throw new CliError(`No cached roadmap "${slug}". Run \`nolto roadmap pull ${slug}\`.`, 2);
2256
2431
  if (args.slugs === void 0 && entry.meta?.repoIdentity != null && entry.meta.repoIdentity !== identity) {
2257
- io.log(`skipped ${slug} (belongs to ${entry.meta.repoIdentity})`);
2432
+ io.log(`skipped ${slug} (belongs to ${stripTerminal(entry.meta.repoIdentity)})`);
2258
2433
  continue;
2259
2434
  }
2260
2435
  roadmaps.push({ slug, ...entry });
@@ -2384,7 +2559,7 @@ async function runSyncCommand(deps, opts = {}) {
2384
2559
  }
2385
2560
  if (!opts.quiet && deps.output.mode === "json") {
2386
2561
  const { planAbsPaths: _planAbsPaths, ...publicResponse } = response;
2387
- printResult({ ...publicResponse, registryAdded }, "json");
2562
+ printResult({ ...publicResponse, registryAdded, ...opts.previousSummary !== void 0 ? { previousSummary: opts.previousSummary } : {} }, "json");
2388
2563
  } else if (!opts.quiet && registryAdded) {
2389
2564
  process.stdout.write(`watch registry: added ${root}
2390
2565
  `);
@@ -2439,10 +2614,10 @@ async function roadmapStatus(deps, slug, fresh = false) {
2439
2614
  return;
2440
2615
  }
2441
2616
  printResult([
2442
- `${roadmap.project.name}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
2443
- `Current: ${current ? `${current.id} \u2014 ${current.title}` : "none"}`,
2444
- `Blocked: ${blocked.map((task) => `${task.id} \u2014 ${task.title}`).join(", ") || "none"}`,
2445
- `Summary: ${roadmap.summary}`,
2617
+ `${stripControl(roadmap.project.name)}: ${stats.done}/${stats.total} done (${stats.progressPct}%)`,
2618
+ `Current: ${current ? `${stripControl(current.id)} \u2014 ${stripControl(current.title)}` : "none"}`,
2619
+ `Blocked: ${blocked.map((task) => `${stripControl(task.id)} \u2014 ${stripControl(task.title)}`).join(", ") || "none"}`,
2620
+ `Summary: ${stripFormatControl(stripControl(roadmap.summary, true)).replace(/[\n\u2028\u2029]/g, "\n ")}`,
2446
2621
  `Revision: ${meta?.revision ?? 0} (pulled ${meta?.pulledAt ?? "unknown"})`
2447
2622
  ].join("\n"), "human");
2448
2623
  }
@@ -2465,6 +2640,11 @@ async function roadmapValidate(deps, slug) {
2465
2640
  async function roadmapSummary(deps, slug, text) {
2466
2641
  const selected = await selectRoadmap(deps, slug);
2467
2642
  const entry = await readCache(process.env, selected.projectId, selected.slug);
2643
+ const previousSummary = entry.roadmap.summary;
2644
+ if (deps.output.mode === "human") {
2645
+ printResult(previousSummary ? `Previous summary (from local cache):
2646
+ ${stripFormatControl(stripControl(previousSummary, true)).replace(/[\n\u2028\u2029]/g, "\n ")}` : "Previous summary (from local cache): (none)", "human");
2647
+ }
2468
2648
  entry.roadmap.summary = text;
2469
2649
  const temp = `${selected.paths.json}.tmp-${randomUUID5()}`;
2470
2650
  try {
@@ -2473,7 +2653,7 @@ async function roadmapSummary(deps, slug, text) {
2473
2653
  } finally {
2474
2654
  await unlink3(temp).catch(() => void 0);
2475
2655
  }
2476
- await runSyncCommand(deps, { slug: selected.slug });
2656
+ await runSyncCommand(deps, { slug: selected.slug, previousSummary });
2477
2657
  }
2478
2658
  async function roadmapAddIssue(deps, slug, taskId, key) {
2479
2659
  const selected = await selectRoadmap(deps, slug);
@@ -2535,7 +2715,11 @@ async function roadmapEvents(deps, slug, opts) {
2535
2715
  const response = await deps.http.get(`/api/projects/${selected.projectId}/roadmaps/${encodeURIComponent(selected.slug)}/events${query.size ? `?${query}` : ""}`);
2536
2716
  if (deps.output.mode === "json") printResult(response, "json");
2537
2717
  else for (const event of response.events) {
2538
- printResult(`rev ${event.revision} ${event.createdAt} ${event.actor?.name ?? "system"} ${event.source} ${event.taskId} ${event.field}: ${event.from ?? "\u2014"} \u2192 ${event.to ?? "\u2014"}`, "human");
2718
+ const [from, to] = [event.from, event.to].map((value) => {
2719
+ const points = Array.from(stripFormatControl(stripControl(value ?? "\u2014")));
2720
+ return points.length > 200 ? `${points.slice(0, 199).join("")}\u2026` : points.join("");
2721
+ });
2722
+ printResult(`rev ${event.revision} ${stripControl(event.createdAt)} ${stripFormatControl(stripControl(event.actor?.name ?? "system"))} ${stripControl(event.source)} ${stripControl(event.taskId ?? "roadmap")} ${stripControl(event.field)}: ${from} \u2192 ${to}`, "human");
2539
2723
  }
2540
2724
  }
2541
2725
  async function roadmapMigrate(deps, yes = false) {
@@ -2624,6 +2808,68 @@ async function roadmapMigrate(deps, yes = false) {
2624
2808
 
2625
2809
  // src/commands/issue.ts
2626
2810
  var emptySettings = { types: [], statuses: [], categories: [] };
2811
+ var confirmHelp = "Send even if the text has references customers cannot open. Use only after a 409 internal_references and the user's go-ahead.";
2812
+ var confirmHint = "\u53C2\u7167\u3092\u5916\u3059\u304B\u66F8\u304D\u63DB\u3048\u308B\u306E\u304C\u5148\u3002\u3053\u306E\u307E\u307E\u9001\u308B\u3068\u3001\u3053\u306E\u6587\u9762\u306F\u304A\u5BA2\u3055\u307E\u306B\u305D\u306E\u307E\u307E\u898B\u3048\u3001\u53C2\u7167\u306F\u958B\u3051\u306A\u3044\u307E\u307E\u6B8B\u308B\u3002\u5229\u7528\u8005\u306B\u78BA\u304B\u3081\u3066\u304B\u3089 --confirm-references \u3092\u4ED8\u3051\u3066\u518D\u5B9F\u884C\u3059\u308B";
2813
+ function sharedOptions(command) {
2814
+ return command.option("--shared", "Write in shared mode (visible to customers). Pro+ projects with customers only.").option("--confirm-references", confirmHelp);
2815
+ }
2816
+ async function checkShared(deps, root, flags, ref) {
2817
+ if (!flags.shared) return;
2818
+ if (flags.priority !== void 0 || flags.category !== void 0) {
2819
+ throw new CliError("--shared \u3067\u306F --priority \u3068 --category \u306F\u4F7F\u3048\u307E\u305B\u3093(\u5171\u6709\u30E2\u30FC\u30C9\u3067\u306F\u53CD\u6620\u3055\u308C\u307E\u305B\u3093)\u3002", 2);
2820
+ }
2821
+ const context3 = await deps.http.get(root);
2822
+ if (context3.shareMode?.available !== true) {
2823
+ throw new CliError("\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u306F\u5171\u6709\u30E2\u30FC\u30C9\u3092\u4F7F\u3048\u307E\u305B\u3093(Pro+ \u3067\u3001\u304A\u5BA2\u3055\u307E\u306E\u3044\u308B\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3060\u3051)\u3002--shared \u3092\u5916\u3059\u3068\u793E\u5185\u306E\u66F8\u304D\u8FBC\u307F\u306B\u306A\u308A\u307E\u3059\u3002", 2);
2824
+ }
2825
+ const key = context3.project?.key;
2826
+ if (ref?.includes("-") && key && ref.slice(0, ref.lastIndexOf("-")).toUpperCase() !== key.toUpperCase()) {
2827
+ throw new CliError(`${stripControl(ref)} \u306F\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8(${stripControl(key)})\u306E\u8AB2\u984C\u30AD\u30FC\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002`, 2);
2828
+ }
2829
+ }
2830
+ function warningLines(warnings) {
2831
+ return Array.isArray(warnings) ? warnings.filter((text) => typeof text === "string").map((text) => `
2832
+ \u6CE8\u610F: ${oneLine(text)}`).join("") : "";
2833
+ }
2834
+ function writeSuffix(flags) {
2835
+ if (flags.shared && flags.confirmReferences) return " (shared, references confirmed)";
2836
+ return flags.shared ? " (shared)" : flags.confirmReferences ? " (references confirmed)" : "";
2837
+ }
2838
+ async function writeRequest(deps, mode2, flags, method, path24, body) {
2839
+ try {
2840
+ return await deps.http[method](
2841
+ path24,
2842
+ flags.confirmReferences ? { ...body, confirmReferences: true } : body,
2843
+ flags.shared ? { "X-Nolto-View": "shared" } : void 0
2844
+ );
2845
+ } catch (error) {
2846
+ if (!(error instanceof CliError)) throw error;
2847
+ if (error.status === 409 && (error.body?.error === "internal_references" || error.body?.code === "internal_references" || error.serverError === "internal_references")) {
2848
+ const { message, detail } = formatInternalReferences(error.body ?? {});
2849
+ throw new CliError(
2850
+ mode2 === "human" ? message : error.message,
2851
+ 2,
2852
+ confirmHint,
2853
+ error.status,
2854
+ mode2 === "json" ? "internal_references" : void 0,
2855
+ error.body,
2856
+ detail
2857
+ );
2858
+ }
2859
+ if (flags.shared && error.status === 404 && (method === "patch" || path24.endsWith("/comments"))) {
2860
+ throw new CliError(
2861
+ error.message,
2862
+ error.exitCode,
2863
+ "\u5171\u6709\u30E2\u30FC\u30C9\u3067\u306F\u3001\u304A\u5BA2\u3055\u307E\u3068\u5171\u6709\u3057\u3066\u3044\u306A\u3044\u8AB2\u984C\u306F\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002\u8AB2\u984C\u3092\u5171\u6709\u3059\u308B\u304B\u3001--shared \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
2864
+ error.status,
2865
+ error.serverError,
2866
+ error.body,
2867
+ error.detail
2868
+ );
2869
+ }
2870
+ throw error;
2871
+ }
2872
+ }
2627
2873
  function context(deps, command) {
2628
2874
  if (!deps.settings.token) throw new CliError("Not authenticated. Run `nolto login` or set NOLTO_TOKEN.", 3);
2629
2875
  const globals = command.optsWithGlobals();
@@ -2698,7 +2944,7 @@ function writeOptions(command, create) {
2698
2944
  command.option("--body <text>", "Issue body").option("--body-file <path>", "Read body from file (- for stdin)").option("--type <name-or-id>", "Issue type").option("--status <name-or-id>", "Issue status").option("--priority <priority>", "high, normal or low").option("--assignee <assignee>", "me, none or UUID").option("--due <YYYY-MM-DD>", "Due date").option("--category <names...>", "Category names or UUIDs").option("--parent <ref>", "Parent issue key or number");
2699
2945
  if (create) command.option("--draft", "Create a draft visible only to you instead of an issue").option("--phase <task-id>", "Attach the created key to a roadmap task (cache) and sync").option("--roadmap <slug>", "Roadmap slug (with --phase; required with multiple cached roadmaps)");
2700
2946
  else command.option("--no-due", "Clear due date").option("--no-parent", "Clear parent").option("-m, --comment <text>", "Comment in the same update");
2701
- return command;
2947
+ return sharedOptions(command);
2702
2948
  }
2703
2949
  function register4(program, deps) {
2704
2950
  const group = program.command("issue").description("List, view and manage project issues.").addHelpText("after", `
@@ -2712,7 +2958,7 @@ nolto issue publish <draft-id>
2712
2958
  | Exit | Meaning |
2713
2959
  |---|---|
2714
2960
  | 0 | Success |
2715
- | 2 | Invalid input, recognized API 404, HTTP 422 (details shown), or roadmap cache/sync failure after creation |
2961
+ | 2 | Invalid input, recognized API 404, HTTP 422 (details shown), secret_detected (possible secret; message shown), internal_references (confirmation required), or roadmap cache/sync failure after creation |
2716
2962
  | 3 | HTTP 401/403; token_scope/token_project includes a token settings hint |
2717
2963
  | 4 | HTTP 402/429 (quota/rate limit). API token writes: 60/minute. On 429, wait Retry-After seconds before retrying. |
2718
2964
  | 5 | Network/generic HTTP errors, including a 404 without an API error string |
@@ -2731,58 +2977,63 @@ nolto issue publish <draft-id>
2731
2977
  });
2732
2978
  writeOptions(group.command("create").description("Create an issue."), true).action(async (flags, command) => {
2733
2979
  const ctx = context(deps, command);
2980
+ if (flags.draft && flags.shared) throw new CliError("--shared cannot be combined with --draft.", 2);
2734
2981
  if (flags.draft && (flags.phase !== void 0 || flags.roadmap !== void 0)) throw new CliError("--phase and --roadmap cannot be used with --draft. Publish the draft first.", 2);
2735
2982
  if (flags.roadmap !== void 0 && flags.phase === void 0) throw new CliError("--roadmap requires --phase.", 2);
2983
+ await checkShared(deps, ctx.root, flags);
2736
2984
  const { input, fromTemplate } = await writeInput(deps, ctx.root, flags, true);
2737
2985
  if (flags.draft) {
2738
- const result2 = await deps.http.post(`${ctx.root}/issue-drafts`, input);
2739
- printResult(ctx.mode === "json" ? result2 : `draft ${result2.draft.id} created
2740
- ${draftUrl(deps.settings.baseUrl, ctx.projectId, result2.draft.id)}`, ctx.mode);
2986
+ const result2 = await writeRequest(deps, ctx.mode, flags, "post", `${ctx.root}/issue-drafts`, input);
2987
+ printResult(ctx.mode === "json" ? result2 : `draft ${result2.draft.id} created${writeSuffix(flags)}
2988
+ ${draftUrl(deps.settings.baseUrl, ctx.projectId, result2.draft.id)}${warningLines(result2.warnings)}`, ctx.mode);
2741
2989
  return;
2742
2990
  }
2743
- const result = await deps.http.post(`${ctx.root}/issues`, input);
2991
+ const result = await writeRequest(deps, ctx.mode, flags, "post", `${ctx.root}/issues`, input);
2744
2992
  const roadmap = flags.phase === void 0 ? void 0 : await attachRoadmap(deps, flags.phase, flags.roadmap, result.issue.key);
2745
- printResult(ctx.mode === "json" ? { ...result, ...roadmap ? { roadmap } : {} } : `${result.issue.key} created
2746
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${fromTemplate ? "\nbody: from template" : ""}`, ctx.mode);
2993
+ printResult(ctx.mode === "json" ? { ...result, ...roadmap ? { roadmap } : {} } : `${result.issue.key} created${writeSuffix(flags)}
2994
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${fromTemplate ? "\nbody: from template" : ""}${warningLines(result.warnings)}`, ctx.mode);
2747
2995
  });
2748
2996
  group.command("drafts").description("List your issue drafts (visible only to you).").action(async (_flags, command) => {
2749
2997
  const ctx = context(deps, command);
2750
2998
  const result = await deps.http.get(`${ctx.root}/issue-drafts`);
2751
2999
  printResult(ctx.mode === "json" ? result : formatDraftList(result), ctx.mode);
2752
3000
  });
2753
- group.command("publish <draft-id>").description("Publish a draft as an issue.").action(async (id, _flags, command) => {
3001
+ group.command("publish <draft-id>").description("Publish a draft as an issue.").action(async (id, flags, command) => {
2754
3002
  const ctx = context(deps, command);
2755
3003
  if (!isUuid(id)) throw new CliError("<draft-id> must be a UUID. Run `nolto issue drafts` to list drafts.", 2);
2756
- const result = await deps.http.post(`${ctx.root}/issue-drafts/${id}/publish`, void 0);
3004
+ const result = await writeRequest(deps, ctx.mode, flags, "post", `${ctx.root}/issue-drafts/${id}/publish`, void 0);
2757
3005
  printResult(ctx.mode === "json" ? result : `${result.issue.key} published
2758
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}`, ctx.mode);
3006
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, result.issue.number)}${warningLines(result.warnings)}`, ctx.mode);
2759
3007
  });
2760
3008
  writeOptions(group.command("update <ref>").description("Update issue fields."), false).action(async (ref, flags, command) => {
2761
3009
  const ctx = context(deps, command);
2762
3010
  const number = parseIssueRef(ref);
3011
+ await checkShared(deps, ctx.root, flags, ref);
2763
3012
  const { input } = await writeInput(deps, ctx.root, flags, false);
2764
- const result = await deps.http.patch(`${ctx.root}/issues/${number}`, input);
2765
- printResult(ctx.mode === "json" ? result : `${result.issue.key} updated
2766
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
3013
+ const result = await writeRequest(deps, ctx.mode, flags, "patch", `${ctx.root}/issues/${number}`, input);
3014
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} updated${writeSuffix(flags)}
3015
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}${warningLines(result.warnings)}`, ctx.mode);
2767
3016
  });
2768
- group.command("comment <ref>").description("Post a comment.").option("-m, --comment <text>", "Comment text").option("--body-file <path>", "Read comment from file (- for stdin)").action(async (ref, flags, command) => {
3017
+ sharedOptions(group.command("comment <ref>").description("Post a comment.").option("-m, --comment <text>", "Comment text").option("--body-file <path>", "Read comment from file (- for stdin)")).action(async (ref, flags, command) => {
2769
3018
  const ctx = context(deps, command);
2770
3019
  const number = parseIssueRef(ref);
3020
+ await checkShared(deps, ctx.root, flags, ref);
2771
3021
  const body = await bodyText(flags.comment, flags.bodyFile);
2772
3022
  if (!body?.trim()) throw new CliError("A comment is required. Use -m or --body-file.", 2);
2773
3023
  const issue = ctx.mode === "human" ? (await deps.http.get(`${ctx.root}/issues/${number}`)).issue : void 0;
2774
- const result = await deps.http.post(`${ctx.root}/issues/${number}/comments`, { body });
2775
- printResult(ctx.mode === "json" ? result : `${issue.key} commented
2776
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
3024
+ const result = await writeRequest(deps, ctx.mode, flags, "post", `${ctx.root}/issues/${number}/comments`, { body });
3025
+ printResult(ctx.mode === "json" ? result : `${issue.key} commented${writeSuffix(flags)}
3026
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}${warningLines(result.warnings)}`, ctx.mode);
2777
3027
  });
2778
- group.command("close <ref>").description("Move an issue to a closed status.").option("--status <name-or-id>", "Closed status (defaults to first by sort order)").option("-m, --comment <text>", "Comment in the same update").action(async (ref, flags, command) => {
3028
+ sharedOptions(group.command("close <ref>").description("Move an issue to a closed status.").option("--status <name-or-id>", "Closed status (defaults to first by sort order)").option("-m, --comment <text>", "Comment in the same update")).action(async (ref, flags, command) => {
2779
3029
  const ctx = context(deps, command);
2780
3030
  const number = parseIssueRef(ref);
3031
+ await checkShared(deps, ctx.root, flags, ref);
2781
3032
  const settings = await deps.http.get(`${ctx.root}/issue-settings`);
2782
3033
  const status = pickClosedStatus(settings, flags.status);
2783
- const result = await deps.http.patch(`${ctx.root}/issues/${number}`, { statusId: status.id, ...flags.comment !== void 0 ? { comment: flags.comment } : {} });
2784
- printResult(ctx.mode === "json" ? result : `${result.issue.key} closed
2785
- ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
3034
+ const result = await writeRequest(deps, ctx.mode, flags, "patch", `${ctx.root}/issues/${number}`, { statusId: status.id, ...flags.comment !== void 0 ? { comment: flags.comment } : {} });
3035
+ printResult(ctx.mode === "json" ? result : `${result.issue.key} closed${writeSuffix(flags)}
3036
+ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}${warningLines(result.warnings)}`, ctx.mode);
2786
3037
  });
2787
3038
  }
2788
3039
 
@@ -2790,87 +3041,6 @@ ${issueUrl(deps.settings.baseUrl, ctx.projectId, number)}`, ctx.mode);
2790
3041
  import { readFile as readFile12, readdir as readdir6, rm as rm3 } from "fs/promises";
2791
3042
  import path16 from "path";
2792
3043
 
2793
- // src/memory-format.ts
2794
- var oneLine = (value) => value.replace(/[\r\n\u0085\u2028\u2029]/g, " ");
2795
- var shellArg = (value) => /^[A-Za-z0-9._/-]+$/.test(value) ? value : JSON.stringify(value);
2796
- var memoryClient = (via) => via?.client || via?.tokenName || "Web";
2797
- function parseMemory(text, importing = false) {
2798
- const lines = text.replace(/\r\n/g, "\n").split("\n");
2799
- if (/^<!--.*-->$/.test(lines[0] ?? "")) lines.shift();
2800
- if (lines.shift() !== "---") throw new CliError("frontmatter \u306E --- \u304C\u3042\u308A\u307E\u305B\u3093\u3002", 2);
2801
- const end = lines.indexOf("---");
2802
- if (end < 0) throw new CliError("frontmatter \u3092 --- \u3067\u9589\u3058\u3066\u304F\u3060\u3055\u3044\u3002", 2);
2803
- const fields = {};
2804
- let metadata = false;
2805
- for (const line2 of lines.slice(0, end)) {
2806
- const match = /^(\s*)([a-zA-Z]+):\s*(.*)$/.exec(line2);
2807
- if (!match) continue;
2808
- const indent = match[1], key = match[2], raw = match[3];
2809
- if (!indent) metadata = key === "metadata";
2810
- if (indent && !(importing && metadata && key === "type")) continue;
2811
- let value = raw.trim();
2812
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2813
- if (["name", "description", "type", "scope", "branch", "revision"].includes(key)) fields[key] = value;
2814
- }
2815
- const body = lines.slice(end + 1);
2816
- if (body[0] === "") body.shift();
2817
- return { ...fields, name: fields.name ?? "", description: fields.description ?? "", body: body.join("\n") };
2818
- }
2819
- function formatMemory(entry) {
2820
- const value = (s) => {
2821
- const safe = oneLine(s);
2822
- return /^['"]|['"]$|^\s|\s$/.test(safe) ? `"${safe}"` : safe;
2823
- };
2824
- return [
2825
- "<!-- 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 -->",
2826
- "---",
2827
- `name: ${entry.name}`,
2828
- `description: ${value(entry.description)}`,
2829
- ...entry.type == null ? [] : [`type: ${entry.type}`],
2830
- `scope: ${entry.scope}`,
2831
- ...entry.scope === "branch" ? [`branch: ${value(entry.branch ?? "")}`] : [],
2832
- `revision: ${entry.revision}`,
2833
- `updated: ${oneLine(entry.updatedAt)}${entry.updatedBy?.name ? ` by ${oneLine(entry.updatedBy.name)}` : ""} (${oneLine(memoryClient(entry.updatedVia))})`,
2834
- "---",
2835
- "",
2836
- entry.body
2837
- ].join("\n");
2838
- }
2839
- function parseScope(scope, hint = "scope: project|user|branch \u3092 frontmatter \u306B\u66F8\u304F") {
2840
- if (scope !== "project" && scope !== "user" && scope !== "branch") {
2841
- throw new CliError(scope ? `scope \u304C\u4E0D\u6B63\u3067\u3059: ${scope}` : "scope \u304C\u5FC5\u8981\u3067\u3059\u3002", 2, hint);
2842
- }
2843
- return scope;
2844
- }
2845
- var count = (n) => n.toLocaleString("en-US");
2846
- var invalidInput = (message, hint) => new CliError(message, 2, hint, void 0, "invalid_input");
2847
- function validateDraft(draft) {
2848
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(draft.name)) {
2849
- 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");
2850
- }
2851
- const description = draft.description.trim();
2852
- 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");
2853
- 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");
2854
- 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");
2855
- 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");
2856
- if (draft.type && !["user", "feedback", "project", "reference"].includes(draft.type)) {
2857
- 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");
2858
- }
2859
- }
2860
- function parseRevision(value) {
2861
- const revision = Number(value);
2862
- 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);
2863
- return revision;
2864
- }
2865
- function detectMemoryClient(env) {
2866
- const agent = env.NOLTO_AGENT?.trim();
2867
- if (agent && /^[\x20-\x7e]+$/.test(agent)) return agent;
2868
- if (env.CLAUDECODE === "1") return "Claude Code";
2869
- if (env.GEMINI_CLI === "1") return "Gemini CLI";
2870
- if (env.CODEX_THREAD_ID) return "Codex";
2871
- return "CLI";
2872
- }
2873
-
2874
3044
  // src/memory-cache.ts
2875
3045
  import { mkdir as mkdir7, readFile as readFile11, readdir as readdir5, rename as rename4, rm as rm2, unlink as unlink4, writeFile as writeFile8 } from "fs/promises";
2876
3046
  import { createHash as createHash3, randomUUID as randomUUID6 } from "crypto";
@@ -2923,11 +3093,13 @@ async function atomicMemoryFile(file, content) {
2923
3093
  }
2924
3094
  }
2925
3095
  async function readMemoryCache(dir, project) {
2926
- const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8) }, meta: { cursor: 0, pulledAt: "" } };
3096
+ const empty = { state: { entries: [], scope: "", projectName: project.slice(0, 8), cleanupCandidates: [] }, meta: { cursor: 0, pulledAt: "" } };
2927
3097
  try {
2928
3098
  const state = JSON.parse(await readFile11(path15.join(dir, ".entries.json"), "utf8"));
2929
3099
  if (!Array.isArray(state.entries) || typeof state.scope !== "string" || typeof state.projectName !== "string") throw new Error("Invalid state");
2930
3100
  if (state.entries.some((e) => e == null || typeof e !== "object" || typeof e.id !== "string" || typeof e.name !== "string")) throw new Error("Invalid entry");
3101
+ if (!Array.isArray(state.cleanupCandidates)) state.cleanupCandidates = [];
3102
+ else state.cleanupCandidates = state.cleanupCandidates.filter((c) => c != null && typeof c === "object" && typeof c.entryId === "string" && c.reason != null && typeof c.reason === "object" && typeof c.reason.code === "string");
2931
3103
  let meta = empty.meta;
2932
3104
  try {
2933
3105
  meta = JSON.parse(await readFile11(path15.join(dir, ".meta.json"), "utf8"));
@@ -2973,11 +3145,38 @@ function sortMemoryEntries(entries) {
2973
3145
  return entries.sort((a, b) => scopeOrder.indexOf(a.scope) - scopeOrder.indexOf(b.scope) || b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));
2974
3146
  }
2975
3147
  var MEMORY_INDEX_MAX_CHARS = 9500;
3148
+ function currentCleanupCandidates(state, context3) {
3149
+ const entries = currentMemoryEntries(state.entries, context3);
3150
+ const live = new Map(entries.map((e) => [e.id, e]));
3151
+ return (state.cleanupCandidates ?? []).flatMap((candidate) => {
3152
+ const entry = live.get(candidate.entryId);
3153
+ if (!entry) return [];
3154
+ if (candidate.reason.code === "superseded" && (typeof candidate.reason.newer !== "string" || !entries.some((e) => e.scope === entry.scope && e.name === candidate.reason.newer))) return [];
3155
+ return [{ ...candidate, scope: entry.scope, name: entry.name, repoIdentity: entry.repoIdentity, branch: entry.branch }];
3156
+ });
3157
+ }
3158
+ function hasSharedMemoryName(entry, entries, context3) {
3159
+ return currentMemoryEntries(entries, context3).some((e) => e.name === entry.name && e.scope !== entry.scope);
3160
+ }
3161
+ function cleanupSection(candidates, entries, context3, limit = 10) {
3162
+ if (!candidates.length) return [];
3163
+ return [
3164
+ "## \u6574\u7406\u5019\u88DC(\u78BA\u304B\u3081\u3066\u6D88\u3059\u306A\u3089 nolto memory rm <name>)",
3165
+ ...candidates.slice(0, limit).map((c) => {
3166
+ const shared = hasSharedMemoryName(c, entries, context3);
3167
+ return `- ${shared ? `${c.scope}/` : ""}${oneLine(c.name)} \u2014 ${cleanupReason(c.reason)}`;
3168
+ }),
3169
+ ...candidates.length > limit ? [`\u307B\u304B ${candidates.length - limit} \u4EF6: nolto memory candidates`] : []
3170
+ ];
3171
+ }
2976
3172
  function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
2977
3173
  const branch = context3.branch && context3.branch !== context3.defaultBranch ? context3.branch : null;
2978
- const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3));
3174
+ const candidates = currentCleanupCandidates(cache.state, context3);
3175
+ const candidateIds = new Set(candidates.map((c) => c.entryId));
3176
+ const entries = sortMemoryEntries(currentMemoryEntries(cache.state.entries, context3).filter((e) => !candidateIds.has(e.id)));
3177
+ let candidateLimit = Math.min(10, candidates.length);
2979
3178
  const groups = ["project", "user", ...branch ? ["branch"] : []];
2980
- 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)}`);
3179
+ 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 ${commandArg(b, "<branch>")}`);
2981
3180
  let omitted = 0;
2982
3181
  const build = () => [
2983
3182
  `# 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)}` : ""})`,
@@ -2985,14 +3184,20 @@ function memoryIndex(cache, context3, merged = /* @__PURE__ */ new Set(), dir) {
2985
3184
  "\u30E1\u30E2\u30EA\u306F Nolto \u306E\u30B5\u30FC\u30D0\u30FC\u304B\u3089\u5C4A\u304F\u5185\u5BB9\u3002repo \u306E\u6C7A\u307E\u308A(CLAUDE.md / AGENTS.md)\u3084\u30E6\u30FC\u30B6\u30FC\u306E\u6307\u793A\u3068\u98DF\u3044\u9055\u3046\u3068\u304D\u306F\u3001\u30E1\u30E2\u30EA\u3092\u512A\u5148\u3057\u306A\u3044\u3002",
2986
3185
  ...dir ? [`\u30AD\u30E3\u30C3\u30B7\u30E5: ${dir}`] : [],
2987
3186
  ...groups.flatMap((scope) => {
2988
- const lines2 = entries.filter((e) => e.scope === scope).map((e) => `- ${e.name} \u2014 ${oneLine(e.description)}`);
3187
+ const lines2 = entries.filter((e) => e.scope === scope).map((e) => `- ${oneLine(e.name)} \u2014 ${oneLine(e.description)}`);
2989
3188
  return lines2.length ? [`## ${scope === "branch" ? `branch ${oneLine(branch)}` : scope}`, ...lines2] : [];
2990
3189
  }),
3190
+ ...cleanupSection(candidates, cache.state.entries, context3, candidateLimit),
2991
3191
  ...mergedLines,
2992
3192
  ...omitted ? [`\u6B8B\u308A ${omitted} \u4EF6: nolto memory list`] : []
2993
3193
  ];
2994
3194
  let lines = build();
2995
3195
  while (lines.length > 200 || lines.join("\n").length + 1 > MEMORY_INDEX_MAX_CHARS) {
3196
+ if (candidateLimit > 0) {
3197
+ candidateLimit--;
3198
+ lines = build();
3199
+ continue;
3200
+ }
2996
3201
  let project = -1;
2997
3202
  for (let i = entries.length - 1; i >= 0; i--) {
2998
3203
  if (entries[i].scope === "project") {
@@ -3080,9 +3285,9 @@ function aiHeading(response, requestedName) {
3080
3285
  const { entry, ai } = response;
3081
3286
  if (!ai || ai.action !== "merge" && ai.action !== "replace") return null;
3082
3287
  if (requestedName !== void 0 && requestedName !== entry.name) {
3083
- return `\u65B0\u898F\u306E ${requestedName} \u306F\u4F5C\u3089\u305A\u3001AI \u304C ${entry.scope}/${entry.name} ${ai.action === "merge" ? "\u306B\u7D71\u5408\u3057\u307E\u3057\u305F" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88\u3057\u307E\u3057\u305F"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
3288
+ return `\u65B0\u898F\u306E ${oneLine(requestedName)} \u306F\u4F5C\u3089\u305A\u3001AI \u304C ${entry.scope}/${oneLine(entry.name)} ${ai.action === "merge" ? "\u306B\u7D71\u5408\u3057\u307E\u3057\u305F" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88\u3057\u307E\u3057\u305F"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
3084
3289
  }
3085
- 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 ?? "")}`;
3290
+ return `AI \u304C\u6574\u7406: ${entry.scope}/${oneLine(entry.name)} ${ai.action === "merge" ? "\u306B\u7D71\u5408" : "\u306E\u77DB\u76FE\u3092\u89E3\u6D88"} (r${entry.revision}) \u2014 ${oneLine(ai.reason ?? "")}`;
3086
3291
  }
3087
3292
  async function createMemoryContext(opts, recover = false) {
3088
3293
  const { projectId: project, root, git } = opts;
@@ -3147,7 +3352,7 @@ async function scanMemoryDir(dir) {
3147
3352
  }
3148
3353
  function importResultLine(scope, result) {
3149
3354
  const { status, name, original, message } = result;
3150
- return `${status} ${scope}/${name}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}`;
3355
+ return `${status} ${scope}/${oneLine(name)}${original !== name ? ` (\u5143: ${oneLine(original)})` : ""}${message ? ` \u2014 ${oneLine(message)}` : ""}`;
3151
3356
  }
3152
3357
  async function importMemoryFiles(opts) {
3153
3358
  const ctx = await createMemoryContext(opts, true);
@@ -3238,7 +3443,7 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
3238
3443
  if (projects.length > 0) {
3239
3444
  process.stdout.write("\nProjects:\n");
3240
3445
  projects.forEach((project, index) => {
3241
- process.stdout.write(` (${index + 1}) ${project.name} \u2014 ${project.id}
3446
+ process.stdout.write(` (${index + 1}) ${stripTerminal(project.name)} \u2014 ${project.id}
3242
3447
  `);
3243
3448
  });
3244
3449
  } else {
@@ -3258,13 +3463,13 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
3258
3463
  if (!isValidProjectKey(key)) throw new CliError("Project key must start with an uppercase letter and contain 2-10 alphanumeric characters.", 2);
3259
3464
  const { orgs } = await http.get("/api/orgs/eligible");
3260
3465
  if (orgs.length === 0) {
3261
- throw new CliError(`No organization to create the project in. Create one at ${baseUrl.replace(/\/+$/, "")}/orgs/new first.`, 2);
3466
+ throw new CliError(`No organization you can create a project in. Ask an organization admin to add you, or create an organization at ${baseUrl.replace(/\/+$/, "")}/orgs/new.`, 2);
3262
3467
  }
3263
3468
  let organization = orgs[0];
3264
3469
  if (orgs.length > 1) {
3265
3470
  process.stdout.write("\nOrganizations:\n");
3266
3471
  orgs.forEach((org, index2) => {
3267
- process.stdout.write(` (${index2 + 1}) ${org.name} \u2014 ${org.id}
3472
+ process.stdout.write(` (${index2 + 1}) ${stripTerminal(org.name)} \u2014 ${org.id}
3268
3473
  `);
3269
3474
  });
3270
3475
  const choice = (await rl.question("Organization number: ")).trim();
@@ -3285,7 +3490,7 @@ async function pickProject(rl, http, projects, promptText, baseUrl) {
3285
3490
  id: created.project.id,
3286
3491
  name: created.project.name ?? name.trim()
3287
3492
  };
3288
- process.stdout.write(`Created project ${project.name} [${key}] (${project.id}) in ${organization.name}
3493
+ process.stdout.write(`Created project ${stripTerminal(project.name)} [${key}] (${project.id}) in ${stripTerminal(organization.name)}
3289
3494
  `);
3290
3495
  return project;
3291
3496
  }
@@ -3299,7 +3504,7 @@ async function selectRepoProject(rl, http, projects, defaultProjectId, baseUrl)
3299
3504
  const defaultProject = defaultProjectId == null ? void 0 : projects.find((project) => project.id === defaultProjectId);
3300
3505
  if (defaultProject != null) {
3301
3506
  const useDefault = await rl.question(
3302
- `Use "${defaultProject.name}" (${defaultProject.id}) for this repository? [Y/n] `
3507
+ `Use "${stripTerminal(defaultProject.name)}" (${defaultProject.id}) for this repository? [Y/n] `
3303
3508
  );
3304
3509
  if (useDefault.trim().toLowerCase() !== "n") {
3305
3510
  return defaultProject;
@@ -3466,7 +3671,7 @@ function register5(program, deps) {
3466
3671
  baseUrl: baseUrl !== DEFAULT_BASE_URL ? baseUrl : void 0,
3467
3672
  defaultProjectId
3468
3673
  });
3469
- const projectDisplay = defaultProjectId != null ? `${defaultProjectName ?? ""} (${defaultProjectId})` : "not set";
3674
+ const projectDisplay = defaultProjectId != null ? `${stripTerminal(defaultProjectName)} (${defaultProjectId})` : "not set";
3470
3675
  process.stdout.write(`
3471
3676
  Saved ${configPath}
3472
3677
  `);
@@ -3510,7 +3715,7 @@ Saved ${configPath}
3510
3715
  );
3511
3716
  if (boundProject != null) {
3512
3717
  process.stdout.write(
3513
- `Existing binding: nolto.json \u2192 "${boundProject.name}" (${boundProject.id})
3718
+ `Existing binding: nolto.json \u2192 "${stripTerminal(boundProject.name)}" (${boundProject.id})
3514
3719
  `
3515
3720
  );
3516
3721
  } else {
@@ -4040,7 +4245,7 @@ function register9(program, deps) {
4040
4245
  }));
4041
4246
  }
4042
4247
  roadmap.command("plan <task>").description("Attach a plan and sync its contents").option("--slug <slug>", "Roadmap slug (required with multiple cached roadmaps)").requiredOption("--path <path>", "Repository-relative plan path").action((task, opts) => roadmapTask(deps, task, opts.slug, { plan: opts.path }));
4043
- roadmap.command("events [slug]").description("Show task event history").option("--since <revision>", "Events after this revision").option("--limit <number>", "Maximum events (1\u2013200)").action((slug, opts) => roadmapEvents(deps, slug, opts));
4248
+ roadmap.command("events [slug]").description("Show task and summary change history").option("--since <revision>", "Events after this revision").option("--limit <number>", "Maximum events (1\u2013200)").action((slug, opts) => roadmapEvents(deps, slug, opts));
4044
4249
  roadmap.command("migrate").description("Migrate repository roadmaps to the server and cache").option("--yes", "Replace differing server roadmaps without prompting").action((opts) => roadmapMigrate(deps, opts.yes));
4045
4250
  }
4046
4251
 
@@ -5211,7 +5416,16 @@ function headers() {
5211
5416
  return { "X-Nolto-Client": detectMemoryClient(process.env) };
5212
5417
  }
5213
5418
  function line(entry) {
5214
- return `${entry.scope}/${entry.name} r${entry.revision} \u2014 ${oneLine(entry.description)}`;
5419
+ return `${entry.scope}/${oneLine(entry.name)} r${entry.revision} \u2014 ${oneLine(entry.description)}`;
5420
+ }
5421
+ async function fetchCandidates(deps, ctx, signal, authErrors = false) {
5422
+ try {
5423
+ const response = await deps.http.get(`${ctx.api}/cleanup-candidates`, signal);
5424
+ return Array.isArray(response.candidates) ? response.candidates.filter((c) => c != null && typeof c === "object" && typeof c.entryId === "string" && c.reason != null && typeof c.reason === "object" && typeof c.reason.code === "string") : null;
5425
+ } catch (error) {
5426
+ if (authErrors && error instanceof CliError && (error.status === 401 || error.status === 403)) throw error;
5427
+ return null;
5428
+ }
5215
5429
  }
5216
5430
  function resolveEntry(ctx, name, target, deleted = false) {
5217
5431
  if (target.scope) parseScope(target.scope, scopeHint);
@@ -5221,16 +5435,16 @@ function resolveEntry(ctx, name, target, deleted = false) {
5221
5435
  const named = ctx.cache.state.entries.filter((e) => e.name === name && (!scope || e.scope === scope));
5222
5436
  const inRepo = (e) => e.scope !== "branch" || e.repoIdentity === ctx.git.repoIdentity;
5223
5437
  const candidates = named.filter((e) => inRepo(e) && (e.scope !== "branch" || e.branch === branch) && (deleted || !e.deleted));
5224
- 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");
5438
+ if (candidates.length > 1) throw new CliError(`\u30E1\u30E2\u30EA ${oneLine(name)} \u306F\u66D6\u6627\u3067\u3059: ${candidates.map((e) => `${e.scope}/${oneLine(e.name)}`).join(", ")}`, 2, "--scope \u3092\u4ED8\u3051\u308B");
5225
5439
  if (candidates.length) return candidates[0];
5226
5440
  const others = [...new Set(named.filter((e) => e.scope === "branch" && inRepo(e) && e.branch !== branch && !e.deleted).map((e) => e.branch))];
5227
5441
  if (others.length) {
5228
- 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`);
5442
+ throw new CliError(`\u30E1\u30E2\u30EA ${oneLine(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 ${commandArg(others[0], "<branch>")} \u3092\u4ED8\u3051\u308B`);
5229
5443
  }
5230
5444
  if (!deleted && named.some((e) => inRepo(e) && e.deleted)) {
5231
- 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>`);
5445
+ throw new CliError(`\u30E1\u30E2\u30EA ${oneLine(name)} \u306F\u524A\u9664\u6E08\u307F\u3067\u3059\u3002`, 2, `\u5C65\u6B74\u306F nolto memory log ${commandArg(name, "<name>")}\u3001\u623B\u3059\u306A\u3089 nolto memory revert ${commandArg(name, "<name>")} <revision>`);
5232
5446
  }
5233
- throw new CliError(`\u30E1\u30E2\u30EA ${name} \u304C\u30AD\u30E3\u30C3\u30B7\u30E5\u306B\u3042\u308A\u307E\u305B\u3093\u3002`, 2, "nolto memory pull");
5447
+ throw new CliError(`\u30E1\u30E2\u30EA ${oneLine(name)} \u304C\u30AD\u30E3\u30C3\u30B7\u30E5\u306B\u3042\u308A\u307E\u305B\u3093\u3002`, 2, "nolto memory pull");
5234
5448
  }
5235
5449
  async function apiCall(deps, ctx, call, op = "read", name = "<name>") {
5236
5450
  try {
@@ -5247,23 +5461,23 @@ async function apiCall(deps, ctx, call, op = "read", name = "<name>") {
5247
5461
  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";
5248
5462
  const lines = typeof body?.aiSkipped === "string" ? [aiSkippedLine(body.aiSkipped)] : [];
5249
5463
  if (Array.isArray(body?.candidates)) {
5250
- lines.push(...body.candidates.map((candidate) => `${candidate.scope}/${candidate.name} r${candidate.revision} (${candidate.score.toFixed(2)}) \u2014 ${oneLine(candidate.description)}`));
5464
+ lines.push(...body.candidates.map((candidate) => `${candidate.scope}/${oneLine(candidate.name)} r${candidate.revision} (${candidate.score.toFixed(2)}) \u2014 ${oneLine(candidate.description)}`));
5251
5465
  }
5252
5466
  if (lines.length) detail = lines.join("\n");
5253
5467
  } else if (code === "memory_exists" && Array.isArray(body?.conflicts)) {
5254
5468
  const conflicts = body.conflicts;
5255
5469
  await updateCache(ctx, deps, conflicts.flatMap((c) => [c.branchEntry, c.projectEntry]), true);
5256
- detail = conflicts.map((c) => `project/${c.name} r${c.projectEntry.revision} \u2190 branch/${c.name} r${c.branchEntry.revision}`).join("\n");
5257
- const branch = shellArg(conflicts[0]?.branchEntry.branch ?? "<branch>");
5258
- const n = conflicts.length === 1 ? conflicts[0].name : "<name>";
5470
+ detail = conflicts.map((c) => `project/${oneLine(c.name)} r${c.projectEntry.revision} \u2190 branch/${oneLine(c.name)} r${c.branchEntry.revision}`).join("\n");
5471
+ const branch = commandArg(conflicts[0]?.branchEntry.branch ?? "<branch>", "<branch>");
5472
+ const n = conflicts.length === 1 ? commandArg(conflicts[0].name, "<name>") : "<name>";
5259
5473
  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`;
5260
5474
  } else if (code === "memory_not_found" && op === "put") {
5261
- 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`;
5475
+ 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 ${commandArg(name, "<name>")} \u3067\u5C65\u6B74\u3092\u898B\u3066 revert`;
5262
5476
  } else if (code === "memory_conflict" && latest2 && (op === "rm" || op === "revert")) {
5263
5477
  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)";
5264
5478
  detail = formatMemory(latest2);
5265
5479
  } else if (code === "memory_exists") {
5266
- 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`;
5480
+ hint = `nolto memory show ${latest2 ? `${commandArg(latest2.name, "<name>")}${["project", "user", "branch"].includes(latest2.scope) ? ` --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`;
5267
5481
  } else if (code === "memory_conflict" && latest2) {
5268
5482
  hint = `\u5185\u5BB9\u3092\u7D71\u5408\u3057\u3001revision \u3092 ${latest2.revision} \u306B\u3057\u3066 put \u3057\u76F4\u3059`;
5269
5483
  detail = formatMemory(latest2);
@@ -5278,18 +5492,20 @@ function printWrite(deps, ctx, action, response, isNew = false, put) {
5278
5492
  }
5279
5493
  const { entry } = response;
5280
5494
  const heading = aiHeading(response, put?.name);
5281
- const lines = [heading ?? `${action} ${entry.scope}/${entry.name} r${entry.revision}${isNew ? " (\u65B0\u898F)" : ""}`];
5495
+ const lifetime = action === "put" ? [entry.expiresOn ? `expires ${oneLine(entry.expiresOn)}` : "", entry.until ? `until ${oneLine(entry.until)}` : ""].filter(Boolean) : [];
5496
+ const lines = [heading ?? `${action} ${entry.scope}/${entry.name} r${entry.revision}${isNew ? " (\u65B0\u898F)" : ""}${lifetime.length ? ` (${lifetime.join("\u3001")})` : ""}`];
5282
5497
  if (heading && put && put.name !== entry.name && !put.allowNew) lines.push(`\u65B0\u898F\u306B\u4F5C\u308B\u306A\u3089: nolto memory put --new ${shellArg(put.file)}`);
5283
5498
  if (response.aiSkipped) lines.push(aiSkippedLine(response.aiSkipped));
5284
5499
  const affected = response.affected ?? [];
5285
5500
  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}`}`);
5286
5501
  const reverts = affected.filter((a) => a.fromRevision >= 1).map((a) => {
5287
5502
  const shared = ctx.cache.state.entries.some((e) => e.name === a.name && e.id !== a.entryId && e.scope !== a.scope);
5288
- return `nolto memory revert ${shellArg(a.name)} ${a.fromRevision}${shared ? ` --scope ${a.scope}` : ""}`;
5503
+ return `nolto memory revert ${commandArg(a.name, "<name>")} ${a.fromRevision}${shared && ["project", "user", "branch"].includes(a.scope) ? ` --scope ${a.scope}` : ""}`;
5289
5504
  });
5290
5505
  if (reverts.length) lines.push(`\u623B\u3059: ${reverts.join(" / ")}`);
5291
5506
  for (const warning of response.warnings ?? []) lines.push(`\u6CE8\u610F: ${typeof warning === "string" ? oneLine(warning) : JSON.stringify(warning)}`);
5292
- process.stdout.write(lines.join("\n") + "\n");
5507
+ if (response.cleanupCandidates !== void 0) lines.push(...cleanupSection(currentCleanupCandidates(ctx.cache.state, ctx.git), ctx.cache.state.entries, ctx.git));
5508
+ process.stdout.write(lines.map(oneLine).join("\n") + "\n");
5293
5509
  }
5294
5510
  async function pull2(deps, opts) {
5295
5511
  let ctx;
@@ -5328,6 +5544,8 @@ async function pull2(deps, opts) {
5328
5544
  if (opts.hook && typeof opts.hook === "string" && !["claude", "codex", "gemini"].includes(opts.hook)) throw new CliError("Unknown hook agent", 2);
5329
5545
  const scope = opts.scope ? [...new Set(opts.scope.split(",").map((s) => parseScope(s.trim(), scopeHint)))].sort().join(",") : "";
5330
5546
  const previous = ctx.cache.state.entries;
5547
+ const revisions = new Map(previous.map((e) => [e.id, e.revision]));
5548
+ const changed = /* @__PURE__ */ new Set();
5331
5549
  const reset = ctx.cache.meta.cursor === 0 || ctx.cache.state.scope !== scope;
5332
5550
  let cursor = reset ? 0 : ctx.cache.meta.cursor;
5333
5551
  let entries = reset ? [] : previous;
@@ -5335,17 +5553,22 @@ async function pull2(deps, opts) {
5335
5553
  const query = new URLSearchParams({ since: String(cursor), ...scope ? { scope } : {} });
5336
5554
  const page = await apiCall(deps, ctx, () => deps.http.get(`${ctx.api}?${query}`, signal));
5337
5555
  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);
5556
+ for (const entry of page.entries) {
5557
+ const revision = revisions.get(entry.id);
5558
+ if (revision === void 0 || revision < entry.revision) changed.add(entry.id);
5559
+ }
5338
5560
  entries = mergeMemoryEntries(entries, page.entries);
5339
5561
  cursor = page.cursor;
5340
5562
  if (!page.hasMore) break;
5341
5563
  }
5342
- const [projects, profile] = await Promise.all([
5564
+ const [projects, profile, cleanupCandidates] = await Promise.all([
5343
5565
  deps.http.get("/api/projects", signal).catch(() => null),
5344
- deps.http.get("/api/me/profile", signal).catch(() => null)
5566
+ deps.http.get("/api/me/profile", signal).catch(() => null),
5567
+ fetchCandidates(deps, ctx, signal)
5345
5568
  ]);
5346
5569
  const projectName = projects?.projects?.find((p) => p.id === ctx.project)?.name ?? ctx.cache.state.projectName;
5347
5570
  const userId = typeof profile?.profile?.id === "string" ? profile.profile.id : ctx.cache.state.userId;
5348
- const next = { ...ctx, cache: { state: { entries, scope, projectName, ...userId ? { userId } : {}, ...ctx.cache.state.tokenFingerprint ? { tokenFingerprint: ctx.cache.state.tokenFingerprint } : {} }, meta: { cursor, pulledAt: (/* @__PURE__ */ new Date()).toISOString() } } };
5571
+ const next = { ...ctx, cache: { state: { entries, scope, projectName, cleanupCandidates: cleanupCandidates ?? (ctx.cache.state.cleanupCandidates ?? []).filter((c) => !changed.has(c.entryId)), ...userId ? { userId } : {}, ...ctx.cache.state.tokenFingerprint ? { tokenFingerprint: ctx.cache.state.tokenFingerprint } : {} }, meta: { cursor, pulledAt: (/* @__PURE__ */ new Date()).toISOString() } } };
5349
5572
  const text = await memoryIndexText(next, deps);
5350
5573
  const unsafe = await saveMemoryCache(ctx.dir, next.cache, previous, text, reset);
5351
5574
  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(", ")}
@@ -5386,11 +5609,16 @@ function register13(program, deps) {
5386
5609
  memory.command("instructions").action(() => {
5387
5610
  process.stdout.write(MEMORY_INSTRUCTIONS + "\n");
5388
5611
  });
5389
- memory.command("list").option("--scope <scope>").option("--all-branches").action(async (opts) => {
5612
+ memory.command("list").option("--scope <scope>").option("--all-branches").option("--deleted").action(async (opts) => {
5390
5613
  const ctx = await context2(deps);
5391
5614
  if (opts.scope) parseScope(opts.scope, scopeHint);
5615
+ if (opts.deleted) {
5616
+ const entries2 = sortMemoryEntries(ctx.cache.state.entries.filter((e) => e.deleted && storableMemoryEntry(e) && (!opts.scope || e.scope === opts.scope)));
5617
+ printResult(deps.output.mode === "json" ? entries2 : entries2.length ? [...entries2.map((e) => `${line(e)}(\u524A\u9664 ${oneLine(e.updatedAt.slice(0, 10))})`), "\u623B\u3059: nolto memory revert <name> <revision>(\u7248\u306F nolto memory log <name>)"].join("\n") : "\u524A\u9664\u6E08\u307F\u306E\u30E1\u30E2\u30EA\u306F\u30AD\u30E3\u30C3\u30B7\u30E5\u306B\u3042\u308A\u307E\u305B\u3093", deps.output.mode);
5618
+ return;
5619
+ }
5392
5620
  const entries = sortMemoryEntries(currentMemoryEntries(ctx.cache.state.entries, ctx.git, opts.allBranches).filter((e) => !opts.scope || e.scope === opts.scope));
5393
- 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);
5621
+ printResult(deps.output.mode === "json" ? entries : entries.map((e) => line(e) + (opts.allBranches && e.scope === "branch" ? ` [${oneLine(e.repoIdentity ?? "")} ${oneLine(e.branch ?? "")}]` : "")).join("\n"), deps.output.mode);
5394
5622
  });
5395
5623
  memory.command("show <name>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").option("--fresh").action(async (name, opts) => {
5396
5624
  const ctx = await context2(deps);
@@ -5399,8 +5627,27 @@ function register13(program, deps) {
5399
5627
  entry = await apiCall(deps, ctx, () => deps.http.get(`${ctx.api}/${encodeURIComponent(entry.id)}`));
5400
5628
  await updateCache(ctx, deps, [entry]);
5401
5629
  }
5402
- if (deps.output.mode === "json") printResult(entry, "json");
5403
- else process.stdout.write(formatMemory(entry));
5630
+ const cleanup = currentCleanupCandidates(ctx.cache.state, ctx.git).find((c) => c.entryId === entry.id)?.reason;
5631
+ const scoped = hasSharedMemoryName(entry, ctx.cache.state.entries, ctx.git);
5632
+ if (deps.output.mode === "json") printResult({ ...entry, ...cleanup ? { cleanup } : {} }, "json");
5633
+ else process.stdout.write(formatMemory(entry, cleanup, scoped));
5634
+ });
5635
+ memory.command("candidates").action(async () => {
5636
+ const ctx = await context2(deps);
5637
+ if (!ctx.cache.meta.pulledAt) {
5638
+ process.stdout.write(pullHint + "\n");
5639
+ return;
5640
+ }
5641
+ const fetched = await fetchCandidates(deps, ctx, void 0, true);
5642
+ if (fetched !== null) {
5643
+ ctx.cache.state.cleanupCandidates = fetched;
5644
+ await updateCache(ctx, deps, [], true);
5645
+ }
5646
+ const candidates = currentCleanupCandidates(ctx.cache.state, ctx.git);
5647
+ printResult(deps.output.mode === "json" ? { candidates } : [
5648
+ ...candidates.length ? candidates.map((c) => `${c.scope}/${oneLine(c.name)} \u2014 ${cleanupReason(c.reason)}`) : ["\u6574\u7406\u5019\u88DC\u306F\u3042\u308A\u307E\u305B\u3093"],
5649
+ ...fetched === null ? ["(\u6700\u7D42\u540C\u671F\u306E\u6642\u70B9\u306E\u5019\u88DC)"] : []
5650
+ ].join("\n"), deps.output.mode);
5404
5651
  });
5405
5652
  memory.command("put <file>").option("--new").option("--no-ai", "skip AI cleanup (Pro+)").action(async (file, opts) => {
5406
5653
  const draft = parseMemory(await inputText(file));
@@ -5408,27 +5655,51 @@ function register13(program, deps) {
5408
5655
  validateDraft(draft);
5409
5656
  const ctx = await context2(deps, true);
5410
5657
  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");
5411
- 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`);
5658
+ if (scope === "branch" && draft.branch !== void 0 && draft.branch !== ctx.git.branch) throw new CliError(`branch ${oneLine(draft.branch)} \u304C\u4ECA\u306E\u30D6\u30E9\u30F3\u30C1 ${oneLine(ctx.git.branch)} \u3068\u7570\u306A\u308A\u307E\u3059\u3002`, 2, `frontmatter \u306E branch \u3092\u6D88\u3059\u304B ${oneLine(ctx.git.branch)} \u306B\u3059\u308B`);
5412
5659
  const response = await apiCall(deps, ctx, () => deps.http.put(ctx.api, {
5413
5660
  scope,
5414
5661
  name: draft.name,
5415
5662
  description: draft.description,
5416
5663
  body: draft.body,
5664
+ expiresOn: draft.ttl !== void 0 ? ttlExpires(draft.ttl, /* @__PURE__ */ new Date()) : draft.expires ?? null,
5665
+ until: draft.until ?? null,
5417
5666
  ...draft.type ? { type: draft.type } : {},
5418
5667
  ...draft.revision !== void 0 ? { baseRevision: parseRevision(draft.revision) } : {},
5419
5668
  ...opts.new ? { allowNew: true } : {},
5420
5669
  ...opts.ai === false ? { aiSkip: true } : {},
5421
5670
  ...scope === "branch" ? { repoIdentity: ctx.git.repoIdentity, branch: ctx.git.branch } : {}
5422
5671
  }, headers()), "put", draft.name);
5672
+ const candidates = await fetchCandidates(deps, ctx, AbortSignal.timeout(3e3));
5673
+ if (candidates !== null) {
5674
+ ctx.cache.state.cleanupCandidates = candidates;
5675
+ response.cleanupCandidates = candidates;
5676
+ } else {
5677
+ const changed = /* @__PURE__ */ new Set([response.entry.id, ...(response.affected ?? []).map((a) => a.entryId)]);
5678
+ ctx.cache.state.cleanupCandidates = (ctx.cache.state.cleanupCandidates ?? []).filter((c) => !changed.has(c.entryId));
5679
+ }
5423
5680
  await updateCache(ctx, deps, writtenEntries(ctx, response));
5424
5681
  printWrite(deps, ctx, "put", response, draft.revision === void 0, { name: draft.name, file, allowNew: opts.new });
5425
5682
  });
5426
- memory.command("rm <name>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (name, opts) => {
5683
+ memory.command("rm <names...>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (names, opts) => {
5427
5684
  const ctx = await context2(deps);
5428
- const entry = resolveEntry(ctx, name, opts);
5429
- const response = await apiCall(deps, ctx, () => deps.http.delete(`${ctx.api}/${encodeURIComponent(entry.id)}?baseRevision=${entry.revision}`, headers()), "rm", name);
5430
- await updateCache(ctx, deps, writtenEntries(ctx, response));
5431
- printWrite(deps, ctx, "rm", response);
5685
+ const results = [];
5686
+ for (const name of names) {
5687
+ try {
5688
+ const entry = resolveEntry(ctx, name, opts);
5689
+ const response = await apiCall(deps, ctx, () => deps.http.delete(`${ctx.api}/${encodeURIComponent(entry.id)}?baseRevision=${entry.revision}`, headers()), "rm", name);
5690
+ await updateCache(ctx, deps, writtenEntries(ctx, response));
5691
+ results.push(response);
5692
+ if (names.length === 1 || deps.output.mode !== "json") printWrite(deps, ctx, "rm", response);
5693
+ } catch (error) {
5694
+ if (names.length === 1) throw error;
5695
+ const message = error instanceof Error ? error.message : String(error);
5696
+ results.push({ name, error: message });
5697
+ const cli = error instanceof CliError ? error : new CliError(message, 2);
5698
+ printError(new CliError(`${oneLine(name)}: ${oneLine(message)}`, 2, cli.hint, cli.status, cli.serverError, cli.body, cli.detail), deps.output.mode);
5699
+ process.exitCode = 2;
5700
+ }
5701
+ }
5702
+ if (names.length > 1 && deps.output.mode === "json") printResult({ results }, "json");
5432
5703
  });
5433
5704
  memory.command("revert <name> <revision>").option("--scope <scope>").option("--branch <branch>", "branch entry of the current repo").action(async (name, revision, opts) => {
5434
5705
  const ctx = await context2(deps);
@@ -5450,7 +5721,7 @@ function register13(program, deps) {
5450
5721
  if (!ctx.git.repoIdentity) throw new CliError("repo \u3092\u8B58\u5225\u3067\u304D\u307E\u305B\u3093\u3002", 2);
5451
5722
  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)));
5452
5723
  if (!opts.all && !names.length) {
5453
- 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);
5724
+ printResult(deps.output.mode === "json" ? selected : selected.length ? selected.map(line).join("\n") : `branch ${oneLine(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);
5454
5725
  return;
5455
5726
  }
5456
5727
  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");