@ref0/workspace 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,6 +73,39 @@ entry point's source:
73
73
  its source under the condition first. `--packages` is `packages/*` and `--condition`
74
74
  `@ref0/source` unless given. The `package-exports` skill reviews the rest: what each runtime
75
75
  resolves, side effects and each entry point's bundle.
76
+ - `commit-message <message-file>` and `commit-message --title <title>`: a commit's subject, as
77
+ the `commit-msg` hook passes it, or a pull request's title, as CI does, is
78
+ `type(scope): subject`, or `type: subject` for a change across the repo. It accepts a `!` before
79
+ the colon and ignores it, since no repo tracks breaking changes. The types are `feat`, `fix`,
80
+ `perf`, `refactor`, `test`, `docs`, `build`, `ci`, `chore` and `revert`, in every repo. The
81
+ scopes are the repo's own, in its root `package.json` as
82
+ `"ref0-workspace": { "commitScopes": ["git", "cli"] }`, or `[]` for none. A commit may also carry
83
+ git's own merge, autosquash and revert subjects, and a title may not.
84
+ - `changelog --repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>`:
85
+ a release's section, `## <version> (<date>)` or `## Unreleased`, from the subjects of main's own
86
+ commits in `<range>`, its first parents, that touch a `--path`, each with its pull request linked
87
+ in `--repo`. git-cliff writes them. A release's range runs from the tag before it to its own, as
88
+ `v0.4.0..HEAD` for 0.5.0, so a changelog holds one section for each tag. The section it prints
89
+ lists features, fixes and performance, each by scope, then one line that counts the other changes
90
+ and links the changelog. The section `--prepend` writes first in that file, over one for the same
91
+ version, lists every type, then the subjects in no format. Each entry's first word is lower case
92
+ unless it's a name, as `properNouns` in `changelog.ts` lists them, or has a capital, a digit or a
93
+ mark inside it, as `GitHub`, `CLI` or `` `Schema` `` do. A range with no such commit says "Nothing
94
+ published changed." The section it prints holds at most `--most-bytes`, 50,000 unless given, for
95
+ a release's pull request to carry: a longer one leaves out its oldest listed changes and ends with
96
+ a line linking the changelog, and the section `--prepend` writes is always whole.
97
+ - `pre-push <remote> <url>`: Git's pre-push hook, which a repo runs from `.vite-hooks/pre-push`
98
+ with the ref lines Git writes on stdin. It refuses a push that deletes `main`, a `deploy/*` or a
99
+ `release/*` branch, or moves one to a commit that doesn't descend from where it is, and names each
100
+ ref. Creating one passes, and so does every other branch. Only `REF0_REWRITE=<repo>`, where
101
+ `<repo>` is the remote's repo name, the last part of its URL without `.git`, lets a refused push
102
+ through, so a rewrite meant for one repo opens no other.
103
+
104
+ `pre-push` stops accidents and isn't a boundary: `git push --no-verify` skips it, as it does every
105
+ hook, and so do `VP_GIT_HOOKS=0` and `HUSKY=0`, which turn off every Vite+ hook, and a checkout
106
+ that never installed the repo's hooks. A job that force-pushes a
107
+ `release/*` branch, as a release workflow's `release/next` does, doesn't install the hooks or sets
108
+ `VP_GIT_HOOKS=0`, and a repo's adoption checks each of its workflows for one.
76
109
 
77
110
  `types` and `type-coverage` run the repo's own `@effect/tsgo`, `tsrs` and `typescript`, its
78
111
  optional peers, resolved from its root, at the versions its catalog pins.
package/dist/bin.mjs CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
+ import { changelog } from "./changelog.mjs";
3
+ import { commitMessage } from "./commit-message.mjs";
2
4
  import { docsBudget } from "./docs-budget.mjs";
3
5
  import { defaultCondition, packageExports } from "./package-exports.mjs";
6
+ import { prePush } from "./pre-push.mjs";
4
7
  import { symbolsCheck } from "./symbols/check.mjs";
5
8
  import { symbolsFind } from "./symbols/find.mjs";
6
9
  import { typeCoverage } from "./type-coverage.mjs";
7
10
  import { types } from "./types/types.mjs";
8
11
  import { execFileSync } from "node:child_process";
9
- import { argv, cwd, exit } from "node:process";
12
+ import { readFileSync } from "node:fs";
13
+ import { argv, cwd, env, exit } from "node:process";
10
14
  import { parseArgs } from "node:util";
11
15
  // src/bin.ts
12
16
  /**
@@ -21,6 +25,13 @@ import { parseArgs } from "node:util";
21
25
  * ref0-workspace type-coverage every TypeScript file in a project, and linted
22
26
  * ref0-workspace package-exports [--packages <glob>]... [--condition <name>]
23
27
  * each package's exports name files it has
28
+ * ref0-workspace commit-message <message-file> a commit's subject is in the format
29
+ * ref0-workspace commit-message --title <title> a pull request's title is in the format
30
+ * ref0-workspace changelog --repo <owner/name> [--path <pathspec>]... [--version <version>
31
+ * [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>
32
+ * a release's notes, from main's subjects
33
+ * ref0-workspace pre-push <remote> <url> Git's pre-push hook: no force-push or delete
34
+ * of main, deploy/* or release/*
24
35
  */
25
36
  /** The root of the Git checkout the command runs in, or where it runs outside one. */
