@antelopejs/tooling-configs 0.2.16 → 0.2.18

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.
Files changed (51) hide show
  1. package/README.md +101 -52
  2. package/dist/bin/api-diff.mjs +430 -107
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/capture.d.mts +1 -0
  6. package/dist/bin/capture.mjs +559 -0
  7. package/dist/bin/check-size.mjs +3 -3
  8. package/dist/bin/checks.mjs +3 -3
  9. package/dist/bin/comment-proof.mjs +4 -3
  10. package/dist/bin/garden.mjs +6 -6
  11. package/dist/bin/ratchet.mjs +316 -10
  12. package/dist/bin/suppressions.mjs +118 -80
  13. package/dist/bin/sync.mjs +554 -153
  14. package/dist/bin/verify.mjs +240 -127
  15. package/dist/capture/index.d.mts +50 -0
  16. package/dist/capture/index.mjs +2 -0
  17. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  18. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  19. package/dist/{ci-workflow-DIsoEgMd.mjs → ci-workflow-ChW4He0r.mjs} +84 -3
  20. package/dist/{files-2FikHZ9F.mjs → files-DJ0TeaTU.mjs} +11 -5
  21. package/dist/formal/index.d.mts +40 -0
  22. package/dist/formal/index.mjs +205 -0
  23. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  24. package/dist/oxc/anti-slop/index.mjs +869 -21
  25. package/dist/oxc/fmt.mjs +1 -1
  26. package/dist/oxc/guardrails/index.d.mts +1 -1
  27. package/dist/oxc/guardrails/index.mjs +736 -4
  28. package/dist/oxc/lint.d.mts +20 -3
  29. package/dist/oxc/lint.mjs +34 -10
  30. package/dist/oxlint-DIV-lLSS.mjs +98 -0
  31. package/dist/{package-Dtjt_lSa.mjs → package-BRTjkzt5.mjs} +29 -3
  32. package/dist/proof-stamp-DDDC0J6l.mjs +279 -0
  33. package/dist/ratchet-BAcLRYuM.mjs +448 -0
  34. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  35. package/dist/scenes-DZVXkcxS.mjs +104 -0
  36. package/dist/shared-igPpEDpS.mjs +622 -0
  37. package/dist/{size-BVgNbLO6.mjs → size-DBatLT-F.mjs} +4 -4
  38. package/dist/suppression-base-9L8dlMQK.mjs +120 -0
  39. package/dist/suppression-budget-C0SkPO5R.mjs +535 -0
  40. package/dist/{suppressions-BJAngUxo.mjs → suppressions-DM60NkvL.mjs} +180 -18
  41. package/dist/templates-CypDm-j9.mjs +121 -0
  42. package/dist/typescript-CM0LrVP7.mjs +222 -0
  43. package/dist/verify/index.d.mts +6 -1
  44. package/dist/verify/index.mjs +1 -1
  45. package/package.json +31 -5
  46. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  47. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  48. package/dist/shared-CsXIMK3I.mjs +0 -34
  49. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  50. package/dist/suppression-budget-Yyf5_J5l.mjs +0 -283
  51. package/dist/typescript-C54ONh9m.mjs +0 -433
package/dist/bin/sync.mjs CHANGED
@@ -1,20 +1,29 @@
1
1
  #!/usr/bin/env node
