@veda-hq/niyam 0.6.21 → 0.6.23

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,508 @@
1
+ import { SETTINGS_PATH, repoAt } from './agent.js';
2
+ const where = `${SETTINGS_PATH}: "docNumbers"`;
3
+ const PATH = /^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[\w@+=,.\/-]+$/;
4
+ const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
+ function record(value, at) {
6
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
7
+ throw new Error(`${at} must be an object`);
8
+ return value;
9
+ }
10
+ function only(value, at, keys) {
11
+ const extra = Object.keys(value).find((key) => !keys.includes(key));
12
+ if (extra !== undefined)
13
+ throw new Error(`${at} has an unknown key "${extra}"; it takes ${keys.map((key) => `"${key}"`).join(', ')}`);
14
+ }
15
+ function text(value, at, pattern) {
16
+ if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value) || (pattern && !pattern.test(value)))
17
+ throw new Error(`${at} must be ${pattern === PATH ? 'a path in the repository' : 'one line of text'}`);
18
+ return value;
19
+ }
20
+ function texts(value, at, pattern) {
21
+ if (!Array.isArray(value))
22
+ throw new Error(`${at} must be a list`);
23
+ return value.map((one, i) => text(one, `${at}[${String(i)}]`, pattern));
24
+ }
25
+ function docKind(name, raw) {
26
+ const at = `${where}.kinds.${name}`;
27
+ const value = record(raw, at);
28
+ only(value, at, ['dir', 'citation', 'frontmatterKey', 'relationships']);
29
+ const relationships = {};
30
+ for (const [dir, keys] of Object.entries(record(value.relationships ?? {}, `${at}.relationships`))) {
31
+ text(dir, `${at}.relationships key`, PATH);
32
+ relationships[dir] = texts(keys, `${at}.relationships.${dir}`, KEY);
33
+ }
34
+ return {
35
+ kind: name,
36
+ dir: text(value.dir, `${at}.dir`, PATH),
37
+ citation: text(value.citation, `${at}.citation`, /^[A-Z][A-Za-z]*$/),
38
+ frontmatterKey: text(value.frontmatterKey ?? name, `${at}.frontmatterKey`, KEY),
39
+ relationships,
40
+ };
41
+ }
42
+ function workItems(raw, kinds) {
43
+ const at = `${where}.workItems`;
44
+ const value = record(raw, at);
45
+ only(value, at, ['kind', 'issueType', 'label', 'lastMovedIssue', 'frozen', 'reserveCommand']);
46
+ const kind = text(value.kind, `${at}.kind`);
47
+ if (!Object.hasOwn(kinds, kind))
48
+ throw new Error(`${at}.kind names "${kind}", which "kinds" does not have`);
49
+ const last = value.lastMovedIssue;
50
+ if (last !== undefined && (typeof last !== 'number' || !Number.isSafeInteger(last) || last < 1))
51
+ throw new Error(`${at}.lastMovedIssue must be an issue number`);
52
+ let frozen;
53
+ if (value.frozen !== undefined) {
54
+ const f = record(value.frozen, `${at}.frozen`);
55
+ only(f, `${at}.frozen`, ['dir', 'entries']);
56
+ const entries = texts(f.entries, `${at}.frozen.entries`, /^\d{4}-[\w.-]+$/);
57
+ frozen = { dir: text(f.dir, `${at}.frozen.dir`, PATH), entries };
58
+ }
59
+ return {
60
+ kind,
61
+ issueType: text(value.issueType, `${at}.issueType`),
62
+ ...(value.label === undefined ? {} : { label: text(value.label, `${at}.label`) }),
63
+ ...(last === undefined ? {} : { lastMovedIssue: last }),
64
+ ...(frozen === undefined ? {} : { frozen }),
65
+ ...(value.reserveCommand === undefined ? {} : { reserveCommand: text(value.reserveCommand, `${at}.reserveCommand`) }),
66
+ };
67
+ }
68
+ /** The settings from their raw JSON; throws with the reason on anything malformed. */
69
+ export function docSettings(raw) {
70
+ const value = record(raw, where);
71
+ only(value, where, ['reservations', 'kinds', 'workItems', 'history']);
72
+ const reservations = text(value.reservations, `${where}.reservations`);
73
+ if (!/^refs\/[\w.{}\/-]+\/$/.test(reservations) || !reservations.includes('{kind}'))
74
+ throw new Error(`${where}.reservations must be a ref prefix under refs/ that names {kind} and ends in /`);
75
+ const kinds = {};
76
+ for (const [name, kind] of Object.entries(record(value.kinds, `${where}.kinds`))) {
77
+ if (!/^[a-z][a-z0-9-]*$/.test(name))
78
+ throw new Error(`${where}.kinds: "${name}" must be a lower-case word`);
79
+ kinds[name] = docKind(name, kind);
80
+ }
81
+ if (Object.keys(kinds).length === 0)
82
+ throw new Error(`${where}.kinds must name at least one kind`);
83
+ const history = value.history === undefined ? [] : texts(value.history, `${where}.history`, /^!?(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[\w@+=,.\/-]+$/);
84
+ return {
85
+ reservations,
86
+ kinds,
87
+ ...(value.workItems === undefined ? {} : { workItems: workItems(value.workItems, kinds) }),
88
+ history,
89
+ };
90
+ }
91
+ /**
92
+ * The settings for the repository at `root`: `"docNumbers"` in its `.github/niyam.json`, or the file that entry
93
+ * names. Throws when there are none, or they cannot be read: nothing is allocated from a guess.
94
+ */
95
+ export function loadDocSettings(sys, root) {
96
+ const path = `${root}/${SETTINGS_PATH}`;
97
+ if (!sys.exists(path))
98
+ throw new Error(`${SETTINGS_PATH} not found in ${root}`);
99
+ const entry = NiyamFileSchema.parse(JSON.parse(sys.read(path))).docNumbers;
100
+ if (entry === undefined)
101
+ throw new Error(`${SETTINGS_PATH} has no "docNumbers": name the document kinds there, or the JSON file that does`);
102
+ if (typeof entry !== 'string')
103
+ return docSettings(entry);
104
+ const file = text(entry, where, PATH);
105
+ if (!sys.exists(`${root}/${file}`))
106
+ throw new Error(`${where} names ${file}, which is not there (run pnpm install?)`);
107
+ return DocSettingsSchema.parse(JSON.parse(sys.read(`${root}/${file}`)));
108
+ }
109
+ /** A kind by its name on the command line, in any case; undefined when the settings have none. */
110
+ export function kindNamed(settings, name) {
111
+ if (name === undefined)
112
+ return undefined;
113
+ const lower = name.toLowerCase();
114
+ return Object.hasOwn(settings.kinds, lower) ? settings.kinds[lower] : undefined;
115
+ }
116
+ /** A document's file name: four digits, a hyphen, a slug, `.md`. */
117
+ const NUMBERED_DOC = /^(\d{4})-.*\.md$/;
118
+ /** A numbered folder or file: four digits and a hyphen. */
119
+ const NUMBERED_ENTRY = /^(\d{4})-/;
120
+ /** The four-digit number a document's file name declares, or null. */
121
+ export function numberFromFilename(name) {
122
+ return NUMBERED_DOC.exec(name)?.[1] ?? null;
123
+ }
124
+ /** The four-digit number a numbered entry's name opens with, or null. */
125
+ export function numberFromEntry(name) {
126
+ return NUMBERED_ENTRY.exec(name)?.[1] ?? null;
127
+ }
128
+ /** The number a file name or a path (`docs/work/0110-y`) declares, or null; only a path has a slash. */
129
+ export function numberFromName(name) {
130
+ return name.includes('/') ? numberFromEntry(name.slice(name.lastIndexOf('/') + 1)) : numberFromFilename(name);
131
+ }
132
+ /**
133
+ * Four digits that open a Work item title: `0150 — setup …` or `0150-slug`. A number later in the title is a
134
+ * citation, and a date (`2026-11-05 …`) or a longer run of digits is not a work number. Missing a work number could
135
+ * hand it out again, while misreading a title only skips a number, so only a whole `YYYY-MM-DD` reads as a date.
136
+ */
137
+ const WORK_ITEM_TITLE = /^(\d{4})(?!\d|-\d\d-\d\d(?!\d))/;
138
+ /** The work number a Work item title opens with, or null. */
139
+ export function numberFromWorkItemTitle(title) {
140
+ return WORK_ITEM_TITLE.exec(title.trimStart())?.[1] ?? null;
141
+ }
142
+ /** The frozen folders a kind counts, by path (`docs/work/0105-x`); none for a kind Work items do not take. */
143
+ export function frozenEntries(settings, kind) {
144
+ const frozen = settings.workItems?.kind === kind ? settings.workItems.frozen : undefined;
145
+ return frozen ? frozen.entries.map((entry) => `${frozen.dir}/${entry}`) : [];
146
+ }
147
+ /** The distinct numbers of a kind's frozen folders, ascending. */
148
+ export function frozenNumbers(settings, kind) {
149
+ return [...new Set(frozenEntries(settings, kind).map((path) => numberFromName(path)))].sort();
150
+ }
151
+ /** What a caught value says; one whose text cannot be read says so instead of throwing out of the handler. */
152
+ export function detail(error) {
153
+ try {
154
+ return error instanceof Error ? error.message : String(error);
155
+ }
156
+ catch {
157
+ // fail-open: this describes an error being reported already; a placeholder is better than a second throw.
158
+ return 'an error whose text could not be read';
159
+ }
160
+ }
161
+ /** A Schema whose check is `check`. */
162
+ export function schema(check) {
163
+ return {
164
+ '~standard': {
165
+ version: 1,
166
+ vendor: 'niyam',
167
+ validate(value) {
168
+ try {
169
+ return { value: check(value) };
170
+ }
171
+ catch (error) {
172
+ // fail-open: an invalid value is the answer here, reported as the issue.
173
+ return { issues: [{ message: detail(error) }] };
174
+ }
175
+ },
176
+ },
177
+ parse: check,
178
+ };
179
+ }
180
+ /** `.github/niyam.json`, for its `"docNumbers"` entry. */
181
+ export const NiyamFileSchema = schema((value) => ({ docNumbers: record(value, SETTINGS_PATH).docNumbers }));
182
+ /** The `"docNumbers"` settings, or the file they are in. */
183
+ export const DocSettingsSchema = schema(docSettings);
184
+ /** `gh pr list --json number,files`: a list; an entry without files lists none, and a file without a path is skipped. */
185
+ export const PullListSchema = schema((value) => {
186
+ if (!Array.isArray(value))
187
+ throw new Error('`gh pr list` returned an unexpected shape');
188
+ return value.map((pr) => {
189
+ const entry = typeof pr === 'object' && pr !== null ? pr : {};
190
+ const files = Array.isArray(entry.files) ? entry.files : [];
191
+ const paths = files.map((file) => (typeof file === 'object' && file !== null ? file.path : undefined)).filter((path) => typeof path === 'string');
192
+ return { number: entry.number, paths, listed: files.length };
193
+ });
194
+ });
195
+ /** One line of the Work item list: `{number, title}`. */
196
+ export const WorkItemLineSchema = schema((value) => {
197
+ const { number, title } = (typeof value === 'object' && value !== null ? value : {});
198
+ if (typeof number !== 'number' || !Number.isInteger(number) || typeof title !== 'string')
199
+ throw new Error('not {number, title}');
200
+ return { number, title };
201
+ });
202
+ /** A whole number from digits the caller has matched; throws on anything else. */
203
+ export function wholeNumber(digits) {
204
+ const number = Number(digits);
205
+ if (!/^\d+$/.test(digits) || !Number.isSafeInteger(number))
206
+ throw new Error(`"${digits}" is not a whole number`);
207
+ return number;
208
+ }
209
+ /** git's output, or null when git failed: "could not tell" is never "nothing there". */
210
+ export function gitOut(sys, root, args) {
211
+ const result = sys.exec('git', args, root === undefined ? {} : { cwd: root });
212
+ return result.code === 0 ? result.stdout : null;
213
+ }
214
+ /** git's output; throws with git's own error when it failed. */
215
+ function gitMust(sys, root, args) {
216
+ const result = sys.exec('git', args, { cwd: root });
217
+ if (result.code !== 0)
218
+ throw new Error(`git ${args.join(' ')}: ${result.stderr.trim() || `exit ${String(result.code)}`}`);
219
+ return result.stdout;
220
+ }
221
+ /** The kind's numbered documents in the working tree, by file name. */
222
+ export function localBasenames(sys, kind, root) {
223
+ return sys.list(`${root}/${kind.dir}`).filter((name) => NUMBERED_DOC.test(name)).sort();
224
+ }
225
+ /**
226
+ * The kind's numbered documents on a ref's tree, by file name; null when the ref cannot be read, which is not the
227
+ * same as a ref with none.
228
+ */
229
+ export function basenamesOnRef(sys, kind, ref, root) {
230
+ const out = gitOut(sys, root, ['ls-tree', '--name-only', ref, `${kind.dir}/`]);
231
+ if (out === null)
232
+ return null;
233
+ return out
234
+ .split('\n')
235
+ .filter(Boolean)
236
+ .map((path) => path.slice(path.lastIndexOf('/') + 1))
237
+ .filter((name) => NUMBERED_DOC.test(name))
238
+ .sort();
239
+ }
240
+ /** gh run by `sys` in `root`. */
241
+ export function ghIn(sys, root) {
242
+ return (args) => {
243
+ const result = sys.exec('gh', args, { cwd: root });
244
+ if (result.code !== 0)
245
+ throw new Error(result.stderr.trim() || `gh exited ${String(result.code)}`);
246
+ return result.stdout;
247
+ };
248
+ }
249
+ /** Open pull requests read at most; far above a repository's steady state. */
250
+ const PR_SCAN_LIMIT = 100;
251
+ /** Files `gh pr list --json files` gives per pull request before it stops. */
252
+ const PR_FILES_PAGE = 100;
253
+ /** Files the REST files list gives at most, paged or not. */
254
+ const PR_FILES_REST_LIMIT = 3000;
255
+ /** Every file of one pull request, paged through the REST list, or why it could not be read whole. */
256
+ function allPrFiles(number, gh) {
257
+ if (typeof number !== 'number' || !Number.isInteger(number))
258
+ return { ok: false, reason: 'no PR number' };
259
+ let paths;
260
+ try {
261
+ paths = gh(['api', `repos/{owner}/{repo}/pulls/${String(number)}/files`, '--paginate', '--jq', '.[].filename'])
262
+ .split('\n')
263
+ .filter((line) => line !== '');
264
+ }
265
+ catch {
266
+ // fail-open: the caller makes this a warning, and a warning makes --reserve refuse.
267
+ return { ok: false, reason: '`gh api` failed' };
268
+ }
269
+ if (paths.length >= PR_FILES_REST_LIMIT)
270
+ return { ok: false, reason: `the API stops at ${String(PR_FILES_REST_LIMIT)} files` };
271
+ return { ok: true, paths };
272
+ }
273
+ /**
274
+ * Numbers open pull requests hold: a pull request holds NNNN when it adds `<dir>/NNNN-*.md` that `mainNames` (the
275
+ * main branch's file names) does not have. Editing a document holds nothing.
276
+ */
277
+ export function prClaimedNumbers(kind, mainNames, gh) {
278
+ const warnings = [];
279
+ const numbers = new Set();
280
+ let raw;
281
+ try {
282
+ raw = gh(['pr', 'list', '--state', 'open', '--limit', String(PR_SCAN_LIMIT), '--json', 'number,files']);
283
+ }
284
+ catch {
285
+ // fail-open: a preview must never block an author; the warning makes --reserve refuse.
286
+ warnings.push('could not read open PRs via `gh` (not installed, not authenticated, or offline) — numbers claimed by unmerged PRs were NOT considered');
287
+ return { numbers, warnings };
288
+ }
289
+ let pulls;
290
+ try {
291
+ pulls = PullListSchema.parse(JSON.parse(raw));
292
+ }
293
+ catch (error) {
294
+ // fail-open: as above, the warning is what makes --reserve refuse.
295
+ warnings.push(error instanceof SyntaxError ? '`gh pr list` returned output that is not JSON — PR claims were NOT considered' : '`gh pr list` returned an unexpected shape — PR claims were NOT considered');
296
+ return { numbers, warnings };
297
+ }
298
+ if (pulls.length >= PR_SCAN_LIMIT)
299
+ warnings.push(`${String(pulls.length)} open PRs listed (the scan limit) — there may be more, and any claim they carry was NOT considered`);
300
+ const onMain = new Set(mainNames);
301
+ const prefix = `${kind.dir}/`;
302
+ for (const pr of pulls) {
303
+ let paths = pr.paths;
304
+ // A pull request at the page's end may hide a document past it: read its whole list.
305
+ if (pr.listed >= PR_FILES_PAGE) {
306
+ const full = allPrFiles(pr.number, gh);
307
+ if (full.ok)
308
+ paths = full.paths;
309
+ else
310
+ warnings.push(`PR #${String(pr.number)} has ${String(pr.listed)}+ files and its full file list could not be read (${full.reason}) — any claim past its first ${String(pr.listed)} listed files was NOT considered`);
311
+ }
312
+ for (const path of paths) {
313
+ if (!path.startsWith(prefix))
314
+ continue;
315
+ const name = path.slice(prefix.length);
316
+ const number = numberFromFilename(name);
317
+ if (number !== null && !onMain.has(name))
318
+ numbers.add(number);
319
+ }
320
+ }
321
+ return { numbers, warnings };
322
+ }
323
+ /**
324
+ * Every Work item issue, open and closed, through the REST list (search caps at 1000 and lags a new issue). Any
325
+ * warning empties the list: a reservation or a clash check must not work from part of it.
326
+ */
327
+ export function listWorkItems(work, gh) {
328
+ const none = (warning) => ({ items: [], warnings: [warning] });
329
+ let raw;
330
+ try {
331
+ raw = gh(['api', '--paginate', `repos/{owner}/{repo}/issues?state=all&type=${encodeURIComponent(work.issueType)}&per_page=100`, '--jq', `.[] | select(.type.name == ${JSON.stringify(work.issueType)}) | {number, title}`]);
332
+ }
333
+ catch {
334
+ // fail-open: a preview must never block an author; the warning makes --reserve refuse.
335
+ return none('could not read Work item issues via `gh` (not installed, not authenticated, or offline) — numbers in their titles were NOT considered');
336
+ }
337
+ const items = [];
338
+ for (const line of raw.split('\n')) {
339
+ if (line.trim() === '')
340
+ continue;
341
+ let parsed;
342
+ try {
343
+ parsed = WorkItemLineSchema.parse(JSON.parse(line));
344
+ }
345
+ catch (error) {
346
+ // fail-open: the warning is what makes --reserve refuse.
347
+ return none(error instanceof SyntaxError ? 'the Work item issue list returned a line that is not JSON — Work item titles were NOT considered' : 'the Work item issue list returned an unexpected shape — Work item titles were NOT considered');
348
+ }
349
+ const { number, title } = parsed;
350
+ items.push({ number, title, workNumber: numberFromWorkItemTitle(title) });
351
+ }
352
+ // A repository with Work items has some, so an empty answer is GitHub answering wrongly, not "none".
353
+ if (items.length === 0)
354
+ return none('the Work item issue list came back empty — Work item titles were NOT considered');
355
+ return { items, warnings: [] };
356
+ }
357
+ /**
358
+ * Candidates skipped for a failure this process cannot classify before it reports the first. `update-ref` says
359
+ * "cannot lock ref" for a lost race, a held lock, a directory/file clash and an unwritable ref store alike; only the
360
+ * first can be told apart, by the ref now being there. A skipped number is a gap for good.
361
+ */
362
+ const INDETERMINATE_SKIP_LIMIT = 3;
363
+ /**
364
+ * Picks the next free number of `kind` and, unless `dryRun`, claims it for good with a reservation ref, created
365
+ * atomically by `update-ref` so two worktrees never get one number. Reads every ref's history of the kind's folder,
366
+ * every reservation ref and every linked worktree's folder, beside `alsoTaken` (numbers the caller knows of that git
367
+ * cannot see). `warn` hears of each candidate it has to skip.
368
+ */
369
+ export function reserveDocNumber(sys, root, settings, kind, options = {}) {
370
+ const { dir, citation } = kind;
371
+ const prefix = settings.reservations.replaceAll('{kind}', kind.kind);
372
+ const used = new Set(options.alsoTaken ?? []);
373
+ const escape = (literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
374
+ const pattern = new RegExp(`(?:${escape(dir)}/|${escape(prefix)})(\\d{4})\\b`, 'g');
375
+ const note = (out) => {
376
+ for (const match of out.matchAll(pattern))
377
+ used.add(wholeNumber(match[1]));
378
+ };
379
+ note(gitMust(sys, root, ['log', '--all', '--format=', '--name-only', '--', dir]));
380
+ note(gitMust(sys, root, ['for-each-ref', prefix]));
381
+ for (const line of gitMust(sys, root, ['worktree', 'list', '--porcelain']).split('\n')) {
382
+ if (!line.startsWith('worktree '))
383
+ continue;
384
+ for (const name of sys.list(`${line.slice('worktree '.length)}/${dir}`))
385
+ note(`${dir}/${name}`);
386
+ }
387
+ let head;
388
+ let first;
389
+ let skipped = 0;
390
+ for (let number = Math.max(0, ...used) + 1; number <= 9999; number += 1) {
391
+ const formatted = String(number).padStart(4, '0');
392
+ if (options.dryRun)
393
+ return formatted;
394
+ // HEAD only to create a ref, so a preview needs no commit.
395
+ head ??= gitMust(sys, root, ['rev-parse', 'HEAD']).trim();
396
+ const ref = `${prefix}${formatted}`;
397
+ const made = sys.exec('git', ['-c', 'core.filesRefLockTimeout=2000', 'update-ref', ref, head, ''], { cwd: root });
398
+ if (made.code === 0)
399
+ return formatted;
400
+ // Lost the race outright: the winner's ref is there, so go on.
401
+ if (gitOut(sys, root, ['show-ref', '--verify', ref]) !== null)
402
+ continue;
403
+ // Not there: a competitor between taking the lock and renaming it into place looks the same as a broken ref
404
+ // store, so skip, but only so many times.
405
+ first ??= new Error(`could not claim ${citation} ${formatted}: ${made.stderr.trim()}`);
406
+ skipped += 1;
407
+ if (skipped > INDETERMINATE_SKIP_LIMIT)
408
+ throw first;
409
+ options.warn?.(`${citation} ${formatted} could not be claimed; skipping it.\n${made.stderr.trim()}`);
410
+ }
411
+ throw new Error(`${citation} number space exhausted`);
412
+ }
413
+ /** Every taken number, then the next free one, previewed or reserved, with where the taken ones came from. */
414
+ export function allocate(sys, root, settings, kind, options) {
415
+ const ref = options.ref ?? 'origin/main';
416
+ const mainNames = basenamesOnRef(sys, kind, ref, root);
417
+ if (mainNames === null)
418
+ return { ok: false, error: `could not read \`${ref}\` — fetch it first (\`git fetch origin main\`). Allocating without it would hand out a number main may already use.` };
419
+ const localNames = localBasenames(sys, kind, root);
420
+ const taken = new Set();
421
+ for (const name of [...mainNames, ...localNames])
422
+ taken.add(numberFromFilename(name));
423
+ const frozen = frozenNumbers(settings, kind.kind);
424
+ for (const number of frozen)
425
+ taken.add(number);
426
+ const warnings = [];
427
+ const countsWorkItems = settings.workItems?.kind === kind.kind;
428
+ let pullRequests = 0;
429
+ let workItems = 0;
430
+ let complete = true;
431
+ if (options.offline) {
432
+ complete = false;
433
+ warnings.push('--offline: numbers claimed by unmerged PRs were NOT considered');
434
+ if (countsWorkItems)
435
+ warnings.push('--offline: numbers in Work item issue titles were NOT considered');
436
+ }
437
+ else {
438
+ const claims = prClaimedNumbers(kind, mainNames, options.gh);
439
+ warnings.push(...claims.warnings);
440
+ if (claims.warnings.length > 0)
441
+ complete = false;
442
+ for (const number of claims.numbers)
443
+ taken.add(number);
444
+ pullRequests = claims.numbers.size;
445
+ if (countsWorkItems && settings.workItems) {
446
+ const listed = listWorkItems(settings.workItems, options.gh);
447
+ warnings.push(...listed.warnings);
448
+ if (listed.warnings.length > 0)
449
+ complete = false;
450
+ const numbers = new Set(listed.items.flatMap((item) => (item.workNumber === null ? [] : [item.workNumber])));
451
+ for (const number of numbers)
452
+ taken.add(number);
453
+ workItems = numbers.size;
454
+ }
455
+ }
456
+ if (options.reserve && !complete)
457
+ return { ok: false, error: `refusing to RESERVE while the GitHub scan is incomplete — a permanent claim must not be made blind to what open PRs and Work items hold. Re-run without \`--reserve\` to preview, or fix the cause: ${warnings.join('; ')}` };
458
+ let next;
459
+ try {
460
+ next = reserveDocNumber(sys, root, settings, kind, { alsoTaken: [...taken].map(wholeNumber), dryRun: !options.reserve, ...(options.warn ? { warn: options.warn } : {}) });
461
+ }
462
+ catch (error) {
463
+ // fail-open: the failure is the return value, and the command exits 1 on it.
464
+ return { ok: false, error: `could not reserve a ${kind.citation} number: ${detail(error).trim()}` };
465
+ }
466
+ return { ok: true, next, sources: { main: mainNames.length, local: localNames.length, pullRequests, workItems, frozen: frozen.length }, warnings };
467
+ }
468
+ const FLAGS = ['--json', '--offline', '--reserve'];
469
+ /** doc-number's arguments: one kind, and its flags. */
470
+ export function docNumberArgs(args) {
471
+ const kinds = args.filter((arg) => !FLAGS.includes(arg));
472
+ const odd = kinds.find((arg) => arg.startsWith('-'));
473
+ if (odd !== undefined)
474
+ throw new Error(`doc-number: unknown option "${odd}"`);
475
+ if (kinds.length !== 1)
476
+ throw new Error('doc-number needs one document kind, such as adr');
477
+ return { kind: kinds[0], json: args.includes('--json'), offline: args.includes('--offline'), reserve: args.includes('--reserve') };
478
+ }
479
+ /**
480
+ * `niyam doc-number <kind> [--reserve] [--json] [--offline]`: the next free number alone on standard output, for
481
+ * `$(…)`, and where it came from on standard error; `--reserve` claims it for good.
482
+ */
483
+ export function docNumber(sys, io, args) {
484
+ const parsed = docNumberArgs(args);
485
+ const { root } = repoAt(sys);
486
+ const settings = loadDocSettings(sys, root);
487
+ const kind = kindNamed(settings, parsed.kind);
488
+ if (kind === undefined) {
489
+ io.err(`niyam doc-number: no document kind "${parsed.kind}"; ${SETTINGS_PATH} names ${Object.keys(settings.kinds).join(', ')}`);
490
+ return 2;
491
+ }
492
+ const result = allocate(sys, root, settings, kind, { offline: parsed.offline, reserve: parsed.reserve, gh: ghIn(sys, root), warn: io.err });
493
+ if (!result.ok) {
494
+ io.err(`❌ ${result.error}`);
495
+ return 1;
496
+ }
497
+ if (parsed.json) {
498
+ io.out(JSON.stringify({ kind: kind.kind, ...result }, null, 2));
499
+ return 0;
500
+ }
501
+ for (const warning of result.warnings)
502
+ io.err(`⚠️ ${warning}`);
503
+ const { main, local, pullRequests, workItems, frozen } = result.sources;
504
+ const work = settings.workItems?.kind === kind.kind ? `, ${String(workItems)} in Work item titles, ${String(frozen)} frozen work folder numbers` : '';
505
+ io.err(`→ next free ${kind.citation} number, against ${String(main)} on origin/main, ${String(local)} local, ${String(pullRequests)} claimed by open PRs${work}${parsed.reserve ? ', reserved' : ' (a preview; --reserve claims it)'}:`);
506
+ io.out(result.next);
507
+ return 0;
508
+ }
package/dist/doctor.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { EXPIRY_WARNING_DAYS, SETTINGS_PATH, account, agentFrom, agentIn, anyLogin, either, hasSettings, loadSettings, repoAt, sameLogin, checkToken, keyBody, keyPairProblem, launcherPath, pathsFor, sessionFileIs, signingKeys, tokenInfo, } from './agent.js';
2
2
  import { LOCKED, clientHooks, hooksHittingLock } from './as-agent.js';
3
- import { FROM_SETUP, cloudLogin, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
3
+ import { FROM_SETUP, SIGNING_KEY_VAR, cloudLogin, fileFromSetup, ranFromSetup, repoReleases } from './cloud.js';
4
+ import { GITHUB_NOREPLY } from './host.js';
4
5
  import { featuresIn } from './features.js';
5
6
  import { typesDrift } from './issue-types.js';
6
7
  import { closing, findingLines, heading, painter, tilde } from './layout.js';
7
8
  import { exposure, exposureFindings, movedFindings, readDeclined, setAside } from './lockout.js';
8
9
  import { CLOUD_SETUP_PATH, HOOKS_PATH, SARATHI_PATH } from './onboard-pull.js';
9
10
  import { leftoverDir, leftoverToken } from './machine.js';
10
- import { GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, missingAutoFixRules, sarathiRunner } from './onboard.js';
11
+ import { BOARD_SECRETS, GUARD_COMMAND, HOOK_COMMAND, OLDER_GUARD_COMMANDS, OLDER_HOOK_COMMANDS, missingAutoFixRules, sarathiRunner } from './onboard.js';
12
+ import { secretNames } from './secrets.js';
11
13
  import { isOrganisation } from './owner-login.js';
12
14
  import { leftBehind } from './owner-step.js';
13
15
  import { repoRoot } from './session-start.js';
@@ -88,6 +90,7 @@ export async function doctor(sys, io, named) {
88
90
  return registered ? { mark: '✓', text: 'signing key registered' } : { mark: '✗', text: 'signing key not registered', fix: MACHINE };
89
91
  }),
90
92
  ...(await typesFindings(sys, token)),
93
+ ...(await boardAppFindings(sys, token)),
91
94
  ];
92
95
  return report(sys, io, agent, [
93
96
  ['This Mac', mac],
@@ -134,30 +137,36 @@ function leftoverFindings(sys, store, agent) {
134
137
  ];
135
138
  }
136
139
  /**
137
- * Whether the organisation's enabled issue types are the work model's, no
138
- * issue here holds another, and every open one here has one but the
139
- * Approvals issue: checked in a repository whose settings turn the board on,
140
- * in an organisation, since onboard keeps them so there.
140
+ * The repository doctor runs in and its settings, parsed, where they turn
141
+ * the board on and doctor has a token to ask GitHub with; else undefined.
141
142
  */
142
- async function typesFindings(sys, token) {
143
- let slug;
144
- let approvals;
143
+ function boardRepo(sys, token) {
145
144
  try {
146
145
  const found = repoAt(sys);
147
146
  const path = `${found.root}/${SETTINGS_PATH}`;
148
147
  if (!token || !sys.exists(path))
149
- return [];
148
+ return undefined;
150
149
  const settings = JSON.parse(sys.read(path));
151
- if (!featuresIn(settings).includes('board'))
152
- return [];
153
- slug = found.slug;
154
- const named = settings?.approvals;
155
- approvals = typeof named === 'number' ? named : undefined;
150
+ return featuresIn(settings).includes('board') ? { slug: found.slug, settings } : undefined;
156
151
  }
157
152
  catch {
158
153
  // Outside a client's clone, or settings doctor cannot read: onboard says what is wrong with them.
159
- return [];
154
+ return undefined;
160
155
  }
156
+ }
157
+ /**
158
+ * Whether the organisation's enabled issue types are the work model's, no
159
+ * issue here holds another, and every open one here has one but the
160
+ * Approvals issue: checked in a repository whose settings turn the board on,
161
+ * in an organisation, since onboard keeps them so there.
162
+ */
163
+ async function typesFindings(sys, token) {
164
+ const here = boardRepo(sys, token);
165
+ if (!here || !token)
166
+ return [];
167
+ const { slug, settings } = here;
168
+ const named = settings?.approvals;
169
+ const approvals = typeof named === 'number' ? named : undefined;
161
170
  const org = slug.split('/')[0];
162
171
  try {
163
172
  return (await isOrganisation(sys, org)) ? [await typesDrift(sys, token, org, slug, approvals)] : [];
@@ -166,6 +175,34 @@ async function typesFindings(sys, token) {
166
175
  return [{ mark: '✗', text: `issue types: cannot ask GitHub (${message(error)})`, fix: 'niyam doctor again' }];
167
176
  }
168
177
  }
178
+ /**
179
+ * Whether the repository has the board app's secrets, which the Slice started
180
+ * job moves a slice to In Progress with when its pull request opens (P-70):
181
+ * checked where the settings turn the board on, in an organisation. A missing
182
+ * one is worth fixing, never broken, since the desktop push still moves the
183
+ * board; secrets GitHub will not list say nothing.
184
+ */
185
+ async function boardAppFindings(sys, token) {
186
+ const here = boardRepo(sys, token);
187
+ if (!here || !token)
188
+ return [];
189
+ const { slug } = here;
190
+ try {
191
+ if (!(await isOrganisation(sys, slug.split('/')[0])))
192
+ return [];
193
+ const names = await secretNames(sys, slug, token);
194
+ if (names === undefined)
195
+ return [];
196
+ const missing = BOARD_SECRETS.filter((name) => !names.includes(name));
197
+ return missing.length === 0
198
+ ? [{ mark: '✓', text: 'board app secrets' }]
199
+ : [{ mark: '▲', text: `no ${missing.join(' or ')} secret, so a slice moves to In Progress only from a desktop push`, fix: `${ONBOARD}, which says how to set up the board app` }];
200
+ }
201
+ catch (error) {
202
+ // fail-open: a read that failed is the one ▲ here, as a missing secret breaks nothing.
203
+ return [{ mark: '▲', text: `board app secrets: cannot ask GitHub (${message(error)})`, fix: 'niyam doctor again' }];
204
+ }
205
+ }
169
206
  /**
170
207
  * Client hooks that reach GitHub outside `as-agent` where doctor runs, a Mac
171
208
  * or a cloud session, and the Auto-fix rules an onboarded repo's Claude Code
@@ -343,6 +380,9 @@ async function cloudDoctor(sys, io, named) {
343
380
  text: 'session-start did not give this session the agent identity, so gh and git stay locked out',
344
381
  fix: 'a new session; its first niyam line says why',
345
382
  });
383
+ const agent = given ?? ('login' in asked ? asked.login : undefined);
384
+ if (agent !== undefined)
385
+ github.push(cloudCommits(sys, agent));
346
386
  const about = 'login' in asked ? asked.login : agents !== undefined ? either(agents) : 'this cloud session';
347
387
  return report(sys, io, about, [
348
388
  ['This cloud session', session],
@@ -350,6 +390,27 @@ async function cloudDoctor(sys, io, named) {
350
390
  ['This repo', repoFindings(sys)],
351
391
  ]);
352
392
  }
393
+ /**
394
+ * Whose a cloud session's commits are: the agent's when session-start gave it
395
+ * the agent's author and signing (the key in SIGNING_KEY_VAR), else Claude's,
396
+ * which PR identity passes, so a warning only, with what makes them the
397
+ * agent's.
398
+ */
399
+ function cloudCommits(sys, agent) {
400
+ const name = sys.env.GIT_AUTHOR_NAME;
401
+ const email = sys.env.GIT_AUTHOR_EMAIL?.toLowerCase() ?? '';
402
+ if (name !== undefined && sameLogin(name, agent) && /^\d+\+/.test(email) && email.endsWith(`+${agent.toLowerCase()}@${GITHUB_NOREPLY}`)) {
403
+ return { mark: '✓', text: `this session's commits are ${agent}'s, signed with ${SIGNING_KEY_VAR}` };
404
+ }
405
+ if (sys.env[SIGNING_KEY_VAR]) {
406
+ return { mark: '▲', text: `${SIGNING_KEY_VAR} is set, but session-start could not use it, so this session's commits are Claude's`, fix: 'a new session; its first niyam line says why' };
407
+ }
408
+ return {
409
+ mark: '▲',
410
+ text: `this session's commits are Claude's: the cloud environment's variables have no ${SIGNING_KEY_VAR}`,
411
+ fix: `niyam cloud-key ${agent} on your Mac, then paste it into the environment's variables`,
412
+ };
413
+ }
353
414
  function message(error) {
354
415
  return error instanceof Error ? error.message : String(error);
355
416
  }