26
37
  const root = () => {
@@ -99,6 +110,24 @@ const checks = /* @__PURE__ */ new Map([
99
110
  if (parsed === void 0) return usageError();
100
111
  return packageExports(root(), parsed);
101
112
  }
113
+ }],
114
+ ["commit-message", {
115
+ args: "<message-file> | --title <title>",
116
+ about: "a commit's subject, or a pull request's title, is type(scope): subject",
117
+ run: (args) => commitMessage(args, root())
118
+ }],
119
+ ["changelog", {
120
+ args: "--repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>",
121
+ about: "a release's notes, from the subjects of main's commits in the range, by type",
122
+ run: (args) => changelog(args, root())
123
+ }],
124
+ ["pre-push", {
125
+ args: "<remote> <url>",
126
+ about: "Git's pre-push hook: refuses a force-push or delete of main, deploy/* or release/*",
127
+ run: ([remote, url, ...extra]) => {
128
+ if (remote === void 0 || url === void 0 || extra.length > 0) return usageError();
129
+ return prePush(cwd(), url, readFileSync(0, "utf8"), env.REF0_REWRITE);
130
+ }
102
131
  }]
103
132
  ]);
104
133
  function usage() {
@@ -0,0 +1,431 @@
1
+ import { commitTypes } from "./commit-message.mjs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { execPath, stdout } from "node:process";
5
+ import { parseArgs } from "node:util";
6
+ import { Buffer } from "node:buffer";
7
+ import { tmpdir } from "node:os";
8
+ import { join, relative, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { Option, Schema } from "effect";
11
+ // src/changelog.ts
12
+ /**
13
+ * A release's notes, from the subjects of the commits on main since the last release, grouped by
14
+ * their type, as `commit-message.ts` reads them, and within it by scope:
15
+ *
16
+ * ref0-workspace changelog --repo <owner/name> [--path <pathspec>]...
17
+ * [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>]
18
+ * [--most-bytes <n>] <range>
19
+ *
20
+ * A release's range runs from the tag before it to its own, such as `v0.4.0..HEAD` for 0.5.0, so a
21
+ * changelog holds one section for each tag, each written by its own run.
22
+ *
23
+ * It prints the release's section, `## <version> (<date>)`, or `## Unreleased` with no version:
24
+ * its features, fixes and performance changes, `listedTypes`, then a line that counts the rest and
25
+ * links the changelog. With `--prepend` it writes the section first in that file, under
26
+ * `# Changelog`, over a section for the same version already there, and that one lists every type.
27
+ *
28
+ * The section it prints holds at most `--most-bytes`, `notesBytesMost` by default, since a release's
29
+ * pull request and its GitHub release carry it. One that's longer leaves out its oldest listed
30
+ * changes, says how many in a line linking the changelog, which holds every one, and says so on
31
+ * stderr: a bound too small for even its heading and those lines prints those alone. The section
32
+ * `--prepend` writes is always whole.
33
+ *
34
+ * The commits are main's own, its first parents in `<range>`, as `git log --first-parent` lists
35
+ * them, that touch a `--path` when it names one: a merged pull request is one line, under its title,
36
+ * and the commits on its branch are none. git-cliff reads them and writes the notes, from a config
37
+ * this module makes from `commitTypes`. Its own `--include-path` isn't used: it reads every commit
38
+ * in the range, merged branches' too, and on a merge it misses what the merge brought and keeps what
39
+ * it didn't.
40
+ *
41
+ * A `<range>` without `..`, such as `HEAD` for a first release, is every commit it reaches. git-cliff
42
+ * reads only `a..b`, so for one it reads all of HEAD's history, and the commit has to be in it.
43
+ */
44
+ /** Each type's heading in the notes, which list them in `commitTypes`' order. */
45
+ const typeHeadings = {
46
+ feat: "Features",
47
+ fix: "Fixes",
48
+ perf: "Performance",
49
+ refactor: "Refactors",
50
+ test: "Tests",
51
+ docs: "Docs",
52
+ build: "Build",
53
+ ci: "CI",
54
+ chore: "Chores",
55
+ revert: "Reverts"
56
+ };
57
+ /** The types a release's notes list. The rest are counted there, and only the changelog lists them. */
58
+ const listedTypes = [
59
+ "feat",
60
+ "fix",
61
+ "perf"
62
+ ];
63
+ /** The heading for a subject in no format, which the notes list last. */
64
+ const otherHeading = "Other";
65
+ /** A type's group in git-cliff's config: its heading, after its place in `commitTypes`, hidden. */
66
+ const groupOf = (type) => `<!-- ${String(commitTypes.indexOf(type)).padStart(2, "0")} -->${typeHeadings[type]}`;
67
+ const listedGroups = new Set(listedTypes.map(groupOf));
68
+ /**
69
+ * The words an entry keeps capitalised when one starts it: names, as git's and home's subjects use
70
+ * them, and the cast's.
71
+ */
72
+ const properNouns = /* @__PURE__ */ new Set([
73
+ "Acme",
74
+ "Blacksmith",
75
+ "Bun",
76
+ "Claude",
77
+ "Cloudflare",
78
+ "Codex",
79
+ "Cursor",
80
+ "Deno",
81
+ "Effect",
82
+ "Gemini",
83
+ "Git",
84
+ "Mo",
85
+ "Neon",
86
+ "Node",
87
+ "Nuxt",
88
+ "Pip",
89
+ "Postgres",
90
+ "Schema",
91
+ "Sol",
92
+ "Turso",
93
+ "Vercel",
94
+ "Vite",
95
+ "Vitest"
96
+ ]);
97
+ /**
98
+ * An entry's words, with its first word in lower case when it's an ordinary word written with a
99
+ * capital, such as `Add` or `The`. A name in `properNouns`, and a word with another capital, a
100
+ * digit, an apostrophe or a mark, such as `GitHub`, `CLI`, `R2`, `Git's` or `` `Schema` ``, stays
101
+ * as written.
102
+ */
103
+ const entryText = (text) => {
104
+ const [word = ""] = text.split(/\s/u, 1);
105
+ if (!/^(?:A|[A-Z][a-z]+)$/u.test(word) || properNouns.has(word)) return text;
106
+ return `${word.toLowerCase()}${text.slice(word.length)}`;
107
+ };
108
+ /** What a section says when no commit in its range touched what's published. */
109
+ const nothingChanged = "Nothing published changed.";
110
+ /**
111
+ * The most UTF-8 bytes the section `changelog` prints may hold. A release's pull request carries it
112
+ * in its body, which GitHub caps at 65,536 characters, beside its own lines.
113
+ */
114
+ const notesBytesMost = 5e4;
115
+ /** The most a git or git-cliff run may print: a release's context is about 2 KiB a commit. */
116
+ const outputLimit = 268435456;
117
+ /** A GitHub repository's `owner/name`, which the notes link each pull request in. */
118
+ const repoName = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u;
119
+ /** git-cliff's command, which runs the binary its platform's package installs. */
120
+ const gitCliff = fileURLToPath(import.meta.resolve("git-cliff/cli"));
121
+ /** One commit's line, by its subject: the scope in bold, then its words, and as written in none. */
122
+ const line = [
123
+ "{% if commit.group is ending_with(\"",
124
+ otherHeading,
125
+ "\") %}{{ commit.raw_message | split(pat=\"\\n\") | first | trim }}",
126
+ "{% else %}{% if commit.scope %}**{{ commit.scope }}:** {% endif %}",
127
+ "{{ commit.message | split(pat=\"\\n\") | first | trim }}{% endif %}"
128
+ ].join("");
129
+ /**
130
+ * git-cliff's config for `repo`: a group for each type, in order, then the rest, with GitHub's old
131
+ * merge subject read as the title it merged, and each `(#N)` linked to its pull request. A release's
132
+ * own commit, `chore: release <version>`, or `Release: <version>` from before the format, is no
133
+ * change of its own, and nor is a merge no pull request made, such as `Merge branch 'x'`; a change
134
+ * to how releases run, such as `chore(ci): release.yml …`, is one. No
135
+ * repo tracks breaking changes, so a `!` a person writes lists under its type like any other.
136
+ */
137
+ const cliffConfig = (repo) => {
138
+ const groups = commitTypes.map((type) => ` { message = '^${type}(\\([^)]*\\))?!?: ', group = "${groupOf(type)}" },`);
139
+ return [
140
+ "[changelog]",
141
+ "header = \"\"",
142
+ `body = """\n${[
143
+ "{% for group, commits in commits | group_by(attribute=\"group\") %}",
144
+ "### {{ group | striptags | trim }}",
145
+ `{% for commit in commits %}\n- ${line}`,
146
+ "{%- endfor %}",
147
+ "{% endfor %}"
148
+ ].join("\n")}\n"""`,
149
+ "footer = \"\"",
150
+ "trim = true",
151
+ "",
152
+ "[git]",
153
+ "conventional_commits = true",
154
+ "filter_unconventional = false",
155
+ "split_commits = false",
156
+ "protect_breaking_commits = false",
157
+ "filter_commits = false",
158
+ "topo_order = false",
159
+ "sort_commits = \"oldest\"",
160
+ "commit_preprocessors = [",
161
+ ` { pattern = '^Merge pull request #(\\d+) from \\S+\\n\\n([^\\n]+)(?s:.*)$', replace = "\${2} (#\${1})" },`,
162
+ ` { pattern = '\\(#(\\d+)\\)$', replace = "([#\${1}](https://github.com/${repo}/pull/\${1}))" },`,
163
+ ` { pattern = '\\(#(\\d+)\\)\\n', replace = "([#\${1}](https://github.com/${repo}/pull/\${1}))\\n" },`,
164
+ "]",
165
+ "commit_parsers = [",
166
+ " { message = '^chore(\\([^)]*\\))?: release v?[0-9]+\\.[0-9]+\\.[0-9]+\\b', skip = true },",
167
+ " { message = '^Release: v?[0-9]+\\.[0-9]+\\.[0-9]+\\b', skip = true },",
168
+ " { message = '^Merge (branch(es)? |remote-tracking branch(es)? |commits? \\x27|tags? \\x27)', skip = true },",
169
+ ...groups,
170
+ ` { message = '.*', group = "<!-- ${commitTypes.length} -->${otherHeading}" },`,
171
+ "]",
172
+ ""
173
+ ].join("\n");
174
+ };
175
+ /** main's own commits in `range` that touch one of `paths`, or any when it names none, oldest first. */
176
+ const mainCommits = (root, range, paths) => execFileSync("git", [
177
+ "log",
178
+ "--first-parent",
179
+ "--reverse",
180
+ "--format=%H",
181
+ range,
182
+ "--",
183
+ ...paths.length === 0 ? ["."] : paths
184
+ ], {
185
+ cwd: root,
186
+ encoding: "utf8",
187
+ maxBuffer: outputLimit,
188
+ stdio: [
189
+ "ignore",
190
+ "pipe",
191
+ "pipe"
192
+ ]
193
+ }).split("\n").filter((sha) => sha !== "");
194
+ /** Every other field git-cliff's context holds, which goes back to it as it came. */
195
+ const rest = [Schema.Record(Schema.String, Schema.Unknown)];
196
+ /**
197
+ * A commit as git-cliff's context holds it: its SHA, the group its config gave it, its scope, its
198
+ * words after the type and scope, its whole message, and the rest.
199
+ */
200
+ const Commit = Schema.StructWithRest(Schema.Struct({
201
+ id: Schema.String,
202
+ group: Schema.String,
203
+ scope: Schema.NullOr(Schema.String),
204
+ message: Schema.String,
205
+ raw_message: Schema.String
206
+ }), rest);
207
+ /** A release as git-cliff's context holds it: the commits it read, and the rest. */
208
+ const Release = Schema.StructWithRest(Schema.Struct({ commits: Schema.Array(Commit) }), rest);
209
+ const decodeContext = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Array(Release)));
210
+ /** What a run git or git-cliff refused said, as `execFileSync`'s error holds it. */
211
+ const decodeRefused = Schema.decodeUnknownOption(Schema.Struct({ stderr: Schema.String }));
212
+ /** The line of a refusal that says why: git's `fatal: …` or git-cliff's `Error: …`, not its logs. */
213
+ const refusal = /^(?:fatal|error|Error): .*$/mu;
214
+ const none = {
215
+ full: "",
216
+ listed: "",
217
+ others: 0,
218
+ cut: 0
219
+ };
220
+ /**
221
+ * The notes for main's commits in `range` that touch `paths`, linked in `repo`: each heading and its
222
+ * lines, or "" when there are none. When `fits` refuses the whole of `listed`, it leaves out the
223
+ * fewest oldest changes it takes for `fits` to take them.
224
+ */
225
+ const releaseNotes = (options) => {
226
+ const { root, repo, range, paths, fits = () => true } = options;
227
+ const shas = mainCommits(root, range, paths);
228
+ if (shas.length === 0) return none;
229
+ const walked = range.includes("..") ? [range] : [];
230
+ const inHead = () => spawnSync("git", [
231
+ "merge-base",
232
+ "--is-ancestor",
233
+ range,
234
+ "HEAD"
235
+ ], { cwd: root }).status === 0;
236
+ if (walked.length === 0 && !inHead()) throw new Error(`${range} isn't in HEAD's history, which is all a range without .. can read`);
237
+ const scratch = mkdtempSync(join(tmpdir(), "ref0-changelog-"));
238
+ try {
239
+ const config = join(scratch, "cliff.toml");
240
+ writeFileSync(config, cliffConfig(repo));
241
+ const cliff = (args) => execFileSync(execPath, [
242
+ gitCliff,
243
+ "--config",
244
+ config,
245
+ ...args
246
+ ], {
247
+ cwd: root,
248
+ encoding: "utf8",
249
+ maxBuffer: outputLimit,
250
+ stdio: [
251
+ "ignore",
252
+ "pipe",
253
+ "pipe"
254
+ ]
255
+ });
256
+ const releases = decodeContext(cliff([
257
+ "--repository",
258
+ root,
259
+ "--context",
260
+ ...walked
261
+ ]));
262
+ const [first] = releases;
263
+ if (first === void 0) return none;
264
+ const read = new Map(releases.flatMap(({ commits }) => commits.map((commit) => [commit.id, commit])));
265
+ const commits = shas.flatMap((sha) => read.get(sha) ?? []);
266
+ if (commits.length === 0) return none;
267
+ const context = join(scratch, "context.json");
268
+ const render = (kept) => {
269
+ if (kept.length === 0) return "";
270
+ const entries = kept.map((commit) => {
271
+ if (commit.group.endsWith(otherHeading)) return commit;
272
+ const message = entryText(commit.message);
273
+ const raw_message = commit.raw_message.replace(commit.message, () => message);
274
+ return {
275
+ ...commit,
276
+ message,
277
+ raw_message
278
+ };
279
+ }).toSorted((a, b) => order(a.scope ?? "~", b.scope ?? "~"));
280
+ writeFileSync(context, JSON.stringify([{
281
+ ...first,
282
+ version: null,
283
+ commits: entries
284
+ }]));
285
+ return tidy(cliff(["--from-context", context]));
286
+ };
287
+ const full = render(commits);
288
+ const listed = commits.filter((commit) => listedGroups.has(commit.group));
289
+ const others = commits.length - listed.length;
290
+ const without = (cut) => render(listed.slice(cut));
291
+ const whole = without(0);
292
+ if (listed.length === 0 || fits(whole, 0, others)) return {
293
+ full,
294
+ listed: whole,
295
+ others,
296
+ cut: 0
297
+ };
298
+ let [low, high] = [1, listed.length];
299
+ while (low < high) {
300
+ const cut = Math.floor((low + high) / 2);
301
+ if (fits(without(cut), cut, others)) high = cut;
302
+ else low = cut + 1;
303
+ }
304
+ return {
305
+ full,
306
+ listed: without(low),
307
+ others,
308
+ cut: low
309
+ };
310
+ } finally {
311
+ rmSync(scratch, {
312
+ recursive: true,
313
+ force: true
314
+ });
315
+ }
316
+ };
317
+ /** -1, 0 or 1 as `a` sorts before, with or after `b`, by code unit, as every machine sorts. */
318
+ const order = (a, b) => a < b ? -1 : a > b ? 1 : 0;
319
+ /** Notes with one blank line before each heading and between blocks, and none at either end. */
320
+ const tidy = (notes) => notes.replace(/\n*^(### )/gmu, "\n\n$1").replace(/\n{3,}/gu, "\n\n").trim();
321
+ /** A release's section: its heading, `## <version> (<date>)` or `## Unreleased`, then its notes. */
322
+ const section = (version, date, notes) => {
323
+ return `${version === void 0 ? "## Unreleased" : `## ${version} (${date})`}\n\n${notes.trim() === "" ? nothingChanged : notes.trim()}\n`;
324
+ };
325
+ /** The line that ends notes missing their `cut` oldest changes, linking `file`, which holds them. */
326
+ const cutLine = (cut, repo, file) => `_${cut} older ${cut === 1 ? "change isn't" : "changes aren't"} listed here: [${file}](https://github.com/${repo}/blob/main/${file}) lists every one._`;
327
+ /** The line that counts the `others` the notes don't list, linking `file`, which lists them. */
328
+ const othersLine = (others, repo, file) => `${others} other ${others === 1 ? "change" : "changes"} (refactors, tests, CI, docs, chores) ${others === 1 ? "is" : "are"} in [${file}](https://github.com/${repo}/blob/main/${file}).`;
329
+ /** The section `changelog` prints: its listed notes, then `cutLine` and `othersLine` when they say any. */
330
+ const printedSection = (version, date, listed, lines) => {
331
+ const heading = version === void 0 ? "## Unreleased" : `## ${version} (${date})`;
332
+ if (lines.length === 0) return section(version, date, listed);
333
+ return `${heading}\n\n${[listed.trim(), ...lines].filter((part) => part !== "").join("\n\n")}\n`;
334
+ };
335
+ const changelogHead = "# Changelog\n";
336
+ /**
337
+ * A changelog with `fresh`, a release's section, first, under `# Changelog`. A section with the
338
+ * same heading's version already there, as on a run that makes the release again, is written over,
339
+ * not added twice.
340
+ */
341
+ const prepend = (existing, fresh) => {
342
+ const heading = /^## \S+/u.exec(fresh)?.[0] ?? fresh;
343
+ const kept = (existing ?? changelogHead).replace(/^# Changelog\n+/u, "").split(/(?=^## )/mu).filter((part) => part.trim() !== "").filter((part) => !part.startsWith(`${heading} `) && !part.startsWith(`${heading}\n`));
344
+ return `${changelogHead}\n${[fresh, ...kept].map((part) => part.trimEnd()).join("\n\n")}\n`;
345
+ };
346
+ const usage = "usage: ref0-workspace changelog --repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>";
347
+ /** The command, on `args`, for the repo at `root`: prints the section, and answers its exit code. */
348
+ const changelog = (args, root) => {
349
+ const parsed = (() => {
350
+ try {
351
+ return parseArgs({
352
+ args: [...args],
353
+ allowPositionals: true,
354
+ options: {
355
+ repo: { type: "string" },
356
+ path: {
357
+ type: "string",
358
+ multiple: true,
359
+ default: []
360
+ },
361
+ version: { type: "string" },
362
+ date: { type: "string" },
363
+ prepend: { type: "string" },
364
+ "most-bytes": { type: "string" }
365
+ }
366
+ });
367
+ } catch {
368
+ return;
369
+ }
370
+ })();
371
+ const values = parsed?.values;
372
+ const [range, ...extra] = parsed?.positionals ?? [];
373
+ if (values === void 0 || range === void 0 || range.startsWith("-") || extra.length > 0 || values.date !== void 0 && values.version === void 0) {
374
+ console.error(usage);
375
+ return 2;
376
+ }
377
+ if (values.repo === void 0 || !repoName.test(values.repo)) {
378
+ console.error(`changelog: --repo is the GitHub repository's owner/name, such as ref-0/home.\n${usage}`);
379
+ return 2;
380
+ }
381
+ if (values.date !== void 0 && !/^\d{4}-\d{2}-\d{2}$/u.test(values.date)) {
382
+ console.error(`changelog: --date is the release's day, as yyyy-mm-dd.\n${usage}`);
383
+ return 2;
384
+ }
385
+ const most = values["most-bytes"] === void 0 ? notesBytesMost : Number(values["most-bytes"]);
386
+ if (!Number.isSafeInteger(most) || most < 1 || !/^\d+$/u.test(values["most-bytes"] ?? "1")) {
387
+ console.error(`changelog: --most-bytes is a count of bytes, such as ${notesBytesMost}.\n${usage}`);
388
+ return 2;
389
+ }
390
+ const { repo } = values;
391
+ const date = values.date ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
392
+ const file = values.prepend === void 0 ? "CHANGELOG.md" : relative(root, resolve(values.prepend));
393
+ const printed = (listed, cut, others) => printedSection(values.version, date, listed, [...cut === 0 ? [] : [cutLine(cut, repo, file)], ...others === 0 ? [] : [othersLine(others, repo, file)]]);
394
+ const fits = (listed, cut, others) => Buffer.byteLength(printed(listed, cut, others)) <= most;
395
+ const read = (() => {
396
+ try {
397
+ return { notes: releaseNotes({
398
+ root,
399
+ repo,
400
+ range,
401
+ paths: values.path,
402
+ fits
403
+ }) };
404
+ } catch (error) {
405
+ const said = Option.match(decodeRefused(error), {
406
+ onNone: () => "",
407
+ onSome: ({ stderr }) => refusal.exec(stderr)?.[0] ?? stderr.trim()
408
+ });
409
+ return { failed: said === "" ? String(error) : said };
410
+ }
411
+ })();
412
+ if ("failed" in read) {
413
+ console.error(`changelog: couldn't read ${range}: ${read.failed}`);
414
+ return 1;
415
+ }
416
+ const { full, listed, others, cut } = read.notes;
417
+ if (values.prepend !== void 0) {
418
+ const existing = (() => {
419
+ try {
420
+ return readFileSync(values.prepend, "utf8");
421
+ } catch {
422
+ return;
423
+ }
424
+ })();
425
+ writeFileSync(values.prepend, prepend(existing, section(values.version, date, full)));
426
+ }
427
+ if (cut > 0) console.error(`changelog: left out the ${cut} oldest of the changes to print at most ${most} bytes; ${file} lists every one.`);
428
+ stdout.write(printed(listed, cut, others));
429
+ return 0;
430
+ };
431
+ export { changelog, cliffConfig, cutLine, entryText, listedTypes, mainCommits, notesBytesMost, nothingChanged, othersLine, prepend, properNouns, releaseNotes, section, typeHeadings };
@@ -0,0 +1,138 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Option, Schema } from "effect";
4
+ // src/commit-message.ts
5
+ /**
6
+ * The commit format every ref-0 repo keeps, `type(scope): subject`, on a commit on a branch and on
7
+ * a pull request's title, which main's merge commit takes as its subject.
8
+ *
9
+ * ref0-workspace commit-message <message-file> the commit-msg hook, on each commit
10
+ * ref0-workspace commit-message --title <title> CI, on the pull request's title
11
+ *
12
+ * The types are the same in every repo, and the release notes group by them, as `changelog.ts`
13
+ * says. Each repo names its own scopes in its root `package.json`, under `ref0-workspace`, as
14
+ * `{ "commitScopes": ["git", "cli"] }`, and its `.agents/repo/commits.md` says what each names.
15
+ *
16
+ * A commit may also carry one of git's own subjects: a merge's, `Merge branch …`,
17
+ * `Merge remote-tracking branch …`, `Merge commit '…'` or `Merge tag '…'`, or the plural git writes
18
+ * for an octopus merge, such as `Merge branches 'a' and 'b'`, an autosquash's,
19
+ * `fixup! …`, `squash! …` or `amend! …`, and a revert's, `Revert "…"` or `Reapply "…"`, which
20
+ * `git revert` writes without running `commit-msg`. A title may not, since it becomes main's
21
+ * subject.
22
+ */
23
+ /** The kinds of change, in the order the release notes list them. */
24
+ const commitTypes = [
25
+ "feat",
26
+ "fix",
27
+ "perf",
28
+ "refactor",
29
+ "test",
30
+ "docs",
31
+ "build",
32
+ "ci",
33
+ "chore",
34
+ "revert"
35
+ ];
36
+ /**
37
+ * git's own subjects, which a commit may carry and a title may not: a merge's, as `fmt-merge-msg`
38
+ * writes it for one or several of a kind, an autosquash's and a revert's.
39
+ */
40
+ const gitsOwn = /^(?:Merge (?:branch(?:es)? |remote-tracking branch(?:es)? |commits? '|tags? ')|(?:fixup|squash|amend)! |(?:Revert|Reapply) ")/u;
41
+ /** `type`, then `(scope)` or nothing, then `!` or nothing, then `: ` and the words. */
42
+ const subjectLine = /^([^\s(!:]+)(?:\(([^()]*)\))?!?: (\S(?:.*\S)?)$/u;
43
+ /** A scope's name, as a repo may give it: lower case words joined by `-`. */
44
+ const scopeName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
45
+ const read = (line, scopes) => {
46
+ const match = subjectLine.exec(line);
47
+ if (match === null) return {
48
+ valid: false,
49
+ problem: `"${line}" isn't "type(scope): subject", or "type: subject" for a change across the repo`
50
+ };
51
+ const [, word = "", named, text = ""] = match;
52
+ const type = commitTypes.find((each) => each === word);
53
+ if (type === void 0) return {
54
+ valid: false,
55
+ problem: `"${word}" isn't a type: use one of ${commitTypes.join(", ")}`
56
+ };
57
+ if (named !== void 0 && !scopes.includes(named)) return {
58
+ valid: false,
59
+ problem: `"${named}" isn't a scope: ${scopes.length === 0 ? "this repo names none, so leave it off" : `use one of ${scopes.join(", ")}, or none`}`
60
+ };
61
+ return {
62
+ valid: true,
63
+ subject: {
64
+ type,
65
+ scope: named,
66
+ text
67
+ }
68
+ };
69
+ };
70
+ /** What's wrong with `line` as a commit's subject or a pull request's title, or undefined. */
71
+ const subjectProblem = (line, checked, scopes) => {
72
+ if (checked === "commit" && gitsOwn.test(line)) return void 0;
73
+ const subject = read(line, scopes);
74
+ return subject.valid ? void 0 : subject.problem;
75
+ };
76
+ /**
77
+ * A comment as git's editor and a commit template write one: `#` alone, or `#` and a space. `-m`
78
+ * keeps every line, so a line such as `#123: a fix` is a subject, never a comment. In the editor,
79
+ * git strips a person's own `#foo` line only after the hook has run, so the hook refuses it as the
80
+ * subject: rare, and it refuses, never lets a subject through.
81
+ */
82
+ const comment = /^#(?: |$)/u;
83
+ /**
84
+ * A commit message's subject, as git keeps it: its first line that isn't blank or a comment,
85
+ * before the `>8` line `commit -v` adds, or undefined for a message with none, which git refuses.
86
+ */
87
+ const messageSubject = (message) => {
88
+ for (const raw of message.split("\n")) {
89
+ if (/^# -+ >8 -+$/u.test(raw)) return void 0;
90
+ const line = raw.trimEnd();
91
+ if (line !== "" && !comment.test(line)) return line;
92
+ }
93
+ };
94
+ /** What's wrong with a commit message's subject, or undefined: an empty one is git's to refuse. */
95
+ const messageProblem = (message, scopes) => {
96
+ const subject = messageSubject(message);
97
+ return subject === void 0 ? void 0 : subjectProblem(subject, "commit", scopes);
98
+ };
99
+ /** The part of a repo's root `package.json` that names its scopes. */
100
+ const Manifest = Schema.Struct({ "ref0-workspace": Schema.Struct({ commitScopes: Schema.Array(Schema.String) }) });
101
+ const decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(Manifest));
102
+ /** The repo's scopes from its root `package.json`, or what's wrong with how it names them. */
103
+ const commitScopes = (root) => {
104
+ const file = join(root, "package.json");
105
+ const where = `${file}'s "ref0-workspace"."commitScopes"`;
106
+ const text = (() => {
107
+ try {
108
+ return readFileSync(file, "utf8");
109
+ } catch {
110
+ return "";
111
+ }
112
+ })();
113
+ const manifest = decodeManifest(text);
114
+ if (Option.isNone(manifest)) return { problem: `${where} isn't a list of words: name the repo's scopes, or [] for none` };
115
+ const scopes = manifest.value["ref0-workspace"].commitScopes;
116
+ const wrong = scopes.find((scope) => !scopeName.test(scope));
117
+ if (wrong !== void 0) return { problem: `${where} holds ${JSON.stringify(wrong)}: a scope is lower case words joined by -` };
118
+ return { scopes };
119
+ };
120
+ /** The command, on `args`, for the repo at `root`: answers its exit code. */
121
+ const commitMessage = (args, root) => {
122
+ const [first, second, ...rest] = args;
123
+ const title = first === "--title";
124
+ if (first === void 0 || rest.length > 0 || title !== (second !== void 0)) {
125
+ console.error("usage: ref0-workspace commit-message <message-file> | --title <title>");
126
+ return 2;
127
+ }
128
+ const config = commitScopes(root);
129
+ if ("problem" in config) {
130
+ console.error(`commit-message: ${config.problem}.`);
131
+ return 2;
132
+ }
133
+ const problem = title ? subjectProblem(second ?? "", "title", config.scopes) : messageProblem(readFileSync(first, "utf8"), config.scopes);
134
+ if (problem === void 0) return 0;
135
+ console.error(`${title ? "The pull request's title" : "The commit's subject"}: ${problem}. .agents/repo/commits.md says how.`);
136
+ return 1;
137
+ };
138
+ export { commitMessage, commitScopes, commitTypes, messageProblem, messageSubject, subjectProblem };
@@ -38,6 +38,15 @@ const budgets = {
38
38
  rules: 8e3,
39
39
  glossaryEntry: 400
40
40
  };
41
+ /** The `model-tier` values a skill's frontmatter may name, as `select-model` defines them. */
42
+ const modelTiers = [
43
+ "lookup",
44
+ "research",
45
+ "code",
46
+ "perf",
47
+ "frontier"
48
+ ];
49
+ const validModelTiers = new Set(modelTiers);
41
50
  const history = /\b\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{4}\b/;
42
51
  /** `text` without fenced blocks or inline code, where a date is an example, not history. */
43
52
  const prose = (text) => text.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "").replace(/`[^`\n]*`/g, "");
@@ -94,6 +103,14 @@ const description = (text) => {
94
103
  const folded = (end === -1 ? rest : rest.slice(0, end)).map((line) => line.trim());
95
104
  return (/^[>|]-?$/.test(first) ? folded.join(" ") : first).replace(/^(["'])([\s\S]*)\1$/, "$2");
96
105
  };
106
+ /**
107
+ * A `SKILL.md`'s frontmatter `model-tier`, trimmed and unquoted. `undefined` when it has none.
108
+ */
109
+ const modelTier = (text) => {
110
+ const line = (/^---\n([\s\S]*?)\n---/.exec(text)?.[1])?.split("\n").find((entry) => entry.startsWith("model-tier:"));
111
+ if (line === void 0) return void 0;
112
+ return line.slice(11).trim().replace(/^(["'])([\s\S]*)\1$/, "$2");
113
+ };
97
114
  /** What the docs break, one line each, with what to do about it. */
98
115
  const problems = (docs, upstream) => {
99
116
  const found = [];
@@ -109,6 +126,8 @@ const problems = (docs, upstream) => {
109
126
  if (skill !== void 0) {
110
127
  const about = description(text) ?? "";
111
128
  if (about.length > budgets.description) found.push(`${path}: its description is ${about.length} characters, over ${budgets.description}. Say what it does, when to use it and which sibling to use instead; cut the method.`);
129
+ const tier = modelTier(text);
130
+ if (ours && tier !== void 0 && !validModelTiers.has(tier)) found.push(`${path}: model-tier "${tier}" is not one of ${modelTiers.join(", ")}. See the select-model skill for the tiers.`);
112
131
  if (ours && bytes(text) > budgets.skill) found.push(`${path}: ${kb(bytes(text))}, over ${kb(budgets.skill)}. ${move(path, text)}`);
113
132
  }
114
133
  if (agents || rules) {
@@ -178,4 +197,4 @@ const docsBudget = (from) => {
178
197
  warnings: warnings(docs, upstream)
179
198
  };
180
199
  };
181
- export { budgets, description, docsBudget, problems, sections, trackedDocs, upstreamSkills, warnings };
200
+ export { budgets, description, docsBudget, modelTier, modelTiers, problems, sections, trackedDocs, upstreamSkills, warnings };
@@ -0,0 +1,85 @@
1
+ import { spawnSync } from "node:child_process";
2
+ // src/pre-push.ts
3
+ /**
4
+ * Refuses a push that deletes, or moves to a commit that doesn't descend from where it is, `main`,
5
+ * a `deploy/` branch or a `release/` branch, run as Git's pre-push hook:
6
+ *
7
+ * ref0-workspace pre-push <remote> <url> the ref lines on stdin, as Git writes them
8
+ *
9
+ * Git writes a line for each ref the push updates, `<local ref> <local sha> <remote ref> <remote
10
+ * sha>`. A local sha of zeros deletes the remote ref, and a remote sha of zeros creates it, which
11
+ * moves nothing back, so it passes. Any other update of a guarded ref passes only when `git
12
+ * merge-base --is-ancestor` finds the remote sha in the local sha's history, which it can't when the
13
+ * checkout hasn't fetched it.
14
+ *
15
+ * `REF0_REWRITE=<repo>` lets the push through when `<repo>` is the remote's repo name, the last part
16
+ * of its URL without `.git`, so a rewrite meant for one repo opens no other. `git push --no-verify`
17
+ * skips every hook, this one too: it stops accidents, and isn't a boundary.
18
+ */
19
+ /** The branches a push may only move forward. */
20
+ const isGuarded = (ref) => ref === "refs/heads/main" || /^refs\/heads\/(?:deploy|release)\/./s.test(ref);
21
+ /**
22
+ * The repo a remote's URL names: `git` for `git@github.com:ref-0/git.git` or `.../ref-0/git/`. It's
23
+ * the path's last part, or what follows `host:` when the path has no `/`, so a colon inside a local
24
+ * folder's name, as in `/srv/project:git.git`, stays in it.
25
+ */
26
+ const repoName = (url) => {
27
+ const path = url.replace(/\/+$/, "");
28
+ return (path.includes("/") ? path.slice(path.lastIndexOf("/") + 1) : path.slice(path.indexOf(":") + 1)).replace(/\.git$/, "");
29
+ };
30
+ const isZero = (sha) => /^0+$/.test(sha);
31
+ /** Whether `ancestor` is in `head`'s history, in the checkout at `at`. */
32
+ const isAncestor = (at, ancestor, head) => spawnSync("git", [
33
+ "merge-base",
34
+ "--is-ancestor",
35
+ ancestor,
36
+ head
37
+ ], {
38
+ cwd: at,
39
+ stdio: "ignore"
40
+ }).status === 0;
41
+ /** A line Git writes, the remote ref with each sha, or nothing when it isn't one. */
42
+ const parse = (line) => {
43
+ const [localRef, local, ref, remote, ...extra] = line.split(" ");
44
+ if (localRef === void 0 || local === void 0 || ref === void 0 || remote === void 0) return void 0;
45
+ return extra.length === 0 ? {
46
+ local,
47
+ ref,
48
+ remote
49
+ } : void 0;
50
+ };
51
+ /** What the update does that the guard refuses, or nothing. */
52
+ const refusal = (at, { local, ref, remote }) => {
53
+ if (!isGuarded(ref)) return void 0;
54
+ if (isZero(local)) return `deletes ${ref}`;
55
+ if (isZero(remote) || isAncestor(at, remote, local)) return void 0;
56
+ return `moves ${ref} from ${remote.slice(0, 12)} to ${local.slice(0, 12)}, not a descendant`;
57
+ };
58
+ /**
59
+ * Answers the hook's exit code for the push to `url`, whose ref lines are `input`, from the checkout
60
+ * at `at`, printing each refusal.
61
+ */
62
+ const prePush = (at, url, input, rewrite) => {
63
+ const lines = input.split("\n").filter((line) => line.trim() !== "");
64
+ const updates = lines.map(parse);
65
+ const malformed = lines.find((_, index) => updates[index] === void 0);
66
+ if (malformed !== void 0) {
67
+ console.error(`ref0-workspace pre-push: can't read the ref line "${malformed}"`);
68
+ return 2;
69
+ }
70
+ const refused = updates.flatMap((update) => {
71
+ const found = update === void 0 ? void 0 : refusal(at, update);
72
+ return found === void 0 ? [] : [found];
73
+ });
74
+ if (refused.length === 0) return 0;
75
+ const repo = repoName(url);
76
+ if (repo !== "" && rewrite === repo) {
77
+ console.error(`ref0-workspace pre-push: REF0_REWRITE=${repo}, so this push ${refused.join(", ")}`);
78
+ return 0;
79
+ }
80
+ for (const line of refused) console.error(`ref0-workspace pre-push: refused, this push ${line}`);
81
+ const other = rewrite === void 0 || rewrite === "" ? "" : ` REF0_REWRITE is ${rewrite}, not ${repo}.`;
82
+ console.error(`Only a rewrite of ${repo} itself, on purpose, moves these back: set REF0_REWRITE=${repo}.${other}`);
83
+ return 1;
84
+ };
85
+ export { isGuarded, prePush, repoName };
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { pid } from "node:process";
3
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { pid } from "node:process";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { createHash } from "node:crypto";
@@ -1,10 +1,10 @@
1
1
  import { manifestInputs, sha256, workspaceFiles } from "./inputs.mjs";
2
2
  import { env } from "node:process";
3
+ import { homedir } from "node:os";
3
4
  import { isAbsolute, join, relative, resolve } from "node:path";
4
5
  import { Option, Schema } from "effect";
5
6
  import { randomBytes } from "node:crypto";
6
7
  import { mkdir, readFile, readdir, rename, stat, unlink, utimes, writeFile } from "node:fs/promises";
7
- import { homedir } from "node:os";
8
8
  // src/types/cache.ts
9
9
  /**
10
10
  * Each project's type check results, kept for every worktree on the machine in one folder,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ref0/workspace",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "The lint and workspace checks every ref-0 repo shares",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,8 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "effect": "4.1.4"
37
+ "effect": "4.1.4",
38
+ "git-cliff": "2.14.2"
38
39
  },
39
40
  "devDependencies": {
40
41
  "@effect/tsgo": "0.70.0",