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,70 @@
1
+ /** What reading a backlog gives (2.2.2). */
2
+ export type ItemType = 'capability' | 'epic' | 'feature' | 'story' | 'bug' | 'spike' | 'task';
3
+ export type Status = 'todo' | 'doing' | 'done';
4
+ /** The four folders items live in. */
5
+ export type ItemFolder = 'capabilities' | 'epics' | 'features' | 'stories';
6
+ export interface Item {
7
+ /** `id` from the front matter, as text; falls back to the file name's ID when missing. */
8
+ id: string;
9
+ /** `type` as written (validation checks it is one of the seven). */
10
+ type: string;
11
+ title: string;
12
+ parent?: string;
13
+ /** Every front-matter field, in file order, unknown ones included. */
14
+ fields: Record<string, unknown>;
15
+ /** Everything after the front matter. */
16
+ body: string;
17
+ /** The file, from the backlog folder: `stories/done/2026-11/1.1.1-cart-api.md`. */
18
+ path: string;
19
+ /** The ID and slug the file name gives (null if the name has none). */
20
+ file: {
21
+ id: string;
22
+ slug: string;
23
+ } | null;
24
+ folder: ItemFolder;
25
+ /** A story-level item's status, from its folder; undefined if it is not in one. */
26
+ status?: Status;
27
+ }
28
+ export interface Sprint {
29
+ /** The file name without `.md`: `2026-S24`. */
30
+ name: string;
31
+ fields: Record<string, unknown>;
32
+ body: string;
33
+ path: string;
34
+ }
35
+ export interface Person {
36
+ name?: string;
37
+ forge?: string;
38
+ [key: string]: unknown;
39
+ }
40
+ export interface Config {
41
+ spec?: string;
42
+ name?: string;
43
+ estimate?: string;
44
+ 'done-folders'?: string;
45
+ repos?: Record<string, string>;
46
+ backlogs?: Record<string, string>;
47
+ [key: string]: unknown;
48
+ }
49
+ /** A file that could not be read as the spec expects, and why. The rest of the backlog still loads. */
50
+ export interface FileError {
51
+ path: string;
52
+ message: string;
53
+ }
54
+ export interface Backlog {
55
+ /** The backlog folder, absolute: `/work/shop/backlog`. */
56
+ dir: string;
57
+ config: Config;
58
+ /** Every item, ordered by ID. */
59
+ items: Item[];
60
+ sprints: Sprint[];
61
+ /** people.yml, by handle (empty if there is none). */
62
+ people: Record<string, Person>;
63
+ /** Files skipped because they could not be parsed. */
64
+ errors: FileError[];
65
+ }
66
+ /** A problem that stops a backlog from loading at all: no config.yml, or one that can't be read. */
67
+ export declare class BacklogError extends Error {
68
+ readonly path?: string | undefined;
69
+ constructor(message: string, path?: string | undefined);
70
+ }
@@ -0,0 +1,10 @@
1
+ /** What reading a backlog gives (2.2.2). */
2
+ /** A problem that stops a backlog from loading at all: no config.yml, or one that can't be read. */
3
+ export class BacklogError extends Error {
4
+ path;
5
+ constructor(message, path) {
6
+ super(message);
7
+ this.path = path;
8
+ this.name = 'BacklogError';
9
+ }
10
+ }
@@ -0,0 +1,28 @@
1
+ import { type Severity } from './rules.js';
2
+ import type { Backlog } from './types.js';
3
+ /**
4
+ * Validation (2.2.5): every rule a backlog can break, as problems with a stable code, the file,
5
+ * what is wrong and how to fix it. Single-file rules use the spec's own JSON Schema (schema/,
6
+ * copied from backlog-spec), so ob agrees with any tool that uses it; the rules that span files
7
+ * are checked here.
8
+ */
9
+ export interface Problem {
10
+ code: string;
11
+ rule: string;
12
+ severity: Severity;
13
+ /** The file, from the backlog folder: `stories/todo/1.1.1-sign-up.md`, `config.yml`. */
14
+ path: string;
15
+ /** The field or part of the file, when there is one. */
16
+ field?: string;
17
+ message: string;
18
+ fix: string;
19
+ }
20
+ /** One problem as a line: `stories/todo/1.1.2-x.md: OB001 [parent] … Fix: …`. */
21
+ export declare function formatProblem(p: Problem): string;
22
+ /** Loads the backlog in `dir` and validates it; a config.yml it can't load is a [config] problem. */
23
+ export declare function validateDir(dir: string): {
24
+ backlog: Backlog | null;
25
+ problems: Problem[];
26
+ };
27
+ /** Every problem in a loaded backlog, ordered by file, then code. */
28
+ export declare function validate(b: Backlog): Problem[];
@@ -0,0 +1,227 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { Ajv } from 'ajv';
4
+ import { isStoryLevel } from './hierarchy.js';
5
+ import { loadBacklog, statusOf } from './read.js';
6
+ import { RULE } from './rules.js';
7
+ import { BacklogError } from './types.js';
8
+ /** One problem as a line: `stories/todo/1.1.2-x.md: OB001 [parent] … Fix: …`. */
9
+ export function formatProblem(p) {
10
+ return `${p.path}: ${p.code} [${p.rule}] ${p.severity === 'warning' ? 'warning: ' : ''}${p.message}. Fix: ${p.fix}.`;
11
+ }
12
+ const HANDLE = /^[a-z0-9][a-z0-9._-]*$/;
13
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
14
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
15
+ const PARENT_TYPE = { story: 'feature', bug: 'feature', spike: 'feature', task: 'feature', feature: 'epic', epic: 'capability' };
16
+ const FOLDER = { capability: 'capabilities', epic: 'epics', feature: 'features' };
17
+ let schemas;
18
+ /** The spec's JSON Schema, compiled once (schema/0.1/, beside src/ and dist/ in the package). */
19
+ function schema() {
20
+ if (!schemas) {
21
+ const ajv = new Ajv({ allErrors: true, strict: false });
22
+ const load = (name) => JSON.parse(readFileSync(new URL(`../../schema/0.1/${name}.schema.json`, import.meta.url), 'utf8'));
23
+ schemas = { item: ajv.compile(load('item')), config: ajv.compile(load('config')) };
24
+ }
25
+ return schemas;
26
+ }
27
+ /** Loads the backlog in `dir` and validates it; a config.yml it can't load is a [config] problem. */
28
+ export function validateDir(dir) {
29
+ try {
30
+ const backlog = loadBacklog(dir);
31
+ return { backlog, problems: validate(backlog) };
32
+ }
33
+ catch (e) {
34
+ if (!(e instanceof BacklogError))
35
+ throw e;
36
+ return { backlog: null, problems: [problem('config', 'config.yml', e.message.replace(/^.*?config\.yml: /, 'config.yml '))] };
37
+ }
38
+ }
39
+ /** Every problem in a loaded backlog, ordered by file, then code. */
40
+ export function validate(b) {
41
+ const out = [];
42
+ const add = (p) => {
43
+ if (!out.some(q => q.code === p.code && q.path === p.path && q.field === p.field && q.message === p.message))
44
+ out.push(p);
45
+ };
46
+ // Files the reader couldn't parse.
47
+ for (const e of b.errors) {
48
+ const rule = e.path.startsWith('sprints/') ? 'sprints' : e.path === 'people.yml' ? 'people' : 'front-matter';
49
+ add(problem(rule, e.path, e.message));
50
+ }
51
+ // config.yml, against the schema.
52
+ if (!schema().config(b.config)) {
53
+ for (const err of schema().config.errors ?? []) {
54
+ const field = fieldOf(err);
55
+ add(problem('config', 'config.yml', err.keyword === 'required' ? `needs "${field}"` : `"${field}" ${describe(err)}`, field));
56
+ }
57
+ }
58
+ const ids = new Map();
59
+ for (const item of b.items)
60
+ ids.set(item.id, [...(ids.get(item.id) ?? []), item]);
61
+ const repos = new Set(Object.keys(b.config.repos ?? {}));
62
+ const sprintNames = new Set(b.sprints.map(s => s.name));
63
+ for (const item of b.items) {
64
+ for (const p of schemaProblems(item))
65
+ add(p);
66
+ for (const p of fileProblems(item))
67
+ add(p);
68
+ // [parent-exists] and the parent's type ([parent]), across files.
69
+ const parent = item.parent;
70
+ if (parent !== undefined && PARENT_TYPE[item.type] !== undefined) {
71
+ const found = ids.get(parent)?.[0];
72
+ if (!found)
73
+ add(problem('parent-exists', item.path, `parent ${parent} is not the id of any item in this backlog`, 'parent'));
74
+ // Only when the schema found nothing wrong with this parent, so a file gets one [parent] problem.
75
+ else if (found.type !== PARENT_TYPE[item.type] && !out.some(q => q.path === item.path && q.rule === 'parent')) {
76
+ add(problem('parent', item.path, `${a(item.type)}'s parent must be ${a(PARENT_TYPE[item.type] ?? '')}, but ${parent} is ${a(found.type)}`, 'parent'));
77
+ }
78
+ }
79
+ // [id-unique]
80
+ const same = ids.get(item.id) ?? [];
81
+ if (same.length > 1) {
82
+ add(problem('id-unique', item.path, `id ${item.id} is also used by ${same.filter(o => o !== item).map(o => o.path).join(', ')}`, 'id'));
83
+ }
84
+ // [repo-listed]
85
+ const repo = item.fields['repo'];
86
+ for (const name of Array.isArray(repo) ? repo : repo === undefined ? [] : [repo]) {
87
+ if (typeof name === 'string' && !repos.has(name)) {
88
+ add(problem('repo-listed', item.path, `repo ${name} is not a key of repos: in config.yml`, 'repo'));
89
+ }
90
+ }
91
+ // [sprints]: the sprint an item names has a file.
92
+ const sprint = item.fields['sprint'];
93
+ if (typeof sprint === 'string' && !sprintNames.has(sprint)) {
94
+ add(problem('sprints', item.path, `sprint ${sprint} has no file sprints/${sprint}.md`, 'sprint'));
95
+ }
96
+ }
97
+ // Sprint files: dates, and no list of their items.
98
+ for (const s of b.sprints) {
99
+ const { start, end } = s.fields;
100
+ for (const [k, v] of [['start', start], ['end', end]]) {
101
+ if (typeof v !== 'string' || !DATE.test(v))
102
+ add(problem('sprints', s.path, v === undefined ? `needs ${k}` : `${k} must be a date, YYYY-MM-DD`, k));
103
+ }
104
+ if (typeof start === 'string' && typeof end === 'string' && DATE.test(start) && DATE.test(end) && end < start) {
105
+ add(problem('sprints', s.path, `ends (${end}) before it starts (${start})`, 'end'));
106
+ }
107
+ for (const [k, v] of Object.entries(s.fields)) {
108
+ if (['items', 'stories', 'children'].includes(k) || (Array.isArray(v) && v.some(x => typeof x === 'string' && b.items.some(i => i.id === x)))) {
109
+ add(problem('not-stored', s.path, `"${k}" lists the sprint's items; items name their sprint instead`, k));
110
+ }
111
+ }
112
+ }
113
+ // people.yml
114
+ for (const [handle, person] of Object.entries(b.people)) {
115
+ if (!HANDLE.test(handle))
116
+ add(problem('people', 'people.yml', `"${handle}" is not a handle`, handle));
117
+ const name = person && typeof person === 'object' ? person.name : undefined;
118
+ if (typeof name !== 'string' || !name.trim())
119
+ add(problem('people', 'people.yml', `${handle} has no name`, handle));
120
+ if (EMAIL.test(JSON.stringify(person)))
121
+ add(problem('no-email', 'people.yml', `${handle} holds an email address`, handle));
122
+ }
123
+ // [local-clones]: each listed backlog is a folder beside this repository.
124
+ const besideRepo = dirname(dirname(b.dir));
125
+ for (const name of Object.keys(b.config.backlogs ?? {})) {
126
+ if (!existsSync(join(besideRepo, name, 'backlog', 'config.yml'))) {
127
+ add(problem('local-clones', 'config.yml', `backlog ${name} has no local clone at ../${name}/backlog/; its items are left out`, 'backlogs'));
128
+ }
129
+ }
130
+ return out.sort((a, c) => (a.path < c.path ? -1 : a.path > c.path ? 1 : a.code < c.code ? -1 : a.code > c.code ? 1 : 0));
131
+ }
132
+ /** The rules one item's front matter can break, from the spec's JSON Schema. */
133
+ function schemaProblems(item) {
134
+ const validate = schema().item;
135
+ if (validate(item.fields))
136
+ return [];
137
+ const out = [];
138
+ for (const e of validate.errors ?? []) {
139
+ if (e.keyword === 'if')
140
+ continue; // a summary that repeats the real error
141
+ const field = fieldOf(e);
142
+ const at = (rule, message) => out.push(problem(rule, item.path, message, field));
143
+ if (['children', 'status', 'progress'].includes(field))
144
+ at('not-stored', `"${field}" is stored, but it is worked out`);
145
+ else if (e.schemaPath.startsWith('#/additionalProperties'))
146
+ at('no-email', `"${field}" holds an email address`);
147
+ else if (field === 'parent') {
148
+ if (e.keyword === 'required')
149
+ at('parent', `${a(item.type)} needs a parent`);
150
+ else if (e.keyword === 'false schema' || e.keyword === 'not')
151
+ at('parent', `${a(item.type)} has no parent`);
152
+ else
153
+ at('parent', `${a(item.type)}'s parent must be ${PARENT_TYPE[item.type] === 'feature' ? 'a feature, such as 2.3' : PARENT_TYPE[item.type] === 'epic' ? 'an epic, such as 2' : 'a capability, such as C1'}`);
154
+ }
155
+ else if (field === 'id' && e.keyword === 'pattern')
156
+ at('id-form', `id ${item.id} is not the form ${a(item.type)} needs`);
157
+ else if (e.keyword === 'required')
158
+ at('fields', `needs "${field}"`);
159
+ else
160
+ at('fields', `"${field}" ${describe(e)}`);
161
+ }
162
+ return out;
163
+ }
164
+ /** The rules one item's file name, folder and body can break. */
165
+ function fileProblems(item) {
166
+ const out = [];
167
+ const name = item.path.slice(item.path.lastIndexOf('/') + 1);
168
+ // [filename]
169
+ if (!item.file)
170
+ out.push(problem('filename', item.path, `"${name}" is not <id>-<slug>.md`, 'filename'));
171
+ else {
172
+ if (item.file.id !== item.id)
173
+ out.push(problem('filename', item.path, `the file is named for ${item.file.id}, but its id is ${item.id}`, 'filename'));
174
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(item.file.slug))
175
+ out.push(problem('filename', item.path, `the slug "${item.file.slug}" must be lowercase letters and digits joined by single dashes`, 'filename'));
176
+ }
177
+ // [item-folder]
178
+ const folder = FOLDER[item.type];
179
+ if (folder !== undefined && item.path !== `${folder}/${name}`)
180
+ out.push(problem('item-folder', item.path, `${a(item.type)} belongs directly in ${folder}/`, 'folder'));
181
+ if (isStoryLevel(item) && !statusOf(item.path))
182
+ out.push(problem('item-folder', item.path, `${a(item.type)} belongs directly in stories/todo/ or stories/doing/, or under stories/done/`, 'folder'));
183
+ // [epic-zero]
184
+ if (item.type === 'feature' && item.id.startsWith('0.') && item.file && !/^\d{4}-(0[1-9]|1[0-2])$/.test(item.file.slug)) {
185
+ out.push(problem('epic-zero', item.path, `feature ${item.id} is in epic 0, so its slug must be its month, YYYY-MM, not "${item.file.slug}"`, 'filename'));
186
+ }
187
+ // [comment-line] and [no-email] under ## Comments
188
+ const comments = item.body.split(/^## Comments[ \t]*$/m)[1]?.split(/^## /m)[0] ?? '';
189
+ for (const line of comments.split(/\r?\n/).filter(l => l.startsWith('- '))) {
190
+ if (!/^- \d{4}-\d{2}-\d{2} @[a-z0-9][a-z0-9._-]*: /.test(line)) {
191
+ out.push(problem('comment-line', item.path, `the comment "${line.slice(0, 40)}" does not start with - YYYY-MM-DD @handle:`, 'comments'));
192
+ }
193
+ if (EMAIL.test(line))
194
+ out.push(problem('no-email', item.path, 'a comment holds an email address', 'comments'));
195
+ }
196
+ return out;
197
+ }
198
+ /** "a story", "an epic". */
199
+ function a(word) {
200
+ return `${/^[aeiou]/.test(word) ? 'an' : 'a'} ${word}`;
201
+ }
202
+ function problem(rule, path, message, field) {
203
+ const r = RULE[rule];
204
+ if (!r)
205
+ throw new Error(`no rule ${rule}`);
206
+ const p = { code: r.code, rule, severity: r.severity, path, message, fix: r.fix };
207
+ if (field !== undefined)
208
+ p.field = field;
209
+ return p;
210
+ }
211
+ function fieldOf(e) {
212
+ return e.instancePath.replace(/^\//, '').split('/')[0] || e.params.missingProperty || '';
213
+ }
214
+ function describe(e) {
215
+ const p = e.params;
216
+ switch (e.keyword) {
217
+ case 'type': return `must be ${String(p['type'])}`;
218
+ case 'enum': return `must be one of ${p['allowedValues'].join(', ')}`;
219
+ case 'const': return `must be ${String(p['allowedValue'])}`;
220
+ case 'minimum': return `must be ${String(p['limit'])} or more`;
221
+ case 'pattern': return 'is not in the right form';
222
+ case 'minItems':
223
+ case 'minLength': return 'must not be empty';
224
+ case 'oneOf': return 'must be a name or a list of names';
225
+ default: return e.message ?? 'is not valid';
226
+ }
227
+ }
@@ -0,0 +1,56 @@
1
+ import type { Item } from './types.js';
2
+ /** A value a tool can write into front matter. */
3
+ export type FieldValue = string | number | boolean | string[];
4
+ /**
5
+ * Changes front-matter fields in an item file's text and returns the new text. Only the
6
+ * characters of each changed value move: every other byte (unknown fields, their order, YAML
7
+ * comments, quoting, blank lines, the body, line endings) stays as it was ([keep-unknown]).
8
+ *
9
+ * value the field is set: its value is replaced in place, or a new line is added at the
10
+ * end of the front matter
11
+ * undefined the field's line is removed
12
+ *
13
+ * A value equal to what the file already says is left alone, so saving an unchanged item gives
14
+ * the same bytes. Throws if the text has no front matter or it isn't a mapping.
15
+ */
16
+ export declare function setFields(text: string, changes: Record<string, FieldValue | undefined>): string;
17
+ /**
18
+ * A value as YAML text on one line. Text fields that look like numbers (IDs, sprints, releases)
19
+ * are written plain, as people write them (`parent: 1.10`); ob reads them as text anyway. Other
20
+ * text is quoted only when YAML would misread it.
21
+ */
22
+ export declare function formatValue(key: string, value: FieldValue): string;
23
+ /** Changes fields in an item's file on disk; returns true if the file changed. */
24
+ export declare function updateItem(backlogDir: string, item: Item, changes: Record<string, FieldValue | undefined>): boolean;
25
+ /** What a new item needs; ID assignment comes from the caller (2.2.6). */
26
+ export interface NewItem {
27
+ id: string;
28
+ type: string;
29
+ title: string;
30
+ parent?: string;
31
+ /** Made from the title when not given. */
32
+ slug?: string;
33
+ /** More fields, written after id, type, title and parent, in this order. */
34
+ fields?: Record<string, FieldValue>;
35
+ /** For story-level items: the recommended shape (spec section 3), with placeholders for what's missing. */
36
+ asA?: string;
37
+ wantTo?: string[];
38
+ soThat?: string[];
39
+ }
40
+ /** A slug from a title: up to six lowercase words of letters and digits, joined by dashes (as the site's maker). */
41
+ export declare function slugify(title: string): string;
42
+ /** The folder a new item goes in: story-level items start in stories/todo/. */
43
+ export declare function folderFor(type: string): string;
44
+ /** A new item's path in the backlog: `stories/todo/2.3.5-ob-list.md`. */
45
+ export declare function newItemPath(n: NewItem): string;
46
+ /**
47
+ * A new item file's text: front matter (id, type, title, parent, then any other fields) and, for
48
+ * a story-level item, the recommended body: "As a … I want to:", "So that:" and "## Comments".
49
+ * The same shape openbacklog.org's story maker writes.
50
+ */
51
+ export declare function newItemText(n: NewItem): string;
52
+ /**
53
+ * Writes a new item file into the backlog and returns its path from the backlog folder. Never
54
+ * overwrites: an existing file is a BacklogError.
55
+ */
56
+ export declare function createItem(backlogDir: string, n: NewItem): string;
@@ -0,0 +1,160 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { isMap, isScalar, parseDocument, stringify } from 'yaml';
5
+ import { BacklogError } from './types.js';
6
+ import { parseMapping, TEXT_FIELDS } from './yaml.js';
7
+ const STORY_LEVEL = ['story', 'bug', 'spike', 'task'];
8
+ /**
9
+ * Changes front-matter fields in an item file's text and returns the new text. Only the
10
+ * characters of each changed value move: every other byte (unknown fields, their order, YAML
11
+ * comments, quoting, blank lines, the body, line endings) stays as it was ([keep-unknown]).
12
+ *
13
+ * value the field is set: its value is replaced in place, or a new line is added at the
14
+ * end of the front matter
15
+ * undefined the field's line is removed
16
+ *
17
+ * A value equal to what the file already says is left alone, so saving an unchanged item gives
18
+ * the same bytes. Throws if the text has no front matter or it isn't a mapping.
19
+ */
20
+ export function setFields(text, changes) {
21
+ let out = text;
22
+ for (const [key, value] of Object.entries(changes))
23
+ out = setField(out, key, value);
24
+ return out;
25
+ }
26
+ function setField(text, key, value) {
27
+ const fm = frontMatter(text);
28
+ const doc = parseDocument(fm.yaml);
29
+ if (doc.errors.length)
30
+ throw new Error(`front matter is not valid YAML: ${doc.errors[0]?.message.split('\n')[0]}`);
31
+ if (doc.contents !== null && !isMap(doc.contents))
32
+ throw new Error('front matter is not a YAML mapping');
33
+ const pair = doc.contents?.items.find(p => isScalar(p.key) && String(p.key.value) === key);
34
+ const at = (offset) => fm.start + offset;
35
+ if (!pair) {
36
+ if (value === undefined)
37
+ return text;
38
+ return text.slice(0, fm.end) + `${key}: ${formatValue(key, value)}${fm.eol}` + text.slice(fm.end);
39
+ }
40
+ const keyStart = pair.key.range?.[0] ?? 0;
41
+ const node = pair.value;
42
+ if (value !== undefined && node?.range && isDeepStrictEqual(currentValue(fm.yaml, key), value))
43
+ return text;
44
+ if (value === undefined) {
45
+ // From the start of the key's line to the end of its value's last line.
46
+ const lineStart = fm.yaml.lastIndexOf('\n', keyStart - 1) + 1;
47
+ const end = lineEnd(fm.yaml, node?.range ? node.range[1] : keyStart);
48
+ return text.slice(0, at(lineStart)) + text.slice(at(end));
49
+ }
50
+ if (node?.range && node.range[1] > node.range[0]) {
51
+ // Replace just the value's characters; a comment after it on the line stays.
52
+ return text.slice(0, at(node.range[0])) + formatValue(key, value) + text.slice(at(node.range[1]));
53
+ }
54
+ // An empty value (`key:`): write the value after the colon.
55
+ const colon = fm.yaml.indexOf(':', keyStart);
56
+ return text.slice(0, at(colon + 1)) + ' ' + formatValue(key, value) + text.slice(at(colon + 1)).replace(/^[ \t]+/, '');
57
+ }
58
+ /** What the front matter currently says for a field, read as ob reads it. */
59
+ function currentValue(yaml, key) {
60
+ return parseMapping(yaml)?.[key];
61
+ }
62
+ /** Where the front matter's YAML is inside a file's text, and the file's line ending. */
63
+ function frontMatter(text) {
64
+ const open = /^---[ \t]*(\r?\n)/.exec(text);
65
+ if (!open)
66
+ throw new Error('has no front matter: it must start with a "---" line');
67
+ const start = open[0].length;
68
+ const close = /^---[ \t]*(?:\r?\n|$)/m.exec(text.slice(start));
69
+ if (!close)
70
+ throw new Error('front matter has no closing "---" line');
71
+ const end = start + close.index;
72
+ return { start, end, yaml: text.slice(start, end), eol: open[1] ?? '\n' };
73
+ }
74
+ /** The offset just past the line ending after `offset`. */
75
+ function lineEnd(s, offset) {
76
+ const nl = s.indexOf('\n', Math.max(0, offset - 1));
77
+ return nl === -1 ? s.length : nl + 1;
78
+ }
79
+ /**
80
+ * A value as YAML text on one line. Text fields that look like numbers (IDs, sprints, releases)
81
+ * are written plain, as people write them (`parent: 1.10`); ob reads them as text anyway. Other
82
+ * text is quoted only when YAML would misread it.
83
+ */
84
+ export function formatValue(key, value) {
85
+ if (Array.isArray(value))
86
+ return `[${value.map(v => formatValue('', v)).join(', ')}]`;
87
+ if (typeof value !== 'string')
88
+ return String(value);
89
+ if (/[\r\n]/.test(value))
90
+ throw new Error(`${key}: a front-matter value must be on one line`);
91
+ if (TEXT_FIELDS.includes(key) && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value))
92
+ return value;
93
+ // YAML 1.1 readers (other tools) take these as booleans or null, so they are always quoted.
94
+ if (/^(y|yes|n|no|on|off|true|false|null|~)$/i.test(value))
95
+ return JSON.stringify(value);
96
+ return stringify(value, { lineWidth: 0 }).trimEnd();
97
+ }
98
+ /** Changes fields in an item's file on disk; returns true if the file changed. */
99
+ export function updateItem(backlogDir, item, changes) {
100
+ const path = join(backlogDir, item.path);
101
+ const before = readFileSync(path, 'utf8');
102
+ let after;
103
+ try {
104
+ after = setFields(before, changes);
105
+ }
106
+ catch (e) {
107
+ throw new BacklogError(`${item.path}: ${e.message}`, path);
108
+ }
109
+ if (after === before)
110
+ return false;
111
+ writeFileSync(path, after);
112
+ return true;
113
+ }
114
+ /** A slug from a title: up to six lowercase words of letters and digits, joined by dashes (as the site's maker). */
115
+ export function slugify(title) {
116
+ return title.normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
117
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').split('-').slice(0, 6).join('-');
118
+ }
119
+ /** The folder a new item goes in: story-level items start in stories/todo/. */
120
+ export function folderFor(type) {
121
+ const folders = { capability: 'capabilities', epic: 'epics', feature: 'features' };
122
+ return folders[type] ?? 'stories/todo';
123
+ }
124
+ /** A new item's path in the backlog: `stories/todo/2.3.5-ob-list.md`. */
125
+ export function newItemPath(n) {
126
+ const slug = n.slug?.trim() || slugify(n.title) || n.type;
127
+ return `${folderFor(n.type)}/${n.id}-${slug}.md`;
128
+ }
129
+ /**
130
+ * A new item file's text: front matter (id, type, title, parent, then any other fields) and, for
131
+ * a story-level item, the recommended body: "As a … I want to:", "So that:" and "## Comments".
132
+ * The same shape openbacklog.org's story maker writes.
133
+ */
134
+ export function newItemText(n) {
135
+ const fm = [`id: ${n.id}`, `type: ${n.type}`, `title: ${formatValue('title', n.title.trim())}`];
136
+ if (n.parent)
137
+ fm.push(`parent: ${formatValue('parent', n.parent)}`);
138
+ for (const [k, v] of Object.entries(n.fields ?? {}))
139
+ fm.push(`${k}: ${formatValue(k, v)}`);
140
+ const lines = ['---', ...fm, '---'];
141
+ if (STORY_LEVEL.includes(n.type)) {
142
+ const want = n.wantTo?.length ? n.wantTo : ['<what they want>'];
143
+ const why = n.soThat?.length ? n.soThat : ['<why, written so it can be checked>'];
144
+ lines.push('', `**As a** ${n.asA?.trim() || '<who>'}, **I want to:**`, ...want.map(l => `- ${l}`), '', '**So that:**', ...why.map(l => `- ${l}`), '', '## Comments');
145
+ }
146
+ return lines.join('\n') + '\n';
147
+ }
148
+ /**
149
+ * Writes a new item file into the backlog and returns its path from the backlog folder. Never
150
+ * overwrites: an existing file is a BacklogError.
151
+ */
152
+ export function createItem(backlogDir, n) {
153
+ const path = newItemPath(n);
154
+ const full = join(backlogDir, path);
155
+ if (existsSync(full))
156
+ throw new BacklogError(`${path}: already exists`, full);
157
+ mkdirSync(dirname(full), { recursive: true });
158
+ writeFileSync(full, newItemText(n), { flag: 'wx' });
159
+ return path;
160
+ }
@@ -0,0 +1,13 @@
1
+ /** The fields a tool must read as the text written ([read-as-text]). */
2
+ export declare const TEXT_FIELDS: string[];
3
+ /**
4
+ * Parses a YAML mapping. Every value is read as YAML would, except the TEXT_FIELDS, which keep
5
+ * the text as written (an unquoted 1.10 stays "1.10", not 1.1). Throws on bad YAML; returns
6
+ * null when the YAML is fine but not a mapping.
7
+ */
8
+ export declare function parseMapping(text: string): Record<string, unknown> | null;
9
+ /** A file's front matter and body: the mapping between the opening and closing `---` lines. */
10
+ export declare function splitFrontMatter(text: string): {
11
+ front: string;
12
+ body: string;
13
+ } | null;
@@ -0,0 +1,28 @@
1
+ import { parse } from 'yaml';
2
+ /** The fields a tool must read as the text written ([read-as-text]). */
3
+ export const TEXT_FIELDS = ['id', 'parent', 'sprint', 'release', 'spec', 'name'];
4
+ /**
5
+ * Parses a YAML mapping. Every value is read as YAML would, except the TEXT_FIELDS, which keep
6
+ * the text as written (an unquoted 1.10 stays "1.10", not 1.1). Throws on bad YAML; returns
7
+ * null when the YAML is fine but not a mapping.
8
+ */
9
+ export function parseMapping(text) {
10
+ const values = parse(text);
11
+ if (values === null || values === undefined)
12
+ return {};
13
+ if (typeof values !== 'object' || Array.isArray(values))
14
+ return null;
15
+ // The failsafe schema reads every scalar as its text.
16
+ const asText = parse(text, { schema: 'failsafe' });
17
+ const out = values;
18
+ for (const key of TEXT_FIELDS) {
19
+ if (key in out && typeof asText[key] === 'string')
20
+ out[key] = asText[key];
21
+ }
22
+ return out;
23
+ }
24
+ /** A file's front matter and body: the mapping between the opening and closing `---` lines. */
25
+ export function splitFrontMatter(text) {
26
+ const m = /^---\r?\n([\s\S]*?)\r?\n?---[ \t]*(?:\r?\n|$)([\s\S]*)$/.exec(text);
27
+ return m ? { front: m[1] ?? '', body: m[2] ?? '' } : null;
28
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "open-backlog",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Open Backlog: a backlog as Markdown files in git. The ob command, and the core library it is built on.",
5
+ "license": "MIT",
6
+ "author": "Brandon Castagna",
7
+ "homepage": "https://openbacklog.org",
8
+ "keywords": [
9
+ "backlog",
10
+ "agile",
11
+ "markdown",
12
+ "git",
13
+ "cli"
14
+ ],
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=22"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/core/index.d.ts",
22
+ "import": "./dist/core/index.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "bin": {
27
+ "ob": "dist/cli/main.js"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "schema",
32
+ "LICENSE",
33
+ "README.md"
34
+ ],
35
+ "scripts": {
36
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli/main.js",
37
+ "lint": "eslint . && tsc --noEmit",
38
+ "test": "vitest run",
39
+ "smoke": "node script/smoke.mjs",
40
+ "check": "npm run lint && npm run build && npm test && npm run smoke"
41
+ },
42
+ "devDependencies": {
43
+ "@eslint/js": "^10.0.1",
44
+ "@types/node": "^22.20.5",
45
+ "eslint": "^10.15.0",
46
+ "typescript": "~6.0.3",
47
+ "typescript-eslint": "^8.73.0",
48
+ "vitest": "^5.1.1"
49
+ },
50
+ "dependencies": {
51
+ "ajv": "^8.20.0",
52
+ "yaml": "^2.9.1"
53
+ }
54
+ }