2
- import { a as formatCeilings, o as isRetired, s as readCeilings, t as CEILINGS_FILE } from "../ceilings-BSw9p4YB.mjs";
2
+ import { a as formatCeilings, l as readCeilings, s as isRetired, t as CEILINGS_FILE } from "../ceilings-B7KayYIG.mjs";
3
+ import { a as repositoryTools, i as parseManifest, n as managedPackage, o as templatePackage, r as packageManager, s as toolingVersions } from "../package-BRTjkzt5.mjs";
4
+ import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-CypDm-j9.mjs";
5
+ import { a as VERIFY_KINDS, c as isVerifyKind, i as SYNCED_SKILL_FILES, l as skillFolder, o as claudeLink, s as claudeLinkTarget, u as planDocsSkills } from "../shared-igPpEDpS.mjs";
3
6
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
4
- import { o as repositoryRoot } from "../files-2FikHZ9F.mjs";
5
- import { a as repositoryTools, i as parseManifest, n as managedPackage, o as toolingVersions, r as packageManager, t as execCommand } from "../package-Dtjt_lSa.mjs";
6
- import { t as measureBaseline } from "../ratchet-DRdIYwmv.mjs";
7
- import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Yyf5_J5l.mjs";
8
- import { a as MUTATION_PATH, c as MISSING_CHECKS_WORKFLOW, d as hasChecksWorkflow, l as ciNodeCallers, o as ciWorkflow, r as CI_PATH, s as mutationCaller, u as ciRenovateSyncCallers } from "../ci-workflow-DIsoEgMd.mjs";
9
- import { a as skillFolder, i as isVerifyKind, n as claudeLink, r as claudeLinkTarget, t as VERIFY_KINDS } from "../kinds-Bzyyi9yk.mjs";
7
+ import { c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
8
+ import { i as recordedRelease, t as measureBaseline } from "../ratchet-BAcLRYuM.mjs";
9
+ import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-C0SkPO5R.mjs";
10
+ import { a as MUTATION_PATH, c as MISSING_CHECKS_WORKFLOW, d as hasChecksWorkflow, l as ciNodeCallers, o as ciWorkflow, r as CI_PATH, s as mutationCaller, u as ciRenovateSyncCallers } from "../ci-workflow-ChW4He0r.mjs";
10
11
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
11
12
  import { dirname, join, resolve } from "node:path";
12
13
  import { execFileSync } from "node:child_process";
14
+ import { isMap, isScalar, isSeq, parseDocument } from "yaml";
15
+ import ts from "typescript";
13
16
  import { parseArgs } from "node:util";
14
- import { isMap, parseDocument } from "yaml";
15
17
  //#region src/guardrails/agents-block.ts
16
18
  const AGENTS_BLOCK_START = "<!-- antelopejs-guardrails:start -->";
17
19
  const AGENTS_BLOCK_END = "<!-- antelopejs-guardrails:end -->";
20
+ const ITERATION = `### While you work
21
+
22
+ \`pnpm run checks\` runs every step, so run it once, at the end. While you iterate, run only the check that covers what you changed:
23
+
24
+ - \`pnpm run typecheck\` after you change types or signatures.
25
+ - \`pnpm exec oxlint <files>\` and \`pnpm exec oxfmt <files>\` on the files you changed.
26
+ - Run one test file instead of the whole suite. In a module that tests with \`ajs module test\`, run \`pnpm run build\`, then \`pnpm exec ajs module test . -f dist/<path>.test.js\`. Repeat \`-f\` for more files.`;
18
27
  const COMMENTS = `### Comments
19
28
 
20
29
  Say it in code. A constraint belongs in a type, a lint rule, or a test. A public item's contract belongs in TSDoc (\`/** */\`) on that item. The only other comments are lint directives that name their rules, \`@ts-expect-error <reason>\`, \`SAFETY: <reason>\` above a type assertion, \`/*!\` license headers, and bundler or formatter directives.
@@ -31,9 +40,9 @@ Hold every test you write or keep to this checklist:
31
40
  - An invariant over many files is a lint rule, not a test.`;
32
41
  const CLEANUP_PROOF = `### Cleanup proof
33
42
 
34
- A behaviour-preserving cleanup PR shows \`antelopejs-api-diff <base-ref>\` passing. Published declarations and built runtime exports stay unchanged; pass \`--allow-added <glob>\` (repeatable, e.g. \`'**/internal/**'\`) to let added entries under that glob pass when their module is \`@internal\`, and copy its "Added (allowed)" list. A comment-only PR shows \`antelopejs-comment-proof <base-ref>\` passing instead of a verifier. Both compare committed HEAD.
43
+ A behaviour-preserving cleanup PR shows \`antelopejs-api-diff <base-ref>\` passing. Published declarations, built runtime exports and the names and signatures a DMS frontend module auto-imports stay unchanged; pass \`--allow-added <glob>\` (repeatable, e.g. \`'**/internal/**'\`) to let added entries under that glob pass when their module is \`@internal\`, and copy its "Added (allowed)" list. Every export under a directory that \`dms.frontend.build.ts\` auto-imports is published, \`@internal\` or not; a helper that must stay private goes under \`app/build/\`. A comment-only PR shows \`antelopejs-comment-proof <base-ref>\` passing instead of a verifier. Both compare committed HEAD.
35
44
 
36
- Copy counts from the proof's base and HEAD table. Never type counts by hand. Keep the command and the committed head beside the copied output. The table counts a lint directive once per rule it names, inline directives included.
45
+ Copy the proof's whole output into the PR body, down to its closing \`<!-- antelopejs-proof ... -->\` line, which stamps the command, base, committed head and a digest. Never type counts by hand. List the lint findings a PR leaves in place by pasting the block \`antelopejs-body-check --findings\` prints and replacing each \`<why>\`. \`antelopejs-body-check <body.md>\` fails an edited or stale proof block, proof output outside one, and a findings line that is not a live diagnostic at HEAD; counts in prose are not checked, so leave them out. The table counts a lint directive once per rule it names, inline directives included.
37
46
 
38
47
  Pass \`--probe <file.cjs>\` to api-diff when changing receivers, positional calls, or modules that no published entry reaches. The same captured script runs against both worktree roots, supplied as \`argv[2]\`, and prints JSON observations. Matching metadata alone does not prove those behaviours.
39
48
 
@@ -44,7 +53,7 @@ Moving a method body into a function keeps how it is called: the same receiver,
44
53
  Verify a boundary against the imports a developer or agent would plausibly write: static and dynamic imports, re-exports, Vue \`src\`, CSS \`@import\`, and worker or child-process entries in normally named files. A construction only an evasion would write, an edit to resolution configuration (\`package.json\` \`browser\`, \`exports\`, \`main\` or \`imports\`, bundler aliases, tsconfig \`paths\`), and a difference observable only by patching private fields or internal methods go under Attention and never block. Public API and ordinary subclass behaviour stay part of the contract.`;
45
54
  const SUPPRESSION_BUDGET = `### Suppression budget
46
55
 
47
- \`guardrails.suppressions.json\` caps the suppressions in authored code: lint directives per rule they name (\`*\` for none), \`@ts-expect-error\`, \`@ts-ignore\` and \`SAFETY:\` comments. A suppression over its ceiling fails: fix the code, or remove another suppression of the same kind. A rule that keeps needing suppressions should be changed in the preset. Never raise or remove a number in that file: the check fails a ceiling higher than on the pull request base, and only the operator approves a raise. A directive disabling \`anti-slop/require-safety-comment-for-type-assertion\` is burn-down debt: remove the assertion, or, where it holds, replace the directive with \`SAFETY: <why it holds>\`, which takes over its room without a raise. After you remove suppressions, run \`pnpm run suppressions:update\` and commit the lowered file.`;
56
+ \`guardrails.suppressions.json\` caps the suppressions in authored code, the repository's own files under \`.agents/\`, \`.claude/\` and the other agent directories included (\`agentFiles\`; only what \`antelopejs-sync\` writes there is skipped): lint directives per rule they name (\`*\` for none), \`@ts-expect-error\`, \`@ts-ignore\` and \`SAFETY:\` comments, and under \`config\` each rule a lint config (\`oxlint.config.*\`, \`.oxlintrc.json\`, \`eslint.config.*\`) switches off or to a warning, keyed by rule and \`files\` glob anchored at the config's directory, so widening or moving a scope is a new ceiling of 0, while narrowing one takes over the room it gives up. Switching a rule off in a config is a suppression too: fix the code its rule reports instead. A suppression over its ceiling fails: fix the code, or remove another suppression of the same kind. A rule that keeps needing suppressions should be changed in the preset. Never raise or remove a number in that file: the check fails a ceiling higher than on the pull request base, and only the operator approves a raise. A directive disabling \`anti-slop/require-safety-comment-for-type-assertion\` is burn-down debt: remove the assertion, or, where it holds, replace the directive with \`SAFETY: <why it holds>\`, which takes over its room without a raise. After you remove suppressions, run \`pnpm run suppressions:update\` and commit the lowered file.`;
48
57
  const SHARED_RULES = [
49
58
  ["Formatting", "oxfmt"],
50
59
  ["Lint findings are errors; no rule warns", "oxlint preset"],
@@ -54,26 +63,37 @@ const SHARED_RULES = [
54
63
  ["Tests import the code under test from local source, not their own package name", "`antelopejs/no-self-import-in-tests`"],
55
64
  ["No assertion that restates a constant", "`antelopejs/no-constant-value-assertion`"],
56
65
  ["No test whose only check is \"is a function\"", "`antelopejs/no-typeof-function-only-test`"],
66
+ ["String-keyed object tables are read through own keys only", "`antelopejs/no-inherited-key-lookup`"],
67
+ ["A type guard checks each member it narrows to; keys with `Object.hasOwn`", "`antelopejs/no-presence-only-type-guard`"],
68
+ ["A type guard checks the nested elements and values it claims", "review; no tool"],
69
+ ["Every file type-aware lint reads is listed by a tsconfig", "`antelopejs/require-tsconfig-include`"],
57
70
  ["Params ≤ 5, function ≤ 120 lines, file ≤ 500 lines, depth ≤ 4, complexity ≤ 20", "`eslint/max-*`, `eslint/complexity`"],
58
- ["Cleanup preserves declarations and built runtime export metadata", "`antelopejs-api-diff <base-ref>`"],
71
+ ["Cleanup preserves declarations, runtime exports and DMS auto-imports", "`antelopejs-api-diff <base-ref>`"],
59
72
  ["Comment-only changes preserve JavaScript emit", "`antelopejs-comment-proof <base-ref>`"],
60
- ["PR-body counts come from tracked code files", "api-diff and comment-proof tables"],
73
+ ["PR-body proof tables are copied unedited from the current head", "`antelopejs-body-check <body.md>`"],
74
+ ["PR-body findings-left lines are live diagnostics at HEAD", "`antelopejs-body-check <body.md>`"],
61
75
  ["Receiver, positional and unpublished-module behaviour", "`antelopejs-api-diff <base-ref> --probe <file.cjs>`"],
62
76
  ["Directive and `SAFETY:` reasons are true of the code", "review; no tool"],
63
77
  ["Evasion-only and patched-internal findings go under Attention", "review; no tool"],
64
78
  ["No-upward rules reject same-tier peers", "review and import probes"],
65
- ["No `@ts-ignore`", "`typescript/ban-ts-comment`"]
79
+ ["No `@ts-ignore`", "`typescript/ban-ts-comment`"],
80
+ ["No once-used type parameter standing in for `unknown`", "`typescript/no-unnecessary-type-parameters`"],
81
+ ["No `any` passed, assigned or returned where a type is declared", "`typescript/no-unsafe-{argument,assignment,return}`"]
66
82
  ];
67
83
  const FULL_RULES = [
68
- ["Files ≤ 20,000 bytes, tests included", "`antelopejs-check-size` (pre-commit)"],
84
+ ["Files ≤ 20,000 bytes, tests and agent files included", "`antelopejs-check-size` (pre-commit)"],
69
85
  ["Suppressions stay within `guardrails.suppressions.json`", "`antelopejs-suppressions` (pre-commit, checks)"],
86
+ ["No lint config switches off a rule to stay under the budget", "`antelopejs-suppressions` (pre-commit, checks)"],
70
87
  ["No added directive disables the `SAFETY:`, comment or test rules", "`antelopejs-suppressions` (pre-commit, checks)"],
71
88
  ["An added suppression gives a specific reason", "`antelopejs-suppressions` (pre-commit, checks)"],
89
+ ["A directive in a file a change touches suppresses something and gives a reason", "`antelopejs-suppressions` (pre-commit, checks)"],
72
90
  ["A block disable is closed in its file", "`antelopejs-suppressions` (pre-commit, checks)"],
73
91
  ["Types check", "`tsc` (pre-push)"],
74
92
  ["No dead files, exports, or dependencies", "knip"],
75
93
  ["Managed files match the pack", "`antelopejs-sync --check`"],
94
+ ["A CI gate reads `needs.<id>` only of jobs in its `needs`", "`antelopejs-sync --check`"],
76
95
  ["Entry-only rules exempt no tracked outsider", "`antelopejs-sync --check`"],
96
+ ["A DMS layer's `build/backend-boundary.ts` is the pack's plugin", "`antelopejs-sync --check`"],
77
97
  ["A test names the wrong implementation it catches", "review; no tool"]
78
98
  ];
79
99
  /** Pads each column the way oxfmt does, so formatting AGENTS.md never reports sync drift. */
@@ -102,6 +122,8 @@ function fullBody(context) {
102
122
  "",
103
123
  `Finish every change with \`pnpm run checks\`. It runs typecheck, lint, format, knip, tests, size, ${context.ratchet ? "ratchet, " : ""}suppressions, and sync, and prints only what failed. The change is done when it prints no failure.`,
104
124
  "",
125
+ ITERATION,
126
+ "",
105
127
  ...pointers(context).flatMap((line) => [line, ""]),
106
128
  "The tools enforce most rules, listed in the table at the end. The sections below hold the rules no tool checks.",
107
129
  "",
@@ -116,7 +138,7 @@ function fullBody(context) {
116
138
  ...context.ratchet ? [
117
139
  "### Debt",
118
140
  "",
119
- "`guardrails.ratchet.json` records the lint findings and oversize files this repository already had. Its numbers only go down. After you remove debt, run `pnpm run ratchet:update` and commit the lowered file. A rule listed there is off for `oxlint`. The ratchet counts it instead, and the pre-commit hook rejects it on every line you add.",
141
+ "`guardrails.ratchet.json` records the lint findings and oversize files this repository already had. Its numbers only go down. After you remove debt, or after a pack upgrade, run `pnpm run ratchet:update` and commit the file: it lowers the numbers and adds only the rules the new pack release enabled, at today's count. Never edit the numbers by hand; CI fails one added or raised against the base. A rule listed there is off for `oxlint`. The ratchet counts it instead, and the pre-commit hook rejects it on every line you add.",
120
142
  ""
121
143
  ] : [],
122
144
  ruleTable([
@@ -156,121 +178,177 @@ function agentsBlock(context) {
156
178
  ].join("\n");
157
179
  }
158
180
  //#endregion
159
- //#region src/guardrails/templates.ts
160
- const PRESET_CONFIGS = [
161
- {
162
- path: "oxlint.config.ts",
163
- legacy: [".oxlintrc.json"],
164
- specifier: "@antelopejs/tooling-configs/oxc/lint",
165
- content: "import { defineConfig } from \"oxlint\";\nimport { antelopePreset } from \"@antelopejs/tooling-configs/oxc/lint\";\n\nexport default defineConfig({\n extends: [antelopePreset()],\n options: { typeAware: true },\n});\n"
166
- },
167
- {
168
- path: "oxfmt.config.ts",
169
- legacy: [".oxfmtrc.json"],
170
- specifier: "@antelopejs/tooling-configs/oxc/fmt",
171
- content: "import { antelopeFmtPreset } from \"@antelopejs/tooling-configs/oxc/fmt\";\n\nexport default antelopeFmtPreset();\n"
172
- },
173
- {
174
- path: "knip.config.ts",
175
- legacy: [
176
- "knip.json",
177
- "knip.jsonc",
178
- ".knip.json"
179
- ],
180
- specifier: "@antelopejs/tooling-configs/knip",
181
- content: "import { antelopeKnipConfig } from \"@antelopejs/tooling-configs/knip\";\n\nexport default antelopeKnipConfig();\n"
181
+ //#region src/guardrails/backend-boundary.ts
182
+ /** Where a DMS frontend layer keeps its backend boundary plugin, relative to the layer. */
183
+ const BACKEND_BOUNDARY_FILE = "build/backend-boundary.ts";
184
+ /** The backend boundary plugin a DMS frontend layer registers in `dms.frontend.build.ts`, for the package that holds the layer. */
185
+ function backendBoundarySource(backendPackage) {
186
+ return `import { existsSync, readFileSync, realpathSync } from 'node:fs'
187
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path'
188
+ import type { DmsVitePluginEntry } from '#dms/frontend-build'
189
+
190
+ type VitePlugin = Extract<DmsVitePluginEntry, { name: string }>
191
+
192
+ const BACKEND_PACKAGE = ${JSON.stringify(backendPackage)}
193
+ const BACKEND_SOURCE = 'src'
194
+ const QUERY_OR_HASH = /[?#].*$/
195
+
196
+ const backendRoots = new Map<string, string | null>()
197
+
198
+ /** Whether a parsed manifest names its package. */
199
+ function isNamedManifest(value: unknown): value is { name: string } {
200
+ return (
201
+ typeof value === 'object' &&
202
+ value !== null &&
203
+ 'name' in value &&
204
+ typeof value.name === 'string'
205
+ )
206
+ }
207
+
208
+ /** The package name a \`package.json\` declares, or \`undefined\`. */
209
+ function packageName(manifest: string): string | undefined {
210
+ try {
211
+ const parsed: unknown = JSON.parse(readFileSync(manifest, 'utf8'))
212
+ return isNamedManifest(parsed) ? parsed.name : undefined
213
+ } catch {
214
+ return undefined
182
215
  }
183
- ];
184
- function presetConfig(current, preset, tools) {
185
- const target = tools.presets[preset.path];
186
- const specifier = target.replaceAll("/", "\\/").replaceAll(".", "\\.");
187
- const imported = new RegExp(`(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*)["']${specifier}["']`);
188
- if (current === void 0) return preset.content.replace(preset.specifier, target);
189
- if (imported.test(current)) return current;
190
- const importLine = preset.content.split("\n").filter((line) => line.includes(preset.specifier)).join("\n").replace(preset.specifier, target);
191
- throw new Error(`${preset.path} does not import its preset. Add \`${importLine}\` and extend that preset, then rerun antelopejs-sync. The file was not replaced.`);
192
- }
193
- function lefthook(current, manager, tools, ratchet = true) {
194
- const exec = execCommand(manager);
195
- const document = parseDocument(current ?? "{}\n");
196
- if (document.errors.length) throw new Error(`lefthook.yml: ${document.errors.map(({ message }) => message).join("; ")}`);
197
- if (!isMap(document.contents)) throw new Error("lefthook.yml must contain a YAML mapping. Merge the guardrail hooks manually and rerun antelopejs-sync.");
198
- if (current === void 0) document.contents.flow = false;
199
- const glob = "*.{js,mjs,cjs,jsx,ts,mts,cts,tsx,vue}";
200
- const hooks = {
201
- "pre-commit": {
202
- "antelopejs-format": {
203
- run: `${exec} oxfmt --no-error-on-unmatched-pattern {staged_files}`,
204
- stage_fixed: true
205
- },
206
- "antelopejs-lint": {
207
- glob,
208
- run: `${exec} oxlint --no-error-on-unmatched-pattern {staged_files}`
209
- },
210
- "antelopejs-size": { run: `${tools.hookPrefix}${tools.commands.size} --staged {staged_files}` },
211
- "antelopejs-ratchet": {
212
- glob,
213
- run: `${tools.hookPrefix}${tools.commands.ratchet} --staged {staged_files}`
214
- },
215
- "antelopejs-suppressions": {
216
- glob,
217
- run: `${tools.hookPrefix}${tools.commands.suppressions} --staged`
216
+ }
217
+
218
+ /** The directory of the backend package that holds \`directory\`, or null. */
219
+ function backendRoot(directory: string): string | null {
220
+ const known = backendRoots.get(directory)
221
+ if (known !== undefined) {
222
+ return known
223
+ }
224
+ const manifest = join(directory, 'package.json')
225
+ const parent = dirname(directory)
226
+ let root: string | null = null
227
+ if (existsSync(manifest)) {
228
+ root = packageName(manifest) === BACKEND_PACKAGE ? directory : null
229
+ } else if (parent !== directory) {
230
+ root = backendRoot(parent)
231
+ }
232
+ backendRoots.set(directory, root)
233
+ return root
234
+ }
235
+
236
+ /**
237
+ * The real path of a resolved module id when it lies under the \`src\`
238
+ * directory of the backend package, or \`undefined\`. The package that owns the
239
+ * file decides, not a path, so the answer is the same in the repository and in
240
+ * the build workspace. Virtual ids and ids that are not files are ignored.
241
+ */
242
+ function backendSourceFile(id: string): string | undefined {
243
+ const path = id.replace(QUERY_OR_HASH, '')
244
+ if (!isAbsolute(path)) {
245
+ return undefined
246
+ }
247
+ let real: string
248
+ try {
249
+ real = realpathSync(path)
250
+ } catch {
251
+ return undefined
252
+ }
253
+ const root = backendRoot(dirname(real))
254
+ if (root === null) {
255
+ return undefined
256
+ }
257
+ return relative(root, real).split(sep)[0] === BACKEND_SOURCE
258
+ ? real
259
+ : undefined
260
+ }
261
+
262
+ /**
263
+ * Fails the build and the dev server when a module of the frontend resolves to
264
+ * a file under the \`src\` of the backend package: the browser reaches the
265
+ * backend only through its HTTP interface. It checks what the whole resolution
266
+ * chain returns, an id marked external included, so an alias is seen through
267
+ * and a symlink the resolver returns is followed to its real path, and it runs
268
+ * before the other plugins (\`enforce: "pre"\`). Vite builds workers with their
269
+ * own plugin list, so the plugin adds itself there too.
270
+ *
271
+ * antelopejs-sync writes this file from \`@antelopejs/tooling-configs\` and
272
+ * restores it on every run: change the plugin in the pack, not here.
273
+ */
274
+ export function backendBoundary(): VitePlugin {
275
+ return {
276
+ ...boundaryCheck(),
277
+ config: () => ({ worker: { plugins: () => [boundaryCheck()] } }),
278
+ }
279
+ }
280
+
281
+ /** The check alone, as a worker build runs it. */
282
+ function boundaryCheck(): VitePlugin {
283
+ return {
284
+ name: \`\${BACKEND_PACKAGE}:backend-boundary\`,
285
+ enforce: 'pre',
286
+ async resolveId(source, importer, options) {
287
+ const resolved = await this.resolve(source, importer, {
288
+ ...options,
289
+ skipSelf: true,
290
+ })
291
+ if (resolved === null) {
292
+ return resolved
218
293
  }
294
+ const file = backendSourceFile(resolved.id)
295
+ if (file === undefined) {
296
+ return resolved
297
+ }
298
+ const from =
299
+ importer === undefined
300
+ ? 'an entry point'
301
+ : importer.replace(QUERY_OR_HASH, '')
302
+ return this.error(
303
+ \`Backend boundary: \${from} imports \${file}, which is under the src of \${BACKEND_PACKAGE}. The frontend reaches the backend only through its HTTP interface.\`,
304
+ )
219
305
  },
220
- "pre-push": { "antelopejs-typecheck": { run: `${manager} run typecheck` } }
221
- };
222
- for (const [hook, commands] of Object.entries(hooks)) {
223
- for (const path of [[hook], [hook, "commands"]]) {
224
- if (!document.hasIn(path)) document.setIn(path, document.createNode({}));
225
- if (!isMap(document.getIn(path))) throw new Error(`lefthook.yml: ${path.join(".")} must be a mapping. Preserve the existing hook and merge its commands before rerunning antelopejs-sync.`);
226
- }
227
- for (const [key, command] of Object.entries(commands)) document.setIn([
228
- hook,
229
- "commands",
230
- key
231
- ], document.createNode(command));
232
306
  }
233
- if (!ratchet) document.deleteIn([
234
- "pre-commit",
235
- "commands",
236
- "antelopejs-ratchet"
237
- ]);
238
- return document.toString({ lineWidth: 0 });
239
- }
240
- const SETUP_SCRIPT = `#!/usr/bin/env bash
241
- set -euo pipefail
242
- cd "$(dirname "$BASH_SOURCE")/.."
243
- export CI=1 COREPACK_ENABLE_DOWNLOAD_PROMPT=0
244
- major="$(tr -d 'v[:space:]' < .nvmrc)"
245
- if [[ "$(node -p 'process.versions.node.split(".")[0]')" != "$major" ]]; then
246
- if command -v fnm >/dev/null 2>&1; then
247
- eval "$(fnm env --shell bash)"
248
- fnm install "$major"
249
- fnm use "$major"
250
- else
251
- export NVM_DIR="\${NVM_DIR:-$HOME/.nvm}"
252
- if [[ ! -s "$NVM_DIR/nvm.sh" ]]; then
253
- git clone --quiet --depth 1 --branch v0.40.3 https://github.com/nvm-sh/nvm.git "$NVM_DIR"
254
- fi
255
- source "$NVM_DIR/nvm.sh" --no-use
256
- nvm install "$major"
257
- nvm use "$major"
258
- fi
259
- fi
260
- pin="$(node -p 'JSON.parse(require("node:fs").readFileSync("package.json", "utf8")).packageManager || "pnpm"')"
261
- manager="\${pin%%@*}"
262
- corepack enable
263
- if [[ "$pin" == *@* ]]; then
264
- corepack prepare "$pin" --activate
265
- fi
266
- case "$manager" in
267
- pnpm) pnpm install --frozen-lockfile ;;
268
- yarn) YARN_ENABLE_IMMUTABLE_INSTALLS=true yarn install --frozen-lockfile ;;
269
- npm) npm ci ;;
270
- bun) bun install --frozen-lockfile ;;
271
- *) printf 'Unsupported package manager %s\\n' "$manager" >&2; exit 1 ;;
272
- esac
307
+ }
273
308
  `;
309
+ }
310
+ /** The syntax tree of `text` without trivia, parentheses or quote style, so a formatter's rewrite compares equal to the original. */
311
+ function formatFreeProgram(text) {
312
+ const parts = [];
313
+ const visit = (node) => {
314
+ if (ts.isParenthesizedExpression(node) || ts.isParenthesizedTypeNode(node)) return void ts.forEachChild(node, visit);
315
+ parts.push(ts.SyntaxKind[node.kind]);
316
+ if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node) || ts.isLiteralExpression(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) parts.push(JSON.stringify(node.text));
317
+ ts.forEachChild(node, visit);
318
+ };
319
+ visit(ts.createSourceFile("backend-boundary.ts", text, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS));
320
+ return parts.join(" ");
321
+ }
322
+ /** The sync plan for every tracked backend boundary plugin under `root`: each one is the pack's plugin for the package that holds its layer, in any formatting. */
323
+ function backendBoundaryArtifacts(root) {
324
+ return execFileSync("git", [
325
+ "ls-files",
326
+ "-z",
327
+ "--",
328
+ `:(glob)**/${BACKEND_BOUNDARY_FILE}`
329
+ ], {
330
+ cwd: root,
331
+ encoding: "utf8"
332
+ }).split("\0").filter((path) => path && dirname(dirname(path)) !== ".").map((path) => {
333
+ const manifest = join(dirname(dirname(dirname(path))), "package.json");
334
+ const name = existsSync(join(root, manifest)) ? parseManifest(readFileSync(join(root, manifest), "utf8")).name : void 0;
335
+ if (!name) return {
336
+ kind: "error",
337
+ path,
338
+ message: `${path} guards the backend package ${manifest}, which has no name. Name that package, then rerun antelopejs-sync.`
339
+ };
340
+ const content = backendBoundarySource(name);
341
+ return formatFreeProgram(existsSync(join(root, path)) ? readFileSync(join(root, path), "utf8") : "") === formatFreeProgram(content) ? {
342
+ kind: "unchanged",
343
+ path
344
+ } : {
345
+ kind: "write",
346
+ path,
347
+ content,
348
+ mode: void 0
349
+ };
350
+ });
351
+ }
274
352
  //#endregion
275
353
  //#region src/guardrails/entry-only.ts
276
354
  const LOAD_RULES = `
@@ -341,6 +419,283 @@ function checkEntryOnlyConfiguration(root) {
341
419
  advisories
342
420
  };
343
421
  }
422
+ //#endregion
423
+ //#region src/guardrails/docs-compat.ts
424
+ const DOCS_COMPAT_START = "<!-- antelopejs-docs-compat:start -->";
425
+ const DOCS_COMPAT_END = "<!-- antelopejs-docs-compat:end -->";
426
+ const DOCS_NODE_START = "<!-- antelopejs-docs-node:start -->";
427
+ const DOCS_NODE_END = "<!-- antelopejs-docs-node:end -->";
428
+ const LOCKFILE = "pnpm-lock.yaml";
429
+ const REQUIREMENTS_HEADING = /^##\s+Requirements\s*$/i;
430
+ const SCOPE = "@antelopejs/";
431
+ const UNRESOLVED = "—";
432
+ const LEGACY_MARKER = /^<!--\s*docs-compat:\s*\.\/package\.json#\w+\s*-->\s*$/;
433
+ const COMPATIBILITY_HEADING = /^##\s+Compatibility\s*$/i;
434
+ const RESOLVED_SECTIONS = [
435
+ "dependencies",
436
+ "optionalDependencies",
437
+ "devDependencies"
438
+ ];
439
+ /** The generated block, rows sorted by package name, formatted as oxfmt leaves it. */
440
+ function compatBlock(rows) {
441
+ const table = [[
442
+ "Package",
443
+ "Supported",
444
+ "Tested with"
445
+ ], ...[...rows].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(({ name, supported, tested }) => [
446
+ `\`${name}\``,
447
+ `\`${supported.replaceAll("|", "\\|")}\``,
448
+ tested === void 0 ? UNRESOLVED : `\`${tested}\``
449
+ ])];
450
+ const widths = [
451
+ 0,
452
+ 1,
453
+ 2
454
+ ].map((column) => Math.max(3, ...table.map((row) => row[column].length)));
455
+ const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
456
+ return [
457
+ DOCS_COMPAT_START,
458
+ "",
459
+ line(table[0]),
460
+ line(widths.map((width) => "-".repeat(width))),
461
+ ...table.slice(1).map(line),
462
+ "",
463
+ DOCS_COMPAT_END,
464
+ ""
465
+ ].join("\n");
466
+ }
467
+ function legacySpanEnd(lines, marker) {
468
+ let index = marker + 1;
469
+ while (index < lines.length && !lines[index].trim()) index++;
470
+ while (index < lines.length && lines[index].trimStart().startsWith("|")) index++;
471
+ while (index < lines.length && !lines[index].trim()) index++;
472
+ return index;
473
+ }
474
+ function replaceLegacyTables(lines, block) {
475
+ const placed = [];
476
+ let replaced = false;
477
+ for (let index = 0; index < lines.length;) {
478
+ if (!LEGACY_MARKER.test(lines[index])) {
479
+ placed.push(lines[index]);
480
+ index++;
481
+ continue;
482
+ }
483
+ if (!replaced) placed.push(...block.split("\n"));
484
+ replaced = true;
485
+ index = legacySpanEnd(lines, index);
486
+ }
487
+ return replaced ? placed : void 0;
488
+ }
489
+ function finalNewline(text) {
490
+ return text.endsWith("\n") ? text : `${text}\n`;
491
+ }
492
+ /** The README with the block in place: replacing the markers, a legacy `docs-compat` table, or under `## Compatibility`. */
493
+ function placeCompatBlock(current, block) {
494
+ const text = current ?? "";
495
+ const start = text.indexOf(DOCS_COMPAT_START);
496
+ const end = text.indexOf(DOCS_COMPAT_END);
497
+ if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-compat markers. Repair or delete them, then rerun antelopejs-sync.");
498
+ if (start !== -1) return `${text.slice(0, start)}${block}${text.slice(end + 35).replace(/^\r?\n/, "")}`;
499
+ const lines = text.split("\n");
500
+ const legacy = replaceLegacyTables(lines, block);
501
+ if (legacy) return finalNewline(legacy.join("\n"));
502
+ const heading = lines.findIndex((line) => COMPATIBILITY_HEADING.test(line));
503
+ if (heading !== -1) {
504
+ let rest = heading + 1;
505
+ while (rest < lines.length && !lines[rest].trim()) rest++;
506
+ return finalNewline([
507
+ ...lines.slice(0, heading + 1),
508
+ "",
509
+ ...block.split("\n"),
510
+ ...lines.slice(rest)
511
+ ].join("\n"));
512
+ }
513
+ const before = text.trimEnd();
514
+ return `${before}${before ? "\n\n" : ""}## Compatibility\n\n${block}`;
515
+ }
516
+ /** The generated Node prerequisite block for an `engines.node` range, formatted as oxfmt leaves it. */
517
+ function nodeBlock(range) {
518
+ return `${DOCS_NODE_START}\n\nThis package requires Node.js \`${range}\`.\n${DOCS_NODE_END}\n`;
519
+ }
520
+ /** The README with the Node block in place: between its markers, under `## Requirements`, or in a new `## Requirements` section at the end. */
521
+ function placeNodeBlock(current, block) {
522
+ const start = current.indexOf(DOCS_NODE_START);
523
+ const end = current.indexOf(DOCS_NODE_END);
524
+ if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-node markers. Repair or delete them, then rerun antelopejs-sync.");
525
+ if (start !== -1) return `${current.slice(0, start)}${block}${current.slice(end + 33).replace(/^\r?\n/, "")}`;
526
+ const lines = current.split("\n");
527
+ const heading = lines.findIndex((line) => REQUIREMENTS_HEADING.test(line));
528
+ if (heading !== -1) {
529
+ let rest = heading + 1;
530
+ while (rest < lines.length && !lines[rest].trim()) rest++;
531
+ return finalNewline([
532
+ ...lines.slice(0, heading + 1),
533
+ "",
534
+ ...block.trimEnd().split("\n"),
535
+ ...rest < lines.length ? ["", ...lines.slice(rest)] : []
536
+ ].join("\n"));
537
+ }
538
+ return `${current.trimEnd()}\n\n## Requirements\n\n${block}`;
539
+ }
540
+ function relative$1(directory, name) {
541
+ return directory ? `${directory}/${name}` : name;
542
+ }
543
+ function isDirectory(root, path) {
544
+ return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
545
+ }
546
+ function subdirectories(root, directory) {
547
+ return readdirSync(join(root, directory), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith(".")).map((entry) => relative$1(directory, entry.name));
548
+ }
549
+ function descendants(root, directory) {
550
+ return subdirectories(root, directory).flatMap((child) => [child, ...descendants(root, child)]);
551
+ }
552
+ function globExpression(pattern) {
553
+ const source = pattern.split("/").map((segment) => segment === "**" ? "(?:.*)" : segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*").replaceAll("?", "[^/]")).join("/").replaceAll("(?:.*)/", "(?:.*/)?");
554
+ return new RegExp(`^${source}$`);
555
+ }
556
+ function expand(root, pattern) {
557
+ let directories = [""];
558
+ for (const segment of pattern.split("/")) if (segment === "**") directories = directories.flatMap((directory) => [directory, ...descendants(root, directory)]);
559
+ else if (/[*?]/.test(segment)) {
560
+ const expression = globExpression(segment);
561
+ directories = directories.flatMap((directory) => subdirectories(root, directory).filter((child) => expression.test(child.slice(child.lastIndexOf("/") + 1))));
562
+ } else directories = directories.map((directory) => relative$1(directory, segment)).filter((directory) => isDirectory(root, directory));
563
+ return directories;
564
+ }
565
+ function normalizePattern(pattern) {
566
+ return pattern.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "");
567
+ }
568
+ function scalarItems(document, path) {
569
+ const node = document.getIn(path, true);
570
+ return isSeq(node) ? node.items.flatMap((item) => isScalar(item) ? [String(item.value)] : []) : [];
571
+ }
572
+ /** pnpm-workspace.yaml `packages`, else package.json `workspaces` as an array or as `{ packages }`; JSON parses as YAML. */
573
+ function workspacePatterns(root) {
574
+ const pnpm = join(root, "pnpm-workspace.yaml");
575
+ if (existsSync(pnpm)) return scalarItems(parseDocument(readFileSync(pnpm, "utf8")), ["packages"]);
576
+ const manifest = parseDocument(readFileSync(join(root, "package.json"), "utf8"));
577
+ return scalarItems(manifest, isMap(manifest.get("workspaces", true)) ? ["workspaces", "packages"] : ["workspaces"]);
578
+ }
579
+ function workspaceDirectories(root) {
580
+ const patterns = workspacePatterns(root);
581
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => globExpression(normalizePattern(pattern.slice(1))));
582
+ const found = /* @__PURE__ */ new Set();
583
+ for (const pattern of patterns.filter((item) => !item.startsWith("!"))) {
584
+ const normalized = normalizePattern(pattern);
585
+ for (const directory of normalized ? expand(root, normalized) : [""]) if (directory && !excluded.some((expression) => expression.test(directory)) && existsSync(join(root, directory, "package.json"))) found.add(directory);
586
+ }
587
+ return [...found].sort();
588
+ }
589
+ function declaredRanges(manifest) {
590
+ const ranges = /* @__PURE__ */ new Map();
591
+ for (const field of [
592
+ manifest.optionalDependencies,
593
+ manifest.dependencies,
594
+ manifest.peerDependencies
595
+ ]) for (const [name, range] of Object.entries(field ?? {})) if (name.startsWith(SCOPE)) ranges.set(name, range);
596
+ return ranges;
597
+ }
598
+ function readManifest(root, directory) {
599
+ return parseManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
600
+ }
601
+ function linkedVersion(root, directory, link) {
602
+ const target = join(root, directory, link);
603
+ return existsSync(join(target, "package.json")) ? parseManifest(readFileSync(join(target, "package.json"), "utf8")).version : void 0;
604
+ }
605
+ function resolvedVersion(root, { document, importer }, directory, name) {
606
+ for (const section of RESOLVED_SECTIONS) {
607
+ const entry = document.getIn([
608
+ "importers",
609
+ importer,
610
+ section,
611
+ name
612
+ ], true);
613
+ const version = isMap(entry) ? entry.get("version", true) : entry;
614
+ if (!isScalar(version)) continue;
615
+ const resolved = String(version.value).split("(")[0];
616
+ return resolved.startsWith("link:") ? linkedVersion(root, directory, resolved.slice(5)) : resolved;
617
+ }
618
+ }
619
+ const UNSHARED_NPMRC = /^\s*shared-workspace-lockfile\s*=\s*false\s*(?:[#;].*)?$/m;
620
+ /** Whether the workspace keeps one root lockfile, or `shared-workspace-lockfile=false` gives each package its own. */
621
+ function sharesLockfile(root) {
622
+ const npmrc = join(root, ".npmrc");
623
+ if (existsSync(npmrc) && UNSHARED_NPMRC.test(readFileSync(npmrc, "utf8"))) return false;
624
+ const workspace = join(root, "pnpm-workspace.yaml");
625
+ return !(existsSync(workspace) && parseDocument(readFileSync(workspace, "utf8")).get("sharedWorkspaceLockfile") === false);
626
+ }
627
+ /** The lockfile path of a package, relative to the root. A shared lockfile is the root's, indexed by the package directory. */
628
+ function lockPath(shared, directory) {
629
+ return shared ? LOCKFILE : relative$1(directory, LOCKFILE);
630
+ }
631
+ function readLock(root, shared, directory) {
632
+ const path = join(root, lockPath(shared, directory));
633
+ return existsSync(path) ? {
634
+ document: parseDocument(readFileSync(path, "utf8")),
635
+ importer: shared ? directory || "." : "."
636
+ } : void 0;
637
+ }
638
+ /** Adds one package's `docs-files` lines and, when it needs one, its README with the generated blocks. */
639
+ function planPackage(root, plan, lock, standard, { directory, ranges, published, node }) {
640
+ const readme = relative$1(directory, "README.md");
641
+ const docs = relative$1(directory, "docs");
642
+ if (!published) return;
643
+ if (ranges.size > 0 || existsSync(join(root, readme))) plan.docsFiles.push(readme);
644
+ if (isDirectory(root, docs)) plan.docsFiles.push(docs);
645
+ const current = existsSync(join(root, readme)) ? readFileSync(join(root, readme), "utf8") : void 0;
646
+ const nodeRange = standard && current !== void 0 ? node : void 0;
647
+ if (ranges.size === 0 && nodeRange === void 0) return;
648
+ const rows = [...ranges].map(([name, supported]) => ({
649
+ name,
650
+ supported,
651
+ tested: lock && resolvedVersion(root, lock, directory, name)
652
+ }));
653
+ try {
654
+ const withRequirements = nodeRange !== void 0 && current !== void 0 ? placeNodeBlock(current, nodeBlock(nodeRange)) : current;
655
+ plan.readmes.push({
656
+ path: readme,
657
+ current,
658
+ content: rows.length > 0 ? placeCompatBlock(withRequirements, compatBlock(rows)) : withRequirements ?? ""
659
+ });
660
+ } catch (error) {
661
+ plan.errors.push(`${readme}: ${error instanceof Error ? error.message : String(error)}`);
662
+ }
663
+ }
664
+ /**
665
+ * Plans the docs-compat block of the root and of every workspace package that is not private and declares an
666
+ * `@antelopejs/*` peer, runtime or optional dependency, and the `docs-files` lines covering the root and every workspace
667
+ * package that is not private.
668
+ * Tested with comes from pnpm-lock.yaml, each package's own when `shared-workspace-lockfile=false`; other package managers get a dash.
669
+ */
670
+ function planDocs(root, manager) {
671
+ const rootManifest = readManifest(root, "");
672
+ const packages = ["", ...workspaceDirectories(root)].map((directory) => {
673
+ const manifest = directory ? readManifest(root, directory) : rootManifest;
674
+ return {
675
+ directory,
676
+ published: !directory || !manifest.private,
677
+ node: manifest.engines?.node,
678
+ ranges: manifest.private ? /* @__PURE__ */ new Map() : declaredRanges(manifest)
679
+ };
680
+ });
681
+ const qualifying = packages.filter(({ ranges }) => ranges.size > 0);
682
+ const plan = {
683
+ readmes: [],
684
+ docsFiles: [],
685
+ errors: [],
686
+ exists: (path) => existsSync(join(root, path))
687
+ };
688
+ const shared = sharesLockfile(root);
689
+ const locks = new Map(packages.map(({ directory }) => [directory, manager === "pnpm" ? readLock(root, shared, directory) : void 0]));
690
+ const missing = manager === "pnpm" ? qualifying.filter(({ directory }) => !locks.get(directory)) : [];
691
+ if (missing.length) {
692
+ for (const path of new Set(missing.map(({ directory }) => lockPath(shared, directory)))) plan.errors.push(`${path} is missing, and the docs-compat block reads Tested with from it: run pnpm install, then rerun antelopejs-sync.`);
693
+ return plan;
694
+ }
695
+ const standard = rootManifest.antelopeJs?.docs?.standard === true;
696
+ for (const item of packages) planPackage(root, plan, locks.get(item.directory), standard, item);
697
+ return plan;
698
+ }
344
699
  /** The kind-specific text of each shared skill. */
345
700
  const KIND_TEXT = {
346
701
  interface: {
@@ -421,7 +776,7 @@ description: ${JSON.stringify(text.description)}
421
776
 
422
777
  ${text.user} Every deterministic step is an \`antelopejs-verify\` command: you choose which journeys to run and judge what they show. Never replace a command with a shell recipe. When a journey you need does not exist, add it to \`verify.config.ts\`, name it in its feature file, then run it.
423
778
 
424
- \`antelopejs-sync\` writes this file and \`package.json\` here, and keeps them in sync. Everything else in \`${folder}/\` is the repository's own layer, which sync never touches.
779
+ \`antelopejs-sync\` writes this file, \`package.json\` and \`tsconfig.json\` here, and keeps them in sync. Everything else in \`${folder}/\` is the repository's own layer, which sync never touches.
425
780
 
426
781
  ## Launch
427
782
 
@@ -466,7 +821,7 @@ ${BIN} clean <run>
466
821
 
467
822
  - \`verify.config.ts\` default-exports a \`VerifyConfig\` from \`@antelopejs/tooling-configs/verify\`:
468
823
  - \`doors\`: one entry per door kind (\`data\`, \`format\`, \`contract\`, \`outbound\`, \`exposure\`, \`publish\`), each \`null\` when it cannot apply or \`{ globs, funnels, containments, why }\`. \`containments\` names the \`feature/journey\` journeys that contain a Data or Format door. Each must fail with that kind's seeded door applied and pass without it: write the journey so one of its checks reads the state the door corrupts.
469
- - \`journeys\`: the repository's journeys by id, each \`{ title, entryPoint, run(context) }\`, using the check helpers the same import exports.
824
+ - \`journeys\`: the repository's journeys by id, each \`{ title, entryPoint, run(context) }\`, using the check helpers the same import exports. A check states what the product must do; an environment that went away is never a failing check. When a journey fails, the harness reruns each service's readiness command, up to four times over about 3.5 s, and looks at every \`ajs project dev\` the journey started, its own readiness probe included. The journey ends NOT VERIFIED, not FAIL, when a service still fails every rerun, an app was killed by SIGKILL, SIGTERM, SIGHUP or SIGINT that the harness did not send, or the app the harness started failed to bind the port the harness gave it (\`EADDRINUSE\` naming that port). An app that exits on its own with an exit code, one that crashes by another signal such as SIGABRT or SIGSEGV, and one that logs \`EADDRINUSE\` for any other port are the product's failure. A break that takes its own service down still reads as an outage: the service stays down, so the journey is NOT VERIFIED and \`seeded\` does not count it. For anything else the journey depends on, such as a process it started with \`context.command\` or an outside endpoint, probe it when a check fails and call \`context.notVerified(reason)\` when it no longer answers.
470
825
  - \`env\`, \`setup\` (commands replacing the build), \`userFacing\` (globs replacing the kind's default) and \`formal\` (formal checks: \`name\`, \`covers\`, \`command\`, \`violation\`, and optionally \`behaviour\` and \`baseCommand\`).
471
826
  ${text.layer}
472
827
  - \`features/<feature>.md\`: frontmatter lists \`covers:\` (source globs), \`docs:\` (pages a verdict judges) and \`journeys:\`, then the sections Sub-features, How to get to it (user POV), Driving it with antelopejs-verify, and Gotchas. \`features/smoke.md\` covers nothing and runs on every verdict; here it runs ${text.smoke}.
@@ -483,7 +838,7 @@ ${BIN} map
483
838
 
484
839
  1. **Run every feature whose \`covers:\` globs the diff touches, plus \`smoke\`.** \`plan\` prints that list as \`run\`.
485
840
  2. **An unmapped surface fails the verdict.** A changed user-facing file no feature covers needs a feature entry, its journeys and its seeded break in the same PR.
486
- 3. **Every registered journey of a feature in \`run\` must have run and passed.** Run whole features. A journey that could not reach the product is NOT VERIFIED, and so is the verdict, whatever else passed: never PASS and never PASS+NOTES.
841
+ 3. **Every registered journey of a feature in \`run\` must have run and passed.** Run whole features. A journey that could not reach the product, or whose environment went away during it, is NOT VERIFIED, and so is the verdict, whatever else passed: never PASS and never PASS+NOTES. Every journey result in the run's evidence counts, also for a feature outside \`run\`: a failed one fails the verdict, because it shows a \`covers:\` glob that misses what the diff broke. A NOT VERIFIED one outside \`run\` is listed under Not verified and caps the result at PASS+NOTES. A journey outside \`run\` that never ran is not required.
487
842
  4. **Docs.** Judge every \`docs:\` page of a touched feature against what the journeys showed. A stale page fails the verdict.
488
843
  5. **Formal checks.** \`${BIN} formal <run>\` runs every formal check of \`verify.config.ts\` that covers the diff, or whose own \`files\` the diff changes, and records it under \`evidence/formal/<name>/\`. For each one it decides, without judgement, whether the diff changed what the covered code does. \`emit\` (the default) compares the structure of the covered files' JavaScript on the base and on HEAD: node kinds, names and literal values, leaving out types, comments, formatting, parentheses and \`export\` keywords. Each use of an imported binding stands for its origin (the resolved module and the imported name), so an import retargeted to another module or alias counts as changed; a function declaration refers to the top-level variables and classes of its own file by file and name, so moving it next to a different variable of the same name counts as changed. Exports are keyed by the origin they export, so a re-export or an \`export { f as run }\` retargeted to another binding counts as changed. Each file must keep its top-level statements and its side-effect imports in order; function declarations, which are hoisted, may move between covered files with their imports. So a type-only edit, a reformat or a moved function declaration counts as unchanged, while reordering statements or moving any other statement counts as changed. \`emit\` judges behaviour, not the public surface: exports are the api-diff's job. \`probe\` runs the check's \`behaviour.command\` with a worktree of each commit and compares what it prints. Then:
489
844
  - a covered check that did not run, or exits non-zero (a tool error, or a check that no longer matches its record), fails the verdict;
@@ -531,7 +886,7 @@ ${BIN} seeded-doors
531
886
  ${BIN} containments
532
887
  \`\`\`
533
888
 
534
- \`seeded\` runs each feature's journeys in a scratch worktree of HEAD without the patch, as the control, and with \`seeded-breaks/<feature>.patch\` applied. It prints \`CAUGHT\` only when a journey that passes in the control fails one of its checks with the patch. Journeys failing in the control and failures without a failing check do not count. \`seeded-doors\` prints \`FLAGGED\` when the path rules flag each patch with its own kind. \`containments\` runs every Data and Format containment journey in a scratch worktree of HEAD without the door, as the control, and with \`seeded-doors/<kind>.patch\` applied. It prints \`CONTAINED\` only when the journey passes in the control and fails one of its checks with the door. \`MISSED\` means it passes with its door, \`UNPROVEN\` that it fails in the control or ends without a failing check, and \`NO-DOOR\` that the kind has no seeded door; the command exits 1 on anything but \`CONTAINED\`.
889
+ \`seeded\` runs each feature's journeys in a scratch worktree of HEAD without the patch, as the control, and with \`seeded-breaks/<feature>.patch\` applied. It prints \`CAUGHT\` only when a journey that passes in the control fails one of its checks with the patch. Journeys failing in the control, failures without a failing check and NOT VERIFIED journeys do not count. A break no journey caught is \`NOT VERIFIED\` when a journey could not reach the product in either run, for example because a service went away, and \`MISSED\` otherwise. The command exits 1 on anything but \`CAUGHT\`. \`seeded-doors\` prints \`FLAGGED\` when the path rules flag each patch with its own kind. \`containments\` runs every Data and Format containment journey in a scratch worktree of HEAD without the door, as the control, and with \`seeded-doors/<kind>.patch\` applied. It prints \`CONTAINED\` only when the journey passes in the control and fails one of its checks with the door. \`MISSED\` means it passes with its door, \`UNPROVEN\` that it fails in the control or ends without a failing check, and \`NO-DOOR\` that the kind has no seeded door; the command exits 1 on anything but \`CONTAINED\`.
535
890
 
536
891
  ## Gotchas
537
892
 
@@ -545,15 +900,36 @@ const SKILL_PACKAGE = `${JSON.stringify({
545
900
  private: true,
546
901
  type: "module"
547
902
  }, null, 2)}\n`;
903
+ /**
904
+ * The skill folder's tsconfig.json: it gives the repository's files there the root compiler options with ES module resolution,
905
+ * so type-aware lint sees real types. The root tsconfig cannot include them: its `rootDir` is usually `src`.
906
+ * `types` names Node: type-aware lint does not discover `@types/node` from this folder, so without it every Node API call
907
+ * in a skill file is error-typed and reported by `typescript/no-unsafe-*` (tooling-configs#93).
908
+ */
909
+ const SKILL_TSCONFIG = `${JSON.stringify({
910
+ extends: "../../../tsconfig.json",
911
+ compilerOptions: {
912
+ rootDir: "../../..",
913
+ types: ["node"],
914
+ module: "nodenext",
915
+ moduleResolution: "nodenext",
916
+ allowImportingTsExtensions: true,
917
+ composite: false,
918
+ noEmit: true
919
+ },
920
+ include: ["**/*.ts"]
921
+ }, null, 2)}\n`;
548
922
  /** Every file of a kind's synced layer, by path relative to the repository root. */
549
923
  function syncedFiles(kind) {
550
- return [{
551
- path: `${skillFolder(kind)}/SKILL.md`,
552
- content: skillText(kind)
553
- }, {
554
- path: `${skillFolder(kind)}/package.json`,
555
- content: SKILL_PACKAGE
556
- }];
924
+ const content = {
925
+ "SKILL.md": skillText(kind),
926
+ "package.json": SKILL_PACKAGE,
927
+ "tsconfig.json": SKILL_TSCONFIG
928
+ };
929
+ return SYNCED_SKILL_FILES.map((file) => ({
930
+ path: `${skillFolder(kind)}/${file}`,
931
+ content: content[file]
932
+ }));
557
933
  }
558
934
  //#endregion
559
935
  //#region src/guardrails/verify-skill.ts
@@ -747,8 +1123,8 @@ const MANAGED_ARTIFACTS = [
747
1123
  {
748
1124
  path: CI_PATH,
749
1125
  profiles: ["full", "template"],
750
- desired: (current) => ({
751
- content: ciWorkflow(current, current === void 0 ? [] : ciNodeCallers(current), current === void 0 ? [] : ciRenovateSyncCallers(current)),
1126
+ desired: (current, context) => ({
1127
+ content: ciWorkflow(current, current === void 0 ? [] : ciNodeCallers(current), current === void 0 ? [] : ciRenovateSyncCallers(current), context.docs),
752
1128
  notes: []
753
1129
  })
754
1130
  },
@@ -762,9 +1138,9 @@ const MANAGED_ARTIFACTS = [
762
1138
  },
763
1139
  {
764
1140
  path: "package.json",
765
- profiles: ["full"],
1141
+ profiles: ["full", "template"],
766
1142
  desired: (current, context) => ({
767
- content: managedPackage(current, context.versions, context),
1143
+ content: context.profile === "full" ? managedPackage(current, context.versions, context) : templatePackage(current, context),
768
1144
  notes: []
769
1145
  })
770
1146
  },
@@ -809,8 +1185,8 @@ const MANAGED_ARTIFACTS = [
809
1185
  {
810
1186
  path: SUPPRESSIONS_FILE,
811
1187
  profiles: ["full"],
812
- desired: (current, context) => ({
813
- content: current ?? context.suppressionBudget,
1188
+ desired: (_current, context) => ({
1189
+ content: context.suppressionBudget,
814
1190
  notes: []
815
1191
  })
816
1192
  }
@@ -854,8 +1230,25 @@ function planSync(current, modes, context) {
854
1230
  });
855
1231
  }
856
1232
  }
1233
+ plan.push(...plannedDocs(context.docs));
857
1234
  return plan;
858
1235
  }
1236
+ function plannedDocs(docs) {
1237
+ if (!docs) return [];
1238
+ return [...docs.errors.map((message) => ({
1239
+ kind: "error",
1240
+ path: "README.md",
1241
+ message
1242
+ })), ...docs.readmes.map(({ path, current, content }) => current === content ? {
1243
+ kind: "unchanged",
1244
+ path
1245
+ } : {
1246
+ kind: "write",
1247
+ path,
1248
+ content,
1249
+ mode: void 0
1250
+ })];
1251
+ }
859
1252
  function repositorySnapshot(root) {
860
1253
  const current = /* @__PURE__ */ new Map();
861
1254
  const modes = /* @__PURE__ */ new Map();
@@ -885,21 +1278,23 @@ function repositoryContext(root, current, profile, verificationSkill) {
885
1278
  const manifest = parseManifest(current.get("package.json") ?? "{}");
886
1279
  const lint = PRESET_CONFIGS[0];
887
1280
  const desiredLint = current.get(lint.path) ?? lint.content;
1281
+ const manager = packageManager(manifest);
888
1282
  return {
889
1283
  profile,
890
1284
  ratchet: current.has(CEILINGS_FILE),
891
- manager: packageManager(manifest),
1285
+ manager,
892
1286
  versions: toolingVersions(),
893
1287
  tools: repositoryTools(manifest),
894
1288
  typeAware: /\btypeAware["']?\s*:\s*true\b/.test(desiredLint),
895
1289
  nuxt: Boolean(manifest.dependencies?.nuxt || manifest.devDependencies?.nuxt || readdirSync(root).some((name) => name.startsWith("nuxt.config."))),
896
1290
  claude: profile === "full" ? claudeProse(root, current) : "",
897
1291
  baseline: "",
898
- suppressionBudget: profile === "full" && !current.has("guardrails.suppressions.json") ? adoptedBudget(root) : "",
1292
+ suppressionBudget: profile === "full" ? adoptedBudget(root, current.get(SUPPRESSIONS_FILE)) : "",
899
1293
  packageName: manifest.name ?? "",
900
1294
  managesCi: current.has(".github/workflows/ci.yml") || !hasChecksWorkflow(root),
901
1295
  verificationSkill,
902
- glossary: ["GLOSSARY.md", "docs/GLOSSARY.md"].find((file) => existsSync(join(root, file)))
1296
+ glossary: ["GLOSSARY.md", "docs/GLOSSARY.md"].find((file) => existsSync(join(root, file))),
1297
+ docs: profile === "full" && current.has("package.json") ? planDocs(root, manager) : void 0
903
1298
  };
904
1299
  }
905
1300
  function writeArtifacts(root, artifacts) {
@@ -927,11 +1322,14 @@ function syncRepository(root, options = {}) {
927
1322
  manifest,
928
1323
  profile
929
1324
  });
1325
+ const writing = planDocsSkills(root);
1326
+ const actions = [...verify.actions, ...writing.actions];
930
1327
  const context = repositoryContext(root, current, profile, verify.verificationSkill);
931
- let plan = planSync(current, modes, context);
1328
+ const boundaries = backendBoundaryArtifacts(root);
1329
+ let plan = [...planSync(current, modes, context), ...boundaries];
932
1330
  const errors = plan.filter((artifact) => artifact.kind === "error").map(({ message }) => message);
933
1331
  const entryOnly = checkEntryOnlyConfiguration(root);
934
- errors.push(...entryOnly.errors, ...verify.errors);
1332
+ errors.push(...entryOnly.errors, ...verify.errors, ...writing.errors);
935
1333
  const notes = plan.flatMap((artifact) => artifact.kind === "migrated" ? artifact.notes : []);
936
1334
  (options.check ? errors : notes).push(...repositoryNotices(root, context));
937
1335
  if (!errors.length && profile === "full" && !options.check && !current.has("guardrails.ratchet.json") && manifest.scripts?.["sync:check"] === void 0) {
@@ -939,21 +1337,24 @@ function syncRepository(root, options = {}) {
939
1337
  const desired = presetConfig(current.get(lint.path), lint, context.tools);
940
1338
  const baseline = measureBaseline(root, desired === current.get(lint.path) ? void 0 : desired);
941
1339
  context.ratchet = !isRetired(baseline);
942
- context.baseline = formatCeilings(baseline);
943
- plan = planSync(current, modes, context);
1340
+ context.baseline = formatCeilings({
1341
+ ...baseline,
1342
+ pack: recordedRelease(void 0)
1343
+ });
1344
+ plan = [...planSync(current, modes, context), ...boundaries];
944
1345
  }
945
1346
  const writes = plan.filter((artifact) => artifact.kind === "write" || artifact.kind === "migrated");
946
1347
  if (!options.check && !errors.length) {
947
1348
  writeArtifacts(root, writes);
948
- applyVerifyActions(root, verify.actions);
1349
+ applyVerifyActions(root, actions);
949
1350
  }
950
1351
  const requiredDependencies = ["lefthook", "knip"];
951
1352
  if (context.typeAware) requiredDependencies.push("oxlint-tsgolint");
952
1353
  const dependenciesAdded = profile === "full" && requiredDependencies.some((name) => !manifest.devDependencies?.[name]);
953
1354
  return {
954
1355
  artifacts: plan,
955
- paths: errors.length ? [] : [...writes, ...verify.actions].map(({ path }) => path),
956
- removed: verify.actions.filter((action) => action.kind === "remove").map(({ path }) => path),
1356
+ paths: errors.length ? [] : [...writes, ...actions].map(({ path }) => path),
1357
+ removed: actions.filter((action) => action.kind === "remove").map(({ path }) => path),
957
1358
  errors,
958
1359
  notes,
959
1360
  verifyNotes: options.check || errors.length ? [] : verify.notes,