@veda-hq/niyam 0.6.21 → 0.6.22
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.
- package/README.md +36 -1
- package/dist/doc-numbers.js +508 -0
- package/dist/hermetic-git.js +32 -0
- package/dist/renumber-doc.js +321 -0
- package/dist/run.js +25 -3
- package/dist/work-item-number.js +262 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -913,6 +913,41 @@ records are in `.tmp/keep-going/`. The settings:
|
|
|
913
913
|
origin's default branch. `printMode` names older print-mode variables read beside `NIYAM_PRINT_MODE`;
|
|
914
914
|
`owner` is who the messages tell a session to tell; `tag` ends each message.
|
|
915
915
|
|
|
916
|
+
**Document numbers are never reused.** `niyam doc-number <kind>` prints the
|
|
917
|
+
next free number for a numbered document kind on stdout, and where it looked
|
|
918
|
+
on stderr (`--json` for both at once). It takes one past every number held in:
|
|
919
|
+
- every ref's history and every worktree's folder;
|
|
920
|
+
- the reservation refs;
|
|
921
|
+
- open pull requests;
|
|
922
|
+
- the titles of Work item issues and the frozen folders, for the kind they share.
|
|
923
|
+
|
|
924
|
+
`--reserve` claims the number for good with an atomic `git update-ref` in the
|
|
925
|
+
repository's shared git store, so concurrent sessions in linked worktrees get
|
|
926
|
+
distinct numbers. It refuses when any GitHub source could not be read.
|
|
927
|
+
`niyam renumber-doc <kind> <from> <to>` previews moving a document to another
|
|
928
|
+
number; `--apply` moves it and rewrites every reference and frontmatter
|
|
929
|
+
relationship to it, outside the history paths. `niyam work-item-number`,
|
|
930
|
+
run from a workflow on issue events and on a schedule, renumbers a Work item
|
|
931
|
+
filed with a taken number. It comments first, then retitles, and stops if the
|
|
932
|
+
title changed meanwhile. It also adds `label` to every Work item that lacks it.
|
|
933
|
+
The settings, inline or as the path of a JSON file:
|
|
934
|
+
|
|
935
|
+
```json
|
|
936
|
+
{ "docNumbers": {
|
|
937
|
+
"reservations": "refs/niyam/{kind}-reservations/",
|
|
938
|
+
"kinds": {
|
|
939
|
+
"adr": { "dir": "docs/adr", "citation": "ADR", "frontmatterKey": "adr",
|
|
940
|
+
"relationships": { "docs/adr": ["supersedes", "superseded_by"] } },
|
|
941
|
+
"rfc": { "dir": "docs/rfcs", "citation": "RFC", "frontmatterKey": "rfc",
|
|
942
|
+
"relationships": { "docs/rfcs": ["supersedes"] } } },
|
|
943
|
+
"workItems": { "kind": "rfc", "issueType": "Work item", "label": "work-item", "lastMovedIssue": 1,
|
|
944
|
+
"frozen": { "dir": "docs/work", "entries": [] } },
|
|
945
|
+
"history": ["docs/work/"]
|
|
946
|
+
} }
|
|
947
|
+
```
|
|
948
|
+
|
|
949
|
+
`workItems` is optional; so is `history`, whose `!` entries are exceptions.
|
|
950
|
+
|
|
916
951
|
**Design frames** is the `figma` feature, an optional extension for clients
|
|
917
952
|
that design in Figma: with it on and two Actions secrets, `FIGMA_LIBRARY`
|
|
918
953
|
(the design library's file key) and `FIGMA_TOKEN`, each State of the slice
|
|
@@ -1420,7 +1455,7 @@ tag and the commit. Install the attached package on each machine with pnpm,
|
|
|
1420
1455
|
once; nothing is built on install:
|
|
1421
1456
|
|
|
1422
1457
|
```bash
|
|
1423
|
-
pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.
|
|
1458
|
+
pnpm add -g https://github.com/veda-hq/niyam/releases/download/v0.6.22/veda-hq-niyam-0.6.22.tgz
|
|
1424
1459
|
```
|
|
1425
1460
|
|
|
1426
1461
|
The package puts one command on `PATH`, `niyam`. Since P-57 a release
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { existsSync, realpathSync, rmSync } from 'node:fs';
|
|
2
|
+
import { devNull, tmpdir } from 'node:os';
|
|
3
|
+
import { isAbsolute, relative } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* Removes a test's fixture folder and all in it, once links are followed; refuses any path that is not strictly
|
|
6
|
+
* inside the system's temporary folder, so a cleanup can never reach a real checkout. Nothing there is fine.
|
|
7
|
+
*/
|
|
8
|
+
export function removeFixtureRoot(path) {
|
|
9
|
+
if (!existsSync(path))
|
|
10
|
+
return;
|
|
11
|
+
const inside = relative(realpathSync(tmpdir()), realpathSync(path));
|
|
12
|
+
if (inside === '' || inside.startsWith('..') || isAbsolute(inside))
|
|
13
|
+
throw new Error(`refusing to remove ${path}: it is not inside ${tmpdir()}`);
|
|
14
|
+
rmSync(path, { recursive: true, force: true });
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* git without the caller's repository or configuration, for tests that build git fixtures: under a git hook the
|
|
18
|
+
* environment carries GIT_DIR and GIT_INDEX_FILE, so a child that inherited them would read and write the hook's
|
|
19
|
+
* repository instead of the fixture, and the machine's global config (hooks, trace targets) would reach it.
|
|
20
|
+
*/
|
|
21
|
+
const HERMETIC = { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' };
|
|
22
|
+
/** `env` (the process's own by default) without any GIT_ variable, and with no global or system config. */
|
|
23
|
+
export function hermeticGitEnv(env = process.env) {
|
|
24
|
+
return { ...Object.fromEntries(Object.entries(env).filter(([key]) => !key.startsWith('GIT_'))), ...HERMETIC };
|
|
25
|
+
}
|
|
26
|
+
/** The same for this process itself, whose git children (the code under test) inherit its environment. */
|
|
27
|
+
export function maskProcessGitEnv(env = process.env) {
|
|
28
|
+
for (const key of Object.keys(env))
|
|
29
|
+
if (key.startsWith('GIT_'))
|
|
30
|
+
Reflect.deleteProperty(env, key);
|
|
31
|
+
Object.assign(env, HERMETIC);
|
|
32
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
import { SETTINGS_PATH, repoAt } from './agent.js';
|
|
3
|
+
import { basenamesOnRef, gitOut, kindNamed, loadDocSettings, localBasenames } from './doc-numbers.js';
|
|
4
|
+
/**
|
|
5
|
+
* Moves a numbered document to another number, taking every reference with it: the file (`git mv`, or a plain
|
|
6
|
+
* rename when git does not track it yet), its own frontmatter key, every citation (`ADR-0057`) and full or relative
|
|
7
|
+
* path in tracked files, and the bare relationship values (`supersedes: '0040'`) the settings name. The rename was
|
|
8
|
+
* never the expensive part of a clash; finding every reference is, so this does it. A dry run by default: some prose
|
|
9
|
+
* narrates history, and only a person can tell, so `--apply` writes.
|
|
10
|
+
*/
|
|
11
|
+
const FOUR_DIGITS = /^\d{4}$/;
|
|
12
|
+
const literal = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
13
|
+
const citationOf = (kind, number) => `${kind.citation}-${number}`;
|
|
14
|
+
/** Tracked files that contain `needle`, by path; under `dir` when given. */
|
|
15
|
+
export function filesContaining(sys, root, needle, dir) {
|
|
16
|
+
const out = gitOut(sys, root, ['grep', '-l', '-F', '--', needle, ...(dir === undefined ? [] : [dir])]);
|
|
17
|
+
return out === null ? [] : out.split('\n').filter(Boolean);
|
|
18
|
+
}
|
|
19
|
+
/** Whether a renumber leaves `path` as written: it records what a document was called then. */
|
|
20
|
+
export function isHistory(settings, path) {
|
|
21
|
+
const matches = (pattern) => (pattern.endsWith('/') ? path.startsWith(pattern) : path === pattern);
|
|
22
|
+
if (settings.history.some((pattern) => pattern.startsWith('!') && matches(pattern.slice(1))))
|
|
23
|
+
return false;
|
|
24
|
+
return settings.history.some((pattern) => !pattern.startsWith('!') && matches(pattern));
|
|
25
|
+
}
|
|
26
|
+
/** The relationship keys `path` carries for `kind`, or none. */
|
|
27
|
+
export function relationshipKeysFor(kind, path) {
|
|
28
|
+
for (const [dir, keys] of Object.entries(kind.relationships))
|
|
29
|
+
if (path.startsWith(`${dir}/`))
|
|
30
|
+
return keys;
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Citations of `from` become `to`, and paths to the old file name the new one. A citation needs a non-digit after
|
|
35
|
+
* it, so `ADR-0057` never matches in `ADR-00571`. A relative path (`../rfcs/…`, `../../rfcs/…`) is rewritten only
|
|
36
|
+
* when, resolved against the file that holds it (`path`), it lands on this very document.
|
|
37
|
+
*/
|
|
38
|
+
export function rewriteReferences(text, kind, from, to, oldName, newName, path) {
|
|
39
|
+
const citation = new RegExp(`${citationOf(kind, literal(from))}(?!\\d)`, 'g');
|
|
40
|
+
const sibling = kind.dir.slice(kind.dir.lastIndexOf('/') + 1);
|
|
41
|
+
const relative = new RegExp(`(?<![\\w./-])((?:\\.\\./)+${literal(sibling)}/)${literal(oldName)}`, 'g');
|
|
42
|
+
const fromDir = posix.dirname(path);
|
|
43
|
+
return text
|
|
44
|
+
.replaceAll(`${kind.dir}/${oldName}`, `${kind.dir}/${newName}`)
|
|
45
|
+
.replace(relative, (match, prefix) => (posix.normalize(posix.join(fromDir, `${prefix}${oldName}`)) === `${kind.dir}/${oldName}` ? `${prefix}${newName}` : match))
|
|
46
|
+
.replace(citation, citationOf(kind, to));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Bare numbers under the relationship keys `path` carries for `kind`: a scalar (`key: '0040'`, `key: 0040`,
|
|
50
|
+
* `key: '0040 (a note)'`), a flow list (`key: ["0022", 0023]`), a block list (`- '0022 (…)'`) and a flow list
|
|
51
|
+
* wrapped over lines, with `# comments`, blank lines in a block and CRLF. A value that is only numbers and commas
|
|
52
|
+
* names each of them; any other value names one document, its leading number, and the rest is description. Keys the
|
|
53
|
+
* kind does not own are left alone: a bare number there could name either kind.
|
|
54
|
+
*/
|
|
55
|
+
export function rewriteRelationships(text, kind, from, to, path) {
|
|
56
|
+
const keys = new Set(relationshipKeysFor(kind, path));
|
|
57
|
+
if (keys.size === 0)
|
|
58
|
+
return text;
|
|
59
|
+
const swap = (value) => (value === from ? to : value);
|
|
60
|
+
const LIST = /^\s*\d{4}(\s*,\s*\d{4})*\s*$/;
|
|
61
|
+
const swapInner = (inner) => (LIST.test(inner) ? inner.replace(/\d{4}/g, swap) : inner.replace(/^(\s*)(\d{4})(?!\d)/, (_whole, lead, number) => `${lead}${swap(number)}`));
|
|
62
|
+
const swapElement = (element) => {
|
|
63
|
+
const quoted = /^(\s*)(['"])([\s\S]*)\2(\s*)$/.exec(element);
|
|
64
|
+
if (quoted === null)
|
|
65
|
+
return swapInner(element);
|
|
66
|
+
const [, pre, quote, inner, post] = quoted;
|
|
67
|
+
return `${pre}${quote}${swapInner(inner)}${quote}${post}`;
|
|
68
|
+
};
|
|
69
|
+
// Top-level commas only; a backslash escapes only inside double quotes, as in YAML.
|
|
70
|
+
const splitElements = (segment) => {
|
|
71
|
+
const parts = [];
|
|
72
|
+
let current = '';
|
|
73
|
+
let quote = null;
|
|
74
|
+
let escaped = false;
|
|
75
|
+
for (const ch of segment) {
|
|
76
|
+
if (escaped)
|
|
77
|
+
escaped = false;
|
|
78
|
+
else if (quote === '"' && ch === '\\')
|
|
79
|
+
escaped = true;
|
|
80
|
+
else if (quote !== null) {
|
|
81
|
+
if (ch === quote)
|
|
82
|
+
quote = null;
|
|
83
|
+
}
|
|
84
|
+
else if (ch === "'" || ch === '"')
|
|
85
|
+
quote = ch;
|
|
86
|
+
else if (ch === ',') {
|
|
87
|
+
parts.push(current);
|
|
88
|
+
current = '';
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
current += ch;
|
|
92
|
+
}
|
|
93
|
+
parts.push(current);
|
|
94
|
+
return parts;
|
|
95
|
+
};
|
|
96
|
+
const swapElements = (segment) => splitElements(segment).map(swapElement).join(',');
|
|
97
|
+
// A comment starts at a # outside quotes that opens the segment or follows whitespace.
|
|
98
|
+
const splitComment = (segment) => {
|
|
99
|
+
let quote = null;
|
|
100
|
+
let escaped = false;
|
|
101
|
+
for (const [i, ch] of [...segment].entries()) {
|
|
102
|
+
if (escaped)
|
|
103
|
+
escaped = false;
|
|
104
|
+
else if (quote === '"' && ch === '\\')
|
|
105
|
+
escaped = true;
|
|
106
|
+
else if (quote !== null) {
|
|
107
|
+
if (ch === quote)
|
|
108
|
+
quote = null;
|
|
109
|
+
}
|
|
110
|
+
else if (ch === "'" || ch === '"')
|
|
111
|
+
quote = ch;
|
|
112
|
+
else if (ch === '#' && (i === 0 || /\s/.test(segment[i - 1])))
|
|
113
|
+
return [segment.slice(0, i), segment.slice(i)];
|
|
114
|
+
}
|
|
115
|
+
return [segment, ''];
|
|
116
|
+
};
|
|
117
|
+
const swapFlowLine = (body) => {
|
|
118
|
+
const [, open, inner, close] = /^(\s*\[?)([\s\S]*?)(\]?\s*)$/.exec(body);
|
|
119
|
+
return `${open}${swapElements(inner)}${close}`;
|
|
120
|
+
};
|
|
121
|
+
const lines = text.split('\n');
|
|
122
|
+
let mode = null;
|
|
123
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
124
|
+
const whole = lines[i];
|
|
125
|
+
const eol = whole.endsWith('\r') ? '\r' : '';
|
|
126
|
+
const [body, comment] = splitComment(eol === '' ? whole : whole.slice(0, -1));
|
|
127
|
+
if (mode === 'flow') {
|
|
128
|
+
lines[i] = `${swapFlowLine(body)}${comment}${eol}`;
|
|
129
|
+
if (/\]\s*$/.test(body))
|
|
130
|
+
mode = null;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (mode === 'block') {
|
|
134
|
+
const item = /^(\s+-\s*)(.*)$/.exec(body);
|
|
135
|
+
if (item !== null) {
|
|
136
|
+
if (/^['"]?\d{4}/.test(item[2]))
|
|
137
|
+
lines[i] = `${item[1]}${swapElements(item[2])}${comment}${eol}`;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (/^\s*$/.test(body))
|
|
141
|
+
continue;
|
|
142
|
+
if (/^\s+\[/.test(body)) {
|
|
143
|
+
lines[i] = `${swapFlowLine(body)}${comment}${eol}`;
|
|
144
|
+
mode = /\]\s*$/.test(body) ? null : 'flow';
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
mode = null;
|
|
148
|
+
}
|
|
149
|
+
const entry = /^\s*([A-Za-z_][A-Za-z0-9_]*):(.*)$/.exec(body);
|
|
150
|
+
if (entry === null || !keys.has(entry[1]))
|
|
151
|
+
continue;
|
|
152
|
+
const key = entry[1];
|
|
153
|
+
const rest = entry[2];
|
|
154
|
+
const head = body.slice(0, body.indexOf(`${key}:`) + key.length + 1);
|
|
155
|
+
if (/^\s*$/.test(rest)) {
|
|
156
|
+
mode = 'block';
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (/^\s*\[/.test(rest)) {
|
|
160
|
+
lines[i] = `${head}${swapFlowLine(rest)}${comment}${eol}`;
|
|
161
|
+
if (!/\]\s*$/.test(rest))
|
|
162
|
+
mode = 'flow';
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (/^\s*['"]?\d{4}/.test(rest))
|
|
166
|
+
lines[i] = `${head}${swapElements(rest)}${comment}${eol}`;
|
|
167
|
+
}
|
|
168
|
+
return lines.join('\n');
|
|
169
|
+
}
|
|
170
|
+
/** Every rewrite that applies to `path`. */
|
|
171
|
+
export function rewriteAll(text, kind, from, to, oldName, newName, path) {
|
|
172
|
+
return rewriteRelationships(rewriteReferences(text, kind, from, to, oldName, newName, path), kind, from, to, path);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Frontmatter lines that still name `from` bare after the rewrite, under keys no kind owns for `path` (`related:`):
|
|
176
|
+
* a bare number there could name either kind, so a person decides, and the command says so rather than exit 0 in
|
|
177
|
+
* silence. A block list's items count under their key.
|
|
178
|
+
*/
|
|
179
|
+
export function residualBareRefs(settings, text, from, path) {
|
|
180
|
+
// The frontmatter's lines: after a first line of ---, up to the next line that starts with ---. Read line by line
|
|
181
|
+
// on purpose, not parsed: a malformed block must still be read.
|
|
182
|
+
const all = text.split('\n').map((line) => line.replace(/\r$/, ''));
|
|
183
|
+
const end = all.findIndex((line, i) => i > 0 && line.startsWith('---'));
|
|
184
|
+
if (all[0] !== '---' || end < 0)
|
|
185
|
+
return [];
|
|
186
|
+
const bare = new RegExp(`(?<![A-Za-z0-9-])${literal(from)}(?!\\d)`);
|
|
187
|
+
const classified = new Set(Object.values(settings.kinds).flatMap((kind) => [kind.frontmatterKey, ...relationshipKeysFor(kind, path)]));
|
|
188
|
+
const flagged = [];
|
|
189
|
+
let enclosing = null;
|
|
190
|
+
for (const line of all.slice(1, end)) {
|
|
191
|
+
const entry = /^\s*([A-Za-z_][A-Za-z0-9_]*):/.exec(line);
|
|
192
|
+
if (entry !== null)
|
|
193
|
+
enclosing = entry[1];
|
|
194
|
+
else if (!/^\s*-\s/.test(line) && line.trim() !== '')
|
|
195
|
+
enclosing = null;
|
|
196
|
+
if (!bare.test(line) || (enclosing !== null && classified.has(enclosing)))
|
|
197
|
+
continue;
|
|
198
|
+
flagged.push(line.trim());
|
|
199
|
+
}
|
|
200
|
+
return flagged;
|
|
201
|
+
}
|
|
202
|
+
/** The document's own frontmatter key (`adr: '0057'`) moved to `to`. */
|
|
203
|
+
export function rewriteFrontmatter(text, kind, from, to) {
|
|
204
|
+
return text.replace(new RegExp(`^(${kind.frontmatterKey}:\\s*['"]?)${literal(from)}(['"]?\\s*)$`, 'm'), `$1${to}$2`);
|
|
205
|
+
}
|
|
206
|
+
/** What a renumber would change, or why it cannot: the target must be free here and on origin/main. */
|
|
207
|
+
export function plan(sys, root, settings, kind, from, to) {
|
|
208
|
+
const local = localBasenames(sys, kind, root);
|
|
209
|
+
const sources = local.filter((name) => name.startsWith(`${from}-`));
|
|
210
|
+
if (sources.length === 0)
|
|
211
|
+
return { ok: false, error: `no ${kind.citation} numbered ${from} in ${kind.dir}/` };
|
|
212
|
+
if (sources.length > 1)
|
|
213
|
+
return { ok: false, error: `${String(sources.length)} files claim ${from} (${sources.join(', ')}) — resolve that collision first, one file at a time` };
|
|
214
|
+
const here = local.filter((name) => name.startsWith(`${to}-`));
|
|
215
|
+
if (here.length > 0)
|
|
216
|
+
return { ok: false, error: `${to} is already used locally by ${here.join(', ')}` };
|
|
217
|
+
const onMain = basenamesOnRef(sys, kind, 'origin/main', root);
|
|
218
|
+
if (onMain === null)
|
|
219
|
+
return { ok: false, error: 'could not read `origin/main` — run `git fetch origin main` first, or the new number may collide exactly as the old one did' };
|
|
220
|
+
const there = onMain.filter((name) => name.startsWith(`${to}-`));
|
|
221
|
+
if (there.length > 0)
|
|
222
|
+
return { ok: false, error: `${to} is already used on origin/main by ${there.join(', ')}` };
|
|
223
|
+
const oldName = sources[0];
|
|
224
|
+
const newName = `${to}-${oldName.slice(from.length + 1)}`;
|
|
225
|
+
const oldPath = `${kind.dir}/${oldName}`;
|
|
226
|
+
const newPath = `${kind.dir}/${newName}`;
|
|
227
|
+
const tracked = gitOut(sys, root, ['ls-files', '--error-unmatch', '--', oldPath]) !== null;
|
|
228
|
+
const candidates = new Set([...filesContaining(sys, root, citationOf(kind, from)), ...filesContaining(sys, root, oldPath)]);
|
|
229
|
+
for (const dir of Object.keys(kind.relationships))
|
|
230
|
+
for (const path of filesContaining(sys, root, from, dir))
|
|
231
|
+
candidates.add(path);
|
|
232
|
+
candidates.delete(oldPath);
|
|
233
|
+
// A file kept only if the rewrite changes it: `git grep -F ADR-0057` also finds ADR-00571.
|
|
234
|
+
const referencing = [];
|
|
235
|
+
const residual = [];
|
|
236
|
+
const docDirs = Object.keys(kind.relationships);
|
|
237
|
+
for (const path of [...candidates].sort()) {
|
|
238
|
+
if (isHistory(settings, path))
|
|
239
|
+
continue;
|
|
240
|
+
const before = sys.read(`${root}/${path}`);
|
|
241
|
+
const after = rewriteAll(before, kind, from, to, oldName, newName, path);
|
|
242
|
+
if (after !== before)
|
|
243
|
+
referencing.push(path);
|
|
244
|
+
if (docDirs.some((dir) => path.startsWith(`${dir}/`)))
|
|
245
|
+
for (const line of residualBareRefs(settings, after, from, path))
|
|
246
|
+
residual.push({ path, line });
|
|
247
|
+
}
|
|
248
|
+
return { ok: true, plan: { from, to, oldPath, newPath, oldName, newName, tracked, referencing, residual } };
|
|
249
|
+
}
|
|
250
|
+
/** Writes the plan: the move, then every rewrite; returns the files written. */
|
|
251
|
+
export function applyPlan(sys, root, kind, p) {
|
|
252
|
+
if (p.tracked) {
|
|
253
|
+
const moved = sys.exec('git', ['mv', p.oldPath, p.newPath], { cwd: root });
|
|
254
|
+
if (moved.code !== 0)
|
|
255
|
+
throw new Error(`git mv ${p.oldPath} ${p.newPath}: ${moved.stderr.trim()}`);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
sys.confine(root, `${root}/${p.newPath}`);
|
|
259
|
+
sys.write(`${root}/${p.newPath}`, sys.read(`${root}/${p.oldPath}`));
|
|
260
|
+
sys.remove(`${root}/${p.oldPath}`);
|
|
261
|
+
}
|
|
262
|
+
const movedAt = `${root}/${p.newPath}`;
|
|
263
|
+
sys.confine(root, movedAt);
|
|
264
|
+
sys.write(movedAt, rewriteAll(rewriteFrontmatter(sys.read(movedAt), kind, p.from, p.to), kind, p.from, p.to, p.oldName, p.newName, p.newPath));
|
|
265
|
+
const changed = [p.newPath];
|
|
266
|
+
for (const path of p.referencing) {
|
|
267
|
+
const at = `${root}/${path}`;
|
|
268
|
+
const before = sys.read(at);
|
|
269
|
+
const after = rewriteAll(before, kind, p.from, p.to, p.oldName, p.newName, path);
|
|
270
|
+
if (after === before)
|
|
271
|
+
continue;
|
|
272
|
+
sys.confine(root, at);
|
|
273
|
+
sys.write(at, after);
|
|
274
|
+
changed.push(path);
|
|
275
|
+
}
|
|
276
|
+
return changed;
|
|
277
|
+
}
|
|
278
|
+
/** renumber-doc's arguments: a kind, two four-digit numbers, and --apply. */
|
|
279
|
+
export function renumberArgs(args) {
|
|
280
|
+
const rest = args.filter((arg) => arg !== '--apply');
|
|
281
|
+
const odd = rest.find((arg) => arg.startsWith('-'));
|
|
282
|
+
if (odd !== undefined)
|
|
283
|
+
throw new Error(`renumber-doc: unknown option "${odd}"`);
|
|
284
|
+
const [kind, from, to, extra] = rest;
|
|
285
|
+
if (kind === undefined || from === undefined || to === undefined || extra !== undefined || !FOUR_DIGITS.test(from) || !FOUR_DIGITS.test(to))
|
|
286
|
+
throw new Error('renumber-doc needs a document kind and two four-digit numbers: renumber-doc <kind> <from> <to> [--apply]');
|
|
287
|
+
if (from === to)
|
|
288
|
+
throw new Error(`renumber-doc: ${from} and ${to} are the same number`);
|
|
289
|
+
return { kind, from, to, apply: args.includes('--apply') };
|
|
290
|
+
}
|
|
291
|
+
/** `niyam renumber-doc <kind> <from> <to> [--apply]`: shows the plan, and with --apply writes it. */
|
|
292
|
+
export function renumberDoc(sys, io, args) {
|
|
293
|
+
const parsed = renumberArgs(args);
|
|
294
|
+
const { root } = repoAt(sys);
|
|
295
|
+
const settings = loadDocSettings(sys, root);
|
|
296
|
+
const kind = kindNamed(settings, parsed.kind);
|
|
297
|
+
if (kind === undefined) {
|
|
298
|
+
io.err(`niyam renumber-doc: no document kind "${parsed.kind}"; ${SETTINGS_PATH} names ${Object.keys(settings.kinds).join(', ')}`);
|
|
299
|
+
return 2;
|
|
300
|
+
}
|
|
301
|
+
const result = plan(sys, root, settings, kind, parsed.from, parsed.to);
|
|
302
|
+
if (!result.ok) {
|
|
303
|
+
io.err(`❌ ${result.error}`);
|
|
304
|
+
return 1;
|
|
305
|
+
}
|
|
306
|
+
const p = result.plan;
|
|
307
|
+
io.out(`${p.oldPath}\n → ${p.newPath}\n`);
|
|
308
|
+
if (p.referencing.length === 0)
|
|
309
|
+
io.out('No other tracked file references it.');
|
|
310
|
+
else
|
|
311
|
+
io.out([`${String(p.referencing.length)} referencing file(s):`, ...p.referencing.map((path) => ` - ${path}`)].join('\n'));
|
|
312
|
+
if (p.residual.length > 0)
|
|
313
|
+
io.out([`\n⚠️ ${String(p.residual.length)} bare reference(s) to ${p.from} under keys this tool does not rewrite (ambiguous namespace) — review by hand:`, ...p.residual.map(({ path, line }) => ` - ${path}: ${line}`)].join('\n'));
|
|
314
|
+
if (!parsed.apply) {
|
|
315
|
+
io.out('\nDry run — nothing changed. Review the list above (some prose narrates history rather than citing a live decision), then re-run with --apply.');
|
|
316
|
+
return 0;
|
|
317
|
+
}
|
|
318
|
+
const changed = applyPlan(sys, root, kind, p);
|
|
319
|
+
io.out(`\n✅ Renumbered ${p.from} → ${p.to}; ${String(changed.length)} file(s) written.\n Review with \`git diff\` and \`git status\`, then commit.`);
|
|
320
|
+
return 0;
|
|
321
|
+
}
|
package/dist/run.js
CHANGED
|
@@ -12,6 +12,9 @@ import { prIdentity } from './identity.js';
|
|
|
12
12
|
import { machine, machineArgs } from './machine.js';
|
|
13
13
|
import { brief, briefArgs, handoff, handoffArgs } from './handoff.js';
|
|
14
14
|
import { cubicDismiss, dismissArgs } from './cubic-dismiss.js';
|
|
15
|
+
import { docNumber, docNumberArgs } from './doc-numbers.js';
|
|
16
|
+
import { renumberArgs, renumberDoc } from './renumber-doc.js';
|
|
17
|
+
import { workItemArgs, workItemNumber } from './work-item-number.js';
|
|
15
18
|
import { keepGoing } from './keep-going.js';
|
|
16
19
|
import { prAutocreate } from './pr-autocreate.js';
|
|
17
20
|
import { prSignals, signalArgs } from './pr-signals.js';
|
|
@@ -87,6 +90,16 @@ Commands:
|
|
|
87
90
|
Claude Code's Stop hook: sends a session back while its branch has commits the base
|
|
88
91
|
lacks and its pull request has not merged, saying what is left ("1 of 5"); --stop
|
|
89
92
|
records why started work stops at this commit. The hook always exits 0
|
|
93
|
+
doc-number <kind> [--reserve] [--json] [--offline]
|
|
94
|
+
The next free number of a numbered document kind (adr), against main, this tree, every
|
|
95
|
+
ref, open pull requests and Work item titles; --reserve claims it for good, and refuses
|
|
96
|
+
when GitHub could not be read. The kinds are .github/niyam.json's "docNumbers"
|
|
97
|
+
renumber-doc <kind> <from> <to> [--apply]
|
|
98
|
+
Move a numbered document to a free number with every citation, path and relationship
|
|
99
|
+
that names it; a dry run unless --apply
|
|
100
|
+
work-item-number [--issue <N>] [--apply]
|
|
101
|
+
Run by a client's workflow on issue events: a Work item whose number something else
|
|
102
|
+
holds is renumbered, with a comment; --apply writes
|
|
90
103
|
help Show this text
|
|
91
104
|
version Print the installed version
|
|
92
105
|
|
|
@@ -128,17 +141,17 @@ export function proposeArgs(args) {
|
|
|
128
141
|
/** Runs one command and returns its exit code: 0 done, 1 failed, 2 bad usage. */
|
|
129
142
|
export async function run(args, io, sys) {
|
|
130
143
|
const [command, ...rest] = args;
|
|
131
|
-
const allowed = command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
|
|
144
|
+
const allowed = command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'pr-autocreate' || command === 'keep-going' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number' ? Infinity : command === 'pre-push' || command === 'pr-signals' ? 2 : command === 'doctor' ? 1 : 0;
|
|
132
145
|
const extra = rest[allowed];
|
|
133
146
|
if (extra !== undefined) {
|
|
134
147
|
io.err(`niyam: unexpected argument "${extra}"`);
|
|
135
148
|
io.err(USAGE);
|
|
136
149
|
return 2;
|
|
137
150
|
}
|
|
138
|
-
if (command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss') {
|
|
151
|
+
if (command === 'onboard' || command === 'machine' || command === 'review-thread' || command === 'as-agent' || command === 'env' || command === 'propose' || command === 'owner-step' || command === 'pr-signals' || command === 'handoff' || command === 'brief' || command === 'cubic-dismiss' || command === 'doc-number' || command === 'renumber-doc' || command === 'work-item-number') {
|
|
139
152
|
// Their options are checked here, so a bad one is bad usage (exit 2).
|
|
140
153
|
try {
|
|
141
|
-
(command === 'onboard' ? onboardArgs : command === 'machine' ? machineArgs : command === 'as-agent' ? asAgentArgs : command === 'env' ? envArgs : command === 'propose' ? proposeArgs : command === 'owner-step' ? ownerStepArgs : command === 'pr-signals' ? signalArgs : command === 'handoff' ? handoffArgs : command === 'brief' ? briefArgs : command === 'cubic-dismiss' ? dismissArgs : threadArgs)(rest);
|
|
154
|
+
(command === 'doc-number' ? docNumberArgs : command === 'renumber-doc' ? renumberArgs : command === 'work-item-number' ? workItemArgs : command === 'onboard' ? onboardArgs : command === 'machine' ? machineArgs : command === 'as-agent' ? asAgentArgs : command === 'env' ? envArgs : command === 'propose' ? proposeArgs : command === 'owner-step' ? ownerStepArgs : command === 'pr-signals' ? signalArgs : command === 'handoff' ? handoffArgs : command === 'brief' ? briefArgs : command === 'cubic-dismiss' ? dismissArgs : threadArgs)(rest);
|
|
142
155
|
}
|
|
143
156
|
catch (error) {
|
|
144
157
|
io.err(`niyam: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -233,7 +246,16 @@ export async function run(args, io, sys) {
|
|
|
233
246
|
case 'cubic-dismiss':
|
|
234
247
|
case 'upgrade':
|
|
235
248
|
case 'owner-step':
|
|
249
|
+
case 'doc-number':
|
|
250
|
+
case 'renumber-doc':
|
|
251
|
+
case 'work-item-number':
|
|
236
252
|
try {
|
|
253
|
+
if (command === 'doc-number')
|
|
254
|
+
return docNumber(await sys(), io, rest);
|
|
255
|
+
if (command === 'renumber-doc')
|
|
256
|
+
return renumberDoc(await sys(), io, rest);
|
|
257
|
+
if (command === 'work-item-number')
|
|
258
|
+
return workItemNumber(await sys(), io, rest);
|
|
237
259
|
if (command === 'upgrade')
|
|
238
260
|
return await upgrade(await sys(), io);
|
|
239
261
|
if (command === 'pr-signals')
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { SETTINGS_PATH, repoAt } from './agent.js';
|
|
2
|
+
import { allocate, basenamesOnRef, detail, frozenEntries, ghIn, listWorkItems, loadDocSettings, numberFromFilename, numberFromName, numberFromWorkItemTitle, prClaimedNumbers, schema, wholeNumber, } from './doc-numbers.js';
|
|
3
|
+
const describe = (item) => `#${String(item.number)} (${item.title})`;
|
|
4
|
+
/** What outside the Work items holds `number` against `item`, or null. */
|
|
5
|
+
function externalHolder(settings, kind, item, number, s) {
|
|
6
|
+
const doc = s.mainNames.find((name) => numberFromFilename(name) === number);
|
|
7
|
+
if (doc !== undefined)
|
|
8
|
+
return `\`${kind.dir}/${doc}\` on main`;
|
|
9
|
+
if (s.prNumbers.has(number))
|
|
10
|
+
return `an open pull request's new ${kind.citation}-${number}`;
|
|
11
|
+
if (item.number <= (settings.workItems?.lastMovedIssue ?? 0))
|
|
12
|
+
return null;
|
|
13
|
+
const frozen = frozenEntries(settings, kind.kind).find((path) => numberFromName(path) === number);
|
|
14
|
+
return frozen === undefined ? null : `the frozen work folder \`${frozen}\``;
|
|
15
|
+
}
|
|
16
|
+
/** Which Work items must move, each with what holds its number. */
|
|
17
|
+
export function planMoves(settings, kind, sources, event) {
|
|
18
|
+
const moving = new Map();
|
|
19
|
+
const items = [...sources.items].sort((a, b) => a.number - b.number);
|
|
20
|
+
if (event !== null) {
|
|
21
|
+
const other = items.find((i) => i.workNumber === event.work && i.number !== event.item.number);
|
|
22
|
+
const holder = other === undefined ? externalHolder(settings, kind, event.item, event.work, sources) : describe(other);
|
|
23
|
+
if (holder !== null)
|
|
24
|
+
moving.set(event.item.number, { item: event.item, work: event.work, holder });
|
|
25
|
+
}
|
|
26
|
+
const keeper = new Map();
|
|
27
|
+
for (const item of items) {
|
|
28
|
+
const work = item.workNumber;
|
|
29
|
+
if (work === null || moving.has(item.number))
|
|
30
|
+
continue;
|
|
31
|
+
const first = keeper.get(work);
|
|
32
|
+
if (first === undefined)
|
|
33
|
+
keeper.set(work, item);
|
|
34
|
+
else
|
|
35
|
+
moving.set(item.number, { item, work, holder: describe(first) });
|
|
36
|
+
}
|
|
37
|
+
for (const [work, item] of keeper) {
|
|
38
|
+
const holder = externalHolder(settings, kind, item, work, sources);
|
|
39
|
+
if (holder !== null)
|
|
40
|
+
moving.set(item.number, { item, work, holder });
|
|
41
|
+
}
|
|
42
|
+
return moving;
|
|
43
|
+
}
|
|
44
|
+
/** The hidden line that tells a rerun this renumber is already explained. */
|
|
45
|
+
export function renumberMarker(from, to) {
|
|
46
|
+
return `<!-- work-item-number: renumbered from ${from} to ${to} -->`;
|
|
47
|
+
}
|
|
48
|
+
/** The comment a renumbered issue carries. */
|
|
49
|
+
export function renumberComment(work, from, to, holder) {
|
|
50
|
+
const reserve = work.reserveCommand ?? `niyam doc-number ${work.kind} --reserve`;
|
|
51
|
+
return [
|
|
52
|
+
`Renumbered from ${from} to ${to}: ${from} is already held by ${holder}. Numbers are identity and never reused.`,
|
|
53
|
+
'',
|
|
54
|
+
`A Work item takes its number from \`${reserve}\` before \`gh issue create\`. This one was filed without it, so the \`work-item-number\` check took the next free number from the same allocator.`,
|
|
55
|
+
renumberMarker(from, to),
|
|
56
|
+
].join('\n');
|
|
57
|
+
}
|
|
58
|
+
/** One issue as `gh api …/issues/N --jq '{number, title, type: .type.name}'` gives it; `type` is null untyped. */
|
|
59
|
+
const IssueSchema = schema((value) => {
|
|
60
|
+
const { title, type } = (typeof value === 'object' && value !== null ? value : {});
|
|
61
|
+
if (typeof title !== 'string' || (type !== null && typeof type !== 'string'))
|
|
62
|
+
throw new Error('unexpected shape');
|
|
63
|
+
return { title, type };
|
|
64
|
+
});
|
|
65
|
+
/** The event's issue as a Work item, or why it needs nothing; throws when it cannot be read. */
|
|
66
|
+
function readEvent(work, gh, issue, previousTitle) {
|
|
67
|
+
const at = `#${String(issue)}`;
|
|
68
|
+
const raw = gh(['api', `repos/{owner}/{repo}/issues/${String(issue)}`, '--jq', '{number, title, type: .type.name}']);
|
|
69
|
+
let read;
|
|
70
|
+
try {
|
|
71
|
+
read = IssueSchema.parse(JSON.parse(raw));
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
throw new Error(error instanceof SyntaxError ? `${at} came back as text that is not JSON` : `${at} came back in an unexpected shape`);
|
|
75
|
+
}
|
|
76
|
+
const { title, type } = read;
|
|
77
|
+
if (type !== work.issueType)
|
|
78
|
+
return `${at} is not a ${work.issueType}`;
|
|
79
|
+
const workNumber = numberFromWorkItemTitle(title);
|
|
80
|
+
if (workNumber === null)
|
|
81
|
+
return `${at}'s title carries no number`;
|
|
82
|
+
// A retitle that keeps the number took nothing new, so an earlier holder must not yield to it.
|
|
83
|
+
if (previousTitle !== undefined && numberFromWorkItemTitle(previousTitle) === workNumber)
|
|
84
|
+
return `${at} kept its number ${workNumber}`;
|
|
85
|
+
return { item: { number: issue, title, workNumber }, work: workNumber };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Comment, then retitle: a run that stops between them leaves the clash, so a rerun renumbers again and, finding the
|
|
89
|
+
* marker, does not comment twice. A title changed since the run listed it stops the renumber: that edit's own run
|
|
90
|
+
* checks it again.
|
|
91
|
+
*/
|
|
92
|
+
function applyRenumber(work, gh, move, was) {
|
|
93
|
+
const issue = String(move.issue);
|
|
94
|
+
const unchanged = () => {
|
|
95
|
+
const now = gh(['api', `repos/{owner}/{repo}/issues/${issue}`, '--jq', '.title']).trimEnd();
|
|
96
|
+
if (now !== was)
|
|
97
|
+
throw new Error(`its title changed during the run, to "${now}"; that edit's own run checks it again`);
|
|
98
|
+
};
|
|
99
|
+
unchanged();
|
|
100
|
+
const comments = gh(['api', '--paginate', `repos/{owner}/{repo}/issues/${issue}/comments`, '--jq', '.[].body']);
|
|
101
|
+
if (!comments.includes(renumberMarker(move.from, move.to)))
|
|
102
|
+
gh(['issue', 'comment', issue, '--body', renumberComment(work, move.from, move.to, move.holder)]);
|
|
103
|
+
unchanged();
|
|
104
|
+
gh(['issue', 'edit', issue, '--title', move.title]);
|
|
105
|
+
}
|
|
106
|
+
/** Checks the event's issue and every Work item; with `apply`, renumbers each clash. An incomplete source is an error. */
|
|
107
|
+
export function checkWorkItemNumbers(sys, root, settings, gh, options = {}) {
|
|
108
|
+
const work = settings.workItems;
|
|
109
|
+
const kind = settings.kinds[work.kind];
|
|
110
|
+
const ref = options.ref ?? 'origin/main';
|
|
111
|
+
let event = null;
|
|
112
|
+
let note = null;
|
|
113
|
+
if (options.issue !== undefined) {
|
|
114
|
+
let read;
|
|
115
|
+
try {
|
|
116
|
+
read = readEvent(work, gh, options.issue, options.previousTitle);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
// fail-open: the failure is the return value, and the command exits 1 on it.
|
|
120
|
+
return { ok: false, error: `could not read #${String(options.issue)}: ${detail(error)}` };
|
|
121
|
+
}
|
|
122
|
+
if (typeof read === 'string')
|
|
123
|
+
note = read;
|
|
124
|
+
else
|
|
125
|
+
event = read;
|
|
126
|
+
}
|
|
127
|
+
const mainNames = basenamesOnRef(sys, kind, ref, root);
|
|
128
|
+
if (mainNames === null)
|
|
129
|
+
return { ok: false, error: `could not read \`${ref}\` — fetch it first` };
|
|
130
|
+
const listed = listWorkItems(work, gh);
|
|
131
|
+
const claims = prClaimedNumbers(kind, mainNames, gh);
|
|
132
|
+
const warnings = [...listed.warnings, ...claims.warnings];
|
|
133
|
+
if (warnings.length > 0)
|
|
134
|
+
return { ok: false, error: `sources incomplete: ${warnings.join('; ')}` };
|
|
135
|
+
const moving = planMoves(settings, kind, { items: listed.items, mainNames, prNumbers: claims.numbers }, event);
|
|
136
|
+
if (moving.size === 0)
|
|
137
|
+
return { ok: true, note, renumbers: [], applied: options.apply ?? false };
|
|
138
|
+
// A preview, not a reservation: a runner's reservation refs die with it. A number picked blind could clash again,
|
|
139
|
+
// so a warning is an error here. Every number above the allocator's answer is free, so the moves count up.
|
|
140
|
+
const next = options.allocate ? options.allocate() : allocate(sys, root, settings, kind, { ref, gh });
|
|
141
|
+
if (!next.ok)
|
|
142
|
+
return next;
|
|
143
|
+
if (next.warnings.length > 0)
|
|
144
|
+
return { ok: false, error: `allocator incomplete: ${next.warnings.join('; ')}` };
|
|
145
|
+
const first = /^\d{4}$/.test(next.next) ? wholeNumber(next.next) : Number.NaN;
|
|
146
|
+
if (!/^\d{4}$/.test(next.next) || first < 1 || first + moving.size > 10_000)
|
|
147
|
+
return { ok: false, error: `no room for ${String(moving.size)} number(s) from ${next.next}` };
|
|
148
|
+
const planned = [...moving.values()].map(({ item, work: from, holder }, index) => {
|
|
149
|
+
const to = String(first + index).padStart(4, '0');
|
|
150
|
+
return { move: { issue: item.number, from, to, holder, title: item.title.trimStart().replace(/^\d{4}/, to) }, was: item.title };
|
|
151
|
+
});
|
|
152
|
+
const renumbers = planned.map(({ move }) => move);
|
|
153
|
+
if (!options.apply)
|
|
154
|
+
return { ok: true, note, renumbers, applied: false };
|
|
155
|
+
for (const { move, was } of planned) {
|
|
156
|
+
try {
|
|
157
|
+
applyRenumber(work, gh, move, was);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
// fail-open: the failure is the return value, and the command exits 1 on it.
|
|
161
|
+
return { ok: false, error: `could not renumber #${String(move.issue)}: ${detail(error)}` };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { ok: true, note, renumbers, applied: true };
|
|
165
|
+
}
|
|
166
|
+
/** Every Work item still without `label`, read before any write; a run that cannot read it changes nothing. */
|
|
167
|
+
export function unlabelledWorkItems(work, gh) {
|
|
168
|
+
const issues = [];
|
|
169
|
+
try {
|
|
170
|
+
const out = gh(['api', '--paginate', `repos/{owner}/{repo}/issues?state=all&type=${encodeURIComponent(work.issueType)}&per_page=100`, '--jq', `.[] | select(.type.name == ${JSON.stringify(work.issueType)}) | select(any(.labels[]; .name == ${JSON.stringify(work.label)}) | not) | .number`]);
|
|
171
|
+
for (const line of out.split('\n')) {
|
|
172
|
+
if (line === '')
|
|
173
|
+
continue;
|
|
174
|
+
if (!/^[1-9]\d{0,8}$/.test(line))
|
|
175
|
+
throw new Error(`unexpected issue number "${line}"`);
|
|
176
|
+
issues.push(wholeNumber(line));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
// fail-open: the failure is the return value, and the command exits 1 on it.
|
|
181
|
+
return { ok: false, error: `could not list unlabelled Work items: ${detail(error)}` };
|
|
182
|
+
}
|
|
183
|
+
return { ok: true, issues };
|
|
184
|
+
}
|
|
185
|
+
/** work-item-number's arguments: `--issue N` and `--apply`. */
|
|
186
|
+
export function workItemArgs(args) {
|
|
187
|
+
let issue;
|
|
188
|
+
let apply = false;
|
|
189
|
+
for (let i = 0; i < args.length; i++) {
|
|
190
|
+
const arg = args[i];
|
|
191
|
+
if (arg === '--apply')
|
|
192
|
+
apply = true;
|
|
193
|
+
else if (arg === '--issue' || arg.startsWith('--issue=')) {
|
|
194
|
+
const value = arg === '--issue' ? args[++i] : arg.slice('--issue='.length);
|
|
195
|
+
if (value === undefined || !/^[1-9]\d{0,7}$/.test(value))
|
|
196
|
+
throw new Error('work-item-number --issue needs an issue number');
|
|
197
|
+
if (issue !== undefined)
|
|
198
|
+
throw new Error('work-item-number takes one --issue');
|
|
199
|
+
issue = wholeNumber(value);
|
|
200
|
+
}
|
|
201
|
+
else
|
|
202
|
+
throw new Error(`work-item-number: unexpected argument "${arg}"`);
|
|
203
|
+
}
|
|
204
|
+
return { ...(issue === undefined ? {} : { issue }), apply };
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* `niyam work-item-number [--issue N] [--apply]`: a preview, or with --apply the renumbers and labels. A retitle's
|
|
208
|
+
* old title comes in WORK_ITEM_PREVIOUS_TITLE, never an argument: anyone filing an issue chooses it.
|
|
209
|
+
*/
|
|
210
|
+
export function workItemNumber(sys, io, args) {
|
|
211
|
+
const parsed = workItemArgs(args);
|
|
212
|
+
const { root } = repoAt(sys);
|
|
213
|
+
const settings = loadDocSettings(sys, root);
|
|
214
|
+
const work = settings.workItems;
|
|
215
|
+
if (work === undefined) {
|
|
216
|
+
io.err(`niyam work-item-number: ${SETTINGS_PATH}'s "docNumbers" names no "workItems"`);
|
|
217
|
+
return 2;
|
|
218
|
+
}
|
|
219
|
+
const gh = ghIn(sys, root);
|
|
220
|
+
const label = work.label;
|
|
221
|
+
const unlabelled = label === undefined ? { ok: true, issues: [] } : unlabelledWorkItems({ ...work, label }, gh);
|
|
222
|
+
if (!unlabelled.ok) {
|
|
223
|
+
io.err(`❌ ${unlabelled.error}`);
|
|
224
|
+
return 1;
|
|
225
|
+
}
|
|
226
|
+
const previous = sys.env.WORK_ITEM_PREVIOUS_TITLE;
|
|
227
|
+
const result = checkWorkItemNumbers(sys, root, settings, gh, { apply: parsed.apply, ...(parsed.issue === undefined ? {} : { issue: parsed.issue }), ...(previous === undefined ? {} : { previousTitle: previous }) });
|
|
228
|
+
let code = 0;
|
|
229
|
+
if (result.ok) {
|
|
230
|
+
if (result.note !== null)
|
|
231
|
+
io.out(`✓ ${result.note}`);
|
|
232
|
+
if (result.renumbers.length === 0)
|
|
233
|
+
io.out('✓ no Work item shares a number');
|
|
234
|
+
const verb = result.applied ? '✓ renumbered' : '→ would renumber';
|
|
235
|
+
for (const move of result.renumbers)
|
|
236
|
+
io.out(`${verb} #${String(move.issue)} from ${move.from} to ${move.to} (${move.from} is held by ${move.holder})`);
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
io.err(`❌ ${result.error}`);
|
|
240
|
+
code = 1;
|
|
241
|
+
}
|
|
242
|
+
if (label === undefined)
|
|
243
|
+
return code;
|
|
244
|
+
// Labelled whatever the number check found: the board needs every Work item.
|
|
245
|
+
if (parsed.apply) {
|
|
246
|
+
for (const issue of unlabelled.issues) {
|
|
247
|
+
try {
|
|
248
|
+
gh(['issue', 'edit', String(issue), '--add-label', label]);
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
// fail-open: reported, and the command exits 1.
|
|
252
|
+
io.err(`❌ could not label #${String(issue)}: ${detail(error)}`);
|
|
253
|
+
return 1;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (unlabelled.issues.length === 0)
|
|
258
|
+
io.out(`✓ every Work item carries ${label}`);
|
|
259
|
+
for (const issue of unlabelled.issues)
|
|
260
|
+
io.out(`${parsed.apply ? '✓ labelled' : '→ would label'} #${String(issue)} ${label}`);
|
|
261
|
+
return code;
|
|
262
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@veda-hq/niyam",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.22",
|
|
4
4
|
"description": "Work rules for repos that track work in GitHub Issues: setup, agent identity, push and PR checks.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@types/node": "24.19.2",
|
|
29
29
|
"@veda-hq/dvara": "0.5.16",
|
|
30
30
|
"@veda-hq/pariksha": "0.5.20",
|
|
31
|
-
"@veda-hq/sarathi": "0.6.
|
|
31
|
+
"@veda-hq/sarathi": "0.6.12",
|
|
32
32
|
"typescript": "7.0.2"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|