@ref0/workspace 0.5.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
@@ -57,8 +57,9 @@ entry point's source:
57
57
 
58
58
  - `docs-budget`: the docs agents load, each within its budget: every skill's description, the
59
59
  repo's own `SKILL.md`s, `AGENTS.md`s, the root's `RULES.md`, and `GLOSSARY.md`. It reads the
60
- Markdown Git tracks. Skills the root's `skills-lock.json` names are upstream copies; without the
61
- lock there are none.
60
+ Markdown Git tracks. A `SKILL.md` fails past 6 KB and warns past 5 KB, each naming its largest
61
+ sections to move to `references/`. Upstream copies are the skills the root's `skills-lock.json`
62
+ names, and each skill with an `.agents/skills/<name>-UPSTREAM.md`.
62
63
  - `symbols find <words...>` and `symbols check <base> [<head>]` or `symbols check --all`: what the
63
64
  repo already has, and a change that copies it, as [Symbols](#symbols) says.
64
65
  - `types`: the types of every project the root `tsconfig.json` reaches, and Effect's rules, with
@@ -72,6 +73,39 @@ entry point's source:
72
73
  its source under the condition first. `--packages` is `packages/*` and `--condition`
73
74
  `@ref0/source` unless given. The `package-exports` skill reviews the rest: what each runtime
74
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.
75
109
 
76
110
  `types` and `type-coverage` run the repo's own `@effect/tsgo`, `tsrs` and `typescript`, its
77
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 = () => {
@@ -54,7 +65,8 @@ const plain = (about, run) => ({
54
65
  });
55
66
  const checks = /* @__PURE__ */ new Map([
56
67
  ["docs-budget", plain("the docs agents load, each within its budget", (at) => {
57
- const { docs, problems } = docsBudget(at);
68
+ const { docs, problems, warnings } = docsBudget(at);
69
+ for (const line of warnings) console.error(`warning: ${line}`);
58
70
  for (const line of problems) console.error(line);
59
71
  if (problems.length > 0) return 1;
60
72
  console.error(`docs-budget: ${docs.length} Markdown files within budget`);
@@ -98,6 +110,24 @@ const checks = /* @__PURE__ */ new Map([
98
110
  if (parsed === void 0) return usageError();
99
111
  return packageExports(root(), parsed);
100
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
+ }
101
131
  }]
102
132
  ]);
103
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 };
@@ -16,24 +16,79 @@ import { join } from "node:path";
16
16
  *
17
17
  * - Every skill's description, upstream copies too: at most 320 characters. An upkeep run that
18
18
  * updates a copy can bring its source's longer description back, and fails here until it's cut.
19
- * - The repo's own `SKILL.md`: at most 10 KB. Upstream copies, those the root's `skills-lock.json`
20
- * names and Cloudflare's `cf-*`, are left as their source wrote them. A repo without the lock
21
- * has no upstream copies.
19
+ * - The repo's own `SKILL.md`: at most 6 KB, with a warning past 5 KB, so each change has room to
20
+ * move a section to `references/` instead of trimming words to fit. Both name the largest
21
+ * sections. Upstream copies, those the root's `skills-lock.json` names, Cloudflare's `cf-*` and
22
+ * any skill with a `<name>-UPSTREAM.md` beside its folder, are left as their source wrote them.
22
23
  * - Root `AGENTS.md`: at most 12 KB. Any other `AGENTS.md`: at most 8 KB. Root `RULES.md`, the rules
23
24
  * every repo's `AGENTS.md` imports, so they load beside each one: at most 8 KB.
24
25
  * - `GLOSSARY.md`: no tables, since `vp fmt` pads each cell to its column's widest, and no entry
25
26
  * over 400 characters.
26
- * - None of these keeps history, such as "Changed 15 Oct 2026": `git log` holds it.
27
+ * - None of these keeps history, such as "Changed 15 Oct 2026" or "ruled out on 19 Nov 2026": `git log`
28
+ * holds it. A full date outside code counts.
27
29
  */
30
+ const bytes = (text) => Buffer.byteLength(text, "utf8");
31
+ const kb = (size) => `${(size / 1e3).toFixed(1)} KB`;
28
32
  const budgets = {
29
33
  description: 320,
30
- skill: 1e4,
34
+ skill: 6e3,
35
+ skillWarning: 5e3,
31
36
  rootAgents: 12e3,
32
37
  agents: 8e3,
33
38
  rules: 8e3,
34
39
  glossaryEntry: 400
35
40
  };
36
- const history = /\b(?:Changed|Decided|Renamed|Hidden|Dropped|Added) \d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{4}\b/;
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);
50
+ const history = /\b\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{4}\b/;
51
+ /** `text` without fenced blocks or inline code, where a date is an example, not history. */
52
+ const prose = (text) => text.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "").replace(/`[^`\n]*`/g, "");
53
+ /**
54
+ * The `## ` sections of a Markdown doc, largest first, each with its heading and its size in bytes,
55
+ * subsections included. Headings inside fenced blocks don't count.
56
+ */
57
+ const sections = (text) => {
58
+ const found = [];
59
+ let fence;
60
+ for (const line of text.split("\n")) {
61
+ const marker = /^(```|~~~)/.exec(line)?.[1];
62
+ if (marker !== void 0) fence = fence === void 0 ? marker : fence === marker ? void 0 : fence;
63
+ if (fence === void 0 && line.startsWith("## ")) found.push({
64
+ heading: line.slice(3),
65
+ size: 0
66
+ });
67
+ const last = found.at(-1);
68
+ if (last !== void 0) last.size += bytes(line) + 1;
69
+ }
70
+ return found.toSorted((a, b) => b.size - a.size);
71
+ };
72
+ /** The largest sections of `text`, for a message: at most three, each with its size. */
73
+ const largest = (text) => sections(text).slice(0, 3).map(({ heading, size }) => `"${heading}" ${kb(size)}`).join(", ");
74
+ /** A reference's file name for a section: its heading's first words in kebab case, no step number. */
75
+ const referenceName = (heading) => {
76
+ return `${heading.replace(/^\d+\.\s*/, "").toLowerCase().split(/[^a-z0-9]+/).filter((word) => word !== "").slice(0, 4).join("-") || "detail"}.md`;
77
+ };
78
+ /**
79
+ * What to do about a `SKILL.md` at `path` past a line: move a section only one step or case needs,
80
+ * word for word, to a reference beside it, and leave a pointer. Never trim words.
81
+ */
82
+ const move = (path, text) => {
83
+ const [first] = sections(text);
84
+ const references = `${path.slice(0, -8)}references/`;
85
+ const named = first === void 0 ? "" : ` (for "${first.heading}", ${referenceName(first.heading)})`;
86
+ return [
87
+ `Largest sections: ${largest(text) || "none"}.`,
88
+ `Move a section only one step or case needs, word for word, to ${references}<topic>.md${named} or an existing reference on its topic, and leave one line in its place: "When <condition>, read [<topic>](references/<file>.md)."`,
89
+ "Don't reword to fit. The create-skill skill's references/thinning.md says how."
90
+ ].join(" ");
91
+ };
37
92
  /**
38
93
  * A `SKILL.md`'s frontmatter description, as one line: plain, quoted, or a folded `>-` block.
39
94
  * `undefined` when it has none.
@@ -48,8 +103,14 @@ const description = (text) => {
48
103
  const folded = (end === -1 ? rest : rest.slice(0, end)).map((line) => line.trim());
49
104
  return (/^[>|]-?$/.test(first) ? folded.join(" ") : first).replace(/^(["'])([\s\S]*)\1$/, "$2");
50
105
  };
51
- const bytes = (text) => Buffer.byteLength(text, "utf8");
52
- const kb = (size) => `${(size / 1e3).toFixed(1)} KB`;
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
+ };
53
114
  /** What the docs break, one line each, with what to do about it. */
54
115
  const problems = (docs, upstream) => {
55
116
  const found = [];
@@ -60,12 +121,14 @@ const problems = (docs, upstream) => {
60
121
  const glossary = path === "GLOSSARY.md";
61
122
  if (skill === void 0 && !agents && !rules && !glossary) continue;
62
123
  const ours = skill === void 0 || !(upstream.has(skill) || skill.startsWith("cf-"));
63
- const said = history.exec(text)?.[0];
124
+ const said = history.exec(prose(text))?.[0];
64
125
  if (ours && said !== void 0) found.push(`${path}: "${said}" is history; leave it to git log and say what holds now.`);
65
126
  if (skill !== void 0) {
66
127
  const about = description(text) ?? "";
67
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.`);
68
- if (ours && bytes(text) > budgets.skill) found.push(`${path}: ${kb(bytes(text))}, over ${kb(budgets.skill)}. Move what one step or case needs to references/, and point to code instead of restating it.`);
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.`);
131
+ if (ours && bytes(text) > budgets.skill) found.push(`${path}: ${kb(bytes(text))}, over ${kb(budgets.skill)}. ${move(path, text)}`);
69
132
  }
70
133
  if (agents || rules) {
71
134
  const limit = rules ? budgets.rules : path === "AGENTS.md" ? budgets.rootAgents : budgets.agents;
@@ -84,14 +147,27 @@ const problems = (docs, upstream) => {
84
147
  return found;
85
148
  };
86
149
  /**
87
- * The skills the skills CLI installed, by folder name, from the lock at `root`: none when there's
88
- * no lock.
150
+ * The repo's own `SKILL.md`s past the warning line but within budget, one line each: they pass,
151
+ * and the next addition should move a section out.
152
+ */
153
+ const warnings = (docs, upstream) => docs.flatMap(({ path, text }) => {
154
+ const skill = /^\.agents\/skills\/([^/]+)\/SKILL\.md$/.exec(path)?.[1];
155
+ if (skill === void 0 || upstream.has(skill) || skill.startsWith("cf-")) return [];
156
+ const size = bytes(text);
157
+ if (size <= budgets.skillWarning || size > budgets.skill) return [];
158
+ return [`${path}: ${kb(size)}, past the ${kb(budgets.skillWarning)} warning line. ${move(path, text)}`];
159
+ });
160
+ /**
161
+ * The upstream copies, by folder name: the skills the skills CLI installed, from the lock at
162
+ * `root`, and each skill with a tracked `.agents/skills/<name>-UPSTREAM.md`, its provenance, among
163
+ * `docs`.
89
164
  */
90
- const upstreamSkills = (root) => {
165
+ const upstreamSkills = (root, docs = []) => {
166
+ const copied = docs.flatMap(({ path }) => /^\.agents\/skills\/([^/]+)-UPSTREAM\.md$/.exec(path)?.[1] ?? []).filter((name) => docs.some(({ path }) => path === `.agents/skills/${name}/SKILL.md`));
91
167
  const path = join(root, "skills-lock.json");
92
- if (!existsSync(path)) return /* @__PURE__ */ new Set();
168
+ if (!existsSync(path)) return new Set(copied);
93
169
  const lock = JSON.parse(readFileSync(path, "utf8"));
94
- return new Set(Object.keys(lock.skills));
170
+ return /* @__PURE__ */ new Set([...Object.keys(lock.skills), ...copied]);
95
171
  };
96
172
  /** The Markdown the checkout at `root` tracks, each by its path from the root, with its text. */
97
173
  const trackedDocs = (root) => execFileSync("git", [
@@ -106,17 +182,19 @@ const trackedDocs = (root) => execFileSync("git", [
106
182
  path,
107
183
  text: readFileSync(join(root, path), "utf8")
108
184
  }));
109
- /** The checkout `from` is in: its root, its tracked docs, and what they break. */
185
+ /** The checkout `from` is in: its root, its tracked docs, what they break and what nears a line. */
110
186
  const docsBudget = (from) => {
111
187
  const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
112
188
  cwd: from,
113
189
  encoding: "utf8"
114
190
  }).trim();
115
191
  const docs = trackedDocs(root);
192
+ const upstream = upstreamSkills(root, docs);
116
193
  return {
117
194
  root,
118
195
  docs,
119
- problems: problems(docs, upstreamSkills(root))
196
+ problems: problems(docs, upstream),
197
+ warnings: warnings(docs, upstream)
120
198
  };
121
199
  };
122
- export { budgets, description, docsBudget, problems, trackedDocs, upstreamSkills };
200
+ export { budgets, description, docsBudget, modelTier, modelTiers, problems, sections, trackedDocs, upstreamSkills, warnings };
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { existsSync, globSync, readFileSync } from "node:fs";
3
3
  import { join, posix } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
- import { Schema } from "effect";
5
+ import { Predicate, Schema } from "effect";
6
6
  // src/package-exports.ts
7
7
  /**
8
8
  * Fails when a workspace package's `exports` names a file nothing has or builds, or a generated
@@ -16,14 +16,19 @@ import { Schema } from "effect";
16
16
  *
17
17
  * - It has an `exports` field, so no other package reaches a file it doesn't list. One nothing
18
18
  * imports, such as a CLI's, is empty.
19
- * - Each target, condition by condition, names a tracked file, or a `dist/` file one of its pack
20
- * entries builds: `dist/<entry>.mjs`, and `dist/<entry>.d.mts` when it packs types. A `*`
21
- * target matches at least one tracked file.
19
+ * - Each target, condition by condition, names a tracked file, or a built file one of its pack
20
+ * entries builds (`<outDir>/<entry>.mjs`, and `<outDir>/<entry>.d.mts` when it packs types) or
21
+ * its `pack.copy` copies there from tracked source files. A `*` target matches at least one
22
+ * tracked file.
22
23
  * - No target names a `*.gen.ts` file, which a tool writes and git ignores.
23
- * - A package that packs builds each entry point that has a `types` condition from a pack entry.
24
+ * - A package that packs builds each entry point that has a `types` condition from a pack entry or
25
+ * `pack.copy`, except a tracked `.d.ts`/`.d.mts`/`.d.cts` declaration file in workspace `exports`
26
+ * when `publishConfig.exports` supplies the published map.
24
27
  * - Each entry point in `exports` with a `types` or `import` target gives its source, a tracked
25
28
  * file, under the source condition first, `--condition`, `@ref0/source` unless it's given, so
26
- * the workspace reads source and only the published package reads what's built.
29
+ * the workspace reads source and only the published package reads what's built. When
30
+ * `publishConfig.exports` supplies the published map, a workspace `exports` entry whose `types`
31
+ * and `import` targets are already tracked source files needs no source condition ahead of them.
27
32
  * `publishConfig.exports`, what the published package exports, has none.
28
33
  *
29
34
  * Under 1 s.
@@ -36,10 +41,25 @@ const Manifest = Schema.Struct({
36
41
  exports: Schema.optionalKey(Exports),
37
42
  publishConfig: Schema.optionalKey(Schema.Struct({ exports: Schema.optionalKey(Exports) }))
38
43
  });
39
- /** What the check reads of one `vp pack` build: its entries, and whether it packs types. */
44
+ const DynamicFn = Schema.declare((value) => Predicate.isFunction(value));
45
+ /** One static asset copy entry in `vp pack`'s `copy` list. */
46
+ const CopyObject = Schema.Struct({
47
+ from: Schema.Union([Schema.String, Schema.Array(Schema.String)]),
48
+ to: Schema.optionalKey(Schema.String),
49
+ flatten: Schema.optionalKey(Schema.Boolean),
50
+ rename: Schema.optionalKey(Schema.Union([Schema.String, DynamicFn]))
51
+ });
52
+ const CopyItem = Schema.Union([Schema.String, CopyObject]);
53
+ /** What the check reads of one `vp pack` build: its entries, output dir, types, and copied files. */
40
54
  const PackBuild = Schema.Struct({
41
55
  entry: Schema.Union([Schema.Array(Schema.String), Schema.Record(Schema.String, Schema.String)]),
42
- dts: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Struct({})]))
56
+ outDir: Schema.optionalKey(Schema.String),
57
+ dts: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Struct({})])),
58
+ copy: Schema.optionalKey(Schema.Union([
59
+ CopyItem,
60
+ Schema.Array(CopyItem),
61
+ DynamicFn
62
+ ]))
43
63
  });
44
64
  /** A `vite.config.ts` module, as far as its `pack`. */
45
65
  const ConfigModule = Schema.Struct({ default: Schema.Struct({ pack: Schema.optionalKey(Schema.Union([PackBuild, Schema.Array(PackBuild)])) }) });
@@ -48,6 +68,8 @@ const decodeConfigModule = Schema.decodeUnknownSync(ConfigModule);
48
68
  const isPaths = Schema.is(Schema.Array(Schema.String));
49
69
  const isBuilds = Schema.is(Schema.Array(PackBuild));
50
70
  const isPath = Schema.is(Schema.String);
71
+ const isCopyItems = Schema.is(Schema.Array(CopyItem));
72
+ const declarationFile = /\.d\.[cm]?ts$/;
51
73
  /** The folder every path in `paths` is in, as `vp pack` names entries below it. */
52
74
  const commonFolder = (paths) => {
53
75
  const [first = [], ...rest] = paths.map((path) => posix.dirname(path).split("/"));
@@ -61,8 +83,44 @@ const entryNames = ({ entry }) => {
61
83
  const folder = commonFolder(entry);
62
84
  return entry.map((path) => posix.relative(folder, path).replace(/\.[cm]?[jt]sx?$/, ""));
63
85
  };
64
- /** The `dist/` files a package's pack builds, by path from the package's folder. */
65
- const builtFiles = (pack) => new Set(pack.flatMap((build) => entryNames(build).flatMap((name) => build.dts === void 0 || build.dts === false ? [`dist/${name}.mjs`] : [`dist/${name}.mjs`, `dist/${name}.d.mts`])));
86
+ /** Converts a simple glob (`*`, `**`, `?`) into a RegExp over POSIX paths. */
87
+ const globToRegExp = (pattern) => {
88
+ const escaped = pattern.replaceAll(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("**/", "(?:.+/)?").replaceAll("**", ".*").replaceAll("*", "[^/]*").replaceAll("?", "[^/]");
89
+ return new RegExp(`^${escaped}$`);
90
+ };
91
+ /** Resolves `from` (explicit path or glob) against `context.tracked` when context is given. */
92
+ const resolvedCopySources = (source, context) => {
93
+ const normalized = posix.normalize(source);
94
+ const isGlob = /[*?[\]{}]/.test(normalized);
95
+ if (context === void 0) return isGlob ? [] : [normalized];
96
+ if (!isGlob) {
97
+ const repoPath = posix.join(context.directory, normalized);
98
+ return context.tracked.has(repoPath) ? [normalized] : [];
99
+ }
100
+ const pattern = globToRegExp(posix.join(context.directory, normalized));
101
+ return [...context.tracked].flatMap((file) => pattern.test(file) ? [posix.relative(context.directory, file)] : []);
102
+ };
103
+ /** Each file one `pack.copy` entry writes into `outDir`, matching tsdown's `resolveCopyEntry`. */
104
+ const copiedByItem = (item, outDir, context) => {
105
+ const froms = isPath(item) ? [item] : isPaths(item.from) ? item.from : [item.from];
106
+ const to = isPath(item) ? outDir : posix.normalize(item.to ?? outDir);
107
+ const flatten = isPath(item) ? true : item.flatten ?? true;
108
+ const rename = isPath(item) ? void 0 : item.rename;
109
+ if (rename !== void 0 && !isPath(rename)) return [];
110
+ return froms.flatMap((source) => resolvedCopySources(source, context).map((resolved) => {
111
+ const base = posix.basename(resolved);
112
+ const dir = posix.dirname(resolved);
113
+ const destFolder = flatten || dir === "." ? to : posix.join(to, ...dir.split("/").slice(1));
114
+ return posix.join(destFolder, rename ?? base);
115
+ }));
116
+ };
117
+ /** The output files a package's pack builds or copies, by path from the package's folder. */
118
+ const builtFiles = (pack, context) => new Set(pack.flatMap((build) => {
119
+ const outDir = posix.normalize(build.outDir ?? "dist");
120
+ const entries = entryNames(build).flatMap((name) => build.dts === void 0 || build.dts === false ? [posix.join(outDir, `${name}.mjs`)] : [posix.join(outDir, `${name}.mjs`), posix.join(outDir, `${name}.d.mts`)]);
121
+ const copies = build.copy === void 0 || Predicate.isFunction(build.copy) ? [] : (isCopyItems(build.copy) ? build.copy : [build.copy]).flatMap((item) => copiedByItem(item, outDir, context));
122
+ return [...entries, ...copies];
123
+ }));
66
124
  /** Each `[condition, path]` of a target; a plain path has no condition. */
67
125
  const paths = (target) => isPath(target) ? [[void 0, target]] : Object.entries(target);
68
126
  /** Whether `pattern`, a target with at most one `*`, matches any of `files`. */
@@ -81,8 +139,17 @@ const problems = (packages, tracked, condition = defaultCondition) => {
81
139
  const found = [];
82
140
  for (const { directory, manifest, pack } of packages) {
83
141
  const at = `${directory}/package.json`;
84
- const built = new Set([...builtFiles(pack)].map((path) => `${directory}/${path}`));
142
+ const built = new Set([...builtFiles(pack, {
143
+ directory,
144
+ tracked
145
+ })].map((path) => posix.join(directory, path)));
146
+ const outDirs = new Set(pack.length === 0 ? ["dist"] : pack.map((build) => posix.normalize(build.outDir ?? "dist")));
147
+ const isOutputPath = (targetPath) => {
148
+ const normalized = posix.normalize(targetPath);
149
+ return [...outDirs].some((dir) => normalized === dir || normalized.startsWith(`${dir}/`));
150
+ };
85
151
  const files = /* @__PURE__ */ new Set([...tracked, ...built]);
152
+ const hasPublishExports = manifest.publishConfig?.exports !== void 0;
86
153
  if (manifest.exports === void 0) {
87
154
  found.push(`${at}: has no exports, so any of its files can be imported. List its entry points, or write "exports": {} if nothing imports it.`);
88
155
  continue;
@@ -102,13 +169,19 @@ const problems = (packages, tracked, condition = defaultCondition) => {
102
169
  continue;
103
170
  }
104
171
  if (matches(file, files)) continue;
105
- found.push(path.startsWith("./dist/") ? `${at}: ${where} names ${path}, which no pack entry builds. Add its entry to pack in vite.config.ts, or point it at a file that's there.` : `${at}: ${where} names ${path}, which isn't tracked. Point it at a file that's there.`);
172
+ found.push(isOutputPath(path) ? `${at}: ${where} names ${path}, which no pack entry builds. Add its entry to pack in vite.config.ts, or point it at a file that's there.` : `${at}: ${where} names ${path}, which isn't tracked. Point it at a file that's there.`);
106
173
  }
107
174
  const types = isPath(target) ? void 0 : target["types"];
108
- const packed = isPath(target) ? [] : ["types", "import"].filter((key) => key in target);
175
+ const packed = isPath(target) ? [] : ["types", "import"].filter((key) => {
176
+ const targetPath = target[key];
177
+ if (targetPath === void 0) return false;
178
+ if (!hasPublishExports) return true;
179
+ return isOutputPath(targetPath) || built.has(posix.join(directory, targetPath));
180
+ });
109
181
  const first = isPath(target) ? void 0 : Object.keys(target)[0];
110
182
  if (field === "exports" && packed.length > 0 && first !== condition) found.push(`${at}: ${name} has ${packed.join(" and ")} but not its source under "${condition}" first. Add "${condition}": its source file, ahead of ${packed.join(" and ")}.`);
111
- if (pack.length > 0 && types !== void 0 && !built.has(posix.join(directory, types))) found.push(`${at}: ${name} has types at ${types}, which no pack entry builds. Add "${entry}"'s source to pack's entry in vite.config.ts.`);
183
+ const workspaceDeclaration = field === "exports" && hasPublishExports && types !== void 0 && declarationFile.test(types) && tracked.has(posix.join(directory, types));
184
+ if (pack.length > 0 && types !== void 0 && !built.has(posix.join(directory, types)) && !workspaceDeclaration) found.push(`${at}: ${name} has types at ${types}, which no pack entry builds. Add "${entry}"'s source to pack's entry in vite.config.ts.`);
112
185
  }
113
186
  }
114
187
  return found;
@@ -138,12 +211,7 @@ const packageExports = async (root, { packages, condition }) => {
138
211
  console.error(`package-exports: no package.json in ${packages.join(" or ")}. Name the packages' folders with --packages.`);
139
212
  return 1;
140
213
  }
141
- const tracked = new Set(execFileSync("git", [
142
- "ls-files",
143
- "-z",
144
- "--",
145
- ...folders
146
- ], {
214
+ const tracked = new Set(execFileSync("git", ["ls-files", "-z"], {
147
215
  cwd: root,
148
216
  encoding: "utf8",
149
217
  maxBuffer: 67108864
@@ -154,4 +222,4 @@ const packageExports = async (root, { packages, condition }) => {
154
222
  console.error(`package-exports: the exports of ${folders.length} packages hold`);
155
223
  return 0;
156
224
  };
157
- export { builtFiles, defaultCondition, packageExports, packageFolders, problems };
225
+ export { builtFiles, defaultCondition, packageExports, packageFolders, problems, readPackages };
@@ -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.5.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",