open-backlog 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * open-backlog: the core library (D1). It reads, parses and validates an Open Backlog and
3
+ * assigns IDs; the ob command (src/cli/) and the board (open-backlog-board) are both built on
4
+ * it, so they can't disagree about the rules. It never imports the CLI.
5
+ *
6
+ * import { readBacklog } from 'open-backlog';
7
+ * const backlog = readBacklog(); // from the working directory, walking up
8
+ * updateItem(backlog.dir, item, { assignee: 'ana' }); // one value changes, nothing else
9
+ *
10
+ * Git (the user's own, D2) and the next ID ([id-numbers]) are in git.ts (2.2.6).
11
+ */
12
+ export { SPEC_URL, SPEC_VERSION } from './spec.js';
13
+ export { addItem, ITEM_TYPES, SLUG_PATTERN, UNPLANNED_TYPES } from './add.js';
14
+ export { fixDuplicates } from './fix.js';
15
+ export { addedIn, changes, commit, git, history, isAncestor, isClean, message, monthOf, move, moveItem, nextId, pull, push, repoRoot, statusPath, usedIds } from './git.js';
16
+ export { initBacklog, initDir, INIT_FOLDERS, INIT_README, NAME_PATTERN } from './init.js';
17
+ export { buildOrder, buildTree, columnOrder, isStoryLevel, progressOf, STORY_LEVEL_TYPES, walk } from './hierarchy.js';
18
+ export { compareIds, parseFileName } from './ids.js';
19
+ export { listItems, recentlyDone, reposOf } from './list.js';
20
+ export { showItem } from './show.js';
21
+ export { findBacklog, loadBacklog, readBacklog, statusOf } from './read.js';
22
+ export { BacklogError } from './types.js';
23
+ export { RULE, RULES } from './rules.js';
24
+ export { formatProblem, validate, validateDir } from './validate.js';
25
+ export { createItem, folderFor, formatValue, newItemPath, newItemText, setFields, slugify, updateItem } from './write.js';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A new backlog (2.3.1): `backlog/` with a two-line config.yml (spec, name) and the folders, each
3
+ * kept in git by a .gitkeep. It never overwrites a file: run again, it finds config.yml and
4
+ * changes nothing.
5
+ */
6
+ /** The folders a new backlog starts with; capabilities/ and sprints/ come when they're needed. */
7
+ export declare const INIT_FOLDERS: readonly ["epics", "features", "stories/todo", "stories/doing", "stories/done"];
8
+ /** A backlog name ([config]): lowercase letters and digits, joined by single dashes. */
9
+ export declare const NAME_PATTERN: RegExp;
10
+ export declare const INIT_README = "# Backlog\n\nThis folder is an [Open Backlog](https://openbacklog.org/spec): every item is a Markdown file,\nand git history is its timeline.\n\n- `config.yml`: the backlog's name and the spec version it follows.\n- `epics/`: large goals, such as `2-build.md`.\n- `features/`: parts of an epic, such as `2.3-cli.md` (feature 3 of epic 2).\n- `stories/`: stories, bugs, spikes and tasks, such as `2.3.4-ob-move.md`, in a folder for\n their status: `todo/`, `doing/` or `done/`. Moving the file changes its status.\n\nThe `ob` command creates, moves, lists and checks items: run `ob --help`.\n";
11
+ export interface InitOptions {
12
+ /** The backlog's name; by default the repository's (or folder's) name, as a slug. */
13
+ name?: string;
14
+ /** Also write backlog/README.md explaining the folders. */
15
+ readme?: boolean;
16
+ }
17
+ export interface InitResult {
18
+ /** The backlog folder. */
19
+ dir: string;
20
+ name: string;
21
+ /** Paths created, relative to the backlog folder; empty when it already existed. */
22
+ created: string[];
23
+ /** True when config.yml was already there, so nothing was changed. */
24
+ existed: boolean;
25
+ }
26
+ /**
27
+ * Where `ob init` puts the backlog: `backlog/` at the top of the git repository holding `from`,
28
+ * or in `from` itself outside git.
29
+ */
30
+ export declare function initDir(from?: string): string;
31
+ /**
32
+ * Creates the backlog in `dir` (a folder named backlog, usually from initDir). If its config.yml
33
+ * exists, nothing is written. Otherwise each missing file is added and existing ones are kept.
34
+ */
35
+ export declare function initBacklog(dir: string, opts?: InitOptions): InitResult;
@@ -0,0 +1,77 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { basename, join, resolve } from 'node:path';
3
+ import { repoRoot } from './git.js';
4
+ import { SPEC_VERSION } from './spec.js';
5
+ import { BacklogError } from './types.js';
6
+ import { formatValue, slugify } from './write.js';
7
+ import { parseMapping } from './yaml.js';
8
+ /**
9
+ * A new backlog (2.3.1): `backlog/` with a two-line config.yml (spec, name) and the folders, each
10
+ * kept in git by a .gitkeep. It never overwrites a file: run again, it finds config.yml and
11
+ * changes nothing.
12
+ */
13
+ /** The folders a new backlog starts with; capabilities/ and sprints/ come when they're needed. */
14
+ export const INIT_FOLDERS = ['epics', 'features', 'stories/todo', 'stories/doing', 'stories/done'];
15
+ /** A backlog name ([config]): lowercase letters and digits, joined by single dashes. */
16
+ export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
17
+ export const INIT_README = `# Backlog
18
+
19
+ This folder is an [Open Backlog](https://openbacklog.org/spec): every item is a Markdown file,
20
+ and git history is its timeline.
21
+
22
+ - \`config.yml\`: the backlog's name and the spec version it follows.
23
+ - \`epics/\`: large goals, such as \`2-build.md\`.
24
+ - \`features/\`: parts of an epic, such as \`2.3-cli.md\` (feature 3 of epic 2).
25
+ - \`stories/\`: stories, bugs, spikes and tasks, such as \`2.3.4-ob-move.md\`, in a folder for
26
+ their status: \`todo/\`, \`doing/\` or \`done/\`. Moving the file changes its status.
27
+
28
+ The \`ob\` command creates, moves, lists and checks items: run \`ob --help\`.
29
+ `;
30
+ /**
31
+ * Where `ob init` puts the backlog: `backlog/` at the top of the git repository holding `from`,
32
+ * or in `from` itself outside git.
33
+ */
34
+ export function initDir(from = process.cwd()) {
35
+ return join(repoRoot(from) ?? resolve(from), 'backlog');
36
+ }
37
+ /**
38
+ * Creates the backlog in `dir` (a folder named backlog, usually from initDir). If its config.yml
39
+ * exists, nothing is written. Otherwise each missing file is added and existing ones are kept.
40
+ */
41
+ export function initBacklog(dir, opts = {}) {
42
+ const root = resolve(dir);
43
+ if (existsSync(join(root, 'config.yml')))
44
+ return { dir: root, name: existingName(root), created: [], existed: true };
45
+ const name = opts.name ?? slugify(basename(resolve(root, '..')));
46
+ if (!NAME_PATTERN.test(name)) {
47
+ throw new BacklogError(opts.name === undefined
48
+ ? `can't make a backlog name from the folder "${basename(resolve(root, '..'))}"; choose one with --name, such as --name my-app`
49
+ : `"${name}" can't be a backlog name: use lowercase letters, digits and dashes, such as my-app`);
50
+ }
51
+ const files = [
52
+ ['config.yml', `spec: ${formatValue('spec', SPEC_VERSION)}\nname: ${formatValue('name', name)}\n`],
53
+ ...INIT_FOLDERS.map((f) => [`${f}/.gitkeep`, '']),
54
+ ];
55
+ if (opts.readme)
56
+ files.push(['README.md', INIT_README]);
57
+ const created = [];
58
+ for (const [path, text] of files) {
59
+ const abs = join(root, path);
60
+ if (existsSync(abs))
61
+ continue;
62
+ mkdirSync(join(abs, '..'), { recursive: true });
63
+ writeFileSync(abs, text, { flag: 'wx' });
64
+ created.push(path);
65
+ }
66
+ return { dir: root, name, created, existed: false };
67
+ }
68
+ /** The name in an existing config.yml, or "" if it can't be read (ob validate says why). */
69
+ function existingName(root) {
70
+ try {
71
+ const name = parseMapping(readFileSync(join(root, 'config.yml'), 'utf8'))?.['name'];
72
+ return typeof name === 'string' ? name : '';
73
+ }
74
+ catch {
75
+ return '';
76
+ }
77
+ }
@@ -0,0 +1,40 @@
1
+ import type { Backlog, Item } from './types.js';
2
+ /**
3
+ * Listing (2.3.5): story-level items in build order, filtered, with old done work left out so a
4
+ * big done/ never floods the list. The board's filters use the same function.
5
+ */
6
+ export interface ListFilters {
7
+ /** Each filter matches any of its values; filters combine (all must match). */
8
+ status?: string[];
9
+ type?: string[];
10
+ /** An epic, feature or capability: items anywhere under it. */
11
+ parent?: string[];
12
+ repo?: string[];
13
+ assignee?: string[];
14
+ sprint?: string[];
15
+ }
16
+ export interface ListOptions {
17
+ /** Include done items however long ago they were finished (default: the last `days`). */
18
+ all?: boolean;
19
+ /** How far back done work is shown, in days (default 30). */
20
+ days?: number;
21
+ /** Now, for the window (tests). */
22
+ now?: Date;
23
+ }
24
+ export interface Listed {
25
+ items: Item[];
26
+ /** Done items left out because they were finished before the window. */
27
+ hiddenDone: number;
28
+ }
29
+ /** An item's repo field as a list (a name or a list of names). */
30
+ export declare function reposOf(item: Item): string[];
31
+ /**
32
+ * Done items finished in the window: those whose file a commit since then moved into (or added
33
+ * to, or changed in) stories/done/, plus any not yet committed. Every commit touching done/ is
34
+ * read and its date checked here: git log --since stops at the first older commit, so one
35
+ * out-of-order date (a rebase) would hide recent work. Null outside git, where there are no
36
+ * dates, so every done item counts as recent.
37
+ */
38
+ export declare function recentlyDone(b: Backlog, since: Date): Set<string> | null;
39
+ /** Story-level items in build order (by number), filtered; done ones from the last 30 days unless `all`. */
40
+ export declare function listItems(b: Backlog, filters?: ListFilters, opts?: ListOptions): Listed;
@@ -0,0 +1,79 @@
1
+ import { git, repoRoot } from './git.js';
2
+ import { buildOrder, isStoryLevel, STORY_LEVEL_TYPES } from './hierarchy.js';
3
+ import { BacklogError } from './types.js';
4
+ /** An item's repo field as a list (a name or a list of names). */
5
+ export function reposOf(item) {
6
+ const r = item.fields['repo'];
7
+ return (Array.isArray(r) ? r : r === undefined || r === null ? [] : [r]).map(String);
8
+ }
9
+ const STATUSES = ['todo', 'doing', 'done'];
10
+ /**
11
+ * Done items finished in the window: those whose file a commit since then moved into (or added
12
+ * to, or changed in) stories/done/, plus any not yet committed. Every commit touching done/ is
13
+ * read and its date checked here: git log --since stops at the first older commit, so one
14
+ * out-of-order date (a rebase) would hide recent work. Null outside git, where there are no
15
+ * dates, so every done item counts as recent.
16
+ */
17
+ export function recentlyDone(b, since) {
18
+ if (!repoRoot(b.dir))
19
+ return null;
20
+ const recent = new Set();
21
+ const cutoff = since.getTime() / 1000;
22
+ let committed = new Set();
23
+ try {
24
+ let time = 0;
25
+ for (const line of git(b.dir, ['log', '-M', '--name-only', '--relative', '--format=%x00%ct', '--', 'stories/done']).split('\n')) {
26
+ if (line.startsWith('\0'))
27
+ time = Number(line.slice(1));
28
+ else if (line && time >= cutoff)
29
+ recent.add(line);
30
+ }
31
+ committed = new Set(git(b.dir, ['ls-tree', '-r', '--name-only', 'HEAD', '--', 'stories/done']).split('\n').filter(Boolean));
32
+ }
33
+ catch {
34
+ // No commits yet: nothing is committed, so every done item is new.
35
+ }
36
+ for (const i of b.items)
37
+ if (i.status === 'done' && !committed.has(i.path))
38
+ recent.add(i.path);
39
+ return recent;
40
+ }
41
+ /** Story-level items in build order (by number), filtered; done ones from the last 30 days unless `all`. */
42
+ export function listItems(b, filters = {}, opts = {}) {
43
+ for (const s of filters.status ?? [])
44
+ if (!STATUSES.includes(s))
45
+ throw new BacklogError(`"${s}" is not a status: use todo, doing or done`);
46
+ for (const t of filters.type ?? [])
47
+ if (!STORY_LEVEL_TYPES.includes(t))
48
+ throw new BacklogError(`"${t}" is not a type ob list shows: use story, bug, spike or task`);
49
+ const byId = new Map(b.items.map(i => [i.id, i]));
50
+ for (const p of filters.parent ?? [])
51
+ if (!byId.has(p))
52
+ throw new BacklogError(`no item ${p} in this backlog`);
53
+ /** True if `ancestor` is the item's parent, its parent's parent, and so on. */
54
+ const under = (item, ancestor) => {
55
+ const seen = new Set();
56
+ for (let p = item.parent; p !== undefined && !seen.has(p); p = byId.get(p)?.parent) {
57
+ if (p === ancestor)
58
+ return true;
59
+ seen.add(p);
60
+ }
61
+ return false;
62
+ };
63
+ const any = (want, have) => !want?.length || want.some(w => have.includes(w));
64
+ const text = (v) => (v === undefined || v === null ? [] : [String(v).replace(/^@/, '')]);
65
+ const matched = buildOrder(b.items.filter(isStoryLevel)).filter(i => any(filters.status, i.status ? [i.status] : [])
66
+ && any(filters.type, [i.type])
67
+ && (!filters.parent?.length || filters.parent.some(p => under(i, p)))
68
+ && any(filters.repo, reposOf(i))
69
+ && any(filters.assignee?.map(a => a.replace(/^@/, '')), text(i.fields['assignee']))
70
+ && any(filters.sprint, text(i.fields['sprint'])));
71
+ if (opts.all)
72
+ return { items: matched, hiddenDone: 0 };
73
+ const now = opts.now ?? new Date();
74
+ const recent = recentlyDone(b, new Date(now.getTime() - (opts.days ?? 30) * 86_400_000));
75
+ if (!recent)
76
+ return { items: matched, hiddenDone: 0 };
77
+ const items = matched.filter(i => i.status !== 'done' || recent.has(i.path));
78
+ return { items, hiddenDone: matched.length - items.length };
79
+ }
@@ -0,0 +1,18 @@
1
+ import type { Backlog, Status } from './types.js';
2
+ /**
3
+ * The backlog folder for a working directory: walks up from `from` to the first folder that
4
+ * holds `backlog/config.yml`, so ob works from anywhere in the repository, inside backlog/
5
+ * included. Throws a BacklogError when there is none.
6
+ */
7
+ export declare function findBacklog(from?: string): string;
8
+ /**
9
+ * Loads the backlog in `dir` (a folder holding config.yml): the config, every item with its
10
+ * status, the sprints and people.yml. A missing or unreadable config.yml throws a BacklogError
11
+ * naming it; any other file that can't be parsed is listed in `errors` and skipped, so one bad
12
+ * file never hides the rest.
13
+ */
14
+ export declare function loadBacklog(dir: string): Backlog;
15
+ /** findBacklog, then loadBacklog. */
16
+ export declare function readBacklog(from?: string): Backlog;
17
+ /** The status a story-level item's folder gives: directly in todo/ or doing/, anywhere under done/. */
18
+ export declare function statusOf(path: string): Status | undefined;
@@ -0,0 +1,151 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve, sep } from 'node:path';
3
+ import { compareIds, parseFileName } from './ids.js';
4
+ import { BacklogError } from './types.js';
5
+ import { parseMapping, splitFrontMatter } from './yaml.js';
6
+ const ITEM_FOLDERS = ['capabilities', 'epics', 'features', 'stories'];
7
+ const STATUSES = ['todo', 'doing', 'done'];
8
+ /**
9
+ * The backlog folder for a working directory: walks up from `from` to the first folder that
10
+ * holds `backlog/config.yml`, so ob works from anywhere in the repository, inside backlog/
11
+ * included. Throws a BacklogError when there is none.
12
+ */
13
+ export function findBacklog(from = process.cwd()) {
14
+ const start = resolve(from);
15
+ for (let dir = start;; dir = dirname(dir)) {
16
+ if (existsSync(join(dir, 'backlog', 'config.yml')))
17
+ return join(dir, 'backlog');
18
+ if (dirname(dir) === dir)
19
+ break;
20
+ }
21
+ throw new BacklogError(`no backlog here: no backlog/config.yml in ${start} or any folder above it`);
22
+ }
23
+ /**
24
+ * Loads the backlog in `dir` (a folder holding config.yml): the config, every item with its
25
+ * status, the sprints and people.yml. A missing or unreadable config.yml throws a BacklogError
26
+ * naming it; any other file that can't be parsed is listed in `errors` and skipped, so one bad
27
+ * file never hides the rest.
28
+ */
29
+ export function loadBacklog(dir) {
30
+ const root = resolve(dir);
31
+ const configPath = join(root, 'config.yml');
32
+ if (!existsSync(configPath))
33
+ throw new BacklogError(`${configPath}: not found; a backlog needs a config.yml`, configPath);
34
+ let config;
35
+ try {
36
+ config = parseMapping(readFileSync(configPath, 'utf8'));
37
+ }
38
+ catch (e) {
39
+ throw new BacklogError(`${configPath}: not valid YAML: ${firstLine(e)}`, configPath);
40
+ }
41
+ if (config === null)
42
+ throw new BacklogError(`${configPath}: must be a YAML mapping, such as "spec: 0.1" and "name: my-app"`, configPath);
43
+ const errors = [];
44
+ const items = [];
45
+ for (const folder of ITEM_FOLDERS) {
46
+ for (const path of markdownFiles(root, folder)) {
47
+ const item = readItem(root, path, folder, errors);
48
+ if (item)
49
+ items.push(item);
50
+ }
51
+ }
52
+ items.sort((a, b) => compareIds(a.id, b.id) || (a.path < b.path ? -1 : 1));
53
+ const sprints = [];
54
+ for (const path of markdownFiles(root, 'sprints')) {
55
+ const read = readFrontMatter(root, path, errors);
56
+ if (read)
57
+ sprints.push({ name: baseName(path).replace(/\.md$/, ''), path, ...read });
58
+ }
59
+ sprints.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
60
+ return { dir: root, config, items, sprints, people: readPeople(root, errors), errors };
61
+ }
62
+ /** findBacklog, then loadBacklog. */
63
+ export function readBacklog(from = process.cwd()) {
64
+ return loadBacklog(findBacklog(from));
65
+ }
66
+ /** The status a story-level item's folder gives: directly in todo/ or doing/, anywhere under done/. */
67
+ export function statusOf(path) {
68
+ const parts = path.split('/');
69
+ if (parts[0] !== 'stories' || !STATUSES.includes(parts[1]))
70
+ return undefined;
71
+ if (parts[1] === 'done')
72
+ return 'done';
73
+ return parts.length === 3 ? parts[1] : undefined;
74
+ }
75
+ function readItem(root, path, folder, errors) {
76
+ const read = readFrontMatter(root, path, errors);
77
+ if (!read)
78
+ return null;
79
+ const { fields, body } = read;
80
+ const file = parseFileName(baseName(path));
81
+ const text = (v) => (v === undefined || v === null ? undefined : String(v));
82
+ const item = {
83
+ id: text(fields['id']) ?? file?.id ?? '',
84
+ type: text(fields['type']) ?? '',
85
+ title: text(fields['title']) ?? '',
86
+ fields,
87
+ body,
88
+ path,
89
+ file,
90
+ folder,
91
+ };
92
+ const parent = text(fields['parent']);
93
+ if (parent !== undefined)
94
+ item.parent = parent;
95
+ const status = statusOf(path);
96
+ if (status)
97
+ item.status = status;
98
+ return item;
99
+ }
100
+ /** A Markdown file's front matter (as a mapping) and body, or null after noting why in `errors`. */
101
+ function readFrontMatter(root, path, errors) {
102
+ const text = readFileSync(join(root, path), 'utf8');
103
+ const split = splitFrontMatter(text);
104
+ if (!split) {
105
+ errors.push({ path, message: 'has no front matter: it must start with a "---" line, the fields, and another "---"' });
106
+ return null;
107
+ }
108
+ try {
109
+ const fields = parseMapping(split.front);
110
+ if (fields === null) {
111
+ errors.push({ path, message: 'front matter is not a YAML mapping of fields' });
112
+ return null;
113
+ }
114
+ return { fields, body: split.body };
115
+ }
116
+ catch (e) {
117
+ errors.push({ path, message: `front matter is not valid YAML: ${firstLine(e)}` });
118
+ return null;
119
+ }
120
+ }
121
+ function readPeople(root, errors) {
122
+ const path = 'people.yml';
123
+ if (!existsSync(join(root, path)))
124
+ return {};
125
+ try {
126
+ const people = parseMapping(readFileSync(join(root, path), 'utf8'));
127
+ if (people !== null)
128
+ return people;
129
+ errors.push({ path, message: 'is not a YAML mapping of handles' });
130
+ }
131
+ catch (e) {
132
+ errors.push({ path, message: `is not valid YAML: ${firstLine(e)}` });
133
+ }
134
+ return {};
135
+ }
136
+ /** Every .md file under `root/folder`, at any depth, as a path from root with "/" separators. */
137
+ function markdownFiles(root, folder) {
138
+ const base = join(root, folder);
139
+ if (!existsSync(base) || !statSync(base).isDirectory())
140
+ return [];
141
+ return readdirSync(base, { recursive: true })
142
+ .filter(f => f.endsWith('.md') && statSync(join(base, f)).isFile())
143
+ .map(f => `${folder}/${f.split(sep).join('/')}`)
144
+ .sort();
145
+ }
146
+ function firstLine(e) {
147
+ return String(e instanceof Error ? e.message : e).split('\n')[0] ?? '';
148
+ }
149
+ function baseName(path) {
150
+ return path.slice(path.lastIndexOf('/') + 1);
151
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Every rule a backlog can break (spec 0.1), each with a stable code. The codes never change
3
+ * meaning: a new rule takes the next free number, and a retired one is never reused. The order
4
+ * is the order the rules appear in the spec.
5
+ *
6
+ * Tool rules that describe how a program behaves ([read-as-text], [keep-unknown]) aren't checked
7
+ * on a backlog; [id-numbers] needs git history (2.2.6). [local-clones] gives a warning.
8
+ */
9
+ export type Severity = 'error' | 'warning';
10
+ export interface Rule {
11
+ code: string;
12
+ rule: string;
13
+ severity: Severity;
14
+ /** How to fix it, said once for the rule; a problem may say more. */
15
+ fix: string;
16
+ }
17
+ export declare const RULES: Rule[];
18
+ export declare const RULE: Record<string, Rule>;
@@ -0,0 +1,21 @@
1
+ const r = (code, rule, fix, severity = 'error') => ({ code, rule, severity, fix });
2
+ export const RULES = [
3
+ r('OB001', 'parent', 'give a story, bug, spike or task a feature as its parent, a feature an epic, an epic a capability or none, and a capability none'),
4
+ r('OB002', 'parent-exists', 'set parent to the id of an item in this backlog, or add that item'),
5
+ r('OB003', 'id-form', 'write the id as its type needs: epic 2, feature 2.3, story 2.3.4, capability C1, whole numbers from 1 with no leading zeros'),
6
+ r('OB004', 'id-unique', 'give the item added later the next free number under its parent, and rename its file to match'),
7
+ r('OB005', 'epic-zero', 'name a feature in epic 0 for its month: slug YYYY-MM, such as 0.1-2026-11.md'),
8
+ r('OB006', 'filename', 'name the file <id>-<slug>.md, with the id as in its front matter and a slug of lowercase letters and digits joined by dashes'),
9
+ r('OB007', 'front-matter', 'start the file with a "---" line, the fields as YAML (key: value), and a closing "---" line'),
10
+ r('OB008', 'fields', 'give every item id, type (capability, epic, feature, story, bug, spike or task) and a one-line title, and each field the format the spec gives'),
11
+ r('OB009', 'repo-listed', 'add the repository under repos: in config.yml, or correct the name in repo'),
12
+ r('OB010', 'not-stored', 'remove the field: children, status and progress are worked out, and a sprint never lists its items'),
13
+ r('OB011', 'no-email', 'replace the email address with a handle, such as jo-smith'),
14
+ r('OB012', 'comment-line', 'start each comment with "- YYYY-MM-DD @handle: "'),
15
+ r('OB013', 'sprints', 'add the sprint file in sprints/, with start and end dates (YYYY-MM-DD) and end not before start'),
16
+ r('OB014', 'people', 'key people.yml by handle (lowercase letters, digits, - _ .), each with a name'),
17
+ r('OB015', 'item-folder', 'move capabilities, epics and features into capabilities/, epics/ and features/, and stories, bugs, spikes and tasks directly into stories/todo/ or stories/doing/, or anywhere under stories/done/'),
18
+ r('OB016', 'config', 'give config.yml spec (such as 0.1) and name (lowercase letters, digits and dashes), and each other key the format the spec gives'),
19
+ r('OB017', 'local-clones', 'clone the backlog beside this repository, in a folder named for its key, to include its items', 'warning'),
20
+ ];
21
+ export const RULE = Object.fromEntries(RULES.map(x => [x.rule, x]));
@@ -0,0 +1,38 @@
1
+ import type { LogEntry } from './git.js';
2
+ import type { Progress } from './hierarchy.js';
3
+ import type { Backlog, Status } from './types.js';
4
+ /**
5
+ * One item in full (2.3.6): where it sits in the plan, its file, its children, progress and
6
+ * history. An ID no longer in the backlog is looked up in git history, so an old reference to a
7
+ * pruned item still leads somewhere ([id-numbers]: its number stays used).
8
+ */
9
+ export interface Shown {
10
+ id: string;
11
+ type: string;
12
+ title: string;
13
+ /** From the backlog folder; for a deleted item, where it was. */
14
+ path: string;
15
+ /** The file names, without .md, from the top of the plan down to this item: 2-build › 2.3-cli › 2.3.4-ob-move. */
16
+ breadcrumb: string[];
17
+ status: Status | null;
18
+ fields: Record<string, unknown>;
19
+ /** The whole file, front matter and body. */
20
+ text: string;
21
+ /** Capabilities, epics and features: worked out from their story-level items (2.2.4). */
22
+ progress: Progress | null;
23
+ children: {
24
+ id: string;
25
+ type: string;
26
+ title: string;
27
+ status: Status | null;
28
+ path: string;
29
+ }[];
30
+ /** Commits that touched the file, newest first; empty outside git. */
31
+ history: LogEntry[];
32
+ /** For an item pruned with git rm: the commit that removed it. Its text is the last version. */
33
+ deleted: LogEntry | null;
34
+ /** Other items with the same ID ([id-unique]), if any. */
35
+ sameId: string[];
36
+ }
37
+ /** An item, or a pruned one from git history; a BacklogError if the ID was never used. */
38
+ export declare function showItem(b: Backlog, id: string): Shown;
@@ -0,0 +1,87 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { git, history, repoRoot } from './git.js';
4
+ import { buildTree, isStoryLevel, progressOf } from './hierarchy.js';
5
+ import { parseFileName } from './ids.js';
6
+ import { statusOf } from './read.js';
7
+ import { BacklogError } from './types.js';
8
+ import { parseMapping, splitFrontMatter } from './yaml.js';
9
+ const stem = (path) => path.slice(path.lastIndexOf('/') + 1).replace(/\.md$/, '');
10
+ /** An item, or a pruned one from git history; a BacklogError if the ID was never used. */
11
+ export function showItem(b, id) {
12
+ const tree = buildTree(b.items);
13
+ const node = tree.byId.get(id);
14
+ const sameId = b.items.filter(i => i.id === id).slice(1).map(i => i.path);
15
+ const childrenOf = (pid) => b.items.filter(i => i.parent === pid && i.id !== pid)
16
+ .map(i => ({ id: i.id, type: i.type, title: i.title, status: i.status ?? null, path: i.path }));
17
+ /** Ancestors' file names (the item's own last), stopping at a loop or a missing parent. */
18
+ const crumbs = (first, own) => {
19
+ const out = [own];
20
+ const seen = new Set();
21
+ for (let p = first?.parent; p !== undefined && !seen.has(p);) {
22
+ seen.add(p);
23
+ const up = tree.byId.get(p);
24
+ out.unshift(up ? stem(up.item.path) : p);
25
+ p = up?.item.parent;
26
+ }
27
+ return out;
28
+ };
29
+ if (node) {
30
+ const item = node.item;
31
+ return {
32
+ id, type: item.type, title: item.title, path: item.path, breadcrumb: crumbs(item, stem(item.path)),
33
+ status: item.status ?? null, fields: item.fields, text: readFileSync(join(b.dir, item.path), 'utf8'),
34
+ progress: isStoryLevel(item) ? null : progressOf(node), children: childrenOf(id),
35
+ history: history(join(b.dir, item.path)), deleted: null, sameId,
36
+ };
37
+ }
38
+ const pruned = findPruned(b, id);
39
+ if (!pruned)
40
+ throw new BacklogError(`no item ${id} in this backlog, now or in its git history`);
41
+ const fields = frontMatter(pruned.text);
42
+ const parent = typeof fields['parent'] === 'string' || typeof fields['parent'] === 'number' ? String(fields['parent']) : undefined;
43
+ const type = String(fields['type'] ?? '');
44
+ const ghost = { parent };
45
+ return {
46
+ id, type, title: String(fields['title'] ?? ''), path: pruned.path, breadcrumb: crumbs(ghost, stem(pruned.path)),
47
+ status: statusOf(pruned.path) ?? null, fields, text: pruned.text, progress: null, children: childrenOf(id),
48
+ history: pruned.history, deleted: pruned.deleted, sameId: [],
49
+ };
50
+ }
51
+ /** The newest commit that removed an item file with this ID (and didn't add it back elsewhere: a move). */
52
+ function findPruned(b, id) {
53
+ const root = repoRoot(b.dir);
54
+ if (!root)
55
+ return null;
56
+ let out;
57
+ try {
58
+ out = git(b.dir, ['log', '--no-renames', '--diff-filter=AD', '--name-status', '--relative', '--date=short',
59
+ '--format=%x00%h%x09%ad%x09%an%x09%s', '--', '.']);
60
+ }
61
+ catch {
62
+ return null; // no commits yet
63
+ }
64
+ for (const block of out.split('\0').filter(Boolean)) {
65
+ const [head = '', ...lines] = block.split('\n').filter(Boolean);
66
+ const [hash = '', date = '', author = '', ...subject] = head.split('\t');
67
+ const changes = lines.map(l => l.split('\t')).map(([st = '', path = '']) => ({ st, path }));
68
+ const added = new Set(changes.filter(c => c.st === 'A').map(c => stem(c.path)));
69
+ const gone = changes.find(c => c.st === 'D' && parseFileName(stem(c.path) + '.md')?.id === id && !added.has(stem(c.path)));
70
+ if (gone) {
71
+ const text = git(b.dir, ['show', `${hash}^:./${gone.path}`]);
72
+ const deleted = { hash, date, author, subject: subject.join('\t') };
73
+ return { path: gone.path, text, deleted, history: history(join(b.dir, gone.path)) };
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ /** A pruned file's front matter, read as the reader reads files; {} if it can't be. */
79
+ function frontMatter(text) {
80
+ try {
81
+ const fm = splitFrontMatter(text);
82
+ return (fm && parseMapping(fm.front)) ?? {};
83
+ }
84
+ catch {
85
+ return {};
86
+ }
87
+ }
@@ -0,0 +1,4 @@
1
+ /** The version of the Open Backlog specification this library implements. */
2
+ export declare const SPEC_VERSION = "0.1";
3
+ /** Where that specification is published. */
4
+ export declare const SPEC_URL = "https://openbacklog.org/spec";
@@ -0,0 +1,4 @@
1
+ /** The version of the Open Backlog specification this library implements. */
2
+ export const SPEC_VERSION = '0.1';
3
+ /** Where that specification is published. */
4
+ export const SPEC_URL = 'https://openbacklog.org/spec';