open-backlog 0.0.0-stage → 0.1.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.
@@ -0,0 +1,486 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync, realpathSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { addItem, BacklogError, buildTree, commit, findBacklog, fixDuplicates, formatProblem, initBacklog, initDir, isStoryLevel, ITEM_TYPES, listItems, loadBacklog, message, moveItem, progressOf, recentlyDone, reposOf, repoRoot, showItem, SPEC_URL, SPEC_VERSION, validateDir } from '../core/index.js';
6
+ const STD = {
7
+ out: t => process.stdout.write(t),
8
+ err: t => process.stderr.write(t),
9
+ ...(process.stdout.isTTY ? { columns: process.stdout.columns || 80 } : {}),
10
+ };
11
+ /** The package's own version, from its package.json (two folders up from src/cli/ or dist/cli/). */
12
+ export function packageVersion() {
13
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
14
+ return pkg.version;
15
+ }
16
+ const COMMANDS = {
17
+ init: {
18
+ summary: 'create backlog/ with config.yml and its folders',
19
+ help: `Usage: ob init [--name <name>] [--readme]
20
+
21
+ Creates backlog/ at the top of this git repository (or here, outside git): a config.yml with
22
+ spec and name, and epics/, features/ and stories/todo, doing and done/, each with a .gitkeep.
23
+ If backlog/config.yml is already there, nothing changes.
24
+
25
+ --name <name> the backlog's name: lowercase letters, digits and dashes
26
+ (default: the repository's folder name)
27
+ --readme also write backlog/README.md, explaining the folders
28
+ `,
29
+ options: { name: { type: 'string' }, readme: { type: 'boolean' } },
30
+ run: (values, positionals, io) => {
31
+ if (positionals.length)
32
+ return usageError(`init takes no arguments (got "${positionals.join(' ')}")`, 'init', io);
33
+ // Real paths on both sides: git gives the repository's top through symlinks (macOS /var).
34
+ const cwd = realpathSync(io.cwd ?? process.cwd());
35
+ const dir = initDir(cwd);
36
+ const shown = relative(cwd, dir) || '.';
37
+ const r = initBacklog(dir, {
38
+ ...(typeof values['name'] === 'string' ? { name: values['name'] } : {}),
39
+ readme: values['readme'] === true,
40
+ });
41
+ if (r.existed) {
42
+ io.out(`${shown}/ already exists${r.name ? ` (${r.name})` : ''}: nothing changed.\n`);
43
+ return 0;
44
+ }
45
+ io.out(`Created the ${r.name} backlog in ${shown}/:\n${r.created.map(p => ` ${p}\n`).join('')}`);
46
+ io.out(repoRoot(cwd)
47
+ ? `Next: git add ${shown} && git commit -m "ob: init ${r.name} backlog"\n`
48
+ : 'Not in a git repository: run git init here to give the backlog its history.\n');
49
+ return 0;
50
+ },
51
+ },
52
+ new: {
53
+ summary: 'add an item with the next free ID, from the template',
54
+ help: `Usage: ob new <type> <title> [--parent <id>] [--slug <slug>] [--edit] [--no-commit]
55
+
56
+ Adds an item with the next free number under its parent, in a file named <id>-<slug>.md
57
+ (stories, bugs, spikes and tasks in stories/todo/), and commits it: "ob: add 2.3.5 Title".
58
+
59
+ ob new epic "Checkout"
60
+ ob new feature "Pay by card" --parent 1
61
+ ob new story "Card form" --parent 1.2 (or bug, spike, task)
62
+ ob new bug "Login fails on Safari" a bug or task with no parent goes into this
63
+ month's feature in epic 0 (0.1-2026-11),
64
+ made if needed
65
+ ob new capability "Identity"
66
+
67
+ --parent <id> the item it is filed under: an epic for a feature, a feature for a story,
68
+ bug, spike or task; a capability for an epic (optional)
69
+ --slug <slug> the file name's words (default: from the title)
70
+ --edit open the new file in $VISUAL or $EDITOR before committing
71
+ --no-commit write the file, leave committing to you
72
+ `,
73
+ options: { parent: { type: 'string', short: 'p' }, slug: { type: 'string' }, edit: { type: 'boolean', short: 'e' }, 'no-commit': { type: 'boolean' } },
74
+ run: (values, positionals, io) => {
75
+ const [type, ...words] = positionals;
76
+ if (type === undefined || !words.length)
77
+ return usageError('ob new needs a type and a title, such as: ob new story "Card form" --parent 1.2', 'new', io);
78
+ if (!ITEM_TYPES.includes(type))
79
+ return usageError(`"${type}" is not a type: use ${ITEM_TYPES.join(', ')}`, 'new', io);
80
+ const env = io.env ?? process.env;
81
+ const editor = env['VISUAL'] || env['EDITOR'];
82
+ const edit = values['edit'] === true;
83
+ if (edit && !editor)
84
+ throw new BacklogError('--edit needs an editor: set $EDITOR (or $VISUAL), such as EDITOR=nano');
85
+ const cwd = realpathSync(io.cwd ?? process.cwd());
86
+ const b = loadBacklog(findBacklog(cwd));
87
+ const title = words.join(' ');
88
+ const noCommit = values['no-commit'] === true;
89
+ const added = addItem(b, {
90
+ type, title,
91
+ ...(typeof values['parent'] === 'string' ? { parent: values['parent'] } : {}),
92
+ ...(typeof values['slug'] === 'string' ? { slug: values['slug'] } : {}),
93
+ commit: !noCommit && !edit,
94
+ ...(io.now ? { day: io.now } : {}),
95
+ });
96
+ const shown = (p) => relative(cwd, join(b.dir, p));
97
+ for (const c of added.created)
98
+ io.out(`Created ${c.id} ${shown(c.path)}\n`);
99
+ let committed = added.committed;
100
+ if (edit && editor) {
101
+ // As git runs an editor: through the shell, so "code --wait" works, with the file as $1.
102
+ const r = spawnSync('sh', ['-c', `${editor} "$1"`, editor, join(b.dir, added.path)], { stdio: 'inherit', env });
103
+ if (r.status !== 0) {
104
+ throw new BacklogError(`the editor (${editor}) exited with ${r.status ?? r.signal ?? r.error?.message}; ${shown(added.path)} is written but not committed`);
105
+ }
106
+ if (!noCommit)
107
+ committed = commit(added.created.map(c => join(b.dir, c.path)), message.add(added.id, title.trim()));
108
+ }
109
+ if (committed)
110
+ io.out(`Committed: ${message.add(added.id, title.trim())}\n`);
111
+ else if (noCommit)
112
+ io.out('Not committed (--no-commit).\n');
113
+ return 0;
114
+ },
115
+ },
116
+ validate: {
117
+ summary: 'check the backlog against the spec; exit 1 on errors',
118
+ help: `Usage: ob validate [--fix] [--no-commit] [--json]
119
+
120
+ Checks every file in the backlog against the spec and prints each problem with its code, the
121
+ file and how to fix it. Exits 1 if there are errors (warnings alone exit 0), so it can run in CI
122
+ or as a git pre-commit hook.
123
+
124
+ --fix renumber duplicate IDs (two branches each added the next number): the one added
125
+ later in git history gets the next free number and its file is renamed, and
126
+ children that came with it get the new parent; all in one commit
127
+ --no-commit with --fix, leave committing to you
128
+ --json print { backlog, valid, errors, warnings, problems, renumbered } for other tools
129
+ `,
130
+ options: { fix: { type: 'boolean' }, 'no-commit': { type: 'boolean' }, json: { type: 'boolean' } },
131
+ run: (values, positionals, io) => {
132
+ if (positionals.length)
133
+ return usageError(`validate takes no arguments (got "${positionals.join(' ')}")`, 'validate', io);
134
+ const cwd = realpathSync(io.cwd ?? process.cwd());
135
+ const dir = findBacklog(cwd);
136
+ const json = values['json'] === true;
137
+ let renumbered = [];
138
+ let committed = false;
139
+ // A config.yml that can't be read is reported below, not fixed.
140
+ if (values['fix'] === true && validateDir(dir).backlog)
141
+ ({ renumbered, committed } = fixDuplicates(dir, { commit: values['no-commit'] !== true }));
142
+ const { backlog, problems } = validateDir(dir);
143
+ const errors = problems.filter(p => p.severity === 'error').length;
144
+ const warnings = problems.length - errors;
145
+ if (json) {
146
+ io.out(JSON.stringify({ backlog: dir, valid: errors === 0, errors, warnings, problems, renumbered, committed }, null, 2) + '\n');
147
+ return errors ? 1 : 0;
148
+ }
149
+ const shown = (p) => relative(cwd, join(dir, p));
150
+ for (const r of renumbered) {
151
+ io.out(`Renumbered ${r.from} to ${r.to}: ${shown(r.path)} → ${shown(r.newPath)}\n`);
152
+ for (const c of r.children)
153
+ io.out(` parent ${r.from} → ${r.to}: ${shown(c.path)}\n`);
154
+ }
155
+ if (committed)
156
+ io.out(`Committed: ${message.renumber(renumbered)}\n`);
157
+ for (const p of problems)
158
+ io.out(formatProblem({ ...p, path: shown(p.path) }) + '\n');
159
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
160
+ const items = backlog ? `, ${count(backlog.items.length, 'item')}` : '';
161
+ io.out(problems.length
162
+ ? `${shown('') || '.'}/: ${count(errors, 'error')}, ${count(warnings, 'warning')}${items}\n`
163
+ : `${shown('') || '.'}/ is valid${items}\n`);
164
+ return errors ? 1 : 0;
165
+ },
166
+ },
167
+ move: {
168
+ summary: 'move a story, bug, spike or task to todo, doing or done',
169
+ help: `Usage: ob move <id> <todo|doing|done> [--no-commit]
170
+ ob start <id> (the same as ob move <id> doing)
171
+ ob done <id> (the same as ob move <id> done)
172
+
173
+ Moves the item's file to stories/<status>/ with git mv and commits only that move:
174
+ "ob: move 2.3.4 to doing". With done-folders: month in config.yml, done files into
175
+ stories/done/YYYY-MM/. Epics, features and capabilities don't move: their status comes from
176
+ their items.
177
+
178
+ --no-commit stage the move (git mv), leave committing to you
179
+ `,
180
+ options: { 'no-commit': { type: 'boolean' } },
181
+ run: (values, positionals, io) => {
182
+ const [id, status, ...extra] = positionals;
183
+ if (id === undefined || status === undefined || extra.length)
184
+ return usageError('ob move needs an id and a status, such as: ob move 2.3.4 doing', 'move', io);
185
+ return moveCommand(id, status, values, io, 'move');
186
+ },
187
+ },
188
+ start: {
189
+ summary: 'ob move <id> doing',
190
+ help: 'Usage: ob start <id> [--no-commit]\n\nThe same as ob move <id> doing: see ob move --help.\n',
191
+ options: { 'no-commit': { type: 'boolean' } },
192
+ run: (values, positionals, io) => {
193
+ const [id, ...extra] = positionals;
194
+ if (id === undefined || extra.length)
195
+ return usageError('ob start needs one id, such as: ob start 2.3.4', 'start', io);
196
+ return moveCommand(id, 'doing', values, io, 'start');
197
+ },
198
+ },
199
+ done: {
200
+ summary: 'ob move <id> done',
201
+ help: 'Usage: ob done <id> [--no-commit]\n\nThe same as ob move <id> done: see ob move --help.\n',
202
+ options: { 'no-commit': { type: 'boolean' } },
203
+ run: (values, positionals, io) => {
204
+ const [id, ...extra] = positionals;
205
+ if (id === undefined || extra.length)
206
+ return usageError('ob done needs one id, such as: ob done 2.3.4', 'done', io);
207
+ return moveCommand(id, 'done', values, io, 'done');
208
+ },
209
+ },
210
+ list: {
211
+ summary: 'list stories, bugs, spikes and tasks in build order, filtered',
212
+ help: `Usage: ob list [filters] [--all] [--json]
213
+
214
+ Lists stories, bugs, spikes and tasks in build order (by number): ID, status, repo and title.
215
+ Done items show for 30 days after they were moved to done (from git history); --all shows
216
+ every one. Plain text, no colour; titles are cut to fit a terminal, never when piped.
217
+
218
+ --status <s> todo, doing or done
219
+ --type <t> story, bug, spike or task
220
+ --parent <id> under this epic, feature or capability
221
+ --repo <name> with this repo (T3)
222
+ --assignee <h> assigned to this handle
223
+ --sprint <name> in this sprint
224
+ --all done items of any age
225
+ --json the same items, as JSON, for other tools
226
+
227
+ Each filter takes one value or several joined by commas (--status todo,doing).
228
+ `,
229
+ options: {
230
+ status: { type: 'string', multiple: true }, type: { type: 'string', multiple: true }, parent: { type: 'string', multiple: true },
231
+ repo: { type: 'string', multiple: true }, assignee: { type: 'string', multiple: true }, sprint: { type: 'string', multiple: true },
232
+ all: { type: 'boolean' }, json: { type: 'boolean' },
233
+ },
234
+ run: (values, positionals, io) => {
235
+ if (positionals.length)
236
+ return usageError(`list takes no arguments (got "${positionals.join(' ')}"); filter with --status, --type, --parent …`, 'list', io);
237
+ const cwd = realpathSync(io.cwd ?? process.cwd());
238
+ const b = loadBacklog(findBacklog(cwd));
239
+ const list = (k) => {
240
+ const v = values[k];
241
+ return Array.isArray(v) ? v.flatMap(x => x.split(',')).map(x => x.trim()).filter(Boolean) : undefined;
242
+ };
243
+ const filters = Object.fromEntries(['status', 'type', 'parent', 'repo', 'assignee', 'sprint'].map(k => [k, list(k)]).filter(([, v]) => v !== undefined));
244
+ let listed;
245
+ try {
246
+ listed = listItems(b, filters, { all: values['all'] === true, ...(io.now ? { now: io.now } : {}) });
247
+ }
248
+ catch (e) {
249
+ if (e instanceof BacklogError && /is not a (status|type)/.test(e.message))
250
+ return usageError(e.message, 'list', io);
251
+ throw e;
252
+ }
253
+ if (values['json'] === true) {
254
+ io.out(JSON.stringify(listed.items.map(i => ({
255
+ id: i.id, type: i.type, status: i.status ?? null, title: i.title, parent: i.parent ?? null, repo: reposOf(i),
256
+ assignee: i.fields['assignee'] ?? null, sprint: i.fields['sprint'] ?? null, path: i.path,
257
+ })), null, 2) + '\n');
258
+ return 0;
259
+ }
260
+ const rows = listed.items.map(i => ({ id: i.id, status: i.status ?? '', repo: reposOf(i).join(','), title: i.title }));
261
+ const w = (f) => Math.max(0, ...rows.map(r => f(r).length));
262
+ const idW = w(r => r.id), stW = w(r => r.status), repoW = w(r => r.repo);
263
+ for (const r of rows) {
264
+ const line = [r.id.padEnd(idW), r.status.padEnd(stW), ...(repoW ? [r.repo.padEnd(repoW)] : []), r.title].join(' ');
265
+ io.out(fit(line, io.columns) + '\n');
266
+ }
267
+ if (listed.hiddenDone)
268
+ io.err(`ob: ${listed.hiddenDone} done ${listed.hiddenDone === 1 ? 'item' : 'items'} finished over 30 days ago not shown; --all shows them\n`);
269
+ return 0;
270
+ },
271
+ },
272
+ show: {
273
+ summary: 'show an item: where it sits, its file, children, progress and history',
274
+ help: `Usage: ob show <id> [--json]
275
+
276
+ Prints the item's place in the plan (2-build › 2.3-cli › 2.3.4-ob-move), its file, its file's
277
+ text, its children (with progress, for a capability, epic or feature) and the commits that
278
+ touched it. An ID pruned with git rm is found in git history: its last version, marked deleted.
279
+
280
+ --json the same, as JSON, for other tools
281
+ `,
282
+ options: { json: { type: 'boolean' } },
283
+ run: (values, positionals, io) => {
284
+ const [id, ...extra] = positionals;
285
+ if (id === undefined || extra.length)
286
+ return usageError('ob show needs one id, such as: ob show 2.3.4', 'show', io);
287
+ const cwd = realpathSync(io.cwd ?? process.cwd());
288
+ const b = loadBacklog(findBacklog(cwd));
289
+ const s = showItem(b, id);
290
+ if (values['json'] === true) {
291
+ io.out(JSON.stringify(s, null, 2) + '\n');
292
+ return 0;
293
+ }
294
+ const shown = relative(cwd, join(b.dir, s.path));
295
+ const lines = [s.breadcrumb.join(' › ')];
296
+ lines.push(s.deleted ? `${shown} (deleted)` : `${shown}${s.status ? ` ${s.status}` : ''}`);
297
+ if (s.deleted)
298
+ lines.push(`Deleted in ${s.deleted.hash} on ${s.deleted.date} by ${s.deleted.author}: ${s.deleted.subject}. Its last version:`);
299
+ if (s.progress)
300
+ lines.push(`Progress: ${progressText(s.progress)}, ${s.progress.doing} doing, ${s.progress.todo} todo`);
301
+ if (s.sameId.length)
302
+ lines.push(`Also id ${id}: ${s.sameId.join(', ')} (run ob validate --fix)`);
303
+ lines.push('', s.text.trimEnd());
304
+ if (s.children.length) {
305
+ const w = Math.max(...s.children.map(c => c.id.length));
306
+ lines.push('', 'Children:', ...s.children.map(c => ` ${c.id.padEnd(w)} ${(c.status ?? c.type).padEnd(7)} ${c.title}`));
307
+ }
308
+ if (s.history.length)
309
+ lines.push('', 'History:', ...s.history.map(h => ` ${h.date} ${h.hash} ${h.author} ${h.subject}`));
310
+ io.out(lines.join('\n') + '\n');
311
+ return 0;
312
+ },
313
+ },
314
+ tree: {
315
+ summary: 'the plan as a tree: capabilities, epics, features with progress, and their items',
316
+ help: `Usage: ob tree [--depth <n>] [--all] [--json]
317
+
318
+ Prints capabilities, epics and features with their status and progress (done of total, worked
319
+ out from their stories, bugs, spikes and tasks), and the items under them, in build order. Done
320
+ items show for 30 days, as in ob list; the progress counts every item.
321
+
322
+ --depth <n> show n levels (1: the top items only)
323
+ --all done items of any age
324
+ --json the same tree, as JSON
325
+ `,
326
+ options: { depth: { type: 'string' }, all: { type: 'boolean' }, json: { type: 'boolean' } },
327
+ run: (values, positionals, io) => {
328
+ if (positionals.length)
329
+ return usageError(`tree takes no arguments (got "${positionals.join(' ')}")`, 'tree', io);
330
+ const depthArg = values['depth'];
331
+ const maxDepth = depthArg === undefined ? Infinity : Number(depthArg);
332
+ if (depthArg !== undefined && (!Number.isInteger(maxDepth) || maxDepth < 1))
333
+ return usageError(`--depth takes a whole number from 1 (got "${String(depthArg)}")`, 'tree', io);
334
+ const cwd = realpathSync(io.cwd ?? process.cwd());
335
+ const b = loadBacklog(findBacklog(cwd));
336
+ const now = io.now ?? new Date();
337
+ const recent = values['all'] === true ? null : recentlyDone(b, new Date(now.getTime() - 30 * 86_400_000));
338
+ let hidden = 0;
339
+ const visible = (n) => {
340
+ const ok = n.item.status !== 'done' || !recent || recent.has(n.item.path);
341
+ if (!ok)
342
+ hidden++;
343
+ return ok;
344
+ };
345
+ const toOut = (n, depth) => {
346
+ const story = isStoryLevel(n.item);
347
+ const p = story ? null : progressOf(n);
348
+ return {
349
+ id: n.item.id, type: n.item.type, title: n.item.title, status: story ? n.item.status ?? null : p?.status ?? null, path: n.item.path, progress: p,
350
+ children: depth + 1 < maxDepth ? n.children.filter(visible).map(c => toOut(c, depth + 1)) : [],
351
+ };
352
+ };
353
+ const roots = buildTree(b.items).roots.filter(visible).map(r => toOut(r, 0));
354
+ if (values['json'] === true)
355
+ io.out(JSON.stringify(roots, null, 2) + '\n');
356
+ else {
357
+ const print = (o, depth) => {
358
+ const head = `${' '.repeat(depth)}${o.id} ${(o.status ?? '-').padEnd(5)}`;
359
+ io.out(fit(`${head} ${o.progress ? `${progressText(o.progress)} ` : ''}${o.title}`, io.columns) + '\n');
360
+ o.children.forEach(c => print(c, depth + 1));
361
+ };
362
+ roots.forEach(r => print(r, 0));
363
+ }
364
+ if (hidden)
365
+ io.err(`ob: ${hidden} done ${hidden === 1 ? 'item' : 'items'} finished over 30 days ago not shown; --all shows them\n`);
366
+ return 0;
367
+ },
368
+ },
369
+ };
370
+ /** "3/9 done (33%)". */
371
+ function progressText(p) {
372
+ return `${p.done}/${p.total} done (${p.percent}%)`;
373
+ }
374
+ /** A line cut to a terminal's width with "…" (whole characters); unchanged when piped. */
375
+ function fit(line, columns) {
376
+ const chars = [...line];
377
+ if (columns === undefined || chars.length <= columns)
378
+ return line;
379
+ return chars.slice(0, Math.max(1, columns - 1)).join('').trimEnd() + '…';
380
+ }
381
+ const STATUSES = ['todo', 'doing', 'done'];
382
+ /** ob move, start and done: checks the item and status, then one git mv and one commit. */
383
+ function moveCommand(id, status, values, io, command) {
384
+ if (!STATUSES.includes(status))
385
+ return usageError(`"${status}" is not a status: use todo, doing or done`, command, io);
386
+ const cwd = realpathSync(io.cwd ?? process.cwd());
387
+ const b = loadBacklog(findBacklog(cwd));
388
+ const found = b.items.filter(i => i.id === id);
389
+ const item = found[0];
390
+ if (!item)
391
+ throw new BacklogError(`no item ${id} in this backlog`);
392
+ if (found.length > 1)
393
+ throw new BacklogError(`${found.length} items have id ${id} (${found.map(i => i.path).join(', ')}); run ob validate --fix first`);
394
+ if (!isStoryLevel(item)) {
395
+ const t = `${/^[aeiou]/.test(item.type) ? 'an' : 'a'} ${item.type}`;
396
+ throw new BacklogError(`${id} is ${t}, which doesn't move: only stories, bugs, spikes and tasks do. ${t[0]?.toUpperCase()}${t.slice(1)} is done when all its items are done`);
397
+ }
398
+ const shown = (p) => relative(cwd, join(b.dir, p));
399
+ if (item.status === status) {
400
+ io.out(`${id} is already in ${status}: ${shown(item.path)}; nothing changed.\n`);
401
+ return 0;
402
+ }
403
+ const r = moveItem(b, item, status, { commit: values['no-commit'] !== true, ...(io.now ? { day: io.now } : {}) });
404
+ io.out(`Moved ${id} to ${status}: ${shown(item.path)} → ${shown(r.path)}\n`);
405
+ if (r.committed)
406
+ io.out(`Committed: ${message.move(id, status)}\n`);
407
+ else if (values['no-commit'] === true)
408
+ io.out('Not committed (--no-commit).\n');
409
+ return 0;
410
+ }
411
+ export function usage() {
412
+ const width = Math.max(...Object.keys(COMMANDS).map(c => c.length));
413
+ return `ob — Open Backlog ${packageVersion()} (spec ${SPEC_VERSION})
414
+
415
+ Usage: ob <command> [options]
416
+ ob [--version] [--help]
417
+
418
+ Commands:
419
+ ${Object.entries(COMMANDS).map(([name, c]) => ` ${name.padEnd(width)} ${c.summary}\n`).join('')}
420
+ Run "ob <command> --help" for its options.
421
+
422
+ A backlog is a folder of Markdown files in git: ${SPEC_URL}
423
+ `;
424
+ }
425
+ /** Every command with its long options, in --help order (the README documents each one). */
426
+ export function commandOptions() {
427
+ return Object.fromEntries(Object.entries(COMMANDS).map(([name, c]) => [name, Object.keys(c.options).filter(o => o !== 'help')]));
428
+ }
429
+ function usageError(message, command, io) {
430
+ io.err(`ob: ${message}\nRun "ob ${command ? `${command} ` : ''}--help" for usage.\n`);
431
+ return 2;
432
+ }
433
+ /**
434
+ * Runs ob with its arguments (without "node" and the script) and returns the exit code:
435
+ * 0 done, 1 the command failed (a BacklogError, from report), 2 bad usage. Writes nothing to
436
+ * process directly, so tests can call it.
437
+ */
438
+ export function run(args, io = STD) {
439
+ const name = args[0] !== undefined && !args[0].startsWith('-') ? args[0] : undefined;
440
+ if (name === undefined) {
441
+ let parsed;
442
+ try {
443
+ parsed = parseArgs({ args, options: { version: { type: 'boolean', short: 'v' }, help: { type: 'boolean', short: 'h' } }, strict: true });
444
+ }
445
+ catch (e) {
446
+ return usageError(e.message, undefined, io);
447
+ }
448
+ if (parsed.values.version)
449
+ io.out(packageVersion() + '\n');
450
+ else
451
+ io.out(usage());
452
+ return 0;
453
+ }
454
+ const command = COMMANDS[name];
455
+ if (!command)
456
+ return usageError(`unknown command "${name}"`, undefined, io);
457
+ let parsed;
458
+ try {
459
+ parsed = parseArgs({ args: args.slice(1), options: { ...command.options, help: { type: 'boolean', short: 'h' } }, allowPositionals: true, strict: true });
460
+ }
461
+ catch (e) {
462
+ return usageError(e.message, name, io);
463
+ }
464
+ if (parsed.values['help']) {
465
+ io.out(command.help);
466
+ return 0;
467
+ }
468
+ try {
469
+ return command.run(parsed.values, parsed.positionals, io);
470
+ }
471
+ catch (e) {
472
+ return report(e, io);
473
+ }
474
+ }
475
+ /**
476
+ * What ob prints for an error that escapes a command, and its exit code: a backlog that can't be
477
+ * read (no config.yml, a file that isn't YAML) is one line naming the file, never a stack trace.
478
+ * Anything else is a bug in ob, so it keeps its stack.
479
+ */
480
+ export function report(e, io = STD) {
481
+ if (e instanceof BacklogError) {
482
+ io.err(`ob: ${e.message}\n`);
483
+ return 1;
484
+ }
485
+ throw e;
486
+ }
@@ -0,0 +1,37 @@
1
+ import type { Backlog, ItemType } from './types.js';
2
+ /**
3
+ * Adding an item (2.3.2): the next free ID under its parent ([id-numbers]), a file from the
4
+ * template, and one commit. Everything is checked before anything is written.
5
+ */
6
+ export declare const ITEM_TYPES: readonly ItemType[];
7
+ /** Types that may be filed with no parent into this month's feature in epic 0. */
8
+ export declare const UNPLANNED_TYPES: readonly ItemType[];
9
+ /** A slug a user chooses: lowercase letters and digits joined by dashes. */
10
+ export declare const SLUG_PATTERN: RegExp;
11
+ export interface AddOptions {
12
+ type: string;
13
+ title: string;
14
+ parent?: string;
15
+ slug?: string;
16
+ /** Commit the new files (default true; nothing to commit outside git). */
17
+ commit?: boolean;
18
+ /** The day, for this month's feature in epic 0. */
19
+ day?: Date;
20
+ }
21
+ export interface Added {
22
+ id: string;
23
+ /** The new item's file, from the backlog folder. */
24
+ path: string;
25
+ /** Every file written, from the backlog folder: epic 0 and the month's feature when they were needed, then the item. */
26
+ created: {
27
+ id: string;
28
+ path: string;
29
+ }[];
30
+ committed: boolean;
31
+ }
32
+ /**
33
+ * Adds an item to the backlog. A bug or task with no parent goes into this month's feature in
34
+ * epic 0 (0.1-2026-11), and the epic and feature are created first if they aren't there.
35
+ * Throws a BacklogError, having written nothing, if the type, title, slug or parent is wrong.
36
+ */
37
+ export declare function addItem(b: Backlog, opts: AddOptions): Added;
@@ -0,0 +1,99 @@
1
+ import { join } from 'node:path';
2
+ import { commit, message, monthOf, nextId } from './git.js';
3
+ import { STORY_LEVEL_TYPES } from './hierarchy.js';
4
+ import { BacklogError } from './types.js';
5
+ import { createItem, slugify } from './write.js';
6
+ /**
7
+ * Adding an item (2.3.2): the next free ID under its parent ([id-numbers]), a file from the
8
+ * template, and one commit. Everything is checked before anything is written.
9
+ */
10
+ export const ITEM_TYPES = ['capability', 'epic', 'feature', 'story', 'bug', 'spike', 'task'];
11
+ /** Types that may be filed with no parent into this month's feature in epic 0. */
12
+ export const UNPLANNED_TYPES = ['bug', 'task'];
13
+ /** A slug a user chooses: lowercase letters and digits joined by dashes. */
14
+ export const SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
15
+ /** The type a parent must have, or null for none; capability is optional for an epic. */
16
+ function parentType(type) {
17
+ if (type === 'feature')
18
+ return 'epic';
19
+ if (type === 'epic')
20
+ return 'capability';
21
+ if (STORY_LEVEL_TYPES.includes(type))
22
+ return 'feature';
23
+ return null;
24
+ }
25
+ /**
26
+ * Adds an item to the backlog. A bug or task with no parent goes into this month's feature in
27
+ * epic 0 (0.1-2026-11), and the epic and feature are created first if they aren't there.
28
+ * Throws a BacklogError, having written nothing, if the type, title, slug or parent is wrong.
29
+ */
30
+ export function addItem(b, opts) {
31
+ const { type } = opts;
32
+ const title = opts.title.trim();
33
+ if (!ITEM_TYPES.includes(type))
34
+ throw new BacklogError(`"${type}" is not a type: use ${ITEM_TYPES.join(', ')}`);
35
+ if (!title)
36
+ throw new BacklogError('a new item needs a title');
37
+ if (/[\r\n]/.test(title))
38
+ throw new BacklogError('a title is one line');
39
+ if (opts.slug !== undefined && !SLUG_PATTERN.test(opts.slug)) {
40
+ throw new BacklogError(`"${opts.slug}" can't be a slug: use lowercase letters, digits and dashes, such as sign-in-form`);
41
+ }
42
+ if (!slugify(title) && opts.slug === undefined)
43
+ throw new BacklogError(`can't make a slug from "${title}"; choose one with --slug`);
44
+ const byId = (id) => b.items.find(i => i.id === id);
45
+ const want = parentType(type);
46
+ const pending = [];
47
+ let parent = opts.parent?.trim() || undefined;
48
+ if (parent !== undefined) {
49
+ if (want === null)
50
+ throw new BacklogError(`${article(type)} ${type} has no parent`);
51
+ if (parent.includes('/'))
52
+ throw new BacklogError(`parent ${parent} is in another backlog; ob new files items under a parent in this one`);
53
+ const p = byId(parent);
54
+ if (!p)
55
+ throw new BacklogError(`parent ${parent} is not in this backlog`);
56
+ if (p.type !== want)
57
+ throw new BacklogError(`parent ${parent} is ${article(p.type)} ${p.type}; ${article(type)} ${type}'s parent must be ${article(want)} ${want}`);
58
+ if (type === 'feature' && parent === '0')
59
+ throw new BacklogError('epic 0 has one feature per month, made by ob new bug or ob new task with no --parent');
60
+ }
61
+ else if (want === 'feature') {
62
+ if (!UNPLANNED_TYPES.includes(type)) {
63
+ throw new BacklogError(`${article(type)} ${type} needs --parent <feature>, such as --parent 2.3; only a bug or task with no parent goes into unplanned work (epic 0)`);
64
+ }
65
+ const month = monthOf(opts.day ?? new Date());
66
+ const epic0 = byId('0');
67
+ if (epic0 && epic0.type !== 'epic')
68
+ throw new BacklogError(`item 0 is ${article(epic0.type)} ${epic0.type}, so there is no epic 0 for unplanned work`);
69
+ const feature = b.items.find(i => i.type === 'feature' && i.parent === '0' && i.file?.slug === month);
70
+ if (feature)
71
+ parent = feature.id;
72
+ else {
73
+ if (!epic0)
74
+ pending.push({ id: '0', type: 'epic', title: 'Unplanned work', slug: 'unplanned' });
75
+ parent = nextId(b, '0');
76
+ pending.push({ id: parent, type: 'feature', title: `Unplanned, ${month}`, parent: '0', slug: month });
77
+ }
78
+ }
79
+ else if (want === 'epic') {
80
+ throw new BacklogError('a feature needs --parent <epic>, such as --parent 2');
81
+ }
82
+ const id = type === 'capability' ? nextId(b, undefined, true) : type === 'epic' ? nextId(b) : nextId(b, parent);
83
+ pending.push({ id, type, title, ...(parent ? { parent } : {}), ...(opts.slug ? { slug: opts.slug } : {}) });
84
+ const created = pending.map(n => ({ id: n.id, path: createItem(b.dir, n) }));
85
+ const path = created[created.length - 1]?.path ?? '';
86
+ let committed = false;
87
+ if (opts.commit !== false) {
88
+ try {
89
+ committed = commit(created.map(c => join(b.dir, c.path)), message.add(id, title));
90
+ }
91
+ catch (e) {
92
+ throw new BacklogError(`created ${created.map(c => c.path).join(', ')}, but did not commit: ${e.message}`);
93
+ }
94
+ }
95
+ return { id, path, created, committed };
96
+ }
97
+ function article(word) {
98
+ return /^[aeiou]/.test(word) ? 'an' : 'a';
99
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `ob validate --fix` (2.3.3): repairs [id-unique], the problem a merge makes when two branches
3
+ * each added the next number. Of items sharing an ID, the one added first in git history keeps
4
+ * it; each one added later gets the next free number under its parent and a file renamed to
5
+ * match (a git mv, so it keeps its history). Children that came with it, added on the same line
6
+ * of history after it, get the new number as their parent. Nothing else changes.
7
+ */
8
+ export interface Renumbered {
9
+ from: string;
10
+ to: string;
11
+ /** The file before and after, from the backlog folder. */
12
+ path: string;
13
+ newPath: string;
14
+ /** Children whose parent changed from `from` to `to`. */
15
+ children: {
16
+ id: string;
17
+ path: string;
18
+ }[];
19
+ }
20
+ /**
21
+ * Renumbers duplicate IDs in the backlog in `dir` and commits every change in one commit
22
+ * ("ob: renumber 2.3.5 to 2.3.6"), unless `commit` is false. Needs git, to tell which copy is
23
+ * newer. Returns what it changed (empty if there were no duplicates).
24
+ */
25
+ export declare function fixDuplicates(dir: string, opts?: {
26
+ commit?: boolean;
27
+ }): {
28
+ renumbered: Renumbered[];
29
+ committed: boolean;
30
+ };