shipbench 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1687 -985
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -328,9 +328,9 @@ var require_common = __commonJS({
328
328
  }
329
329
  return target;
330
330
  }
331
- function repeat(string, count) {
331
+ function repeat(string, count2) {
332
332
  var result = "", cycle;
333
- for (cycle = 0; cycle < count; cycle += 1) {
333
+ for (cycle = 0; cycle < count2; cycle += 1) {
334
334
  result += string;
335
335
  }
336
336
  return result;
@@ -1717,11 +1717,11 @@ var require_loader = __commonJS({
1717
1717
  }
1718
1718
  return false;
1719
1719
  }
1720
- function writeFoldedLines(state, count) {
1721
- if (count === 1) {
1720
+ function writeFoldedLines(state, count2) {
1721
+ if (count2 === 1) {
1722
1722
  state.result += " ";
1723
- } else if (count > 1) {
1724
- state.result += common.repeat("\n", count - 1);
1723
+ } else if (count2 > 1) {
1724
+ state.result += common.repeat("\n", count2 - 1);
1725
1725
  }
1726
1726
  }
1727
1727
  function readPlainScalar(state, nodeIndent, withinFlowCollection) {
@@ -3905,6 +3905,7 @@ function resolveLayout(raw, legacyLayout, columnIds, options2) {
3905
3905
  const detail = error instanceof Error ? error.message : "Invalid layout.";
3906
3906
  options2.onWarning?.({
3907
3907
  path: source,
3908
+ code: "layout-unparseable",
3908
3909
  message: `${detail} Manual ordering was ignored; using deterministic fallback order.`
3909
3910
  });
3910
3911
  return {};
@@ -3917,6 +3918,7 @@ function resolveLayout(raw, legacyLayout, columnIds, options2) {
3917
3918
  }
3918
3919
  options2.onWarning?.({
3919
3920
  path: source,
3921
+ code: "layout-column-unknown",
3920
3922
  message: `Layout key(s) ${unknownKeys.map((key) => `"${key}"`).join(", ")} do not match any configured column. Manual ordering for ${unknownKeys.length === 1 ? "that column" : "those columns"} was ignored; using deterministic fallback order there.`
3921
3923
  });
3922
3924
  return pruned;
@@ -3936,11 +3938,22 @@ function deepMerge(defaults, overrides) {
3936
3938
  }
3937
3939
  return result;
3938
3940
  }
3939
- async function loadConfig(adapter, options2 = {}) {
3941
+ async function resolveConfig(adapter, options2 = {}) {
3940
3942
  const raw = await adapter.readFile(CONFIG_PATH);
3941
- const parsedConfig = JSON.parse(raw);
3943
+ let parsedConfig;
3944
+ try {
3945
+ parsedConfig = JSON.parse(raw);
3946
+ } catch (error) {
3947
+ return {
3948
+ kind: "unreadable",
3949
+ errors: [error instanceof Error ? error : new Error(String(error))]
3950
+ };
3951
+ }
3942
3952
  if (typeof parsedConfig !== "object" || parsedConfig === null || Array.isArray(parsedConfig)) {
3943
- throw new Error("Config must contain a JSON object.");
3953
+ return {
3954
+ kind: "unreadable",
3955
+ errors: [new Error("Config must contain a JSON object.")]
3956
+ };
3944
3957
  }
3945
3958
  const userConfig = parsedConfig;
3946
3959
  const layoutRaw = await adapter.readFileIfExists(LAYOUT_PATH);
@@ -3958,10 +3971,15 @@ async function loadConfig(adapter, options2 = {}) {
3958
3971
  );
3959
3972
  config.layout = resolveLayout(layoutRaw, legacyLayout, columnIds, options2);
3960
3973
  const errors = validateConfig(config);
3961
- if (errors.length > 0) {
3962
- throw new Error(`Invalid ShipBench config: ${errors.join(" ")}`);
3974
+ return errors.length > 0 ? { kind: "invalid", errors, userConfig } : { kind: "resolved", config, userConfig };
3975
+ }
3976
+ async function loadConfig(adapter, options2 = {}) {
3977
+ const resolution = await resolveConfig(adapter, options2);
3978
+ if (resolution.kind === "unreadable") throw resolution.errors[0];
3979
+ if (resolution.kind === "invalid") {
3980
+ throw new Error(`Invalid ShipBench config: ${resolution.errors.join(" ")}`);
3963
3981
  }
3964
- return config;
3982
+ return resolution.config;
3965
3983
  }
3966
3984
  function validateConfig(config) {
3967
3985
  const errors = [];
@@ -4541,44 +4559,85 @@ function unreadableUpdatesWarning(task) {
4541
4559
  return {
4542
4560
  slug: task.slug,
4543
4561
  field: "updates",
4562
+ code: "updates-unreadable",
4544
4563
  message: `Malformed Updates section: ${task.unreadableUpdates.reason} The section is preserved verbatim in the file and is not part of the description.`
4545
4564
  };
4546
4565
  }
4547
- function validateTask(task, config, knownSlugs, knownRelatedSlugs) {
4566
+ function validateTask(task, config, knownSlugs, knownRelatedSlugs, archiveConsulted) {
4548
4567
  const warnings = [];
4549
4568
  const validStatuses = new Set(config.columns.map((c) => c.id));
4550
4569
  const updatesWarning = unreadableUpdatesWarning(task);
4551
4570
  if (updatesWarning) {
4552
4571
  warnings.push(updatesWarning);
4553
4572
  }
4573
+ const { title } = task.frontmatter;
4574
+ if (typeof title !== "string" || !title.trim()) {
4575
+ warnings.push({
4576
+ slug: task.slug,
4577
+ field: "title",
4578
+ code: "title-invalid",
4579
+ message: title === void 0 || title === null ? "Missing title. Every task needs a non-empty `title`." : typeof title === "string" ? "Blank title. Every task needs a non-empty `title`." : `Expected title to be text (got ${JSON.stringify(title)}).`
4580
+ });
4581
+ }
4554
4582
  if (!validStatuses.has(task.frontmatter.status)) {
4555
4583
  warnings.push({
4556
4584
  slug: task.slug,
4557
4585
  field: "status",
4558
- message: `Unknown status "${task.frontmatter.status}". Valid: ${[...validStatuses].join(", ")}`
4586
+ code: "status-unknown",
4587
+ message: task.frontmatter.status === void 0 || task.frontmatter.status === null ? `Missing status. Valid: ${[...validStatuses].join(", ")}` : `Unknown status "${task.frontmatter.status}". Valid: ${[...validStatuses].join(", ")}`
4559
4588
  });
4560
4589
  }
4561
4590
  if (task.frontmatter.priority && !config.priority.values.includes(task.frontmatter.priority)) {
4562
4591
  warnings.push({
4563
4592
  slug: task.slug,
4564
4593
  field: "priority",
4594
+ code: "priority-unknown",
4565
4595
  message: `Unknown priority "${task.frontmatter.priority}". Valid: ${config.priority.values.join(", ")}`
4566
4596
  });
4567
4597
  }
4598
+ const { tags } = task.frontmatter;
4599
+ if (tags !== void 0 && tags !== null && (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string"))) {
4600
+ warnings.push({
4601
+ slug: task.slug,
4602
+ field: "tags",
4603
+ code: "tags-invalid",
4604
+ message: "Expected tags to be a list of text labels."
4605
+ });
4606
+ }
4607
+ for (const field of ["created", "updated"]) {
4608
+ const value = task.frontmatter[field];
4609
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) {
4610
+ warnings.push({
4611
+ slug: task.slug,
4612
+ field,
4613
+ code: "timestamp-invalid",
4614
+ message: value === void 0 || value === null ? `Missing ${field} timestamp. Core sets it on every write; restore it from Git history.` : `Expected ${field} to be an ISO 8601 timestamp (got ${JSON.stringify(value)}).`
4615
+ });
4616
+ }
4617
+ }
4568
4618
  const dependsOn = task.frontmatter.depends_on;
4569
- if (dependsOn !== void 0 && !Array.isArray(dependsOn)) {
4619
+ if (dependsOn !== void 0 && (!Array.isArray(dependsOn) || dependsOn.some((entry) => typeof entry !== "string"))) {
4570
4620
  warnings.push({
4571
4621
  slug: task.slug,
4572
4622
  field: "depends_on",
4623
+ code: "depends-on-invalid",
4573
4624
  message: "Expected depends_on to be a list of task slugs."
4574
4625
  });
4575
4626
  } else if (dependsOn) {
4576
- for (const dep of dependsOn) {
4577
- if (!knownSlugs.has(dep)) {
4627
+ for (const dep of new Set(dependsOn)) {
4628
+ if (dep === task.slug) {
4578
4629
  warnings.push({
4579
4630
  slug: task.slug,
4580
4631
  field: "depends_on",
4581
- message: `Dangling dependency "${dep}" \u2014 no live task file matches that slug (it may be archived).`
4632
+ code: "depends-on-self",
4633
+ message: `The task depends on itself, so it can never become available.`
4634
+ });
4635
+ } else if (!knownSlugs.has(dep)) {
4636
+ warnings.push({
4637
+ slug: task.slug,
4638
+ field: "depends_on",
4639
+ code: "depends-on-dangling",
4640
+ message: archiveConsulted ? `Dangling dependency "${dep}" \u2014 no live or archived task file matches that slug, so the task can never become available.` : `Dangling dependency "${dep}" \u2014 no live task file matches that slug (it may be archived).`
4582
4641
  });
4583
4642
  }
4584
4643
  }
@@ -4588,14 +4647,23 @@ function validateTask(task, config, knownSlugs, knownRelatedSlugs) {
4588
4647
  warnings.push({
4589
4648
  slug: task.slug,
4590
4649
  field: "related",
4650
+ code: "related-invalid",
4591
4651
  message: "Expected related to be a list of task slugs."
4592
4652
  });
4593
4653
  }
4594
4654
  for (const target of relatedSlugs(task)) {
4595
- if (!knownRelatedSlugs.has(target)) {
4655
+ if (target === task.slug) {
4656
+ warnings.push({
4657
+ slug: task.slug,
4658
+ field: "related",
4659
+ code: "related-self",
4660
+ message: "The task lists itself in related. Reads ignore the entry."
4661
+ });
4662
+ } else if (!knownRelatedSlugs.has(target)) {
4596
4663
  warnings.push({
4597
4664
  slug: task.slug,
4598
4665
  field: "related",
4666
+ code: "related-dangling",
4599
4667
  message: `Dangling related task "${target}" \u2014 no live or archived task file matches that slug.`
4600
4668
  });
4601
4669
  }
@@ -4605,6 +4673,7 @@ function validateTask(task, config, knownSlugs, knownRelatedSlugs) {
4605
4673
  warnings.push({
4606
4674
  slug: task.slug,
4607
4675
  field: "flag",
4676
+ code: "flag-invalid",
4608
4677
  message: "Expected flag to be `true` or a short reason. The task reads as unflagged."
4609
4678
  });
4610
4679
  }
@@ -4613,13 +4682,14 @@ function validateTask(task, config, knownSlugs, knownRelatedSlugs) {
4613
4682
  warnings.push({
4614
4683
  slug: task.slug,
4615
4684
  field,
4685
+ code: "field-unknown",
4616
4686
  message: `Unknown frontmatter field "${field}" (preserved).`
4617
4687
  });
4618
4688
  }
4619
4689
  }
4620
4690
  return warnings;
4621
4691
  }
4622
- async function listTasksInDirectory(adapter, config, directory, additionalKnownSlugs = [], otherDirectorySlugs = []) {
4692
+ async function listTasksInDirectory(adapter, config, directory, additionalKnownSlugs = [], otherDirectorySlugs = [], archiveConsulted = false) {
4623
4693
  const files = await adapter.listFiles(directory);
4624
4694
  const mdFiles = files.filter((f) => f.endsWith(".md"));
4625
4695
  if (mdFiles.length === 0) {
@@ -4640,6 +4710,7 @@ async function listTasksInDirectory(adapter, config, directory, additionalKnownS
4640
4710
  warnings.push({
4641
4711
  slug,
4642
4712
  field: "frontmatter",
4713
+ code: "frontmatter-unparseable",
4643
4714
  message: `Could not parse frontmatter in "${path}": ${error.file.reason}`
4644
4715
  });
4645
4716
  }
@@ -4654,7 +4725,15 @@ async function listTasksInDirectory(adapter, config, directory, additionalKnownS
4654
4725
  ...directorySlugs
4655
4726
  ]);
4656
4727
  for (const task of tasks) {
4657
- warnings.push(...validateTask(task, config, knownSlugs, knownRelatedSlugs));
4728
+ warnings.push(
4729
+ ...validateTask(
4730
+ task,
4731
+ config,
4732
+ knownSlugs,
4733
+ knownRelatedSlugs,
4734
+ archiveConsulted
4735
+ )
4736
+ );
4658
4737
  }
4659
4738
  return { tasks, warnings, unreadable };
4660
4739
  }
@@ -4674,7 +4753,8 @@ async function listTasks(adapter, config, options2 = {}) {
4674
4753
  config,
4675
4754
  TASKS_DIR,
4676
4755
  archivedSlugs,
4677
- archiveFiles
4756
+ archiveFiles,
4757
+ options2.archivedTasks !== void 0 || options2.archivedSlugs !== void 0
4678
4758
  );
4679
4759
  return { ...result, archivedSlugs: await archiveFiles };
4680
4760
  }
@@ -4693,7 +4773,8 @@ async function listArchivedTasks(adapter, config) {
4693
4773
  config,
4694
4774
  ARCHIVE_DIR,
4695
4775
  liveSlugs,
4696
- liveSlugs
4776
+ liveSlugs,
4777
+ true
4697
4778
  );
4698
4779
  }
4699
4780
  function taskFileSlugs(result) {
@@ -5008,6 +5089,7 @@ var CONFIG_PATH3 = ".shipbench/config.json";
5008
5089
  var LAYOUT_PATH3 = ".shipbench/layout.json";
5009
5090
  var README_PATH = ".shipbench/README.md";
5010
5091
  var AGENTS_PATH = ".shipbench/AGENTS.md";
5092
+ var SCAFFOLD_PATHS = [README_PATH, AGENTS_PATH];
5011
5093
  var TASKS_DIR2 = ".shipbench/tasks";
5012
5094
  var ARCHIVE_DIR2 = `${TASKS_DIR2}/archive`;
5013
5095
  function formatProjectInitializationError(state) {
@@ -5089,8 +5171,24 @@ async function inspectProjectInitialization(adapter) {
5089
5171
  };
5090
5172
  }
5091
5173
  }
5092
- function generateReadme(name) {
5093
- return `# ${name} \u2014 ShipBench Project Board
5174
+ var SCAFFOLD_STAMP_PATTERN = /^\uFEFF?<!-- shipbench-scaffold ([^\s:]+):/;
5175
+ function scaffoldStamp(version) {
5176
+ return `<!-- shipbench-scaffold ${version}: keep this line. It records the ShipBench version that wrote this file, so an upgrade can tell your edits from template changes. See https://shipbench.dev/docs/upgrading/ -->
5177
+
5178
+ `;
5179
+ }
5180
+ function readScaffoldStamp(content) {
5181
+ return SCAFFOLD_STAMP_PATTERN.exec(content)?.[1] ?? null;
5182
+ }
5183
+ async function readScaffoldStamps(adapter) {
5184
+ const files = await adapter.readFiles(SCAFFOLD_PATHS);
5185
+ return SCAFFOLD_PATHS.flatMap((path) => {
5186
+ const content = files.get(path);
5187
+ return content === void 0 ? [] : [{ path, version: readScaffoldStamp(content) }];
5188
+ });
5189
+ }
5190
+ function generateReadme(name, version) {
5191
+ return `${scaffoldStamp(version)}# ${name} \u2014 ShipBench Project Board
5094
5192
 
5095
5193
  This directory contains the ShipBench project board for **${name}**. Everything lives in Git alongside your code \u2014 no external service required.
5096
5194
 
@@ -5193,11 +5291,11 @@ Both commands also take \`--body <text>\` and \`--body-file <path>\` in place of
5193
5291
  Archived tasks live in \`tasks/archive/\` and are excluded from normal board reads. Archiving moves the file without changing its frontmatter or timestamps; unarchiving restores the same file to \`tasks/\`.
5194
5292
  `;
5195
5293
  }
5196
- function generateAgentsMd(name) {
5294
+ function generateAgentsMd(name, version) {
5197
5295
  const config = DEFAULT_CONFIG;
5198
5296
  const validStatuses = config.columns.map((c) => c.id).join(", ");
5199
5297
  const validPriorities = config.priority.values.join(", ");
5200
- return `# ${name} \u2014 ShipBench Agent Instructions
5298
+ return `${scaffoldStamp(version)}# ${name} \u2014 ShipBench Agent Instructions
5201
5299
 
5202
5300
  This file describes how to interact with the ShipBench task board for **${name}**.
5203
5301
 
@@ -5241,7 +5339,7 @@ Task description in Markdown.
5241
5339
  - **assignee** (optional): Freeform string label (e.g. \`claude\`, \`antigravity\`, or \`human\`). Informational only \u2014 task eligibility is governed strictly by \`status\` and \`depends_on\`. Moving a task to \`in-progress\` signals that work has started.
5242
5340
  - **tags** (optional): Array of freeform strings.
5243
5341
  - **depends_on** (optional): Array of task slugs that must be finished before this task can start. An omitted field and an empty array mean the same thing. A slug must name a task file that exists; a task may not depend on itself, and two tasks may not depend on each other.
5244
- - **related** (optional): Array of task slugs this task is associated with \u2014 the spike behind a decision, a sibling task sharing a surface. It points at other work without ordering it: it gates nothing, never blocks archiving, and stays out of the dependency graph. A slug must name a live or archived task file, and a task may not name itself. The association reads in both directions: JSON from \`task list\` and \`task search\` shows it from either task in \`related_tasks\`, while \`task get\` reports the file as written. Use \`depends_on\` when one task has to finish first, and \`related\` when the other task only explains or shares context.
5342
+ - **related** (optional): Array of task slugs this task is associated with \u2014 the spike behind a decision, a sibling task sharing a surface. It points at other work without ordering it: it gates nothing, never blocks archiving, and stays out of the dependency graph. A slug must name a live or archived task file, and a task may not name itself. The association reads in both directions: JSON from \`task list\` and \`task search\` shows it from either task in \`related_tasks\`, while \`task get\` reports the file as written. Use \`depends_on\` when one task has to finish first, and \`related\` when the other task only explains or shares context. When a description links to another task, also record that task here (or in \`depends_on\`): a slug resolves wherever the task is filed, while a relative Markdown link stops resolving once either file moves to \`tasks/archive/\`.
5245
5343
  - **flag** (optional): Marks the task for attention without changing its column \u2014 a one-line reason, or \`true\` when there is none to give. What a flag means is this project's call. Informational only: it gates nothing, and nothing clears it automatically. Omit the field when the task is not flagged.
5246
5344
  - **created** (required): ISO 8601 timestamp. Set once on creation, never modify.
5247
5345
  - **updated** (required): ISO 8601 timestamp. Update on every modification.
@@ -5367,6 +5465,7 @@ Commands work from any subdirectory of the board: the CLI uses the nearest \`.sh
5367
5465
  - **Read one task**: \`shipbench task get <slug>\`
5368
5466
  - **Search tasks**: \`shipbench task search "<query>" --json\`
5369
5467
  - **Inspect dependencies**: \`shipbench task graph --json\`
5468
+ - **Check the board's structure**: \`shipbench validate --json\` after hand edits, a merge, or a batch of changes (writes nothing; exits 1 when it finds an error, and \`--archived\` adds the archive)
5370
5469
  - **Include descriptions in a list**: \`shipbench task list --json --include-body\`
5371
5470
  - **Create a task**: \`shipbench task create "Task title" --status=todo\`
5372
5471
  - **Create a task with a description**: \`shipbench task create "Task title" --body-file=description.md\` (or \`--body "One-line description."\`)
@@ -5443,12 +5542,18 @@ Set up this board with \`shipbench init\`.
5443
5542
  `;
5444
5543
  }
5445
5544
  async function initProject(adapter, options2) {
5545
+ if (!/^[^\s:]+$/.test(options2.version)) {
5546
+ throw new Error(
5547
+ `ShipBench version "${options2.version}" can't be stamped into the scaffold: it must be non-empty, without spaces or colons.`
5548
+ );
5549
+ }
5446
5550
  const initialState = await inspectProjectInitialization(adapter);
5447
5551
  if (initialState.kind === "initialized") {
5448
5552
  return {
5449
5553
  created: false,
5450
5554
  config: initialState.config,
5451
- warnings: initialState.warnings
5555
+ warnings: initialState.warnings,
5556
+ scaffold: await readScaffoldStamps(adapter)
5452
5557
  };
5453
5558
  }
5454
5559
  if (initialState.kind !== "missing") {
@@ -5461,8 +5566,8 @@ async function initProject(adapter, options2) {
5461
5566
  [".shipbench/config.json", `${JSON.stringify(config, null, 2)}
5462
5567
  `],
5463
5568
  [".shipbench/layout.json", "{}\n"],
5464
- [".shipbench/README.md", generateReadme(options2.name)],
5465
- [".shipbench/AGENTS.md", generateAgentsMd(options2.name)],
5569
+ [README_PATH, generateReadme(options2.name, options2.version)],
5570
+ [AGENTS_PATH, generateAgentsMd(options2.name, options2.version)],
5466
5571
  [
5467
5572
  ".shipbench/tasks/welcome-to-shipbench.md",
5468
5573
  generateWelcomeTask(options2.name)
@@ -5479,10 +5584,50 @@ async function initProject(adapter, options2) {
5479
5584
  return {
5480
5585
  created: true,
5481
5586
  config: createdState.config,
5482
- warnings: createdState.warnings
5587
+ warnings: createdState.warnings,
5588
+ scaffold: SCAFFOLD_PATHS.map((path) => ({ path, version: options2.version }))
5483
5589
  };
5484
5590
  }
5485
5591
 
5592
+ // ../../packages/core/src/links.ts
5593
+ var INLINE_LINK = /\]\(\s*(<[^>\n]*>|[^\s)]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\s*\)/g;
5594
+ var REFERENCE_DEFINITION = /^ {0,3}\[[^\]\n]+\]:\s*(<[^>\n]*>|\S+)/gm;
5595
+ var FENCED_CODE = /^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1[^\n]*$|(?![\s\S]))/gm;
5596
+ var INLINE_CODE = /(`+)[^`]*?\1/g;
5597
+ var SCHEME = /^[a-z][a-z0-9+.-]*:/i;
5598
+ var TASK_HREF = /^(?:\.\/)?(?:archive\/|\.\.\/)?([^/]+)\.md$|(?:^|\/)\.shipbench\/tasks\/(?:archive\/)?([^/]+)\.md$/;
5599
+ function taskSlugOfHref(raw) {
5600
+ const href = raw.startsWith("<") ? raw.slice(1, -1).trim() : raw;
5601
+ if (!href || href.startsWith("#") || SCHEME.test(href)) return null;
5602
+ const path = href.replace(/[?#].*$/, "");
5603
+ let decoded;
5604
+ try {
5605
+ decoded = decodeURIComponent(path);
5606
+ } catch {
5607
+ return null;
5608
+ }
5609
+ const match = TASK_HREF.exec(decoded);
5610
+ return match ? match[1] ?? match[2] : null;
5611
+ }
5612
+ function taskLinkTargets(markdown) {
5613
+ const prose = markdown.replace(FENCED_CODE, "").replace(INLINE_CODE, "");
5614
+ const slugs = /* @__PURE__ */ new Set();
5615
+ for (const pattern of [INLINE_LINK, REFERENCE_DEFINITION]) {
5616
+ for (const match of prose.matchAll(pattern)) {
5617
+ const slug = taskSlugOfHref(match[1]);
5618
+ if (slug) slugs.add(slug);
5619
+ }
5620
+ }
5621
+ return [...slugs];
5622
+ }
5623
+ function tasksLinkingTo(tasks, slug) {
5624
+ return tasks.filter(
5625
+ (task) => task.slug !== slug && [task.body, ...task.comments.map((comment) => comment.text)].some(
5626
+ (text) => taskLinkTargets(text).includes(slug)
5627
+ )
5628
+ ).map((task) => task.slug).sort();
5629
+ }
5630
+
5486
5631
  // ../../packages/core/src/search.ts
5487
5632
  var SNIPPET_CONTEXT_BEFORE = 40;
5488
5633
  var SNIPPET_CONTEXT_AFTER = 80;
@@ -5617,9 +5762,461 @@ function searchTasks(tasks, query, options2 = {}) {
5617
5762
  ).map((entry) => entry.match);
5618
5763
  }
5619
5764
 
5765
+ // ../../packages/core/src/validate.ts
5766
+ var CONFIG_PATH4 = ".shipbench/config.json";
5767
+ var TASKS_DIR3 = ".shipbench/tasks";
5768
+ var ARCHIVE_DIR3 = `${TASKS_DIR3}/archive`;
5769
+ var ERROR_CODES = /* @__PURE__ */ new Set([
5770
+ "config-unparseable",
5771
+ "config-invalid",
5772
+ "layout-unparseable",
5773
+ "frontmatter-unparseable",
5774
+ "updates-unreadable",
5775
+ "title-invalid",
5776
+ "status-unknown",
5777
+ "priority-unknown",
5778
+ "tags-invalid",
5779
+ "timestamp-invalid",
5780
+ "depends-on-invalid",
5781
+ "depends-on-self",
5782
+ "depends-on-dangling",
5783
+ "dependency-cycle",
5784
+ "related-invalid",
5785
+ "flag-invalid",
5786
+ "slug-reused-in-archive"
5787
+ ]);
5788
+ function severityOf(code) {
5789
+ return ERROR_CODES.has(code) ? "error" : "warning";
5790
+ }
5791
+ var KNOWN_CONFIG_KEYS = {
5792
+ version: null,
5793
+ name: null,
5794
+ columns: null,
5795
+ default_column: null,
5796
+ done_column: null,
5797
+ done_display: ["max"],
5798
+ priority: ["values", "default"],
5799
+ schema: ["custom_fields"],
5800
+ layout: null
5801
+ };
5802
+ function unknownConfigKeys(userConfig) {
5803
+ const unknown = [];
5804
+ for (const [key, value] of Object.entries(userConfig)) {
5805
+ if (!Object.hasOwn(KNOWN_CONFIG_KEYS, key)) {
5806
+ unknown.push(key);
5807
+ continue;
5808
+ }
5809
+ const nested = KNOWN_CONFIG_KEYS[key];
5810
+ if (!nested || typeof value !== "object" || value === null) continue;
5811
+ if (Array.isArray(value)) continue;
5812
+ for (const child of Object.keys(value)) {
5813
+ if (!nested.includes(child)) unknown.push(`${key}.${child}`);
5814
+ }
5815
+ }
5816
+ return unknown;
5817
+ }
5818
+ function configWarningProblem(warning) {
5819
+ const code = warning.code ?? "layout-unparseable";
5820
+ return {
5821
+ severity: severityOf(code),
5822
+ code,
5823
+ path: warning.path,
5824
+ message: warning.message
5825
+ };
5826
+ }
5827
+ function taskWarningProblem(warning, directory) {
5828
+ const code = warning.code ?? "field-unknown";
5829
+ return {
5830
+ severity: severityOf(code),
5831
+ code,
5832
+ path: `${directory}/${warning.slug}.md`,
5833
+ slug: warning.slug,
5834
+ field: warning.field,
5835
+ message: warning.message
5836
+ };
5837
+ }
5838
+ function dependencyList(task) {
5839
+ const { depends_on: dependsOn } = task.frontmatter;
5840
+ if (!Array.isArray(dependsOn)) return [];
5841
+ return dependsOn.filter((slug) => typeof slug === "string");
5842
+ }
5843
+ function dependencyCycles(tasks) {
5844
+ const edges = /* @__PURE__ */ new Map();
5845
+ for (const task of tasks) edges.set(task.slug, []);
5846
+ for (const task of tasks) {
5847
+ edges.set(
5848
+ task.slug,
5849
+ [...new Set(dependencyList(task))].filter(
5850
+ (slug) => slug !== task.slug && edges.has(slug)
5851
+ )
5852
+ );
5853
+ }
5854
+ const index = /* @__PURE__ */ new Map();
5855
+ const low = /* @__PURE__ */ new Map();
5856
+ const onStack = /* @__PURE__ */ new Set();
5857
+ const stack = [];
5858
+ const groups = [];
5859
+ let next = 0;
5860
+ for (const root of [...edges.keys()].sort()) {
5861
+ if (index.has(root)) continue;
5862
+ const work = [
5863
+ { slug: root, edge: 0 }
5864
+ ];
5865
+ index.set(root, next);
5866
+ low.set(root, next);
5867
+ next += 1;
5868
+ stack.push(root);
5869
+ onStack.add(root);
5870
+ while (work.length > 0) {
5871
+ const frame = work[work.length - 1];
5872
+ const targets = edges.get(frame.slug);
5873
+ if (frame.edge < targets.length) {
5874
+ const target = targets[frame.edge];
5875
+ frame.edge += 1;
5876
+ if (!index.has(target)) {
5877
+ index.set(target, next);
5878
+ low.set(target, next);
5879
+ next += 1;
5880
+ stack.push(target);
5881
+ onStack.add(target);
5882
+ work.push({ slug: target, edge: 0 });
5883
+ } else if (onStack.has(target)) {
5884
+ low.set(
5885
+ frame.slug,
5886
+ Math.min(low.get(frame.slug), index.get(target))
5887
+ );
5888
+ }
5889
+ continue;
5890
+ }
5891
+ work.pop();
5892
+ const parent = work[work.length - 1];
5893
+ if (parent) {
5894
+ low.set(
5895
+ parent.slug,
5896
+ Math.min(low.get(parent.slug), low.get(frame.slug))
5897
+ );
5898
+ }
5899
+ if (low.get(frame.slug) === index.get(frame.slug)) {
5900
+ const group = [];
5901
+ let member;
5902
+ do {
5903
+ member = stack.pop();
5904
+ onStack.delete(member);
5905
+ group.push(member);
5906
+ } while (member !== frame.slug);
5907
+ if (group.length > 1) groups.push(group);
5908
+ }
5909
+ }
5910
+ }
5911
+ return groups.map((group) => {
5912
+ const members = new Set(group);
5913
+ const start = [...group].sort()[0];
5914
+ const previous = /* @__PURE__ */ new Map();
5915
+ const queue = [start];
5916
+ while (queue.length > 0) {
5917
+ const slug = queue.shift();
5918
+ for (const target of [...edges.get(slug)].sort()) {
5919
+ if (!members.has(target)) continue;
5920
+ if (target === start) {
5921
+ const loop = [slug];
5922
+ for (let at = slug; at !== start; ) {
5923
+ at = previous.get(at);
5924
+ loop.unshift(at);
5925
+ }
5926
+ return [...loop, start];
5927
+ }
5928
+ if (!previous.has(target)) {
5929
+ previous.set(target, slug);
5930
+ queue.push(target);
5931
+ }
5932
+ }
5933
+ }
5934
+ return [...group, start];
5935
+ }).sort((a, b) => a[0].localeCompare(b[0]));
5936
+ }
5937
+ function ignoredEntries(files, directory) {
5938
+ return files.filter(
5939
+ (file) => !file.endsWith(".md") && !file.startsWith(".") && !(directory === TASKS_DIR3 && file === "archive")
5940
+ ).sort().map((file) => `${directory}/${file}`);
5941
+ }
5942
+ async function validateProject(adapter, options2 = {}) {
5943
+ const problems = [];
5944
+ const configWarnings = [];
5945
+ const resolution = await resolveConfig(adapter, {
5946
+ onWarning: (warning) => {
5947
+ configWarnings.push(warning);
5948
+ }
5949
+ });
5950
+ if (resolution.kind === "unreadable") {
5951
+ const reason = resolution.errors[0].message.trim().replace(/\.?$/, ".");
5952
+ problems.push({
5953
+ severity: "error",
5954
+ code: "config-unparseable",
5955
+ path: CONFIG_PATH4,
5956
+ message: `${reason} Tasks were not checked, because their statuses and priorities are checked against this file.`
5957
+ });
5958
+ return report(problems, { tasks: null, archived: null });
5959
+ }
5960
+ for (const key of unknownConfigKeys(resolution.userConfig)) {
5961
+ problems.push({
5962
+ severity: "warning",
5963
+ code: "config-field-unknown",
5964
+ path: CONFIG_PATH4,
5965
+ field: key,
5966
+ message: `Unknown config key "${key}". Core ignores it; check the spelling if it was meant to change a setting.`
5967
+ });
5968
+ }
5969
+ if (resolution.kind === "invalid") {
5970
+ for (const error of resolution.errors) {
5971
+ problems.push({
5972
+ severity: "error",
5973
+ code: "config-invalid",
5974
+ path: CONFIG_PATH4,
5975
+ message: error
5976
+ });
5977
+ }
5978
+ problems.push(...configWarnings.map(configWarningProblem));
5979
+ return report(problems, { tasks: null, archived: null });
5980
+ }
5981
+ problems.push(...configWarnings.map(configWarningProblem));
5982
+ const config = resolution.config;
5983
+ const [liveFiles, archiveFiles] = await Promise.all([
5984
+ adapter.listFiles(TASKS_DIR3),
5985
+ adapter.listFiles(ARCHIVE_DIR3)
5986
+ ]);
5987
+ const archiveSlugs = archiveFiles.filter((file) => file.endsWith(".md")).map((file) => file.replace(/\.md$/, ""));
5988
+ const live = await listTasks(adapter, config, {
5989
+ archivedSlugs: archiveSlugs
5990
+ });
5991
+ const liveSlugs = /* @__PURE__ */ new Set([
5992
+ ...live.tasks.map((task) => task.slug),
5993
+ ...live.unreadable.map((file) => file.slug)
5994
+ ]);
5995
+ const taskProblems = live.warnings.map(
5996
+ (warning) => taskWarningProblem(warning, TASKS_DIR3)
5997
+ );
5998
+ for (const slug of archiveSlugs) {
5999
+ if (!liveSlugs.has(slug)) continue;
6000
+ taskProblems.push({
6001
+ severity: "error",
6002
+ code: "slug-reused-in-archive",
6003
+ path: `${TASKS_DIR3}/${slug}.md`,
6004
+ slug,
6005
+ message: `"${slug}" names both a live task and ${ARCHIVE_DIR3}/${slug}.md. Archiving or unarchiving either one overwrites the other; give one of them a new slug.`
6006
+ });
6007
+ }
6008
+ for (const cycle of dependencyCycles(live.tasks)) {
6009
+ taskProblems.push({
6010
+ severity: "error",
6011
+ code: "dependency-cycle",
6012
+ path: `${TASKS_DIR3}/${cycle[0]}.md`,
6013
+ slug: cycle[0],
6014
+ field: "depends_on",
6015
+ message: `Dependency cycle: ${cycle.join(" \u2192 ")}. None of these tasks can become available until one of them stops depending on the next.`,
6016
+ cycle
6017
+ });
6018
+ }
6019
+ for (const path of ignoredEntries(liveFiles, TASKS_DIR3)) {
6020
+ taskProblems.push({
6021
+ severity: "warning",
6022
+ code: "file-ignored",
6023
+ path,
6024
+ message: "Not a task file, so no read shows it. Task files end in `.md`; rename it if it was meant to be one."
6025
+ });
6026
+ }
6027
+ let archivedCount = null;
6028
+ if (options2.archived) {
6029
+ const archived = await listArchivedTasks(adapter, config);
6030
+ archivedCount = archived.tasks.length + archived.unreadable.length;
6031
+ taskProblems.push(
6032
+ ...archived.warnings.map(
6033
+ (warning) => taskWarningProblem(warning, ARCHIVE_DIR3)
6034
+ )
6035
+ );
6036
+ for (const path of ignoredEntries(archiveFiles, ARCHIVE_DIR3)) {
6037
+ taskProblems.push({
6038
+ severity: "warning",
6039
+ code: "file-ignored",
6040
+ path,
6041
+ message: "Not a task file, so no read shows it. Task files end in `.md`; rename it if it was meant to be one."
6042
+ });
6043
+ }
6044
+ }
6045
+ problems.push(
6046
+ ...taskProblems.map((problem, order) => ({ problem, order })).sort(
6047
+ (a, b) => a.problem.path.localeCompare(b.problem.path) || a.order - b.order
6048
+ ).map(({ problem }) => problem)
6049
+ );
6050
+ return report(problems, {
6051
+ tasks: live.tasks.length + live.unreadable.length,
6052
+ archived: archivedCount
6053
+ });
6054
+ }
6055
+ function report(problems, checked) {
6056
+ const errors = problems.filter((p) => p.severity === "error").length;
6057
+ return {
6058
+ valid: errors === 0,
6059
+ errors,
6060
+ warnings: problems.length - errors,
6061
+ checked,
6062
+ problems
6063
+ };
6064
+ }
6065
+
5620
6066
  // src/cli.ts
5621
6067
  import { readFile as readFile3 } from "fs/promises";
5622
- import { Command, InvalidArgumentError, Option } from "commander";
6068
+ import { Command } from "commander";
6069
+
6070
+ // src/commands/context.ts
6071
+ function taskJson(task) {
6072
+ return {
6073
+ slug: task.slug,
6074
+ status: task.frontmatter.status,
6075
+ frontmatter: task.frontmatter,
6076
+ body: task.body,
6077
+ comments: task.comments
6078
+ };
6079
+ }
6080
+ async function requireLiveTask(ctx, command, config, slug, action) {
6081
+ const existing = await getTask(ctx.adapter, config, slug);
6082
+ if (existing) return existing;
6083
+ const archived = await getTask(ctx.adapter, config, slug, {
6084
+ archived: true
6085
+ });
6086
+ command.error(
6087
+ archived ? `Task '${slug}' is archived. Unarchive it before ${action}.` : `Task '${slug}' not found.`
6088
+ );
6089
+ return null;
6090
+ }
6091
+
6092
+ // src/commands/options.ts
6093
+ import { InvalidArgumentError } from "commander";
6094
+ function commaList(value) {
6095
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
6096
+ }
6097
+ function accumulateCommaList(value, previous) {
6098
+ return [...previous ?? [], ...commaList(value)];
6099
+ }
6100
+ function dedupePreservingCase(values) {
6101
+ const seen = /* @__PURE__ */ new Set();
6102
+ const result = [];
6103
+ for (const value of values) {
6104
+ const key = value.toLowerCase();
6105
+ if (seen.has(key)) continue;
6106
+ seen.add(key);
6107
+ result.push(value);
6108
+ }
6109
+ return result;
6110
+ }
6111
+ function parseNonNegativeInteger(value) {
6112
+ const parsed = Number(value);
6113
+ if (!Number.isInteger(parsed) || parsed < 0) {
6114
+ throw new InvalidArgumentError("Value must be a non-negative integer.");
6115
+ }
6116
+ return parsed;
6117
+ }
6118
+
6119
+ // src/commands/archive.ts
6120
+ function registerArchive(task, ctx) {
6121
+ const { adapter, data, chrome, output, printTask } = ctx;
6122
+ task.command("archive [slug]").description("Archive one task, or older done tasks in bulk").option("--done", "Archive done tasks in bulk").option(
6123
+ "--keep <count>",
6124
+ "Number of most-recent done tasks to keep live",
6125
+ parseNonNegativeInteger
6126
+ ).option(
6127
+ "--force",
6128
+ "Archive a non-done task even when live tasks depend on it"
6129
+ ).option(
6130
+ "--json",
6131
+ "Output the archived task as JSON (an array of them with --done)"
6132
+ ).addHelpText(
6133
+ "after",
6134
+ "\nA non-done task with live dependents is blocked unless --force is used.\n"
6135
+ ).action(async (slug, raw) => {
6136
+ if (Boolean(slug) === Boolean(raw.done)) {
6137
+ throw new Error("Provide either a task slug or --done, but not both.");
6138
+ }
6139
+ if (raw.keep !== void 0 && !raw.done) {
6140
+ throw new Error("--keep can only be used with --done.");
6141
+ }
6142
+ if (raw.force && raw.done) {
6143
+ throw new Error("--force can only be used when archiving one task.");
6144
+ }
6145
+ const config = await ctx.loadConfig();
6146
+ const warnAboutLinksToArchived = async (slugs) => {
6147
+ if (slugs.length === 0) return;
6148
+ const { tasks } = await listTasks(adapter, config);
6149
+ for (const archivedSlug of slugs) {
6150
+ const linking = tasksLinkingTo(tasks, archivedSlug);
6151
+ if (linking.length === 0) continue;
6152
+ output.warning(
6153
+ `${linking.join(", ")} ${linking.length === 1 ? "links" : "link"} to ${archivedSlug}, which is now at archive/${archivedSlug}.md. Update the link, or name ${archivedSlug} in related.`
6154
+ );
6155
+ }
6156
+ };
6157
+ if (raw.done) {
6158
+ const { tasks } = await listTasks(adapter, config);
6159
+ const doneTasks = tasks.filter(
6160
+ (candidate) => candidate.frontmatter.status === config.done_column
6161
+ ).sort(
6162
+ (a, b) => Date.parse(b.frontmatter.updated) - Date.parse(a.frontmatter.updated) || a.slug.localeCompare(b.slug)
6163
+ );
6164
+ const keep = raw.keep === void 0 && config.done_display.max <= 0 ? doneTasks.length : raw.keep ?? config.done_display.max;
6165
+ const candidates = doneTasks.slice(keep);
6166
+ const archived = [];
6167
+ for (const candidate of candidates) {
6168
+ archived.push(await archiveTask(adapter, config, candidate.slug));
6169
+ if (!raw.json) chrome(`Archived task: ${candidate.slug}`);
6170
+ }
6171
+ await warnAboutLinksToArchived(archived.map((task2) => task2.slug));
6172
+ if (raw.json) {
6173
+ data(JSON.stringify(archived.map(taskJson), null, 2));
6174
+ return;
6175
+ }
6176
+ if (candidates.length === 0) chrome("No done tasks archived.");
6177
+ return;
6178
+ }
6179
+ try {
6180
+ const archived = await archiveTask(adapter, config, slug, {
6181
+ force: raw.force
6182
+ });
6183
+ if (raw.json) {
6184
+ printTask(archived);
6185
+ } else {
6186
+ chrome(`Archived task: ${slug}`);
6187
+ }
6188
+ await warnAboutLinksToArchived([archived.slug]);
6189
+ } catch (error) {
6190
+ if (error instanceof ArchiveBlockedError) {
6191
+ throw new Error(
6192
+ `Cannot archive "${error.slug}" because live tasks depend on it: ${error.dependentSlugs.join(", ")}. Re-run with --force to archive it anyway.`
6193
+ );
6194
+ }
6195
+ throw error;
6196
+ }
6197
+ });
6198
+ task.command("unarchive <slug>").description("Restore an archived task").option("--json", "Output the resulting task as JSON").action(async (slug, raw) => {
6199
+ const config = await ctx.loadConfig();
6200
+ const restored = await unarchiveTask(adapter, config, slug);
6201
+ if (raw.json) {
6202
+ printTask(restored);
6203
+ return;
6204
+ }
6205
+ chrome(`Unarchived task: ${slug}`);
6206
+ });
6207
+ task.command("delete <slug>").description("Delete a task").option("--json", "Output the deleted slug as JSON").action(async (slug, raw) => {
6208
+ const config = await ctx.loadConfig();
6209
+ await deleteTask(adapter, config, slug);
6210
+ if (raw.json) {
6211
+ data(JSON.stringify({ slug, deleted: true }, null, 2));
6212
+ return;
6213
+ }
6214
+ chrome(`Deleted task: ${slug}`);
6215
+ });
6216
+ }
6217
+
6218
+ // src/commands/board.ts
6219
+ import { InvalidArgumentError as InvalidArgumentError2 } from "commander";
5623
6220
 
5624
6221
  // src/boardServer.ts
5625
6222
  import { spawn } from "child_process";
@@ -5632,7 +6229,7 @@ import { dirname as dirname2, extname, join as join3, resolve, sep as sep2 } fro
5632
6229
  import { platform } from "process";
5633
6230
 
5634
6231
  // src/tui/paths.ts
5635
- var CONFIG_PATH4 = ".shipbench/config.json";
6232
+ var CONFIG_PATH5 = ".shipbench/config.json";
5636
6233
  var LAYOUT_PATH4 = ".shipbench/layout.json";
5637
6234
 
5638
6235
  // src/tui/watch.ts
@@ -5641,7 +6238,7 @@ import chokidar from "chokidar";
5641
6238
  var DEBOUNCE_MS = 150;
5642
6239
  async function watchProject(cwd, onChange, debounceMs = DEBOUNCE_MS) {
5643
6240
  const tasksDir = join2(cwd, ".shipbench", "tasks");
5644
- const configFile = join2(cwd, CONFIG_PATH4);
6241
+ const configFile = join2(cwd, CONFIG_PATH5);
5645
6242
  const layoutFile = join2(cwd, LAYOUT_PATH4);
5646
6243
  const watcher = chokidar.watch(
5647
6244
  [tasksDir, configFile, layoutFile],
@@ -6054,7 +6651,7 @@ function closeServer(server) {
6054
6651
  }
6055
6652
  async function startBoardServer(options2) {
6056
6653
  try {
6057
- await options2.adapter.readFile(CONFIG_PATH4);
6654
+ await options2.adapter.readFile(CONFIG_PATH5);
6058
6655
  } catch {
6059
6656
  throw new Error(
6060
6657
  "No .shipbench/config.json found. Run shipbench init first."
@@ -6262,7 +6859,7 @@ async function readBoard(adapter, filters) {
6262
6859
  let config;
6263
6860
  const configWarnings = [];
6264
6861
  try {
6265
- if (await adapter.readFileIfExists(CONFIG_PATH4) === null) {
6862
+ if (await adapter.readFileIfExists(CONFIG_PATH5) === null) {
6266
6863
  return { ok: false, message: MISSING_CONFIG_MESSAGE };
6267
6864
  }
6268
6865
  config = await loadConfig(adapter, {
@@ -6323,13 +6920,13 @@ var COL_PADDING = 2;
6323
6920
  function meterFitsIn(columnWidth, tiers) {
6324
6921
  return columnWidth >= MIN_COL_WIDTH + tiers + 1;
6325
6922
  }
6326
- function columnWidthFor(width, count) {
6327
- if (count <= 0) return 0;
6328
- const chrome = count * COL_PADDING + (count - 1);
6329
- return Math.floor((width - chrome) / count);
6923
+ function columnWidthFor(width, count2) {
6924
+ if (count2 <= 0) return 0;
6925
+ const chrome = count2 * COL_PADDING + (count2 - 1);
6926
+ return Math.floor((width - chrome) / count2);
6330
6927
  }
6331
- function fits(width, count) {
6332
- return count > 0 && columnWidthFor(width, count) >= MIN_COL_WIDTH;
6928
+ function fits(width, count2) {
6929
+ return count2 > 0 && columnWidthFor(width, count2) >= MIN_COL_WIDTH;
6333
6930
  }
6334
6931
  function shareRows(needs, available) {
6335
6932
  const out = needs.map(() => 0);
@@ -6564,15 +7161,15 @@ function countLabel(column, filtered) {
6564
7161
  function sectionHeader(column, width, model, options2) {
6565
7162
  const { style } = options2;
6566
7163
  const label = column.label.toUpperCase();
6567
- const count = countLabel(column, model.filtered);
7164
+ const count2 = countLabel(column, model.filtered);
6568
7165
  const attrs = column.isUncategorized ? ["yellow", "bold"] : column.isDone ? ["dim"] : ["bold"];
6569
7166
  const labelCut = truncate(
6570
7167
  label,
6571
- Math.max(0, width - displayWidth(count) - 2)
7168
+ Math.max(0, width - displayWidth(count2) - 2)
6572
7169
  );
6573
- const ruleWidth = width - displayWidth(labelCut) - displayWidth(count) - (labelCut ? 2 : 0);
6574
- if (ruleWidth < 0) return fit(count, width);
6575
- return style(labelCut, ...attrs) + (labelCut ? " " : "") + style(BOX.rule.repeat(ruleWidth), "dim") + (labelCut ? " " : "") + style(count, "dim");
7170
+ const ruleWidth = width - displayWidth(labelCut) - displayWidth(count2) - (labelCut ? 2 : 0);
7171
+ if (ruleWidth < 0) return fit(count2, width);
7172
+ return style(labelCut, ...attrs) + (labelCut ? " " : "") + style(BOX.rule.repeat(ruleWidth), "dim") + (labelCut ? " " : "") + style(count2, "dim");
6576
7173
  }
6577
7174
  function columnBody(column, width, rows, model, format, options2) {
6578
7175
  const { style } = options2;
@@ -6601,11 +7198,11 @@ function visibleTasks(column, rows) {
6601
7198
  function collapsedChips(columns, model, options2) {
6602
7199
  const { style } = options2;
6603
7200
  return columns.map((column) => {
6604
- const count = countLabel(column, model.filtered);
7201
+ const count2 = countLabel(column, model.filtered);
6605
7202
  if (column.isUncategorized) {
6606
- return style(`${BOX.warn} ${count} uncategorized`, "yellow");
7203
+ return style(`${BOX.warn} ${count2} uncategorized`, "yellow");
6607
7204
  }
6608
- return style(`${column.label.toLowerCase()} ${count}`, "dim");
7205
+ return style(`${column.label.toLowerCase()} ${count2}`, "dim");
6609
7206
  });
6610
7207
  }
6611
7208
  function updatedLabel(at) {
@@ -6872,25 +7469,136 @@ async function runTui(options2) {
6872
7469
  screen.close();
6873
7470
  }
6874
7471
 
6875
- // src/cli.ts
6876
- var VERSION = true ? "0.9.0" : "0.0.0-dev";
6877
- function commaList(value) {
6878
- return value.split(",").map((s) => s.trim()).filter(Boolean);
6879
- }
6880
- function accumulateCommaList(value, previous) {
6881
- return [...previous ?? [], ...commaList(value)];
6882
- }
6883
- function dedupePreservingCase(values) {
6884
- const seen = /* @__PURE__ */ new Set();
6885
- const result = [];
6886
- for (const value of values) {
6887
- const key = value.toLowerCase();
6888
- if (seen.has(key)) continue;
6889
- seen.add(key);
6890
- result.push(value);
7472
+ // src/commands/board.ts
7473
+ function parsePort(value) {
7474
+ const port = Number(value);
7475
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
7476
+ throw new InvalidArgumentError2("Port must be an integer from 1 to 65535.");
6891
7477
  }
6892
- return result;
7478
+ return port;
7479
+ }
7480
+ function registerBoard(program, ctx) {
7481
+ const { adapter, cwd, chrome, output, requireBoard } = ctx;
7482
+ const board = program.command("board").description("Open the board UI");
7483
+ board.command("web", { isDefault: true }).description("Open the board UI in a browser (the default for `board`)").option("--port <number>", "Port to listen on", parsePort, 4321).option("--no-open", "Do not open the browser automatically").action(async (raw) => {
7484
+ await requireBoard();
7485
+ const server = await startBoardServer({
7486
+ adapter,
7487
+ cwd,
7488
+ bundleDir: resolveBoardBundleDir(),
7489
+ port: raw.port,
7490
+ warn: chrome
7491
+ });
7492
+ output.brand();
7493
+ for (const line of formatBoardStatus(server.url, cwd)) chrome(line);
7494
+ if (raw.open) openBrowser(server.url);
7495
+ const shutdown = async () => {
7496
+ await server.close();
7497
+ process.exit(0);
7498
+ };
7499
+ process.once("SIGINT", () => {
7500
+ void shutdown();
7501
+ });
7502
+ process.once("SIGTERM", () => {
7503
+ void shutdown();
7504
+ });
7505
+ await new Promise(() => {
7506
+ });
7507
+ });
7508
+ board.command("terminal").aliases(["term", "tui"]).description("Render the board in the terminal (read-only, live, no input)").option(
7509
+ "-s, --status <statuses>",
7510
+ "Columns to render (comma-separated; defaults to every configured column)",
7511
+ commaList
7512
+ ).option("-a, --assignee <assignee>", "Filter by assignee").option("-p, --priority <priority>", "Filter by priority").option(
7513
+ "--tag <tag>",
7514
+ "Filter by tag (comma-separated or repeatable with AND semantics)",
7515
+ accumulateCommaList
7516
+ ).option(
7517
+ "--exclude-tag <tag>",
7518
+ "Leave out tasks carrying any of these tags (comma-separated or repeatable)",
7519
+ accumulateCommaList
7520
+ ).option("--flagged", "Only tasks with a flag set").addHelpText(
7521
+ "after",
7522
+ "\nTakes no keyboard input: Ctrl-C exits. Never writes to the board.\nWith stdout redirected it prints one 80x24 frame and exits.\n"
7523
+ ).action(async (raw) => {
7524
+ await requireBoard();
7525
+ await runTui({
7526
+ adapter,
7527
+ cwd,
7528
+ filters: {
7529
+ statuses: raw.status,
7530
+ tags: raw.tag,
7531
+ excludedTags: raw.excludeTag,
7532
+ assignee: raw.assignee,
7533
+ priority: raw.priority,
7534
+ flagged: raw.flagged
7535
+ }
7536
+ });
7537
+ });
7538
+ }
7539
+
7540
+ // src/commands/init.ts
7541
+ var UPGRADING_URL = "https://shipbench.dev/docs/upgrading/";
7542
+ function formatProjectWarning(warning) {
7543
+ const source = "path" in warning ? warning.path : warning.slug;
7544
+ return `${source}: ${warning.message}`;
7545
+ }
7546
+ function registerInit(program, ctx, settings) {
7547
+ const { adapter, chrome, output } = ctx;
7548
+ const { defaultProjectName, ancestorBoard, version } = settings;
7549
+ program.command("init").description(
7550
+ "Initialize ShipBench in the current repository; leave an existing valid project unchanged"
7551
+ ).option(
7552
+ "-n, --name <name>",
7553
+ "Project name (defaults to current directory name)"
7554
+ ).action(async (raw) => {
7555
+ const name = (raw.name ?? defaultProjectName).trim() || defaultProjectName;
7556
+ let result;
7557
+ try {
7558
+ result = await initProject(adapter, { name, version });
7559
+ } catch (error) {
7560
+ throw new CliExitError(
7561
+ `ShipBench files were not modified. ${error instanceof Error ? error.message : "Initialization failed."}`,
7562
+ 2
7563
+ );
7564
+ }
7565
+ if (!result.created && raw.name !== void 0 && result.config.name !== name) {
7566
+ throw new CliExitError(
7567
+ `ShipBench files were not modified. Existing project name "${result.config.name}" does not match --name "${name}".`,
7568
+ 2
7569
+ );
7570
+ }
7571
+ output.brand();
7572
+ for (const warning of result.warnings) {
7573
+ output.warning(formatProjectWarning(warning));
7574
+ }
7575
+ if (result.created) {
7576
+ chrome(`Initialized .shipbench/ for "${name}" in current directory.`);
7577
+ if (ancestorBoard !== void 0) {
7578
+ chrome(
7579
+ `Note: ${ancestorBoard} already has a .shipbench/ board. This one is separate, and tasks on one cannot depend on tasks on the other.`
7580
+ );
7581
+ }
7582
+ } else {
7583
+ chrome(`ShipBench is already initialized for "${result.config.name}".`);
7584
+ const behind = result.scaffold.filter((file) => file.version !== version);
7585
+ for (const file of behind) {
7586
+ chrome(
7587
+ file.version === null ? `${file.path} records no ShipBench version.` : `${file.path} was written by ShipBench ${file.version}; this is ${version}.`
7588
+ );
7589
+ }
7590
+ if (behind.length > 0) {
7591
+ chrome(`To update without losing your edits, see ${UPGRADING_URL}`);
7592
+ }
7593
+ }
7594
+ if (result.created) {
7595
+ for (const line of formatInitNextSteps()) chrome(line);
7596
+ }
7597
+ });
6893
7598
  }
7599
+
7600
+ // src/commands/taskQuery.ts
7601
+ import { InvalidArgumentError as InvalidArgumentError3, Option } from "commander";
6894
7602
  function assertKnownFilterValues(command, label, values, valid) {
6895
7603
  if (!values || values.length === 0) return;
6896
7604
  const validSet = new Set(valid);
@@ -6950,46 +7658,13 @@ function flagSuffix(task) {
6950
7658
  if (!flag) return "";
6951
7659
  return flag.reason ? ` \u2014 flagged: ${flag.reason}` : " \u2014 flagged";
6952
7660
  }
6953
- function parsePort(value) {
6954
- const port = Number(value);
6955
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
6956
- throw new InvalidArgumentError("Port must be an integer from 1 to 65535.");
6957
- }
6958
- return port;
6959
- }
6960
- function parseNonNegativeInteger(value) {
6961
- const parsed = Number(value);
6962
- if (!Number.isInteger(parsed) || parsed < 0) {
6963
- throw new InvalidArgumentError("Value must be a non-negative integer.");
6964
- }
6965
- return parsed;
6966
- }
6967
7661
  function parsePositiveInteger(value) {
6968
7662
  const parsed = Number(value);
6969
7663
  if (!Number.isInteger(parsed) || parsed < 1) {
6970
- throw new InvalidArgumentError("Value must be a positive integer.");
6971
- }
6972
- return parsed;
6973
- }
6974
- function parseLayoutPosition(value) {
6975
- const parsed = Number(value);
6976
- if (!Number.isInteger(parsed) || parsed < -1) {
6977
- throw new InvalidArgumentError(
6978
- "Position must be an integer of -1 or greater (-1 appends)."
6979
- );
7664
+ throw new InvalidArgumentError3("Value must be a positive integer.");
6980
7665
  }
6981
7666
  return parsed;
6982
7667
  }
6983
- function readPlacement(raw) {
6984
- if (raw.top) return { kind: "top" };
6985
- if (raw.bottom) return { kind: "bottom" };
6986
- if (raw.before !== void 0) return { kind: "before", anchor: raw.before };
6987
- if (raw.after !== void 0) return { kind: "after", anchor: raw.after };
6988
- if (raw.position !== void 0) {
6989
- return { kind: "position", index: raw.position };
6990
- }
6991
- return void 0;
6992
- }
6993
7668
  function orderTasksForBoard(tasks, config) {
6994
7669
  const validStatuses = new Set(config.columns.map((column) => column.id));
6995
7670
  const ordered = [];
@@ -7085,49 +7760,9 @@ function formatTaskDependencyQuery(query) {
7085
7760
  }
7086
7761
  return lines;
7087
7762
  }
7088
- function bodyOption() {
7089
- return new Option("--body <text>", "Description as Markdown text").conflicts([
7090
- "bodyFile"
7091
- ]);
7092
- }
7093
- function bodyFileOption() {
7094
- return new Option(
7095
- "--body-file <path>",
7096
- 'Read the description from a UTF-8 file; "-" reads stdin'
7097
- ).conflicts(["body"]);
7098
- }
7099
- function updateTextOption() {
7100
- return new Option("--body <text>", "Update text as Markdown").conflicts([
7101
- "bodyFile"
7102
- ]);
7103
- }
7104
- function updateTextFileOption() {
7105
- return new Option(
7106
- "--body-file <path>",
7107
- 'Read the update text from a UTF-8 file; "-" reads stdin'
7108
- ).conflicts(["body"]);
7109
- }
7110
- async function readProcessStdin() {
7111
- const chunks = [];
7112
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
7113
- return Buffer.concat(chunks).toString("utf8");
7114
- }
7115
- function enableExitOverride(command) {
7116
- command.exitOverride();
7117
- for (const child of command.commands) enableExitOverride(child);
7118
- }
7119
7763
  function formatUnreadableFile(file) {
7120
7764
  return `[unreadable] ${file.path}: ${file.reason} (${file.slug})`;
7121
7765
  }
7122
- function taskJson(task) {
7123
- return {
7124
- slug: task.slug,
7125
- status: task.frontmatter.status,
7126
- frontmatter: task.frontmatter,
7127
- body: task.body,
7128
- comments: task.comments
7129
- };
7130
- }
7131
7766
  function unreadableFileJson(file, includeBody) {
7132
7767
  return {
7133
7768
  slug: file.slug,
@@ -7136,707 +7771,50 @@ function unreadableFileJson(file, includeBody) {
7136
7771
  ...includeBody ? { content: file.content } : {}
7137
7772
  };
7138
7773
  }
7139
- function formatProjectWarning(warning) {
7140
- const source = "path" in warning ? warning.path : warning.slug;
7141
- return `${source}: ${warning.message}`;
7142
- }
7143
- function createCli(opts) {
7144
- const { adapter, defaultProjectName } = opts;
7145
- const cwd = opts.cwd ?? process.cwd();
7146
- const writeData = opts.out ?? ((line) => console.log(line));
7147
- const writeChrome = opts.err ?? ((line) => console.error(line));
7148
- const isInteractive = opts.isInteractive ?? process.stdout.isTTY === true;
7149
- const output = createCliOutput({
7150
- writeData,
7151
- writeChrome,
7152
- isStdoutTty: isInteractive,
7153
- env: opts.env ?? process.env
7154
- });
7155
- const { data, chrome } = output;
7156
- const missingBoardMessage = opts.missingBoardMessage ?? formatMissingBoard(`in ${cwd}`);
7157
- const requireBoard = async () => {
7158
- if (await adapter.readFileIfExists(CONFIG_PATH4) === null) {
7159
- throw new Error(missingBoardMessage);
7160
- }
7161
- };
7162
- const loadCliConfig = async () => {
7163
- try {
7164
- return await loadConfig(adapter, {
7165
- onWarning: (warning) => {
7166
- output.warning(`${warning.path}: ${warning.message}`);
7774
+ function registerTaskGet(task, ctx) {
7775
+ const { adapter, data, output } = ctx;
7776
+ const getTaskCommand = task.command("get <slug>").alias("show").description("Retrieve one task as JSON").option("--archived", "Retrieve the task from the archive instead").option(
7777
+ "--json",
7778
+ "Accepted for consistency; the output is JSON either way"
7779
+ );
7780
+ getTaskCommand.action(async (slug, raw) => {
7781
+ const config = await ctx.loadConfig();
7782
+ const found = await getTask(adapter, config, slug, {
7783
+ archived: raw.archived
7784
+ });
7785
+ if (!found) {
7786
+ if (!raw.archived) {
7787
+ const archived = await getTask(adapter, config, slug, {
7788
+ archived: true
7789
+ });
7790
+ if (archived) {
7791
+ getTaskCommand.error(
7792
+ `Task '${slug}' is archived. Pass --archived to retrieve.`
7793
+ );
7794
+ return;
7167
7795
  }
7168
- });
7169
- } catch (error) {
7170
- await requireBoard();
7171
- throw error;
7172
- }
7173
- };
7174
- const readTextFile = opts.readTextFile ?? ((path) => readFile3(path, "utf8"));
7175
- const readStdin = opts.readStdin ?? readProcessStdin;
7176
- const resolveBody = async (raw) => {
7177
- if (raw.bodyFile === void 0) return raw.body;
7178
- if (raw.bodyFile === "-") return readStdin();
7179
- try {
7180
- return await readTextFile(raw.bodyFile);
7181
- } catch (error) {
7182
- throw new Error(
7183
- `Cannot read --body-file "${raw.bodyFile}": ${error instanceof Error ? error.message : String(error)}`
7184
- );
7796
+ }
7797
+ getTaskCommand.error(`Task '${slug}' not found.`);
7798
+ return;
7185
7799
  }
7186
- };
7187
- const resolveUpdateText = async (command, positional, raw) => {
7188
- const fromOption = await resolveBody(raw);
7189
- if (positional != null && fromOption !== void 0) {
7190
- command.error(
7191
- "Pass the update text once: either positionally or with --body / --body-file, not both."
7192
- );
7193
- return void 0;
7800
+ const updatesWarning = unreadableUpdatesWarning(found);
7801
+ if (updatesWarning) {
7802
+ output.warning(`${found.slug}: ${updatesWarning.message}`);
7194
7803
  }
7195
- return positional ?? fromOption;
7196
- };
7197
- const requireLiveTask = async (command, config, slug, action) => {
7198
- const existing = await getTask(adapter, config, slug);
7199
- if (existing) return existing;
7200
- const archived = await getTask(adapter, config, slug, { archived: true });
7201
- command.error(
7202
- archived ? `Task '${slug}' is archived. Unarchive it before ${action}.` : `Task '${slug}' not found.`
7203
- );
7204
- return null;
7205
- };
7206
- const printTask = (task2) => data(JSON.stringify(taskJson(task2), null, 2));
7207
- const program = new Command().name("shipbench").description("Git-native project management for solo developers.").enablePositionalOptions().version(VERSION, "-v, --version", "output the version").option(
7208
- "-C <path>",
7209
- "Use the board in the specified directory, without searching above it"
7210
- );
7211
- const writingCommands = /* @__PURE__ */ new Set([
7212
- "task create",
7213
- "task edit",
7214
- "task comment",
7215
- "task comment edit",
7216
- "task comment delete",
7217
- "task flag",
7218
- "task unflag",
7219
- "task move",
7220
- "task archive",
7221
- "task unarchive",
7222
- "task delete"
7223
- ]);
7224
- if (opts.searchedFrom !== void 0 && opts.searchedFrom !== cwd) {
7225
- program.hook("preAction", (_root, action) => {
7226
- const names = [];
7227
- for (let command = action; command?.parent; ) {
7228
- names.unshift(command.name());
7229
- command = command.parent;
7230
- }
7231
- if (writingCommands.has(names.join(" "))) {
7232
- chrome(`Using .shipbench/ from ${cwd}`);
7233
- }
7234
- });
7235
- }
7236
- program.configureOutput({
7237
- writeOut: (line) => data(line.replace(/\n$/, "")),
7238
- writeErr: (line) => chrome(line.replace(/\n$/, ""))
7239
- });
7240
- program.command("init").description(
7241
- "Initialize ShipBench in the current repository; leave an existing valid project unchanged"
7242
- ).option(
7243
- "-n, --name <name>",
7244
- "Project name (defaults to current directory name)"
7245
- ).action(async (raw) => {
7246
- const name = (raw.name ?? defaultProjectName).trim() || defaultProjectName;
7247
- let result;
7248
- try {
7249
- result = await initProject(adapter, { name });
7250
- } catch (error) {
7251
- throw new CliExitError(
7252
- `ShipBench files were not modified. ${error instanceof Error ? error.message : "Initialization failed."}`,
7253
- 2
7254
- );
7255
- }
7256
- if (!result.created && raw.name !== void 0 && result.config.name !== name) {
7257
- throw new CliExitError(
7258
- `ShipBench files were not modified. Existing project name "${result.config.name}" does not match --name "${name}".`,
7259
- 2
7260
- );
7261
- }
7262
- output.brand();
7263
- for (const warning of result.warnings) {
7264
- output.warning(formatProjectWarning(warning));
7265
- }
7266
- if (result.created) {
7267
- chrome(`Initialized .shipbench/ for "${name}" in current directory.`);
7268
- if (opts.ancestorBoard !== void 0) {
7269
- chrome(
7270
- `Note: ${opts.ancestorBoard} already has a .shipbench/ board. This one is separate, and tasks on one cannot depend on tasks on the other.`
7271
- );
7272
- }
7273
- } else {
7274
- chrome(`ShipBench is already initialized for "${result.config.name}".`);
7275
- }
7276
- if (result.created) {
7277
- for (const line of formatInitNextSteps()) chrome(line);
7278
- }
7279
- });
7280
- const task = program.command("task").description("Manage tasks");
7281
- task.command("create <title>").description("Create a new task").option("-s, --status <status>", "Column to place the task in").option("-a, --assignee <assignee>", "Assignee label").option("-p, --priority <priority>", "Priority value").option(
7282
- "-t, --tags <tags>",
7283
- "Tags (comma-separated, repeatable)",
7284
- accumulateCommaList
7285
- ).option(
7286
- "-d, --depends-on <slugs>",
7287
- "Slugs this task depends on (comma-separated, repeatable)",
7288
- accumulateCommaList,
7289
- []
7290
- ).option(
7291
- "--related <slugs>",
7292
- "Slugs of live or archived tasks this one relates to, without depending on them (comma-separated, repeatable)",
7293
- accumulateCommaList,
7294
- []
7295
- ).addOption(bodyOption()).addOption(bodyFileOption()).option("--json", "Output the created task as JSON").addHelpText(
7296
- "after",
7297
- "\nPrefer --body-file for anything multi-line: the file is read as UTF-8 by\nShipBench, so the description never passes through shell quoting or encoding.\n"
7298
- ).action(async (title, raw) => {
7299
- const body = await resolveBody(raw);
7300
- const config = await loadCliConfig();
7301
- const created = await createTask(
7302
- adapter,
7303
- config,
7304
- title,
7305
- {
7306
- status: raw.status,
7307
- assignee: raw.assignee,
7308
- priority: raw.priority,
7309
- tags: raw.tags && dedupePreservingCase(raw.tags),
7310
- depends_on: raw.dependsOn,
7311
- related: raw.related
7312
- },
7313
- body
7314
- );
7315
- if (raw.json) {
7316
- printTask(created);
7317
- return;
7318
- }
7319
- chrome(`Created task: ${created.slug}`);
7320
- });
7321
- const commaListOption = (flags, description) => new Option(flags, description).argParser(accumulateCommaList);
7322
- const editCommand = task.command("edit <slug>").description("Revise a task's description or its validated metadata").option(
7323
- "--title <text>",
7324
- "Set the title (the slug and filename do not change)"
7325
- ).option("-p, --priority <value>", "Set the priority").addOption(
7326
- new Option("-a, --assignee <label>", "Set the assignee label").conflicts([
7327
- "clearAssignee"
7328
- ])
7329
- ).addOption(
7330
- new Option("--clear-assignee", "Remove the assignee").conflicts([
7331
- "assignee"
7332
- ])
7333
- ).addOption(
7334
- commaListOption(
7335
- "-t, --tags <tags>",
7336
- "Replace every tag (comma-separated or repeatable)"
7337
- ).conflicts(["addTag", "removeTag", "clearTags"])
7338
- ).addOption(
7339
- commaListOption(
7340
- "--add-tag <tags>",
7341
- "Add tags, keeping the others (comma-separated or repeatable)"
7342
- ).conflicts(["tags", "clearTags"])
7343
- ).addOption(
7344
- commaListOption(
7345
- "--remove-tag <tags>",
7346
- "Remove tags, keeping the others (comma-separated or repeatable)"
7347
- ).conflicts(["tags", "clearTags"])
7348
- ).addOption(
7349
- new Option("--clear-tags", "Remove every tag").conflicts([
7350
- "tags",
7351
- "addTag",
7352
- "removeTag"
7353
- ])
7354
- ).addOption(
7355
- commaListOption(
7356
- "-d, --depends-on <slugs>",
7357
- "Replace every dependency (comma-separated or repeatable)"
7358
- ).conflicts(["addDependsOn", "removeDependsOn", "clearDependsOn"])
7359
- ).addOption(
7360
- commaListOption(
7361
- "--add-depends-on <slugs>",
7362
- "Add dependencies, keeping the others (comma-separated or repeatable)"
7363
- ).conflicts(["dependsOn", "clearDependsOn"])
7364
- ).addOption(
7365
- commaListOption(
7366
- "--remove-depends-on <slugs>",
7367
- "Remove dependencies, keeping the others (comma-separated or repeatable)"
7368
- ).conflicts(["dependsOn", "clearDependsOn"])
7369
- ).addOption(
7370
- new Option("--clear-depends-on", "Remove every dependency").conflicts([
7371
- "dependsOn",
7372
- "addDependsOn",
7373
- "removeDependsOn"
7374
- ])
7375
- ).addOption(
7376
- commaListOption(
7377
- "--related <slugs>",
7378
- "Replace every related task (comma-separated or repeatable)"
7379
- ).conflicts(["addRelated", "removeRelated", "clearRelated"])
7380
- ).addOption(
7381
- commaListOption(
7382
- "--add-related <slugs>",
7383
- "Add related tasks, keeping the others (comma-separated or repeatable)"
7384
- ).conflicts(["related", "clearRelated"])
7385
- ).addOption(
7386
- commaListOption(
7387
- "--remove-related <slugs>",
7388
- "Remove related tasks, keeping the others (comma-separated or repeatable)"
7389
- ).conflicts(["related", "clearRelated"])
7390
- ).addOption(
7391
- new Option(
7392
- "--clear-related",
7393
- "Remove every related task this task's file records"
7394
- ).conflicts(["related", "addRelated", "removeRelated"])
7395
- ).addOption(bodyOption()).addOption(bodyFileOption()).option("--json", "Output the edited task as JSON").addHelpText(
7396
- "after",
7397
- "\nPass at least one change. Every change is applied in a single validated\nwrite: if any value is rejected the task is left exactly as it was. Status\nand board placement stay with `shipbench task move`; the Task Updates section\nstays with `shipbench task comment`. A title edit never renames the file.\n"
7398
- );
7399
- editCommand.action(async (slug, raw) => {
7400
- const body = await resolveBody(raw);
7401
- const clearAssignee = Boolean(raw.clearAssignee);
7402
- const clearTags = Boolean(raw.clearTags);
7403
- const clearDependsOn = Boolean(raw.clearDependsOn);
7404
- const addTag = raw.addTag;
7405
- const removeTag = raw.removeTag;
7406
- const replaceTags = raw.tags;
7407
- const addDependsOn = raw.addDependsOn;
7408
- const removeDependsOn = raw.removeDependsOn;
7409
- const replaceDependsOn = raw.dependsOn;
7410
- const clearRelated = Boolean(raw.clearRelated);
7411
- const addRelated = raw.addRelated;
7412
- const removeRelated = raw.removeRelated;
7413
- const replaceRelated = raw.related;
7414
- const requestedAnything = body !== void 0 || raw.title !== void 0 || raw.priority !== void 0 || raw.assignee !== void 0 || clearAssignee || replaceTags !== void 0 || addTag !== void 0 || removeTag !== void 0 || clearTags || replaceDependsOn !== void 0 || addDependsOn !== void 0 || removeDependsOn !== void 0 || clearDependsOn || replaceRelated !== void 0 || addRelated !== void 0 || removeRelated !== void 0 || clearRelated;
7415
- if (!requestedAnything) {
7416
- editCommand.error(
7417
- "Provide at least one change: --body/--body-file, --title, --priority, --assignee/--clear-assignee, --tags/--add-tag/--remove-tag/--clear-tags, --depends-on/--add-depends-on/--remove-depends-on/--clear-depends-on, or --related/--add-related/--remove-related/--clear-related."
7418
- );
7419
- return;
7420
- }
7421
- const config = await loadCliConfig();
7422
- const existing = await requireLiveTask(
7423
- editCommand,
7424
- config,
7425
- slug,
7426
- "editing"
7427
- );
7428
- if (!existing) return;
7429
- const before = existing.frontmatter;
7430
- const fields = {};
7431
- const changes = [];
7432
- const list = (values) => values.length > 0 ? `[${values.join(", ")}]` : "(none)";
7433
- if (raw.title !== void 0 && raw.title !== before.title) {
7434
- fields.title = raw.title;
7435
- changes.push(`title "${before.title}" \u2192 "${raw.title}"`);
7436
- }
7437
- if (raw.priority !== void 0 && raw.priority !== before.priority) {
7438
- fields.priority = raw.priority;
7439
- changes.push(
7440
- `priority ${before.priority ?? "(unset)"} \u2192 ${raw.priority}`
7441
- );
7442
- }
7443
- if (raw.assignee !== void 0) {
7444
- if (raw.assignee !== (before.assignee ?? void 0)) {
7445
- fields.assignee = raw.assignee;
7446
- changes.push(
7447
- `assignee ${before.assignee ?? "(unset)"} \u2192 ${raw.assignee}`
7448
- );
7449
- }
7450
- } else if (clearAssignee && before.assignee !== void 0) {
7451
- fields.assignee = void 0;
7452
- changes.push(`assignee ${before.assignee} \u2192 (unset)`);
7453
- }
7454
- const currentTags = before.tags ?? [];
7455
- let nextTags;
7456
- if (replaceTags !== void 0) {
7457
- nextTags = dedupePreservingCase(replaceTags);
7458
- } else if (clearTags) {
7459
- nextTags = [];
7460
- } else if (addTag !== void 0 || removeTag !== void 0) {
7461
- const removed = new Set((removeTag ?? []).map((tag) => tag.toLowerCase()));
7462
- nextTags = dedupePreservingCase([
7463
- ...currentTags.filter((tag) => !removed.has(tag.toLowerCase())),
7464
- ...addTag ?? []
7465
- ]);
7466
- }
7467
- if (nextTags !== void 0 && (nextTags.length !== currentTags.length || nextTags.some((tag, index) => tag !== currentTags[index]))) {
7468
- fields.tags = nextTags.length > 0 ? nextTags : void 0;
7469
- changes.push(`tags ${list(currentTags)} \u2192 ${list(nextTags)}`);
7470
- }
7471
- const currentDeps = before.depends_on ?? [];
7472
- let nextDeps;
7473
- if (replaceDependsOn !== void 0) {
7474
- nextDeps = dedupePreservingCase(replaceDependsOn);
7475
- } else if (clearDependsOn) {
7476
- nextDeps = [];
7477
- } else if (addDependsOn !== void 0 || removeDependsOn !== void 0) {
7478
- const removed = new Set(removeDependsOn ?? []);
7479
- nextDeps = dedupePreservingCase([
7480
- ...currentDeps.filter((dep) => !removed.has(dep)),
7481
- ...addDependsOn ?? []
7482
- ]);
7483
- }
7484
- if (nextDeps !== void 0 && (nextDeps.length !== currentDeps.length || nextDeps.some((dep, index) => dep !== currentDeps[index]))) {
7485
- fields.depends_on = nextDeps;
7486
- changes.push(`depends_on ${list(currentDeps)} \u2192 ${list(nextDeps)}`);
7487
- }
7488
- const currentRelated = relatedSlugs(existing);
7489
- let nextRelated;
7490
- if (replaceRelated !== void 0) {
7491
- nextRelated = dedupePreservingCase(replaceRelated);
7492
- } else if (clearRelated) {
7493
- nextRelated = [];
7494
- } else if (addRelated !== void 0 || removeRelated !== void 0) {
7495
- const notOwn = (removeRelated ?? []).filter(
7496
- (target) => !currentRelated.includes(target)
7497
- );
7498
- if (notOwn.length > 0) {
7499
- const [live, archived] = await Promise.all([
7500
- listTasks(adapter, config),
7501
- listArchivedTasks(adapter, config)
7502
- ]);
7503
- const holds = (candidate, target) => candidate.slug === target && relatedSlugs(candidate).includes(slug);
7504
- for (const target of notOwn) {
7505
- if (live.tasks.some((candidate) => holds(candidate, target))) {
7506
- editCommand.error(
7507
- `Cannot remove related task "${target}" from ${slug}: the link is recorded in ${target}'s file, not this one. Remove it there: shipbench task edit ${target} --remove-related ${slug}`
7508
- );
7509
- return;
7510
- }
7511
- if (archived.tasks.some((candidate) => holds(candidate, target))) {
7512
- editCommand.error(
7513
- `Cannot remove related task "${target}" from ${slug}: the link is recorded in the archived task ${target}'s file, not this one. Unarchive ${target} to edit it.`
7514
- );
7515
- return;
7516
- }
7517
- }
7518
- }
7519
- const removed = new Set(removeRelated ?? []);
7520
- nextRelated = dedupePreservingCase([
7521
- ...currentRelated.filter((target) => !removed.has(target)),
7522
- ...addRelated ?? []
7523
- ]);
7524
- }
7525
- if (nextRelated !== void 0 && (nextRelated.length !== currentRelated.length || nextRelated.some((target, index) => target !== currentRelated[index]))) {
7526
- fields.related = nextRelated;
7527
- changes.push(`related ${list(currentRelated)} \u2192 ${list(nextRelated)}`);
7528
- }
7529
- if (body !== void 0) {
7530
- changes.push(body.trim() ? "description" : "description cleared");
7531
- }
7532
- if (changes.length === 0) {
7533
- if (raw.json) {
7534
- printTask(existing);
7535
- return;
7536
- }
7537
- chrome(`No changes for ${slug}: every field already holds that value.`);
7538
- return;
7539
- }
7540
- const { task: edited } = await updateTask(
7541
- adapter,
7542
- config,
7543
- slug,
7544
- fields,
7545
- body
7546
- );
7547
- if (raw.json) {
7548
- printTask(edited);
7549
- return;
7550
- }
7551
- chrome(`Updated ${edited.slug}: ${changes.join("; ")}`);
7552
- if (fields.title !== void 0) {
7553
- chrome(`Slug and filename unchanged: ${edited.slug}`);
7554
- }
7555
- });
7556
- const BODY_FILE_HELP = "\nPrefer --body-file for anything multi-line: the file is read as UTF-8 by\nShipBench, so the text never passes through shell quoting or encoding.\n";
7557
- const commentCommand = task.command("comment").description("Manage timestamped entries in the task Updates section").argument("[slug]", "Task slug").argument("[text]", "Update text").addOption(updateTextOption()).addOption(updateTextFileOption()).option("--json", "Output the resulting task as JSON").addHelpText("after", BODY_FILE_HELP);
7558
- commentCommand.action(async (slug, text, raw) => {
7559
- const resolved = await resolveUpdateText(commentCommand, text, raw);
7560
- if (!slug || resolved === void 0) {
7561
- throw new InvalidArgumentError(
7562
- "Append requires a task slug and update text (positional, --body <text>, or --body-file <path>)."
7563
- );
7564
- }
7565
- const config = await loadCliConfig();
7566
- const updated = await addComment(adapter, config, slug, resolved);
7567
- if (raw.json) {
7568
- printTask(updated);
7569
- return;
7570
- }
7571
- chrome(`Added update to ${updated.slug}`);
7572
- });
7573
- const commentEditCommand = commentCommand.command("edit <slug> <index> [text]").description(
7574
- "Edit an Updates entry by zero-based index without changing its timestamp"
7575
- ).addOption(updateTextOption()).addOption(updateTextFileOption()).option("--json", "Output the resulting task as JSON").addHelpText("after", BODY_FILE_HELP);
7576
- commentEditCommand.action(async (slug, index, text, raw) => {
7577
- const resolved = await resolveUpdateText(commentEditCommand, text, raw);
7578
- if (resolved === void 0) {
7579
- commentEditCommand.error(
7580
- "Provide the replacement text positionally, or with --body <text> or --body-file <path>."
7581
- );
7582
- return;
7583
- }
7584
- const config = await loadCliConfig();
7585
- const parsedIndex = parseNonNegativeInteger(index);
7586
- const updated = await editComment(
7587
- adapter,
7588
- config,
7589
- slug,
7590
- parsedIndex,
7591
- resolved
7592
- );
7593
- if (raw.json) {
7594
- printTask(updated);
7595
- return;
7596
- }
7597
- chrome(`Edited update ${parsedIndex} on ${updated.slug}`);
7598
- });
7599
- commentCommand.command("delete <slug> <index>").description("Delete an Updates entry by zero-based index").option("--json", "Output the resulting task as JSON").action(async (slug, index, raw) => {
7600
- const config = await loadCliConfig();
7601
- const parsedIndex = parseNonNegativeInteger(index);
7602
- const updated = await deleteComment(adapter, config, slug, parsedIndex);
7603
- if (raw.json) {
7604
- printTask(updated);
7605
- return;
7606
- }
7607
- chrome(`Deleted update ${parsedIndex} from ${updated.slug}`);
7608
- });
7609
- const getTaskCommand = task.command("get <slug>").alias("show").description("Retrieve one task as JSON").option("--archived", "Retrieve the task from the archive instead").option(
7610
- "--json",
7611
- "Accepted for consistency; the output is JSON either way"
7612
- );
7613
- getTaskCommand.action(async (slug, raw) => {
7614
- const config = await loadCliConfig();
7615
- const found = await getTask(adapter, config, slug, {
7616
- archived: raw.archived
7617
- });
7618
- if (!found) {
7619
- if (!raw.archived) {
7620
- const archived = await getTask(adapter, config, slug, {
7621
- archived: true
7622
- });
7623
- if (archived) {
7624
- getTaskCommand.error(
7625
- `Task '${slug}' is archived. Pass --archived to retrieve.`
7626
- );
7627
- return;
7628
- }
7629
- }
7630
- getTaskCommand.error(`Task '${slug}' not found.`);
7631
- return;
7632
- }
7633
- const updatesWarning = unreadableUpdatesWarning(found);
7634
- if (updatesWarning) {
7635
- output.warning(`${found.slug}: ${updatesWarning.message}`);
7636
- }
7637
- data(
7638
- JSON.stringify(
7639
- {
7640
- ...taskJson(found),
7641
- ...found.unreadableUpdates ? { unreadable_updates: found.unreadableUpdates } : {}
7642
- },
7643
- null,
7644
- 2
7645
- )
7646
- );
7647
- });
7648
- const flagCommand = task.command("flag <slug> [reason]").description("Flag a task for attention, with an optional one-line reason").option("--json", "Output the resulting task as JSON").addHelpText(
7649
- "after",
7650
- "\nWhat a flag means is the project's call. A flag never moves the task, and\nnothing clears it for you: run `shipbench task unflag <slug>` once it no\nlonger applies. Flagging a flagged task replaces its reason.\n"
7651
- );
7652
- flagCommand.action(
7653
- async (slug, reason, raw) => {
7654
- const config = await loadCliConfig();
7655
- const existing = await requireLiveTask(
7656
- flagCommand,
7657
- config,
7658
- slug,
7659
- "flagging"
7660
- );
7661
- if (!existing) return;
7662
- const flag = reason == null ? true : reason;
7663
- const before = taskFlag(existing);
7664
- if (before && before.reason === (flag === true ? null : flag.trim())) {
7665
- if (raw.json) {
7666
- printTask(existing);
7667
- return;
7668
- }
7669
- chrome(`No changes for ${slug}: it already carries that flag.`);
7670
- return;
7671
- }
7672
- const { task: flagged } = await updateTask(adapter, config, slug, {
7673
- flag
7674
- });
7675
- if (raw.json) {
7676
- printTask(flagged);
7677
- return;
7678
- }
7679
- const after = taskFlag(flagged);
7680
- chrome(
7681
- after?.reason ? `Flagged ${flagged.slug}: ${after.reason}` : `Flagged ${flagged.slug}`
7682
- );
7683
- }
7684
- );
7685
- const unflagCommand = task.command("unflag <slug>").description("Clear a task's flag").option("--json", "Output the resulting task as JSON");
7686
- unflagCommand.action(async (slug, raw) => {
7687
- const config = await loadCliConfig();
7688
- const existing = await requireLiveTask(
7689
- unflagCommand,
7690
- config,
7691
- slug,
7692
- "unflagging"
7693
- );
7694
- if (!existing) return;
7695
- if (existing.frontmatter.flag === void 0) {
7696
- if (raw.json) {
7697
- printTask(existing);
7698
- return;
7699
- }
7700
- chrome(`No changes for ${slug}: it is not flagged.`);
7701
- return;
7702
- }
7703
- const { task: unflagged } = await updateTask(adapter, config, slug, {
7704
- flag: void 0
7705
- });
7706
- if (raw.json) {
7707
- printTask(unflagged);
7708
- return;
7709
- }
7710
- chrome(`Unflagged ${slug}`);
7711
- });
7712
- const moveCommand = task.command("move <slug>").description("Move a task to another column and/or another position").option(
7713
- "-t, --to <status>",
7714
- "Target column (defaults to the task's current column)"
7715
- ).addOption(
7716
- new Option("--top", "Place first in the destination column").conflicts([
7717
- "bottom",
7718
- "before",
7719
- "after",
7720
- "position"
7721
- ])
7722
- ).addOption(
7723
- new Option("--bottom", "Place last in the destination column").conflicts([
7724
- "top",
7725
- "before",
7726
- "after",
7727
- "position"
7728
- ])
7729
- ).addOption(
7730
- new Option(
7731
- "--before <slug>",
7732
- "Place immediately before this task"
7733
- ).conflicts(["top", "bottom", "after", "position"])
7734
- ).addOption(
7735
- new Option(
7736
- "--after <slug>",
7737
- "Place immediately after this task"
7738
- ).conflicts(["top", "bottom", "before", "position"])
7739
- ).addOption(
7740
- new Option("--position <n>", "Place at this 0-based index (-1 appends)").argParser(parseLayoutPosition).conflicts(["top", "bottom", "before", "after"])
7741
- ).option("--json", "Output the resulting task as JSON").addHelpText(
7742
- "after",
7743
- "\nPlacement flags are mutually exclusive and cannot target the done column,\nwhich is always ordered by last update. Reorder only when asked to.\n"
7744
- ).action(async (slug, raw) => {
7745
- const config = await loadCliConfig();
7746
- const placement = readPlacement(raw);
7747
- if (!placement) {
7748
- if (raw.to === void 0) {
7749
- moveCommand.error(
7750
- "Provide --to, a placement flag (--top, --bottom, --before, --after, --position), or both."
7751
- );
7752
- return;
7753
- }
7754
- const moved2 = await moveTask(adapter, config, slug, raw.to);
7755
- if (raw.json) {
7756
- printTask(moved2);
7757
- return;
7758
- }
7759
- chrome(`Moved ${moved2.slug} \u2192 ${moved2.frontmatter.status}`);
7760
- return;
7761
- }
7762
- const { tasks } = await listTasks(adapter, config);
7763
- const target = tasks.find((candidate) => candidate.slug === slug);
7764
- if (!target) {
7765
- moveCommand.error(`Task '${slug}' not found.`);
7766
- return;
7767
- }
7768
- const toStatus = raw.to ?? target.frontmatter.status;
7769
- const validStatuses = new Set(config.columns.map((column2) => column2.id));
7770
- if (!validStatuses.has(toStatus)) {
7771
- moveCommand.error(
7772
- `Invalid status "${toStatus}". Valid: ${[...validStatuses].join(", ")}`
7773
- );
7774
- return;
7775
- }
7776
- if (toStatus === config.done_column) {
7777
- moveCommand.error(
7778
- `The '${toStatus}' column carries no manual order \u2014 it is always sorted by last update. Move without a placement flag.`
7779
- );
7780
- return;
7781
- }
7782
- const column = orderedTasksForColumn(
7783
- tasks,
7784
- config.layout,
7785
- toStatus,
7786
- validStatuses,
7787
- config.done_column
7788
- ).filter((candidate) => candidate.slug !== slug);
7789
- let position;
7790
- if (placement.kind === "top") {
7791
- position = 0;
7792
- } else if (placement.kind === "bottom") {
7793
- position = -1;
7794
- } else if (placement.kind === "position") {
7795
- position = placement.index;
7796
- } else {
7797
- const { anchor } = placement;
7798
- if (anchor === slug) {
7799
- moveCommand.error(`Cannot place '${slug}' ${placement.kind} itself.`);
7800
- return;
7801
- }
7802
- const anchorIndex = column.findIndex(
7803
- (candidate) => candidate.slug === anchor
7804
- );
7805
- if (anchorIndex === -1) {
7806
- const live = tasks.find((candidate) => candidate.slug === anchor);
7807
- if (live) {
7808
- moveCommand.error(
7809
- `Anchor task '${anchor}' is in the '${live.frontmatter.status}' column, not '${toStatus}'.`
7810
- );
7811
- } else if (await getTask(adapter, config, anchor, { archived: true })) {
7812
- moveCommand.error(
7813
- `Anchor task '${anchor}' is archived and is not on the board.`
7814
- );
7815
- } else {
7816
- moveCommand.error(`Anchor task '${anchor}' not found.`);
7817
- }
7818
- return;
7819
- }
7820
- position = placement.kind === "before" ? anchorIndex : anchorIndex + 1;
7821
- }
7822
- const fromStatus = target.frontmatter.status;
7823
- const { task: moved } = await reorderTask(
7824
- adapter,
7825
- config,
7826
- slug,
7827
- toStatus,
7828
- position
7829
- );
7830
- if (raw.json) {
7831
- printTask(moved);
7832
- return;
7833
- }
7834
- const placedAt = position < 0 || position > column.length ? column.length : position;
7835
- chrome(
7836
- fromStatus === toStatus ? `Reordered ${moved.slug} in ${toStatus} \u2192 position ${placedAt} of ${column.length + 1}` : `Moved ${moved.slug} \u2192 ${toStatus} at position ${placedAt} of ${column.length + 1}`
7804
+ data(
7805
+ JSON.stringify(
7806
+ {
7807
+ ...taskJson(found),
7808
+ ...found.unreadableUpdates ? { unreadable_updates: found.unreadableUpdates } : {}
7809
+ },
7810
+ null,
7811
+ 2
7812
+ )
7837
7813
  );
7838
- chrome("Wrote .shipbench/layout.json");
7839
7814
  });
7815
+ }
7816
+ function registerTaskQueries(task, ctx) {
7817
+ const { adapter, data, chrome, isInteractive } = ctx;
7840
7818
  const listCommand = task.command("list").description("List live tasks in board order, optionally filtered");
7841
7819
  listCommand.addOption(
7842
7820
  new Option(
@@ -7880,11 +7858,11 @@ function createCli(opts) {
7880
7858
  "Include Markdown descriptions and Updates in JSON output"
7881
7859
  ).action(async (raw) => {
7882
7860
  if (raw.archived && (raw.available || raw.blocked)) {
7883
- throw new InvalidArgumentError(
7861
+ throw new InvalidArgumentError3(
7884
7862
  "--available and --blocked cannot be used with --archived."
7885
7863
  );
7886
7864
  }
7887
- const config = await loadCliConfig();
7865
+ const config = await ctx.loadConfig();
7888
7866
  const filters = resolveTaskFilters(listCommand, raw, config);
7889
7867
  const availabilityStatus = filters.statuses.length > 0 ? filters.statuses : void 0;
7890
7868
  const archivedPromise = raw.archived ? void 0 : listArchivedTasks(adapter, config);
@@ -8010,14 +7988,14 @@ function createCli(opts) {
8010
7988
  "Include full descriptions and Task Updates in JSON output"
8011
7989
  ).action(async (query, raw) => {
8012
7990
  if (!query.trim()) {
8013
- throw new InvalidArgumentError("Search query must not be blank.");
7991
+ throw new InvalidArgumentError3("Search query must not be blank.");
8014
7992
  }
8015
7993
  if ((raw.available || raw.blocked) && (raw.archived || raw.all)) {
8016
- throw new InvalidArgumentError(
7994
+ throw new InvalidArgumentError3(
8017
7995
  "--available and --blocked cannot be used with --archived or --all."
8018
7996
  );
8019
7997
  }
8020
- const config = await loadCliConfig();
7998
+ const config = await ctx.loadConfig();
8021
7999
  const filters = resolveTaskFilters(searchCommand, raw, config);
8022
8000
  const availabilityStatus = filters.statuses.length > 0 ? filters.statuses : void 0;
8023
8001
  const searchArchive = Boolean(raw.archived || raw.all);
@@ -8151,7 +8129,7 @@ function createCli(opts) {
8151
8129
  parsePositiveInteger
8152
8130
  ).option("--json", "Emit machine-readable JSON");
8153
8131
  graphCommand.action(async (slug, raw) => {
8154
- const config = await loadCliConfig();
8132
+ const config = await ctx.loadConfig();
8155
8133
  if (slug === void 0) {
8156
8134
  if (raw.blockers || raw.dependents || raw.depth !== void 0) {
8157
8135
  graphCommand.error(
@@ -8159,183 +8137,907 @@ function createCli(opts) {
8159
8137
  );
8160
8138
  return;
8161
8139
  }
8162
- }
8163
- const liveResult = await listTasks(adapter, config);
8164
- const archivedResult = raw.archived ? await listArchivedTasks(adapter, config) : void 0;
8165
- if (slug !== void 0) {
8166
- const query = queryTaskDependencies(slug, liveResult.tasks, config, {
8167
- direction: raw.blockers && !raw.dependents ? "blockers" : raw.dependents && !raw.blockers ? "dependents" : "both",
8168
- depth: raw.depth,
8169
- archivedTasks: archivedResult?.tasks,
8170
- // Readiness matches `task list`: an archived dependency is
8171
- // satisfied whether or not --archived walks into it.
8172
- archivedSlugs: archivedResult ? taskFileSlugs(archivedResult) : liveResult.archivedSlugs,
8173
- unreadableSlugs: liveResult.unreadable.map((file) => file.slug)
8174
- });
8175
- if (!query) {
8176
- if (!raw.archived && liveResult.archivedSlugs?.includes(slug)) {
8177
- graphCommand.error(
8178
- `Task '${slug}' is archived. Pass --archived to query it.`
8140
+ }
8141
+ const liveResult = await listTasks(adapter, config);
8142
+ const archivedResult = raw.archived ? await listArchivedTasks(adapter, config) : void 0;
8143
+ if (slug !== void 0) {
8144
+ const query = queryTaskDependencies(slug, liveResult.tasks, config, {
8145
+ direction: raw.blockers && !raw.dependents ? "blockers" : raw.dependents && !raw.blockers ? "dependents" : "both",
8146
+ depth: raw.depth,
8147
+ archivedTasks: archivedResult?.tasks,
8148
+ // Readiness matches `task list`: an archived dependency is
8149
+ // satisfied whether or not --archived walks into it.
8150
+ archivedSlugs: archivedResult ? taskFileSlugs(archivedResult) : liveResult.archivedSlugs,
8151
+ unreadableSlugs: liveResult.unreadable.map((file) => file.slug)
8152
+ });
8153
+ if (!query) {
8154
+ if (!raw.archived && liveResult.archivedSlugs?.includes(slug)) {
8155
+ graphCommand.error(
8156
+ `Task '${slug}' is archived. Pass --archived to query it.`
8157
+ );
8158
+ } else {
8159
+ graphCommand.error(`Task '${slug}' not found.`);
8160
+ }
8161
+ return;
8162
+ }
8163
+ if (raw.json || !isInteractive) {
8164
+ data(JSON.stringify(query, null, 2));
8165
+ return;
8166
+ }
8167
+ for (const line of formatTaskDependencyQuery(query)) data(line);
8168
+ return;
8169
+ }
8170
+ const graph = buildTaskDependencyGraph(liveResult.tasks, {
8171
+ archivedTasks: archivedResult?.tasks,
8172
+ archivedSlugs: archivedResult ? taskFileSlugs(archivedResult) : void 0
8173
+ });
8174
+ if (raw.json || !isInteractive) {
8175
+ data(JSON.stringify(graph, null, 2));
8176
+ return;
8177
+ }
8178
+ for (const line of formatTaskDependencyGraph(graph)) data(line);
8179
+ });
8180
+ }
8181
+
8182
+ // src/commands/taskState.ts
8183
+ import { InvalidArgumentError as InvalidArgumentError4, Option as Option2 } from "commander";
8184
+ function parseLayoutPosition(value) {
8185
+ const parsed = Number(value);
8186
+ if (!Number.isInteger(parsed) || parsed < -1) {
8187
+ throw new InvalidArgumentError4(
8188
+ "Position must be an integer of -1 or greater (-1 appends)."
8189
+ );
8190
+ }
8191
+ return parsed;
8192
+ }
8193
+ function readPlacement(raw) {
8194
+ if (raw.top) return { kind: "top" };
8195
+ if (raw.bottom) return { kind: "bottom" };
8196
+ if (raw.before !== void 0) return { kind: "before", anchor: raw.before };
8197
+ if (raw.after !== void 0) return { kind: "after", anchor: raw.after };
8198
+ if (raw.position !== void 0) {
8199
+ return { kind: "position", index: raw.position };
8200
+ }
8201
+ return void 0;
8202
+ }
8203
+ function registerTaskState(task, ctx) {
8204
+ const { adapter, chrome, printTask } = ctx;
8205
+ const flagCommand = task.command("flag <slug> [reason]").description("Flag a task for attention, with an optional one-line reason").option("--json", "Output the resulting task as JSON").addHelpText(
8206
+ "after",
8207
+ "\nWhat a flag means is the project's call. A flag never moves the task, and\nnothing clears it for you: run `shipbench task unflag <slug>` once it no\nlonger applies. Flagging a flagged task replaces its reason.\n"
8208
+ );
8209
+ flagCommand.action(
8210
+ async (slug, reason, raw) => {
8211
+ const config = await ctx.loadConfig();
8212
+ const existing = await requireLiveTask(
8213
+ ctx,
8214
+ flagCommand,
8215
+ config,
8216
+ slug,
8217
+ "flagging"
8218
+ );
8219
+ if (!existing) return;
8220
+ const flag = reason == null ? true : reason;
8221
+ const before = taskFlag(existing);
8222
+ if (before && before.reason === (flag === true ? null : flag.trim())) {
8223
+ if (raw.json) {
8224
+ printTask(existing);
8225
+ return;
8226
+ }
8227
+ chrome(`No changes for ${slug}: it already carries that flag.`);
8228
+ return;
8229
+ }
8230
+ const { task: flagged } = await updateTask(adapter, config, slug, {
8231
+ flag
8232
+ });
8233
+ if (raw.json) {
8234
+ printTask(flagged);
8235
+ return;
8236
+ }
8237
+ const after = taskFlag(flagged);
8238
+ chrome(
8239
+ after?.reason ? `Flagged ${flagged.slug}: ${after.reason}` : `Flagged ${flagged.slug}`
8240
+ );
8241
+ }
8242
+ );
8243
+ const unflagCommand = task.command("unflag <slug>").description("Clear a task's flag").option("--json", "Output the resulting task as JSON");
8244
+ unflagCommand.action(async (slug, raw) => {
8245
+ const config = await ctx.loadConfig();
8246
+ const existing = await requireLiveTask(
8247
+ ctx,
8248
+ unflagCommand,
8249
+ config,
8250
+ slug,
8251
+ "unflagging"
8252
+ );
8253
+ if (!existing) return;
8254
+ if (existing.frontmatter.flag === void 0) {
8255
+ if (raw.json) {
8256
+ printTask(existing);
8257
+ return;
8258
+ }
8259
+ chrome(`No changes for ${slug}: it is not flagged.`);
8260
+ return;
8261
+ }
8262
+ const { task: unflagged } = await updateTask(adapter, config, slug, {
8263
+ flag: void 0
8264
+ });
8265
+ if (raw.json) {
8266
+ printTask(unflagged);
8267
+ return;
8268
+ }
8269
+ chrome(`Unflagged ${slug}`);
8270
+ });
8271
+ const moveCommand = task.command("move <slug>").description("Move a task to another column and/or another position").option(
8272
+ "-t, --to <status>",
8273
+ "Target column (defaults to the task's current column)"
8274
+ ).addOption(
8275
+ new Option2("--top", "Place first in the destination column").conflicts([
8276
+ "bottom",
8277
+ "before",
8278
+ "after",
8279
+ "position"
8280
+ ])
8281
+ ).addOption(
8282
+ new Option2("--bottom", "Place last in the destination column").conflicts([
8283
+ "top",
8284
+ "before",
8285
+ "after",
8286
+ "position"
8287
+ ])
8288
+ ).addOption(
8289
+ new Option2(
8290
+ "--before <slug>",
8291
+ "Place immediately before this task"
8292
+ ).conflicts(["top", "bottom", "after", "position"])
8293
+ ).addOption(
8294
+ new Option2(
8295
+ "--after <slug>",
8296
+ "Place immediately after this task"
8297
+ ).conflicts(["top", "bottom", "before", "position"])
8298
+ ).addOption(
8299
+ new Option2("--position <n>", "Place at this 0-based index (-1 appends)").argParser(parseLayoutPosition).conflicts(["top", "bottom", "before", "after"])
8300
+ ).option("--json", "Output the resulting task as JSON").addHelpText(
8301
+ "after",
8302
+ "\nPlacement flags are mutually exclusive and cannot target the done column,\nwhich is always ordered by last update. Reorder only when asked to.\n"
8303
+ ).action(async (slug, raw) => {
8304
+ const config = await ctx.loadConfig();
8305
+ const placement = readPlacement(raw);
8306
+ if (!placement) {
8307
+ if (raw.to === void 0) {
8308
+ moveCommand.error(
8309
+ "Provide --to, a placement flag (--top, --bottom, --before, --after, --position), or both."
8310
+ );
8311
+ return;
8312
+ }
8313
+ const moved2 = await moveTask(adapter, config, slug, raw.to);
8314
+ if (raw.json) {
8315
+ printTask(moved2);
8316
+ return;
8317
+ }
8318
+ chrome(`Moved ${moved2.slug} \u2192 ${moved2.frontmatter.status}`);
8319
+ return;
8320
+ }
8321
+ const { tasks } = await listTasks(adapter, config);
8322
+ const target = tasks.find((candidate) => candidate.slug === slug);
8323
+ if (!target) {
8324
+ moveCommand.error(`Task '${slug}' not found.`);
8325
+ return;
8326
+ }
8327
+ const toStatus = raw.to ?? target.frontmatter.status;
8328
+ const validStatuses = new Set(config.columns.map((column2) => column2.id));
8329
+ if (!validStatuses.has(toStatus)) {
8330
+ moveCommand.error(
8331
+ `Invalid status "${toStatus}". Valid: ${[...validStatuses].join(", ")}`
8332
+ );
8333
+ return;
8334
+ }
8335
+ if (toStatus === config.done_column) {
8336
+ moveCommand.error(
8337
+ `The '${toStatus}' column carries no manual order \u2014 it is always sorted by last update. Move without a placement flag.`
8338
+ );
8339
+ return;
8340
+ }
8341
+ const column = orderedTasksForColumn(
8342
+ tasks,
8343
+ config.layout,
8344
+ toStatus,
8345
+ validStatuses,
8346
+ config.done_column
8347
+ ).filter((candidate) => candidate.slug !== slug);
8348
+ let position;
8349
+ if (placement.kind === "top") {
8350
+ position = 0;
8351
+ } else if (placement.kind === "bottom") {
8352
+ position = -1;
8353
+ } else if (placement.kind === "position") {
8354
+ position = placement.index;
8355
+ } else {
8356
+ const { anchor } = placement;
8357
+ if (anchor === slug) {
8358
+ moveCommand.error(`Cannot place '${slug}' ${placement.kind} itself.`);
8359
+ return;
8360
+ }
8361
+ const anchorIndex = column.findIndex(
8362
+ (candidate) => candidate.slug === anchor
8363
+ );
8364
+ if (anchorIndex === -1) {
8365
+ const live = tasks.find((candidate) => candidate.slug === anchor);
8366
+ if (live) {
8367
+ moveCommand.error(
8368
+ `Anchor task '${anchor}' is in the '${live.frontmatter.status}' column, not '${toStatus}'.`
8369
+ );
8370
+ } else if (await getTask(adapter, config, anchor, { archived: true })) {
8371
+ moveCommand.error(
8372
+ `Anchor task '${anchor}' is archived and is not on the board.`
8179
8373
  );
8180
8374
  } else {
8181
- graphCommand.error(`Task '${slug}' not found.`);
8375
+ moveCommand.error(`Anchor task '${anchor}' not found.`);
8182
8376
  }
8183
8377
  return;
8184
8378
  }
8185
- if (raw.json || !isInteractive) {
8186
- data(JSON.stringify(query, null, 2));
8187
- return;
8188
- }
8189
- for (const line of formatTaskDependencyQuery(query)) data(line);
8190
- return;
8379
+ position = placement.kind === "before" ? anchorIndex : anchorIndex + 1;
8191
8380
  }
8192
- const graph = buildTaskDependencyGraph(liveResult.tasks, {
8193
- archivedTasks: archivedResult?.tasks,
8194
- archivedSlugs: archivedResult ? taskFileSlugs(archivedResult) : void 0
8195
- });
8196
- if (raw.json || !isInteractive) {
8197
- data(JSON.stringify(graph, null, 2));
8381
+ const fromStatus = target.frontmatter.status;
8382
+ const { task: moved } = await reorderTask(
8383
+ adapter,
8384
+ config,
8385
+ slug,
8386
+ toStatus,
8387
+ position
8388
+ );
8389
+ if (raw.json) {
8390
+ printTask(moved);
8198
8391
  return;
8199
8392
  }
8200
- for (const line of formatTaskDependencyGraph(graph)) data(line);
8393
+ const placedAt = position < 0 || position > column.length ? column.length : position;
8394
+ chrome(
8395
+ fromStatus === toStatus ? `Reordered ${moved.slug} in ${toStatus} \u2192 position ${placedAt} of ${column.length + 1}` : `Moved ${moved.slug} \u2192 ${toStatus} at position ${placedAt} of ${column.length + 1}`
8396
+ );
8397
+ chrome("Wrote .shipbench/layout.json");
8201
8398
  });
8202
- task.command("archive [slug]").description("Archive one task, or older done tasks in bulk").option("--done", "Archive done tasks in bulk").option(
8203
- "--keep <count>",
8204
- "Number of most-recent done tasks to keep live",
8205
- parseNonNegativeInteger
8399
+ }
8400
+
8401
+ // src/commands/taskWrite.ts
8402
+ import { InvalidArgumentError as InvalidArgumentError5, Option as Option3 } from "commander";
8403
+
8404
+ // src/commands/editFields.ts
8405
+ function storedList(raw, nullIsValid) {
8406
+ if (raw === void 0 || raw === null && nullIsValid) {
8407
+ return { values: [], valid: true, raw };
8408
+ }
8409
+ if (!Array.isArray(raw)) return { values: [], valid: false, raw };
8410
+ const values = raw.filter(
8411
+ (entry) => typeof entry === "string"
8412
+ );
8413
+ return { values, valid: values.length === raw.length, raw };
8414
+ }
8415
+ function listChanged(current, next) {
8416
+ return !current.valid || next.length !== current.values.length || next.some((value, index) => value !== current.values[index]);
8417
+ }
8418
+ function storedRelated(task) {
8419
+ const current = storedList(task.frontmatter.related, true);
8420
+ if (current.valid) current.values = relatedSlugs(task);
8421
+ return current;
8422
+ }
8423
+ function requestsMetadataChange(request) {
8424
+ return request.title !== void 0 || request.priority !== void 0 || request.assignee !== void 0 || Boolean(request.clearAssignee) || request.tags !== void 0 || request.addTag !== void 0 || request.removeTag !== void 0 || Boolean(request.clearTags) || request.dependsOn !== void 0 || request.addDependsOn !== void 0 || request.removeDependsOn !== void 0 || Boolean(request.clearDependsOn) || request.related !== void 0 || request.addRelated !== void 0 || request.removeRelated !== void 0 || Boolean(request.clearRelated);
8425
+ }
8426
+ function relatedRemovalsNotRecordedHere(task, request) {
8427
+ if (request.related !== void 0 || request.clearRelated) return [];
8428
+ if (request.addRelated === void 0 && request.removeRelated === void 0) {
8429
+ return [];
8430
+ }
8431
+ const current = storedRelated(task);
8432
+ return (request.removeRelated ?? []).filter(
8433
+ (target) => !current.values.includes(target)
8434
+ );
8435
+ }
8436
+ function diffTaskEdit(task, request) {
8437
+ const before = task.frontmatter;
8438
+ const fields = {};
8439
+ const changes = [];
8440
+ const list = (values) => values.length > 0 ? `[${values.join(", ")}]` : "(none)";
8441
+ const storedAs = (stored) => stored.valid ? list(stored.values) : `(invalid: ${JSON.stringify(stored.raw)})`;
8442
+ if (request.title !== void 0 && request.title !== before.title) {
8443
+ fields.title = request.title;
8444
+ changes.push(`title "${before.title}" \u2192 "${request.title}"`);
8445
+ }
8446
+ if (request.priority !== void 0 && request.priority !== before.priority) {
8447
+ fields.priority = request.priority;
8448
+ changes.push(
8449
+ `priority ${before.priority ?? "(unset)"} \u2192 ${request.priority}`
8450
+ );
8451
+ }
8452
+ if (request.assignee !== void 0) {
8453
+ if (request.assignee !== (before.assignee ?? void 0)) {
8454
+ fields.assignee = request.assignee;
8455
+ changes.push(
8456
+ `assignee ${before.assignee ?? "(unset)"} \u2192 ${request.assignee}`
8457
+ );
8458
+ }
8459
+ } else if (request.clearAssignee && before.assignee !== void 0) {
8460
+ fields.assignee = void 0;
8461
+ changes.push(`assignee ${before.assignee} \u2192 (unset)`);
8462
+ }
8463
+ const currentTags = storedList(before.tags, true);
8464
+ let nextTags;
8465
+ if (request.tags !== void 0) {
8466
+ nextTags = dedupePreservingCase(request.tags);
8467
+ } else if (request.clearTags) {
8468
+ nextTags = [];
8469
+ } else if (request.addTag !== void 0 || request.removeTag !== void 0) {
8470
+ const removed = new Set(
8471
+ (request.removeTag ?? []).map((tag) => tag.toLowerCase())
8472
+ );
8473
+ nextTags = dedupePreservingCase([
8474
+ ...currentTags.values.filter((tag) => !removed.has(tag.toLowerCase())),
8475
+ ...request.addTag ?? []
8476
+ ]);
8477
+ }
8478
+ if (nextTags !== void 0 && listChanged(currentTags, nextTags)) {
8479
+ fields.tags = nextTags.length > 0 ? nextTags : void 0;
8480
+ changes.push(`tags ${storedAs(currentTags)} \u2192 ${list(nextTags)}`);
8481
+ }
8482
+ const currentDeps = storedList(before.depends_on, false);
8483
+ let nextDeps;
8484
+ if (request.dependsOn !== void 0) {
8485
+ nextDeps = dedupePreservingCase(request.dependsOn);
8486
+ } else if (request.clearDependsOn) {
8487
+ nextDeps = [];
8488
+ } else if (request.addDependsOn !== void 0 || request.removeDependsOn !== void 0) {
8489
+ const removed = new Set(request.removeDependsOn ?? []);
8490
+ nextDeps = dedupePreservingCase([
8491
+ ...currentDeps.values.filter((dep) => !removed.has(dep)),
8492
+ ...request.addDependsOn ?? []
8493
+ ]);
8494
+ }
8495
+ if (nextDeps !== void 0 && listChanged(currentDeps, nextDeps)) {
8496
+ fields.depends_on = nextDeps;
8497
+ changes.push(`depends_on ${storedAs(currentDeps)} \u2192 ${list(nextDeps)}`);
8498
+ }
8499
+ const currentRelated = storedRelated(task);
8500
+ let nextRelated;
8501
+ if (request.related !== void 0) {
8502
+ nextRelated = dedupePreservingCase(request.related);
8503
+ } else if (request.clearRelated) {
8504
+ nextRelated = [];
8505
+ } else if (request.addRelated !== void 0 || request.removeRelated !== void 0) {
8506
+ const removed = new Set(request.removeRelated ?? []);
8507
+ nextRelated = dedupePreservingCase([
8508
+ ...currentRelated.values.filter((target) => !removed.has(target)),
8509
+ ...request.addRelated ?? []
8510
+ ]);
8511
+ }
8512
+ if (nextRelated !== void 0 && listChanged(currentRelated, nextRelated)) {
8513
+ fields.related = nextRelated;
8514
+ changes.push(`related ${storedAs(currentRelated)} \u2192 ${list(nextRelated)}`);
8515
+ }
8516
+ return { fields, changes };
8517
+ }
8518
+
8519
+ // src/commands/taskWrite.ts
8520
+ function bodyOption() {
8521
+ return new Option3("--body <text>", "Description as Markdown text").conflicts([
8522
+ "bodyFile"
8523
+ ]);
8524
+ }
8525
+ function bodyFileOption() {
8526
+ return new Option3(
8527
+ "--body-file <path>",
8528
+ 'Read the description from a UTF-8 file; "-" reads stdin'
8529
+ ).conflicts(["body"]);
8530
+ }
8531
+ function updateTextOption() {
8532
+ return new Option3("--body <text>", "Update text as Markdown").conflicts([
8533
+ "bodyFile"
8534
+ ]);
8535
+ }
8536
+ function updateTextFileOption() {
8537
+ return new Option3(
8538
+ "--body-file <path>",
8539
+ 'Read the update text from a UTF-8 file; "-" reads stdin'
8540
+ ).conflicts(["body"]);
8541
+ }
8542
+ var commaListOption = (flags, description) => new Option3(flags, description).argParser(accumulateCommaList);
8543
+ var BODY_FILE_HELP = "\nPrefer --body-file for anything multi-line: the file is read as UTF-8 by\nShipBench, so the text never passes through shell quoting or encoding.\n";
8544
+ async function resolveUpdateText(ctx, command, positional, raw) {
8545
+ const fromOption = await ctx.resolveBody(raw);
8546
+ if (positional != null && fromOption !== void 0) {
8547
+ command.error(
8548
+ "Pass the update text once: either positionally or with --body / --body-file, not both."
8549
+ );
8550
+ return void 0;
8551
+ }
8552
+ return positional ?? fromOption;
8553
+ }
8554
+ function registerTaskWrite(task, ctx) {
8555
+ const { adapter, chrome, printTask } = ctx;
8556
+ task.command("create <title>").description("Create a new task").option("-s, --status <status>", "Column to place the task in").option("-a, --assignee <assignee>", "Assignee label").option("-p, --priority <priority>", "Priority value").option(
8557
+ "-t, --tags <tags>",
8558
+ "Tags (comma-separated, repeatable)",
8559
+ accumulateCommaList
8206
8560
  ).option(
8207
- "--force",
8208
- "Archive a non-done task even when live tasks depend on it"
8561
+ "-d, --depends-on <slugs>",
8562
+ "Slugs this task depends on (comma-separated, repeatable)",
8563
+ accumulateCommaList,
8564
+ []
8209
8565
  ).option(
8210
- "--json",
8211
- "Output the archived task as JSON (an array of them with --done)"
8212
- ).addHelpText(
8566
+ "--related <slugs>",
8567
+ "Slugs of live or archived tasks this one relates to, without depending on them (comma-separated, repeatable)",
8568
+ accumulateCommaList,
8569
+ []
8570
+ ).addOption(bodyOption()).addOption(bodyFileOption()).option("--json", "Output the created task as JSON").addHelpText(
8213
8571
  "after",
8214
- "\nA non-done task with live dependents is blocked unless --force is used.\n"
8215
- ).action(async (slug, raw) => {
8216
- if (Boolean(slug) === Boolean(raw.done)) {
8217
- throw new Error("Provide either a task slug or --done, but not both.");
8218
- }
8219
- if (raw.keep !== void 0 && !raw.done) {
8220
- throw new Error("--keep can only be used with --done.");
8221
- }
8222
- if (raw.force && raw.done) {
8223
- throw new Error("--force can only be used when archiving one task.");
8572
+ "\nPrefer --body-file for anything multi-line: the file is read as UTF-8 by\nShipBench, so the description never passes through shell quoting or encoding.\n"
8573
+ ).action(async (title, raw) => {
8574
+ const body = await ctx.resolveBody(raw);
8575
+ const config = await ctx.loadConfig();
8576
+ const created = await createTask(
8577
+ adapter,
8578
+ config,
8579
+ title,
8580
+ {
8581
+ status: raw.status,
8582
+ assignee: raw.assignee,
8583
+ priority: raw.priority,
8584
+ tags: raw.tags && dedupePreservingCase(raw.tags),
8585
+ depends_on: raw.dependsOn,
8586
+ related: raw.related
8587
+ },
8588
+ body
8589
+ );
8590
+ if (raw.json) {
8591
+ printTask(created);
8592
+ return;
8224
8593
  }
8225
- const config = await loadCliConfig();
8226
- if (raw.done) {
8227
- const { tasks } = await listTasks(adapter, config);
8228
- const doneTasks = tasks.filter(
8229
- (candidate) => candidate.frontmatter.status === config.done_column
8230
- ).sort(
8231
- (a, b) => Date.parse(b.frontmatter.updated) - Date.parse(a.frontmatter.updated) || a.slug.localeCompare(b.slug)
8594
+ chrome(`Created task: ${created.slug}`);
8595
+ });
8596
+ const editCommand = task.command("edit <slug>").description("Revise a task's description or its validated metadata").option(
8597
+ "--title <text>",
8598
+ "Set the title (the slug and filename do not change)"
8599
+ ).option("-p, --priority <value>", "Set the priority").addOption(
8600
+ new Option3("-a, --assignee <label>", "Set the assignee label").conflicts([
8601
+ "clearAssignee"
8602
+ ])
8603
+ ).addOption(
8604
+ new Option3("--clear-assignee", "Remove the assignee").conflicts([
8605
+ "assignee"
8606
+ ])
8607
+ ).addOption(
8608
+ commaListOption(
8609
+ "-t, --tags <tags>",
8610
+ "Replace every tag (comma-separated or repeatable)"
8611
+ ).conflicts(["addTag", "removeTag", "clearTags"])
8612
+ ).addOption(
8613
+ commaListOption(
8614
+ "--add-tag <tags>",
8615
+ "Add tags, keeping the others (comma-separated or repeatable)"
8616
+ ).conflicts(["tags", "clearTags"])
8617
+ ).addOption(
8618
+ commaListOption(
8619
+ "--remove-tag <tags>",
8620
+ "Remove tags, keeping the others (comma-separated or repeatable)"
8621
+ ).conflicts(["tags", "clearTags"])
8622
+ ).addOption(
8623
+ new Option3("--clear-tags", "Remove every tag").conflicts([
8624
+ "tags",
8625
+ "addTag",
8626
+ "removeTag"
8627
+ ])
8628
+ ).addOption(
8629
+ commaListOption(
8630
+ "-d, --depends-on <slugs>",
8631
+ "Replace every dependency (comma-separated or repeatable)"
8632
+ ).conflicts(["addDependsOn", "removeDependsOn", "clearDependsOn"])
8633
+ ).addOption(
8634
+ commaListOption(
8635
+ "--add-depends-on <slugs>",
8636
+ "Add dependencies, keeping the others (comma-separated or repeatable)"
8637
+ ).conflicts(["dependsOn", "clearDependsOn"])
8638
+ ).addOption(
8639
+ commaListOption(
8640
+ "--remove-depends-on <slugs>",
8641
+ "Remove dependencies, keeping the others (comma-separated or repeatable)"
8642
+ ).conflicts(["dependsOn", "clearDependsOn"])
8643
+ ).addOption(
8644
+ new Option3("--clear-depends-on", "Remove every dependency").conflicts([
8645
+ "dependsOn",
8646
+ "addDependsOn",
8647
+ "removeDependsOn"
8648
+ ])
8649
+ ).addOption(
8650
+ commaListOption(
8651
+ "--related <slugs>",
8652
+ "Replace every related task (comma-separated or repeatable)"
8653
+ ).conflicts(["addRelated", "removeRelated", "clearRelated"])
8654
+ ).addOption(
8655
+ commaListOption(
8656
+ "--add-related <slugs>",
8657
+ "Add related tasks, keeping the others (comma-separated or repeatable)"
8658
+ ).conflicts(["related", "clearRelated"])
8659
+ ).addOption(
8660
+ commaListOption(
8661
+ "--remove-related <slugs>",
8662
+ "Remove related tasks, keeping the others (comma-separated or repeatable)"
8663
+ ).conflicts(["related", "clearRelated"])
8664
+ ).addOption(
8665
+ new Option3(
8666
+ "--clear-related",
8667
+ "Remove every related task this task's file records"
8668
+ ).conflicts(["related", "addRelated", "removeRelated"])
8669
+ ).addOption(bodyOption()).addOption(bodyFileOption()).option("--json", "Output the edited task as JSON").addHelpText(
8670
+ "after",
8671
+ "\nPass at least one change. Every change is applied in a single validated\nwrite: if any value is rejected the task is left exactly as it was. Status\nand board placement stay with `shipbench task move`; the Task Updates section\nstays with `shipbench task comment`. A title edit never renames the file.\n"
8672
+ );
8673
+ editCommand.action(async (slug, raw) => {
8674
+ const body = await ctx.resolveBody(raw);
8675
+ const request = {
8676
+ title: raw.title,
8677
+ priority: raw.priority,
8678
+ assignee: raw.assignee,
8679
+ clearAssignee: Boolean(raw.clearAssignee),
8680
+ tags: raw.tags,
8681
+ addTag: raw.addTag,
8682
+ removeTag: raw.removeTag,
8683
+ clearTags: Boolean(raw.clearTags),
8684
+ dependsOn: raw.dependsOn,
8685
+ addDependsOn: raw.addDependsOn,
8686
+ removeDependsOn: raw.removeDependsOn,
8687
+ clearDependsOn: Boolean(raw.clearDependsOn),
8688
+ related: raw.related,
8689
+ addRelated: raw.addRelated,
8690
+ removeRelated: raw.removeRelated,
8691
+ clearRelated: Boolean(raw.clearRelated)
8692
+ };
8693
+ if (body === void 0 && !requestsMetadataChange(request)) {
8694
+ editCommand.error(
8695
+ "Provide at least one change: --body/--body-file, --title, --priority, --assignee/--clear-assignee, --tags/--add-tag/--remove-tag/--clear-tags, --depends-on/--add-depends-on/--remove-depends-on/--clear-depends-on, or --related/--add-related/--remove-related/--clear-related."
8232
8696
  );
8233
- const keep = raw.keep === void 0 && config.done_display.max <= 0 ? doneTasks.length : raw.keep ?? config.done_display.max;
8234
- const candidates = doneTasks.slice(keep);
8235
- const archived = [];
8236
- for (const candidate of candidates) {
8237
- archived.push(await archiveTask(adapter, config, candidate.slug));
8238
- if (!raw.json) chrome(`Archived task: ${candidate.slug}`);
8697
+ return;
8698
+ }
8699
+ const config = await ctx.loadConfig();
8700
+ const existing = await requireLiveTask(
8701
+ ctx,
8702
+ editCommand,
8703
+ config,
8704
+ slug,
8705
+ "editing"
8706
+ );
8707
+ if (!existing) return;
8708
+ const notOwn = relatedRemovalsNotRecordedHere(existing, request);
8709
+ if (notOwn.length > 0) {
8710
+ const [live, archived] = await Promise.all([
8711
+ listTasks(adapter, config),
8712
+ listArchivedTasks(adapter, config)
8713
+ ]);
8714
+ const holds = (candidate, target) => candidate.slug === target && relatedSlugs(candidate).includes(slug);
8715
+ for (const target of notOwn) {
8716
+ if (live.tasks.some((candidate) => holds(candidate, target))) {
8717
+ editCommand.error(
8718
+ `Cannot remove related task "${target}" from ${slug}: the link is recorded in ${target}'s file, not this one. Remove it there: shipbench task edit ${target} --remove-related ${slug}`
8719
+ );
8720
+ return;
8721
+ }
8722
+ if (archived.tasks.some((candidate) => holds(candidate, target))) {
8723
+ editCommand.error(
8724
+ `Cannot remove related task "${target}" from ${slug}: the link is recorded in the archived task ${target}'s file, not this one. Unarchive ${target} to edit it.`
8725
+ );
8726
+ return;
8727
+ }
8239
8728
  }
8729
+ }
8730
+ const { fields, changes } = diffTaskEdit(existing, request);
8731
+ if (body !== void 0) {
8732
+ changes.push(body.trim() ? "description" : "description cleared");
8733
+ }
8734
+ if (changes.length === 0) {
8240
8735
  if (raw.json) {
8241
- data(JSON.stringify(archived.map(taskJson), null, 2));
8736
+ printTask(existing);
8242
8737
  return;
8243
8738
  }
8244
- if (candidates.length === 0) chrome("No done tasks archived.");
8739
+ chrome(`No changes for ${slug}: every field already holds that value.`);
8245
8740
  return;
8246
8741
  }
8247
- try {
8248
- const archived = await archiveTask(adapter, config, slug, {
8249
- force: raw.force
8250
- });
8251
- if (raw.json) {
8252
- printTask(archived);
8253
- return;
8254
- }
8255
- chrome(`Archived task: ${slug}`);
8256
- } catch (error) {
8257
- if (error instanceof ArchiveBlockedError) {
8258
- throw new Error(
8259
- `Cannot archive "${error.slug}" because live tasks depend on it: ${error.dependentSlugs.join(", ")}. Re-run with --force to archive it anyway.`
8260
- );
8261
- }
8262
- throw error;
8742
+ const { task: edited } = await updateTask(
8743
+ adapter,
8744
+ config,
8745
+ slug,
8746
+ fields,
8747
+ body
8748
+ );
8749
+ if (raw.json) {
8750
+ printTask(edited);
8751
+ return;
8752
+ }
8753
+ chrome(`Updated ${edited.slug}: ${changes.join("; ")}`);
8754
+ if (fields.title !== void 0) {
8755
+ chrome(`Slug and filename unchanged: ${edited.slug}`);
8263
8756
  }
8264
8757
  });
8265
- task.command("unarchive <slug>").description("Restore an archived task").option("--json", "Output the resulting task as JSON").action(async (slug, raw) => {
8266
- const config = await loadCliConfig();
8267
- const restored = await unarchiveTask(adapter, config, slug);
8758
+ const commentCommand = task.command("comment").description("Manage timestamped entries in the task Updates section").argument("[slug]", "Task slug").argument("[text]", "Update text").addOption(updateTextOption()).addOption(updateTextFileOption()).option("--json", "Output the resulting task as JSON").addHelpText("after", BODY_FILE_HELP);
8759
+ commentCommand.action(async (slug, text, raw) => {
8760
+ const resolved = await resolveUpdateText(ctx, commentCommand, text, raw);
8761
+ if (!slug || resolved === void 0) {
8762
+ throw new InvalidArgumentError5(
8763
+ "Append requires a task slug and update text (positional, --body <text>, or --body-file <path>)."
8764
+ );
8765
+ }
8766
+ const config = await ctx.loadConfig();
8767
+ const updated = await addComment(adapter, config, slug, resolved);
8268
8768
  if (raw.json) {
8269
- printTask(restored);
8769
+ printTask(updated);
8270
8770
  return;
8271
8771
  }
8272
- chrome(`Unarchived task: ${slug}`);
8772
+ chrome(`Added update to ${updated.slug}`);
8273
8773
  });
8274
- task.command("delete <slug>").description("Delete a task").option("--json", "Output the deleted slug as JSON").action(async (slug, raw) => {
8275
- const config = await loadCliConfig();
8276
- await deleteTask(adapter, config, slug);
8774
+ const commentEditCommand = commentCommand.command("edit <slug> <index> [text]").description(
8775
+ "Edit an Updates entry by zero-based index without changing its timestamp"
8776
+ ).addOption(updateTextOption()).addOption(updateTextFileOption()).option("--json", "Output the resulting task as JSON").addHelpText("after", BODY_FILE_HELP);
8777
+ commentEditCommand.action(async (slug, index, text, raw) => {
8778
+ const resolved = await resolveUpdateText(
8779
+ ctx,
8780
+ commentEditCommand,
8781
+ text,
8782
+ raw
8783
+ );
8784
+ if (resolved === void 0) {
8785
+ commentEditCommand.error(
8786
+ "Provide the replacement text positionally, or with --body <text> or --body-file <path>."
8787
+ );
8788
+ return;
8789
+ }
8790
+ const config = await ctx.loadConfig();
8791
+ const parsedIndex = parseNonNegativeInteger(index);
8792
+ const updated = await editComment(
8793
+ adapter,
8794
+ config,
8795
+ slug,
8796
+ parsedIndex,
8797
+ resolved
8798
+ );
8277
8799
  if (raw.json) {
8278
- data(JSON.stringify({ slug, deleted: true }, null, 2));
8800
+ printTask(updated);
8279
8801
  return;
8280
8802
  }
8281
- chrome(`Deleted task: ${slug}`);
8803
+ chrome(`Edited update ${parsedIndex} on ${updated.slug}`);
8282
8804
  });
8283
- const board = program.command("board").description("Open the board UI");
8284
- board.command("web", { isDefault: true }).description("Open the board UI in a browser (the default for `board`)").option("--port <number>", "Port to listen on", parsePort, 4321).option("--no-open", "Do not open the browser automatically").action(async (raw) => {
8285
- await requireBoard();
8286
- const server = await startBoardServer({
8287
- adapter,
8288
- cwd,
8289
- bundleDir: resolveBoardBundleDir(),
8290
- port: raw.port,
8291
- warn: chrome
8292
- });
8293
- output.brand();
8294
- for (const line of formatBoardStatus(server.url, cwd)) chrome(line);
8295
- if (raw.open) openBrowser(server.url);
8296
- const shutdown = async () => {
8297
- await server.close();
8298
- process.exit(0);
8299
- };
8300
- process.once("SIGINT", () => {
8301
- void shutdown();
8302
- });
8303
- process.once("SIGTERM", () => {
8304
- void shutdown();
8305
- });
8306
- await new Promise(() => {
8307
- });
8805
+ commentCommand.command("delete <slug> <index>").description("Delete an Updates entry by zero-based index").option("--json", "Output the resulting task as JSON").action(async (slug, index, raw) => {
8806
+ const config = await ctx.loadConfig();
8807
+ const parsedIndex = parseNonNegativeInteger(index);
8808
+ const updated = await deleteComment(adapter, config, slug, parsedIndex);
8809
+ if (raw.json) {
8810
+ printTask(updated);
8811
+ return;
8812
+ }
8813
+ chrome(`Deleted update ${parsedIndex} from ${updated.slug}`);
8308
8814
  });
8309
- board.command("terminal").aliases(["term", "tui"]).description("Render the board in the terminal (read-only, live, no input)").option(
8310
- "-s, --status <statuses>",
8311
- "Columns to render (comma-separated; defaults to every configured column)",
8312
- commaList
8313
- ).option("-a, --assignee <assignee>", "Filter by assignee").option("-p, --priority <priority>", "Filter by priority").option(
8314
- "--tag <tag>",
8315
- "Filter by tag (comma-separated or repeatable with AND semantics)",
8316
- accumulateCommaList
8317
- ).option(
8318
- "--exclude-tag <tag>",
8319
- "Leave out tasks carrying any of these tags (comma-separated or repeatable)",
8320
- accumulateCommaList
8321
- ).option("--flagged", "Only tasks with a flag set").addHelpText(
8815
+ }
8816
+
8817
+ // src/validation.ts
8818
+ function problemHint(problem) {
8819
+ const slug = problem.slug;
8820
+ if (slug === void 0) return void 0;
8821
+ switch (problem.code) {
8822
+ case "title-invalid":
8823
+ return `shipbench task edit ${slug} --title "<title>"`;
8824
+ case "status-unknown":
8825
+ return `shipbench task move ${slug} --to=<status>`;
8826
+ case "priority-unknown":
8827
+ return `shipbench task edit ${slug} --priority=<priority>`;
8828
+ case "tags-invalid":
8829
+ return `shipbench task edit ${slug} --tags=<tag,tag> (or --clear-tags)`;
8830
+ case "depends-on-invalid":
8831
+ return `shipbench task edit ${slug} --depends-on=<slug,slug> (or --clear-depends-on)`;
8832
+ case "depends-on-self":
8833
+ return `shipbench task edit ${slug} --remove-depends-on=${slug}`;
8834
+ case "depends-on-dangling":
8835
+ return `shipbench task edit ${slug} --remove-depends-on=<slug>`;
8836
+ case "dependency-cycle": {
8837
+ const next = problem.cycle?.[1];
8838
+ return next === void 0 ? void 0 : `remove one link, for example: shipbench task edit ${slug} --remove-depends-on=${next}`;
8839
+ }
8840
+ case "related-invalid":
8841
+ return `shipbench task edit ${slug} --related=<slug,slug> (or --clear-related)`;
8842
+ case "related-self":
8843
+ return `shipbench task edit ${slug} --remove-related=${slug}`;
8844
+ case "related-dangling":
8845
+ return `shipbench task edit ${slug} --remove-related=<slug>`;
8846
+ case "flag-invalid":
8847
+ return `shipbench task flag ${slug} "<reason>" (or shipbench task unflag ${slug})`;
8848
+ default:
8849
+ return void 0;
8850
+ }
8851
+ }
8852
+ function validationReportJson(report2) {
8853
+ return {
8854
+ ...report2,
8855
+ problems: report2.problems.map((problem) => {
8856
+ const hint = problemHint(problem);
8857
+ return hint === void 0 ? problem : { ...problem, hint };
8858
+ })
8859
+ };
8860
+ }
8861
+ function formatValidationProblems(report2) {
8862
+ const lines = [];
8863
+ let path;
8864
+ for (const problem of report2.problems) {
8865
+ if (problem.path !== path) {
8866
+ if (path !== void 0) lines.push("");
8867
+ path = problem.path;
8868
+ lines.push(path);
8869
+ }
8870
+ const label = problem.severity === "error" ? "error " : "warning";
8871
+ lines.push(` ${label} ${problem.code}: ${problem.message}`);
8872
+ const hint = problemHint(problem);
8873
+ if (hint !== void 0) lines.push(` fix: ${hint}`);
8874
+ }
8875
+ return lines;
8876
+ }
8877
+ function count(n, noun) {
8878
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
8879
+ }
8880
+ function formatValidationSummary(report2) {
8881
+ const { tasks, archived } = report2.checked;
8882
+ const found = report2.problems.length === 0 ? "No problems found" : [
8883
+ ...report2.errors > 0 ? [count(report2.errors, "error")] : [],
8884
+ ...report2.warnings > 0 ? [count(report2.warnings, "warning")] : []
8885
+ ].join(" and ");
8886
+ if (tasks === null) return `${found}. Task files were not checked.`;
8887
+ const scope = archived === null ? `${count(tasks, "task file")}. Archive not checked.` : `${count(tasks, "task file")} and ${count(archived, "archived task file")}.`;
8888
+ return `${found} in ${scope}`;
8889
+ }
8890
+
8891
+ // src/commands/validate.ts
8892
+ function registerValidate(program, ctx) {
8893
+ const { adapter, data, chrome, missingBoardMessage } = ctx;
8894
+ program.command("validate").description(
8895
+ "Check the project's config, layout, and task files for structural problems, without changing them"
8896
+ ).option("--archived", "Also check the files in tasks/archive/").option("--json", "Emit the report as machine-readable JSON").addHelpText(
8322
8897
  "after",
8323
- "\nTakes no keyboard input: Ctrl-C exits. Never writes to the board.\nWith stdout redirected it prints one 80x24 frame and exits.\n"
8898
+ "\nExits 0 when nothing is an error (warnings alone pass), 1 when anything is,\nand 2 when the check could not run. It checks structure only: it cannot tell\nwhether a task is finished or its reasoning is sound.\n"
8324
8899
  ).action(async (raw) => {
8325
- await requireBoard();
8326
- await runTui({
8327
- adapter,
8328
- cwd,
8329
- filters: {
8330
- statuses: raw.status,
8331
- tags: raw.tag,
8332
- excludedTags: raw.excludeTag,
8333
- assignee: raw.assignee,
8334
- priority: raw.priority,
8335
- flagged: raw.flagged
8900
+ if (await adapter.readFileIfExists(CONFIG_PATH5) === null) {
8901
+ throw new CliExitError(missingBoardMessage, 2);
8902
+ }
8903
+ let report2;
8904
+ try {
8905
+ report2 = await validateProject(adapter, {
8906
+ archived: Boolean(raw.archived)
8907
+ });
8908
+ } catch (error) {
8909
+ throw new CliExitError(
8910
+ `Could not validate the project: ${error instanceof Error ? error.message : String(error)}`,
8911
+ 2
8912
+ );
8913
+ }
8914
+ if (raw.json) {
8915
+ data(JSON.stringify(validationReportJson(report2), null, 2));
8916
+ } else {
8917
+ for (const line of formatValidationProblems(report2)) data(line);
8918
+ }
8919
+ const summary = formatValidationSummary(report2);
8920
+ if (!report2.valid) throw new CliExitError(summary, 1);
8921
+ if (!raw.json) chrome(summary);
8922
+ });
8923
+ }
8924
+
8925
+ // src/cli.ts
8926
+ var VERSION = true ? "0.11.0" : "0.0.0-dev";
8927
+ async function readProcessStdin() {
8928
+ const chunks = [];
8929
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
8930
+ return Buffer.concat(chunks).toString("utf8");
8931
+ }
8932
+ function enableExitOverride(command) {
8933
+ command.exitOverride();
8934
+ for (const child of command.commands) enableExitOverride(child);
8935
+ }
8936
+ function createCli(opts) {
8937
+ const { adapter, defaultProjectName } = opts;
8938
+ const cwd = opts.cwd ?? process.cwd();
8939
+ const version = opts.version ?? VERSION;
8940
+ const writeData = opts.out ?? ((line) => console.log(line));
8941
+ const writeChrome = opts.err ?? ((line) => console.error(line));
8942
+ const isInteractive = opts.isInteractive ?? process.stdout.isTTY === true;
8943
+ const output = createCliOutput({
8944
+ writeData,
8945
+ writeChrome,
8946
+ isStdoutTty: isInteractive,
8947
+ env: opts.env ?? process.env
8948
+ });
8949
+ const { data, chrome } = output;
8950
+ const missingBoardMessage = opts.missingBoardMessage ?? formatMissingBoard(`in ${cwd}`);
8951
+ const requireBoard = async () => {
8952
+ if (await adapter.readFileIfExists(CONFIG_PATH5) === null) {
8953
+ throw new Error(missingBoardMessage);
8954
+ }
8955
+ };
8956
+ const loadCliConfig = async () => {
8957
+ try {
8958
+ return await loadConfig(adapter, {
8959
+ onWarning: (warning) => {
8960
+ output.warning(`${warning.path}: ${warning.message}`);
8961
+ }
8962
+ });
8963
+ } catch (error) {
8964
+ await requireBoard();
8965
+ throw error;
8966
+ }
8967
+ };
8968
+ const readTextFile = opts.readTextFile ?? ((path) => readFile3(path, "utf8"));
8969
+ const readStdin = opts.readStdin ?? readProcessStdin;
8970
+ const resolveBody = async (raw) => {
8971
+ if (raw.bodyFile === void 0) return raw.body;
8972
+ if (raw.bodyFile === "-") return readStdin();
8973
+ try {
8974
+ return await readTextFile(raw.bodyFile);
8975
+ } catch (error) {
8976
+ throw new Error(
8977
+ `Cannot read --body-file "${raw.bodyFile}": ${error instanceof Error ? error.message : String(error)}`
8978
+ );
8979
+ }
8980
+ };
8981
+ const printTask = (task2) => data(JSON.stringify(taskJson(task2), null, 2));
8982
+ const program = new Command().name("shipbench").description("Git-native project management for solo developers.").enablePositionalOptions().version(version, "-v, --version", "output the version").option(
8983
+ "-C <path>",
8984
+ "Use the board in the specified directory, without searching above it"
8985
+ );
8986
+ const writingCommands = /* @__PURE__ */ new Set([
8987
+ "task create",
8988
+ "task edit",
8989
+ "task comment",
8990
+ "task comment edit",
8991
+ "task comment delete",
8992
+ "task flag",
8993
+ "task unflag",
8994
+ "task move",
8995
+ "task archive",
8996
+ "task unarchive",
8997
+ "task delete"
8998
+ ]);
8999
+ if (opts.searchedFrom !== void 0 && opts.searchedFrom !== cwd) {
9000
+ program.hook("preAction", (_root, action) => {
9001
+ const names = [];
9002
+ for (let command = action; command?.parent; ) {
9003
+ names.unshift(command.name());
9004
+ command = command.parent;
9005
+ }
9006
+ if (writingCommands.has(names.join(" "))) {
9007
+ chrome(`Using .shipbench/ from ${cwd}`);
8336
9008
  }
8337
9009
  });
9010
+ }
9011
+ program.configureOutput({
9012
+ writeOut: (line) => data(line.replace(/\n$/, "")),
9013
+ writeErr: (line) => chrome(line.replace(/\n$/, ""))
8338
9014
  });
9015
+ const ctx = {
9016
+ adapter,
9017
+ cwd,
9018
+ isInteractive,
9019
+ output,
9020
+ data,
9021
+ chrome,
9022
+ missingBoardMessage,
9023
+ requireBoard,
9024
+ loadConfig: loadCliConfig,
9025
+ resolveBody,
9026
+ printTask
9027
+ };
9028
+ registerInit(program, ctx, {
9029
+ defaultProjectName,
9030
+ ancestorBoard: opts.ancestorBoard,
9031
+ version
9032
+ });
9033
+ registerValidate(program, ctx);
9034
+ const task = program.command("task").description("Manage tasks");
9035
+ registerTaskWrite(task, ctx);
9036
+ registerTaskGet(task, ctx);
9037
+ registerTaskState(task, ctx);
9038
+ registerTaskQueries(task, ctx);
9039
+ registerArchive(task, ctx);
9040
+ registerBoard(program, ctx);
8339
9041
  if (opts.exitOverride) enableExitOverride(program);
8340
9042
  return program;
8341
9043
  }