@maniumek/suwgate 0.2.0 → 0.4.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.
Files changed (62) hide show
  1. package/README.md +132 -24
  2. package/dist/cli.js +49 -5
  3. package/dist/dev/db.d.ts +1 -1
  4. package/dist/dev/db.js +25 -0
  5. package/dist/dev/logs.js +9 -1
  6. package/dist/dev/settings.d.ts +2 -0
  7. package/dist/dev/settings.js +5 -2
  8. package/dist/eslint/index.js +4 -1
  9. package/dist/gate/check.d.ts +10 -0
  10. package/dist/gate/check.js +94 -18
  11. package/dist/gate/config.d.ts +19 -1
  12. package/dist/gate/config.js +119 -4
  13. package/dist/gate/contract.d.ts +13 -0
  14. package/dist/gate/guardsStep.d.ts +3 -1
  15. package/dist/gate/guardsStep.js +14 -3
  16. package/dist/gate/plan.d.ts +20 -1
  17. package/dist/gate/plan.js +92 -20
  18. package/dist/gate/report.d.ts +1 -0
  19. package/dist/gate/report.js +12 -3
  20. package/dist/gate/repository.d.ts +1 -0
  21. package/dist/gate/repository.js +8 -0
  22. package/dist/gate/runner.js +18 -3
  23. package/dist/guards/comments/hash.js +22 -1
  24. package/dist/guards/dotnet/appsettingsBound.js +29 -2
  25. package/dist/guards/dotnet/index.js +2 -1
  26. package/dist/guards/dotnet/suwbackkitWiring.d.ts +2 -0
  27. package/dist/guards/dotnet/suwbackkitWiring.js +31 -0
  28. package/dist/guards/repository/imagePins.js +1 -1
  29. package/dist/guards/repository/index.js +2 -0
  30. package/dist/guards/repository/justModules.js +28 -10
  31. package/dist/guards/repository/noRawColors.js +1 -1
  32. package/dist/guards/repository/scriptsCalled.js +38 -11
  33. package/dist/guards/repository/suwfrontkitWiring.d.ts +2 -0
  34. package/dist/guards/repository/suwfrontkitWiring.js +52 -0
  35. package/dist/profiles/contract.js +81 -38
  36. package/dist/profiles/criteria.d.ts +1 -0
  37. package/dist/profiles/criteria.js +1 -1
  38. package/dist/profiles/criteriaRan.d.ts +22 -0
  39. package/dist/profiles/criteriaRan.js +152 -0
  40. package/dist/profiles/database.js +11 -4
  41. package/dist/profiles/dotnet.d.ts +2 -0
  42. package/dist/profiles/dotnet.js +39 -6
  43. package/dist/profiles/dotnetGuards.d.ts +3 -0
  44. package/dist/profiles/dotnetGuards.js +54 -0
  45. package/dist/profiles/everyRepository.js +2 -0
  46. package/dist/profiles/index.d.ts +2 -0
  47. package/dist/profiles/index.js +2 -0
  48. package/dist/profiles/library.js +12 -7
  49. package/dist/profiles/node.js +21 -7
  50. package/dist/profiles/presets/knip.d.ts +1 -0
  51. package/dist/profiles/presets/knip.js +4 -2
  52. package/dist/profiles/presets/playwright.d.ts +3 -1
  53. package/dist/profiles/presets/playwright.js +7 -1
  54. package/dist/profiles/reports.d.ts +35 -0
  55. package/dist/profiles/reports.js +60 -0
  56. package/dist/profiles/shell.d.ts +6 -0
  57. package/dist/profiles/shell.js +39 -4
  58. package/dist/profiles/verdict.d.ts +9 -0
  59. package/dist/profiles/verdict.js +124 -0
  60. package/dist/profiles/web.js +25 -6
  61. package/package.json +2 -2
  62. package/schema/suwgate.schema.json +82 -4
package/README.md CHANGED
@@ -8,6 +8,8 @@ One quality gate for every project: `suwgate check` runs the steps a project's p
8
8
  pnpm add -D @maniumek/suwgate
9
9
  pnpm exec suwgate check # the whole gate, the same CI runs
10
10
  pnpm exec suwgate check --quick # the guards, and the quick steps for what changed since master
11
+ pnpm exec suwgate step # the steps of this repository, with their titles
12
+ pnpm exec suwgate step e2e -- --headed -g notes # one step and what it needs; after --, arguments for its tool
11
13
  ```
12
14
 
13
15
  `suwgate.yml` in the repository root says what the repository is and where it departs from the defaults:
@@ -33,11 +35,26 @@ exceptions:
33
35
  - `profiles` (`web`, `library`, `dotnet`, `database`) bring their default steps in their order (the table below). A web-only repository runs nothing of .NET; the database
34
36
  guards run only with `database`.
35
37
  - `steps.add` runs more (`name`, `run`, optionally `title`, `quick`, `after`, `limitSeconds`); `steps.skip` leaves a step out,
36
- always with a `reason`.
38
+ always with a `reason`; `steps.configure` sets the knobs of a profile's step (below).
39
+ - `env` sets variables for every step and `unset` removes them (`*` and `?` match any characters, without regard to case, as .NET
40
+ reads configuration): `unset: [Models__*, LLM_MODEL_*]` keeps every step away from a real model. A step's own `env` and `unset`
41
+ in `steps.configure` come after them.
37
42
  - `quick.limitSeconds` is the budget of `suwgate check --quick` (default 20): the quick gate fails above it. A machine that is slow
38
43
  across the board overrides it with `SUWGATE_QUICK_LIMIT=<seconds>`.
39
44
  - `exceptions` let one target through one guard, always with a `reason`; `suwgate check` counts them in its report, and an
40
- exception that no longer matches anything fails the gate until it is deleted.
45
+ exception that no longer matches anything fails the gate until it is deleted. Two optional fields, for the repository guards
46
+ (the .NET packages match by target only):
47
+ - `message` narrows it to the target's findings whose message contains that text, so a second finding in the same file still
48
+ fails: `{ guard: no-raw-colors, target: Myapp.Web/src/mail.tsx, message: "#1e66f5", reason: … }`.
49
+ - `once: true` makes it a one-time exception, for a finding that goes away once the change is on master, such as an
50
+ owner-approved edit of an applied migration (`migrations-unchanged`). It holds only while master's `suwgate.yml` does not
51
+ have it, that is on the branch that adds it. After the merge it excepts nothing (a later edit of the same script fails
52
+ again) and is never stale, so the first run on master stays green; the report asks to delete it with the next change.
53
+ - A reason shared by many exceptions can be a YAML anchor (`reason: &sdk the SDK implements it`, then `reason: *sdk`), up to
54
+ 10 000 aliases.
55
+ - `guards.skip` turns one whole guard off, always with a `reason`: a repository guard, or a .NET guard (`architecture/*`,
56
+ `database/*`), which `SuwgateGuards.VerifyAll` then does not run and the `dotnet-test` step does not ask evidence for. A
57
+ library, for example: `guards: { skip: [{ guard: architecture/endpoints, reason: a library has no server }] }`.
41
58
  - The schema is in the package, `schema/suwgate.schema.json`. VS Code checks the file as you type with
42
59
  `"yaml.schemas": { "./node_modules/@maniumek/suwgate/schema/suwgate.schema.json": "suwgate.yml" }` in `.vscode/settings.json`.
43
60
  - `settings` configure a guard by its id, for example `dependency-direction: { applications: [Myapp.*] }`,
@@ -83,19 +100,76 @@ exec node_modules/.bin/suwgate hook pre-commit
83
100
  ([docs/adr/0001-suwgate-hook-pre-commit.md](docs/adr/0001-suwgate-hook-pre-commit.md)).
84
101
  - The `hooks` guard checks that these lines are there.
85
102
 
103
+ ## Run one step
104
+
105
+ `suwgate step <id>` runs one step of the plan with the steps it needs (its `after`, transitively, so `pnpm-install` and the
106
+ build come with it) and prints the report `suwgate check` prints, with the same exit code. `--only` runs that step alone,
107
+ `--verbose` lists every step and shows the whole output of a failed one. `suwgate step` alone lists the steps of the repository.
108
+
109
+ - After `--`, arguments go to the step's tool, where the step's command puts them: `suwgate step e2e -- --headed -g notes`
110
+ (Playwright), `suwgate step unit-tests -- -t "saves a note"` (Vitest), `suwgate step dotnet-test -- --filter-class "*Notes*"`
111
+ (xUnit v3 on Microsoft.Testing.Platform: `--filter-class`, `--filter-method`, `--filter-namespace`, `--filter-trait name=value`
112
+ and their `--filter-not-*`). The steps that take them: `unit-tests`, `stories`, `e2e`, `visual`, `consumer-app`, `dotnet-test`;
113
+ any other step refuses `--` and names these.
114
+ - A step named on the command line runs even when `steps.skip` leaves it out of the gate, so a repository that keeps `e2e`
115
+ out of `suwgate check` still runs it with `suwgate step e2e`; the steps it needs keep their skips.
116
+ - A step waits for some steps only for the order of the full gate (`e2e` for `dotnet-test` and `api-contract`, which rebuild the
117
+ server): `suwgate step e2e` does not run them.
118
+ - It is not a gate pass: the Stop hook does not count it, and the next turn still runs the quick gate.
119
+ - The evidence still applies where it makes sense for one step: a test step that ran 0 tests fails (a filter that matches
120
+ nothing is a mistake); `dotnet-test` asks the .NET guards' evidence only when it gets no arguments, because a filtered run
121
+ leaves guards out on purpose; `criteria-ran` reads the reports of the same run, so `suwgate step criteria-ran` runs every
122
+ test step first, and with `--only` it has no reports and fails.
123
+
124
+ A recipe for people: `e2e *args:` then `@suwgate step e2e -- {{ args }}`.
125
+
126
+ ## Configure a step of the profiles
127
+
128
+ ```yaml
129
+ steps:
130
+ configure:
131
+ e2e:
132
+ limitSeconds: 900
133
+ after: [grammar]
134
+ env: { E2E_MODEL: stand-in }
135
+ unset: [Models__*]
136
+ settings:
137
+ before: ["rm -rf .artifacts/e2e/versions"]
138
+ ```
139
+
140
+ `limitSeconds` replaces the step's ceiling, `after` adds steps it waits for (a step of the profiles or of `steps.add`), `env`
141
+ and `unset` change its environment after the top-level ones, and `settings` go to the step, checked by the step's own schema.
142
+ A step that `steps.skip` names cannot be configured, and an added step takes these fields in `steps.add`. There is no `run`:
143
+ replacing a step's command is `steps.skip` with the reason plus `steps.add`, so the report shows that the profile's step did
144
+ not run.
145
+
146
+ The settings of the steps:
147
+
148
+ | Step | Setting | What it does |
149
+ | :------------- | :------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
150
+ | `e2e` | `before: [<command>, …]` | commands run in the repository root, in order, after the database is fresh and before Playwright (clear a folder the server keeps, build what the `webServer` runs with `--no-build`) |
151
+ | `dotnet-test` | `excludeTraits: [live=true]` | tests with one of these traits are outside the gate (they call a real model or service): `--filter-not-trait`, and `criteria-ran` names a criterion only they name, with the fix |
152
+ | `api-contract` | `contract: Myapp.Server/openapi.json` | where the contract is, relative to the dotnet directory (default `contract/openapi.json`); `api-version` compares the same file and reads its version from the `package.json` beside it |
153
+ | `api-version` | `breaking: never` | every breaking change fails; the default, `major`, lets one through with a new major version |
154
+
155
+ A database that is not the compose service `db` (a `docker run` container that also creates a database per tenant) is named
156
+ once, in the `dev` section: `dev.database.up` and `dev.database.psql` ([docs/dev.md](docs/dev.md)). `suwgate dev db up`, the
157
+ `database-up` step and the `e2e` step run them instead of docker compose; in CI, the `database-command` input of `gate.yml`
158
+ ([docs/ci.md](docs/ci.md)).
159
+
86
160
  ### The steps of the profiles
87
161
 
88
162
  Each step looks where its profile lives (`directories`) and passes with nothing to check when the repository has nothing for it.
89
163
 
90
- | Profile | Steps |
91
- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
92
- | `web`, `library` | `pnpm-install` (only without `node_modules`), `typecheck` (every `tsconfig*.json` but `tsconfig.build.json`), `lint`, `unit-tests` (the Vitest project `unit` when the config names one), `format`, `knip` |
93
- | `web` | `e2e`: `playwright test -c e2e/playwright.config.ts`, after the build, the database and the .NET tests; with a `dev` section, first the checkout's variables (`suwgate dev checkout-env`) and a fresh, empty `E2E_DATABASE` (`dev db up`, then drop and create it); Playwright's `webServer` starts and stops the server and the web app |
94
- | `library` | `stories` (with `.storybook/`), `publint`, `attw`, `consumer-app` (packs the library into a copy of `gate/consumer/app`, builds it, runs `gate/consumer/playwright.config.ts`), `visual` (`visual/playwright.config.ts` in the Playwright image of the installed `@playwright/test`), `changeset` |
95
- | `dotnet` | `dotnet-build`, `dotnet-format`, `dotnet-test` (with a `dev` section, under the checkout's variables, so two worktrees never share a test database; `--quick`: only the test projects that use `Suwgate.Architecture` or `Suwgate.Database`); every .NET step leaves no idle MSBuild worker or build server behind |
96
- | `dotnet`, `web` | with `contract/openapi.json`: `api-contract` (the contract and `src/api/openapi.d.ts` of the web app regenerated from the server's project, the one that references `Microsoft.Extensions.ApiDescription.Server`), `api-version` (oasdiff against master; a break needs a new major version in `contract/package.json`), `contract-pins` (every test tagged `contract <name>@<version>` names a version) |
97
- | `database` | `database-up`: `docker compose --profile db up -d --wait db`, not in CI |
98
- | every repository | `compose` (with a compose file), `criteria`, `shellcheck`, `gitleaks` |
164
+ | Profile | Steps |
165
+ | :--------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
+ | `web`, `library` | `pnpm-install` (only without `node_modules`), `typecheck` (every `tsconfig*.json` but `tsconfig.build.json`, with `tsc --showConfig`), `lint` (with `eslint --print-config`), `unit-tests` (the Vitest project `unit` when the config names one; 0 tests fail), `format`, `knip` |
167
+ | `web` | `e2e`: `playwright test -c e2e/playwright.config.ts`, after the build and the database (and, in the full gate, the .NET tests and the contract); with a `dev` section, first the checkout's variables (`suwgate dev checkout-env`) and a fresh, empty `E2E_DATABASE` (`dev db up`, then drop and create it), then `settings.before`; Playwright's `webServer` starts and stops the server and the web app |
168
+ | `library` | `stories` (with `.storybook/`), `publint`, `attw`, `consumer-app` (packs the library into a copy of `gate/consumer/app`, builds it, runs `gate/consumer/playwright.config.ts`), `visual` (`visual/playwright.config.ts` in the Playwright image of the installed `@playwright/test`), `changeset` |
169
+ | `dotnet` | `dotnet-build`, `dotnet-format`, `dotnet-test` (fails on 0 tests and unless every .NET guard of the profiles ran; with a `dev` section, under the checkout's variables, so two worktrees never share a test database; `--quick`: only the test projects that use `Suwgate.Architecture` or `Suwgate.Database`); every .NET step leaves no idle MSBuild worker or build server behind |
170
+ | `dotnet`, `web` | with `contract/openapi.json` (or `settings.contract`): `api-contract` (the contract and `src/api/openapi.d.ts` of the web app regenerated from the server's project, the one that references `Microsoft.Extensions.ApiDescription.Server`), `api-version` (oasdiff against master; a break needs a new major version in the `package.json` beside the contract, or fails with `breaking: never`), `contract-pins` (every test tagged `contract <name>@<version>` names a version) |
171
+ | `database` | `database-up`: `docker compose --profile db up -d --wait db`, or `dev.database.up`; not in CI, where the workflow starts it |
172
+ | every repository | `compose` (with a compose file), `criteria`, `shellcheck`, `gitleaks` |
99
173
 
100
174
  `criteria` runs `vdoc.py criteria` of the suwagent plugin, pinned by commit and SHA-256: every acceptance criterion of the specs in
101
175
  `docs/visual/spec/` is named by a guardrail. The kinds of guardrail come with the profiles; `criteria.json` in the repository root
@@ -121,14 +195,14 @@ adds the repository's own (`{ "kinds": [{ "kind", "paths", "how" }] }`, optional
121
195
 
122
196
  The configs of the tools the steps run extend suwgate's, so an application keeps only its own paths:
123
197
 
124
- | Tool | The application's file |
125
- | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
126
- | Prettier | `.prettierrc.json`: `"@maniumek/suwgate/prettier"` (with a plugin: spread it in `prettier.config.js`) |
127
- | TypeScript | `{ "extends": "@maniumek/suwgate/tsconfig/browser", "include": ["src"] }`; `tsconfig/node` for the configs, scripts and tests run by Node; `tsconfig/strict` for the options alone |
128
- | knip | `knip.config.ts`: `export { default } from "@maniumek/suwgate/knip"`, or `knip({ entry: [...] })`; it ignores the tools the steps run and the generated API types, and reads the steps' Playwright configs |
129
- | Vitest | `unitTests({ environment: "jsdom" })` and `storyTests({ plugin, provider })` from `@maniumek/suwgate/vitest`: the projects `unit` and `stories` the steps run |
130
- | Playwright | `defineConfig(e2eTests({ use: { baseURL }, webServer }))` or `defineConfig(visualTests())` from `@maniumek/suwgate/playwright` |
131
- | ESLint | `app({ root, features, shared, sharedImports, storage })` from `@maniumek/suwgate/eslint`: a feature imports itself and the shared folders, a shared folder only itself and what `sharedImports` allows it (`[["design", "api"]]`: design may import api) |
198
+ | Tool | The application's file |
199
+ | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
200
+ | Prettier | `.prettierrc.json`: `"@maniumek/suwgate/prettier"` (with a plugin: spread it in `prettier.config.js`) |
201
+ | TypeScript | `{ "extends": "@maniumek/suwgate/tsconfig/browser", "include": ["src"] }`; `tsconfig/node` for the configs, scripts and tests run by Node; `tsconfig/strict` for the options alone |
202
+ | knip | `knip.config.ts`: `export { default } from "@maniumek/suwgate/knip"`, or `knip({ entry: [...] })`; it ignores the tools the steps run (Prettier among them) and the issues of the generated API types, and reads the steps' Playwright configs |
203
+ | Vitest | `unitTests({ environment: "jsdom" })` and `storyTests({ plugin, provider })` from `@maniumek/suwgate/vitest`: the projects `unit` and `stories` the steps run |
204
+ | Playwright | `defineConfig(e2eTests({ use: { baseURL }, webServer, reporter }))` or `defineConfig(visualTests())` from `@maniumek/suwgate/playwright`; `e2eTests` keeps the app's `reporter` (an HTML report in CI) and adds the JSON report the `e2e` step reads |
205
+ | ESLint | `app({ root, features, shared, sharedImports, storage })` from `@maniumek/suwgate/eslint`: a feature imports itself and the shared folders, a shared folder only itself and what `sharedImports` allows it (`[["design", "api"]]`: design may import api); the import resolver reads the first of `projects`, the one of `src/` (or a root tsconfig with references) |
132
206
 
133
207
  ### What the config files must say
134
208
 
@@ -154,15 +228,49 @@ The configs of the tools the steps run extend suwgate's, so an application keeps
154
228
 
155
229
  ### The .NET guards
156
230
 
157
- In the xUnit tests of a .NET application:
231
+ One xUnit test in the gate's test project runs every guard of the `dotnet` and `database` profiles:
158
232
 
159
233
  ```csharp
160
- [Fact]
161
- public void Every_interface_has_two_implementations() =>
162
- Guards.Verify(InterfacesHaveTwoImplementations.Of(typeof(ServerApp).Assembly));
234
+ public sealed class GuardTests
235
+ {
236
+ [Fact]
237
+ public void Every_guard_of_suwgate_passes() =>
238
+ SuwgateGuards.VerifyAll(
239
+ new GuardInputs { Production = [typeof(ServerApp).Assembly], Tests = [typeof(GuardTests).Assembly], Server = typeof(ServerApp) },
240
+ new DatabaseProfile()
241
+ );
242
+ }
163
243
  ```
164
244
 
165
- `Guards.Verify` reads the exceptions of that guard from the nearest `suwgate.yml` above the test's output folder.
245
+ `VerifyAll` reads the nearest `suwgate.yml` above the test's output folder (profiles, `guards.skip`, exceptions, settings), finds
246
+ the solution, `layers.json`, the sources and the migrations itself, and takes from the test only what it cannot find
247
+ ([dotnet/Suwgate.Architecture/README.md](dotnet/Suwgate.Architecture/README.md) lists the inputs).
248
+
249
+ ### What the gate proves ran
250
+
251
+ A check counts only when the tool shows it ran, not because a file or a line of text is there:
252
+
253
+ - The .NET guards: `dotnet-test` points `SUWGATE_EVIDENCE` at a fresh folder of this gate run, and every guard that runs (through
254
+ `VerifyAll` or `Guards.Verify`) writes its id and outcome there. The step fails unless every guard of the profiles that
255
+ `guards.skip` does not name is in it, so a deleted guard test, a `[Fact(Skip = …)]` or a filtered-out one fails the gate.
256
+ - Zero tests fail: `unit-tests`, `stories` (Vitest, its JSON report), `e2e` (Playwright, its JSON report) and `dotnet-test`
257
+ (`--zero-tests-policy strict` of Microsoft.Testing.Platform, and xUnit's XML report) fail when the tool ran no test, also when
258
+ every test was skipped. A repository with truly no tests for a profile skips the step in `suwgate.yml` with a reason.
259
+ - `typecheck` reads `tsc --showConfig` of every tsconfig it checks: the strict options of the suwgate preset must be in effect, so
260
+ an override that turns one off fails, naming the option.
261
+ - `lint` reads `eslint --print-config` of a source file of `src/`: `suwgate/no-comments` and `boundaries/dependencies` must be
262
+ errors there.
263
+ - `criteria-ran`, after the test steps: every acceptance criterion of a living spec (`docs/visual/spec/`) that a test names
264
+ (`[Trait("criterion", "<id>")]`, a title or story name `"<id>: …"`) must have a test naming it that ran and passed in this run,
265
+ by the reports of xUnit, Vitest and Playwright. A criterion named only by tests of a step `steps.skip` names is not checked; one
266
+ named only by tests that `excludeTraits` of `dotnet-test` keeps out of the gate fails with the fix: a gate test with a stand-in.
267
+ - The kits are wired, not only installed: `suwbackkit-wiring` (dotnet) asks a web server that references `Suwbackkit.Server` to
268
+ call `AddServerDefaults` and `MapServerDefaults`; `suwfrontkit-wiring` (web, library) asks an app whose `package.json` depends
269
+ on `@maniumek/suwfrontkit` to load `@maniumek/suwfrontkit/theme.css` from the main module of its `index.html`, or from a
270
+ stylesheet that module imports. Both read the sources: the evidence (a run hitting `/health`, a built stylesheet with the
271
+ kit's tokens) needs a running server or a production build, which the gate does not have in every repository.
272
+ - The reports live in a temporary folder of the run (`SUWGATE_RUN`), deleted when `suwgate check` ends. `dotnet-test` asks xUnit
273
+ for its XML report (`--report-xunit-xml`), so every .NET test project tests with xUnit v3.
166
274
 
167
275
  `suwgate dev db|logs|smoke|server|tmux|checkout-env` runs the local stack of the template (database, logs, smoke test, server, tmux
168
276
  session, worktree databases) from a `dev` section of `suwgate.yml`: [docs/dev.md](docs/dev.md).
package/dist/cli.js CHANGED
@@ -1,21 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
- import { check } from "./gate/check.js";
4
+ import { check, step } from "./gate/check.js";
5
5
  import { dev } from "./dev/index.js";
6
6
  import { loadConfig } from "./gate/config.js";
7
7
  import { PROFILES } from "./gate/contract.js";
8
8
  import { repositoryRoot } from "./gate/repository.js";
9
9
  import { guards } from "./guards/index.js";
10
- import { stepsFor } from "./profiles/index.js";
10
+ import { dotnetGuards, stepsFor, verdict } from "./profiles/index.js";
11
11
  import { guardEdit } from "./session/guardEdit.js";
12
12
  import { preCommit, runTool } from "./session/preCommit.js";
13
13
  import { stop } from "./session/stop.js";
14
- const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate hook <guard-edit|stop|pre-commit> | suwgate dev <command> | suwgate --help | --version
14
+ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|stop|pre-commit> | suwgate dev <command> | suwgate --help | --version
15
15
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
16
16
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
17
17
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
18
- --verbose list every step with its time, also when all pass
18
+ --verbose list every step with its time, also when all pass, and the whole output of a failed step
19
+ suwgate step the steps of this repository, with their titles and the tool that takes -- arguments
20
+ suwgate step <id> one step and the steps it needs (after, transitively), with the same report; not a gate
21
+ pass: the Stop hook does not count it. --only: that step alone. After --, arguments for the
22
+ step's tool: suwgate step e2e -- --headed -g notes (Playwright), suwgate step unit-tests --
23
+ -t "name" (Vitest), suwgate step dotnet-test -- --filter-method "*Notes*" (xUnit v3)
19
24
  suwgate hook guard-edit Claude Code PreToolUse hook: refuses an agent's edit of the gate and of generated files
20
25
  (ALLOW_GATE_EDIT=1 lifts the gate part for one session); only files of its own project
21
26
  (CLAUDE_PROJECT_DIR, else the git checkout it runs in), with the lists of its profiles
@@ -23,9 +28,12 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate hook <guard-
23
28
  suwgate hook pre-commit git pre-commit hook: gitleaks on the staged changes, then the quick gate
24
29
  suwgate dev <db|logs|smoke|server|tmux|checkout-env>
25
30
  the local stack of the repository (the dev section of suwgate.yml); suwgate dev --help
31
+ suwgate verdict <tests|guards|tsconfig|eslint> ...
32
+ what the steps call after their tool: did tests run, did the .NET guards run (evidence),
33
+ are the strict compiler options and the eslint rules in effect
26
34
  Every step has a ceiling (SUWGATE_STEP_LIMIT seconds overrides them all). A step whose tool is missing is SKIP,
27
35
  and a SKIP fails the gate when CI is set. Exit code: 0 green, 1 red, 2 a usage or suwgate.yml problem.`;
28
- const catalog = { guards, stepsFor };
36
+ const catalog = { guards, dotnetGuards, stepsFor };
29
37
  function version() {
30
38
  const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
31
39
  return manifest.version;
@@ -45,9 +53,45 @@ function readInput() {
45
53
  return "";
46
54
  }
47
55
  }
56
+ async function runStep(argv) {
57
+ const separator = argv.indexOf("--");
58
+ const own = separator === -1 ? argv : argv.slice(0, separator);
59
+ const args = separator === -1 ? [] : argv.slice(separator + 1);
60
+ if (own.includes("--help")) {
61
+ console.log(USAGE);
62
+ return 0;
63
+ }
64
+ const { values, positionals } = parseArgs({
65
+ args: [...own],
66
+ allowPositionals: true,
67
+ strict: true,
68
+ options: { only: { type: "boolean" }, verbose: { type: "boolean" } },
69
+ });
70
+ if (positionals.length > 1)
71
+ throw new Error(`suwgate step takes one step id, not ${positionals.join(" ")}`);
72
+ const result = await step({
73
+ cwd: process.cwd(),
74
+ id: positionals[0],
75
+ only: values.only === true,
76
+ args,
77
+ verbose: values.verbose === true,
78
+ env: process.env,
79
+ catalog,
80
+ });
81
+ (result.exitCode === 0 ? console.log : console.error)(result.text);
82
+ return result.exitCode;
83
+ }
48
84
  async function main(argv) {
49
85
  if (argv[0] === "dev")
50
86
  return dev(argv.slice(1));
87
+ if (argv[0] === "step")
88
+ return runStep(argv.slice(1));
89
+ if (argv[0] === "verdict") {
90
+ const result = verdict(argv.slice(1));
91
+ if (result.text !== "")
92
+ console.error(result.text);
93
+ return result.exitCode;
94
+ }
51
95
  const { values, positionals } = parseArgs({
52
96
  args: [...argv],
53
97
  allowPositionals: true,
package/dist/dev/db.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type Exec, type Io } from "./process.ts";
2
2
  import type { DevSettings } from "./settings.ts";
3
- export declare const DB_USAGE = "usage: suwgate dev db up | down | reset [--yes] | psql [psql args] | logs | status\nThe local PostgreSQL for development and tests: the database service of the compose file (dev.compose), published on the\nloopback, its data in a named volume that survives down. Needs docker (on Fedora: podman behind the docker command).\n up start it (and dev.compose.extraServices), or leave it running, and wait until it answers; prints its address\n down stop it, the data stays in the volume\n reset delete the containers and the volume with all the data, after asking (--yes does not ask)\n psql psql in it as its owner in the app's database, e.g. suwgate dev db psql -d postgres -c \"select 1\"\n logs follow its log\n status what runs";
3
+ export declare const DB_USAGE = "usage: suwgate dev db up | down | reset [--yes] | psql [psql args] | logs | status\nThe local PostgreSQL for development and tests: the database service of the compose file (dev.compose), published on the\nloopback, its data in a named volume that survives down. Needs docker (on Fedora: podman behind the docker command).\nA repository whose database is not a compose service names its own commands in dev.database.up and dev.database.psql:\nup and psql run them, the other commands are its own.\n up start it (and dev.compose.extraServices), or leave it running, and wait until it answers; prints its address\n down stop it, the data stays in the volume\n reset delete the containers and the volume with all the data, after asking (--yes does not ask)\n psql psql in it as its owner in the app's database, e.g. suwgate dev db psql -d postgres -c \"select 1\"\n logs follow its log\n status what runs";
4
4
  export type DbCommand = {
5
5
  kind: "up" | "down" | "logs" | "status";
6
6
  } | {
package/dist/dev/db.js CHANGED
@@ -3,6 +3,8 @@ import { Failure, UsageError } from "./process.js";
3
3
  export const DB_USAGE = `usage: suwgate dev db up | down | reset [--yes] | psql [psql args] | logs | status
4
4
  The local PostgreSQL for development and tests: the database service of the compose file (dev.compose), published on the
5
5
  loopback, its data in a named volume that survives down. Needs docker (on Fedora: podman behind the docker command).
6
+ A repository whose database is not a compose service names its own commands in dev.database.up and dev.database.psql:
7
+ up and psql run them, the other commands are its own.
6
8
  up start it (and dev.compose.extraServices), or leave it running, and wait until it answers; prints its address
7
9
  down stop it, the data stays in the volume
8
10
  reset delete the containers and the volume with all the data, after asking (--yes does not ask)
@@ -76,8 +78,31 @@ export function askOnTerminal(question) {
76
78
  lines.close();
77
79
  });
78
80
  }
81
+ function ownCommand(settings, command) {
82
+ const { up, psql } = settings.database;
83
+ if (up === null && psql === null)
84
+ return null;
85
+ if (command.kind === "up" && up !== null)
86
+ return ["bash", "-c", `{ ${up}\n} >&2`];
87
+ if (command.kind === "psql" && psql !== null)
88
+ return ["bash", "-c", `${psql} "$@"`, "suwgate", ...command.args];
89
+ const named = [up === null ? "" : `dev.database.up (${up})`, psql === null ? "" : `dev.database.psql (${psql})`].filter(Boolean);
90
+ throw new Failure(`suwgate dev db ${command.kind}: this repository runs its database with its own commands, ${named.join(" and ")} in suwgate.yml, so ${command.kind} is the repository's own too: run it there`, 2);
91
+ }
92
+ async function runOwn(argv, command, environment) {
93
+ const { status } = await environment.exec(argv, { cwd: environment.settings.root });
94
+ if (status !== 0 && command.kind === "up") {
95
+ throw new Failure(`suwgate dev db: the database did not start: ${environment.settings.database.up ?? ""} failed (exit ${status})`);
96
+ }
97
+ if (status === 0 && command.kind === "up")
98
+ environment.io.out(databaseUrl(environment.settings));
99
+ return status;
100
+ }
79
101
  export async function runDb(command, environment) {
80
102
  const { settings, exec, io } = environment;
103
+ const own = ownCommand(settings, command);
104
+ if (own !== null)
105
+ return runOwn(own, command, environment);
81
106
  if (command.kind === "reset" && !command.yes) {
82
107
  const answer = await environment.ask("Delete the local database with all its data? [y/N] ");
83
108
  if (answer.trim() !== "y") {
package/dist/dev/logs.js CHANGED
@@ -58,6 +58,14 @@ function field(record, name) {
58
58
  const value = record[name];
59
59
  return typeof value === "string" ? value : "";
60
60
  }
61
+ function traceIdOf(record) {
62
+ const scopes = Array.isArray(record["Scopes"]) ? record["Scopes"] : [];
63
+ const inScope = scopes
64
+ .filter((scope) => typeof scope === "object" && scope !== null)
65
+ .map((scope) => field(scope, "TraceId"))
66
+ .find((traceId) => traceId !== "");
67
+ return field(record, "TraceId") || (inScope ?? "");
68
+ }
61
69
  function oneLine(value) {
62
70
  return value.replace(/\s*[\r\n]+\s*/g, " ");
63
71
  }
@@ -76,7 +84,7 @@ export function formatLine(line, command) {
76
84
  return null;
77
85
  if (!command.all && !SHOWN_LEVELS.includes(level))
78
86
  return null;
79
- const traceId = field(record, "TraceId");
87
+ const traceId = traceIdOf(record);
80
88
  const exception = field(record, "Exception").split(/[\r\n]/, 1)[0] ?? "";
81
89
  const shownException = exception === "" ? "" : ` | ${exception.slice(0, EXCEPTION_LIMIT)}`;
82
90
  const shownTrace = traceId === "" ? "" : ` trace=${traceId}`;
@@ -25,6 +25,8 @@ export interface DevSettings {
25
25
  user: string;
26
26
  password: string;
27
27
  name: string;
28
+ up: string | null;
29
+ psql: string | null;
28
30
  };
29
31
  serverProject: string | null;
30
32
  webDirectory: string | null;
@@ -12,10 +12,11 @@ export const DEFAULT_SMOKE_CHECKS = [
12
12
  },
13
13
  ];
14
14
  const NAME = /^[a-z][a-z0-9-]*$/;
15
+ const MAX_ALIASES = 10_000;
15
16
  const ROOT_KEYS = ["name", "portOffset", "ports", "compose", "database", "server", "smoke"];
16
17
  const PORT_KEYS = Object.keys(BASE_PORTS);
17
18
  const COMPOSE_KEYS = ["file", "profile", "databaseService", "serverService", "extraServices"];
18
- const DATABASE_KEYS = ["user", "password", "name"];
19
+ const DATABASE_KEYS = ["user", "password", "name", "up", "psql"];
19
20
  const SERVER_KEYS = ["project", "logFile"];
20
21
  const SMOKE_KEYS = ["checks"];
21
22
  const CHECK_KEYS = ["path", "expect", "hint"];
@@ -124,6 +125,8 @@ export function resolveSettings(raw, directories, root) {
124
125
  user,
125
126
  password: text(databaseRaw, "password", "dev.database", user, problems),
126
127
  name: text(databaseRaw, "name", "dev.database", name, problems),
128
+ up: databaseRaw["up"] === undefined ? null : text(databaseRaw, "up", "dev.database", "", problems),
129
+ psql: databaseRaw["psql"] === undefined ? null : text(databaseRaw, "psql", "dev.database", "", problems),
127
130
  },
128
131
  serverProject: typeof serverRaw["project"] === "string" ? serverRaw["project"] : stringOrNull(directories["dotnet"]),
129
132
  webDirectory: stringOrNull(directories["web"]),
@@ -142,7 +145,7 @@ export function loadSettings(root) {
142
145
  const file = path.join(root, "suwgate.yml");
143
146
  if (!existsSync(file))
144
147
  throw new Failure(`no suwgate.yml in ${root}: suwgate dev reads its settings from the dev section there`, 2);
145
- const data = (parse(readFileSync(file, "utf8")) ?? {});
148
+ const data = (parse(readFileSync(file, "utf8"), { maxAliasCount: MAX_ALIASES }) ?? {});
146
149
  const directories = typeof data["directories"] === "object" && data["directories"] !== null ? data["directories"] : {};
147
150
  return resolveSettings(data["dev"], directories, root);
148
151
  }
@@ -35,6 +35,9 @@ export function strict(options) {
35
35
  extends: [tseslint.configs.disableTypeChecked],
36
36
  });
37
37
  }
38
+ function sourceProject(options) {
39
+ return path.resolve(options.root, options.projects?.[0] ?? "./tsconfig.json");
40
+ }
38
41
  function featureBoundaries(options) {
39
42
  const shared = options.shared ?? [];
40
43
  return {
@@ -43,7 +46,7 @@ function featureBoundaries(options) {
43
46
  settings: {
44
47
  "boundaries/root-path": options.root,
45
48
  "import/resolver": {
46
- typescript: { project: (options.projects ?? ["./tsconfig.json"]).map((project) => path.resolve(options.root, project)) },
49
+ typescript: { project: sourceProject(options) },
47
50
  node: { extensions: [".ts", ".tsx"] },
48
51
  },
49
52
  "boundaries/elements": [
@@ -6,8 +6,18 @@ export interface CheckOptions {
6
6
  env: NodeJS.ProcessEnv;
7
7
  catalog: Catalog;
8
8
  }
9
+ export interface StepOptions {
10
+ cwd: string;
11
+ id: string | undefined;
12
+ only: boolean;
13
+ args: readonly string[];
14
+ verbose: boolean;
15
+ env: NodeJS.ProcessEnv;
16
+ catalog: Catalog;
17
+ }
9
18
  export interface CheckResult {
10
19
  exitCode: number;
11
20
  text: string;
12
21
  }
13
22
  export declare function check(options: CheckOptions): Promise<CheckResult>;
23
+ export declare function step(options: StepOptions): Promise<CheckResult>;
@@ -1,7 +1,12 @@
1
- import { loadConfig } from "./config.js";
2
- import { plan } from "./plan.js";
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { parse } from "yaml";
5
+ import { loadConfig, MAX_ALIASES } from "./config.js";
6
+ import { sameException } from "./guardsStep.js";
7
+ import { allSteps, GUARDS_STEP, listSteps, plan } from "./plan.js";
3
8
  import { report } from "./report.js";
4
- import { changedFiles, repositoryFiles, repositoryRoot } from "./repository.js";
9
+ import { changedFiles, fileOnMaster, repositoryFiles, repositoryRoot } from "./repository.js";
5
10
  import { runSteps } from "./runner.js";
6
11
  const DEFAULT_QUICK_LIMIT_SECONDS = 20;
7
12
  function seconds(env, name) {
@@ -10,44 +15,115 @@ function seconds(env, name) {
10
15
  return null;
11
16
  return /^\d+$/.test(value) && Number(value) > 0 ? Number(value) : `${name} must be a whole number of seconds, not '${value}'`;
12
17
  }
13
- export async function check(options) {
14
- const command = `suwgate check${options.quick ? " --quick" : ""}`;
15
- const root = repositoryRoot(options.cwd);
18
+ function prepare(command, cwd, env, catalog) {
19
+ const root = repositoryRoot(cwd);
16
20
  if (root === null)
17
- return { exitCode: 2, text: `${command}: ${options.cwd} is not inside a git repository` };
18
- const quickLimit = seconds(options.env, "SUWGATE_QUICK_LIMIT");
19
- const stepLimit = seconds(options.env, "SUWGATE_STEP_LIMIT");
21
+ return { exitCode: 2, text: `${command}: ${cwd} is not inside a git repository` };
22
+ const quickLimit = seconds(env, "SUWGATE_QUICK_LIMIT");
23
+ const stepLimit = seconds(env, "SUWGATE_STEP_LIMIT");
20
24
  for (const limit of [quickLimit, stepLimit]) {
21
25
  if (typeof limit === "string")
22
26
  return { exitCode: 2, text: `${command}: ${limit}` };
23
27
  }
24
- const loaded = loadConfig(root, options.catalog);
28
+ const loaded = loadConfig(root, catalog);
25
29
  if ("problems" in loaded)
26
30
  return { exitCode: 2, text: [`${command}: suwgate.yml is not valid:`, ...loaded.problems.map((line) => ` ${line}`)].join("\n") };
31
+ return {
32
+ root,
33
+ config: loaded.config,
34
+ stepLimit: typeof stepLimit === "number" ? stepLimit : null,
35
+ quickLimit: typeof quickLimit === "number" ? quickLimit : null,
36
+ };
37
+ }
38
+ function mergedOnceExceptions(root, config) {
39
+ const once = config.exceptions.filter((exception) => exception.once === true);
40
+ if (once.length === 0)
41
+ return [];
42
+ const text = fileOnMaster(root, "suwgate.yml");
43
+ if (text === null)
44
+ return [];
45
+ let onMaster;
46
+ try {
47
+ onMaster = parse(text, { maxAliasCount: MAX_ALIASES })?.exceptions;
48
+ }
49
+ catch {
50
+ return [];
51
+ }
52
+ const listed = Array.isArray(onMaster) ? onMaster : [];
53
+ return once.filter((exception) => listed.some((other) => sameException(other, exception)));
54
+ }
55
+ async function run(command, prepared, options) {
56
+ const { root, config } = prepared;
27
57
  let changed;
58
+ const merged = mergedOnceExceptions(root, config);
28
59
  const steps = plan({
29
60
  root,
30
61
  quick: options.quick,
31
- config: loaded.config,
62
+ config,
32
63
  catalog: options.catalog,
33
64
  files: repositoryFiles(root),
34
65
  changed: () => (changed ??= changedFiles(root)),
66
+ merged,
67
+ ...(options.target === undefined ? {} : { target: options.target }),
35
68
  });
36
69
  const began = performance.now();
37
- const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "" }, typeof stepLimit === "number" ? stepLimit : null);
70
+ const runFolder = mkdtempSync(path.join(tmpdir(), "suwgate-run-"));
71
+ const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "", SUWGATE_RUN: runFolder }, prepared.stepLimit).finally(() => rmSync(runFolder, { recursive: true, force: true }));
38
72
  const totalSeconds = Math.round((performance.now() - began) / 1000);
39
73
  const { text, passed } = report({
40
74
  results,
41
75
  command,
42
76
  totalSeconds,
43
- quickLimit: options.quick
44
- ? typeof quickLimit === "number"
45
- ? quickLimit
46
- : (loaded.config.quickLimitSeconds ?? DEFAULT_QUICK_LIMIT_SECONDS)
47
- : null,
77
+ quickLimit: options.quick ? (prepared.quickLimit ?? config.quickLimitSeconds ?? DEFAULT_QUICK_LIMIT_SECONDS) : null,
48
78
  ci: (options.env["CI"] ?? "") !== "",
49
- exceptions: loaded.config.exceptions.length,
79
+ exceptions: config.exceptions.length,
80
+ mergedOnce: merged.length,
50
81
  verbose: options.verbose,
51
82
  });
52
83
  return { exitCode: passed ? 0 : 1, text };
53
84
  }
85
+ export async function check(options) {
86
+ const command = `suwgate check${options.quick ? " --quick" : ""}`;
87
+ const prepared = prepare(command, options.cwd, options.env, options.catalog);
88
+ if ("exitCode" in prepared)
89
+ return prepared;
90
+ return run(command, prepared, options);
91
+ }
92
+ function listing(config, root, catalog) {
93
+ const listed = listSteps({ root, quick: false, config, catalog, files: [], changed: () => [] });
94
+ const width = Math.max(...listed.map((step) => step.id.length));
95
+ return [
96
+ "usage: suwgate step <id> [--only] [--verbose] [-- <arguments for the step's tool>]; the steps of this repository:",
97
+ ...listed.map((step) => ` ${step.id.padEnd(width)} ${step.title}${step.args === undefined ? "" : ` [-- args: ${step.args}]`}${step.skipped === undefined ? "" : ` [skipped in suwgate.yml: ${step.skipped}]`}`),
98
+ ].join("\n");
99
+ }
100
+ export async function step(options) {
101
+ const command = `suwgate step${options.id === undefined ? "" : ` ${options.id}`}`;
102
+ const prepared = prepare(command, options.cwd, options.env, options.catalog);
103
+ if ("exitCode" in prepared)
104
+ return prepared;
105
+ const { config, root } = prepared;
106
+ if (options.id === undefined)
107
+ return { exitCode: 0, text: listing(config, root, options.catalog) };
108
+ const steps = allSteps(config, options.catalog);
109
+ const chosen = steps.find((candidate) => candidate.id === options.id);
110
+ if (chosen === undefined && options.id !== GUARDS_STEP) {
111
+ return { exitCode: 2, text: `${command}: this repository has no step "${options.id}"\n${listing(config, root, options.catalog)}` };
112
+ }
113
+ if (options.args.length > 0 && chosen?.args === undefined) {
114
+ const taking = steps
115
+ .filter((candidate) => candidate.args !== undefined)
116
+ .map((candidate) => `${candidate.id} (${candidate.args ?? ""})`);
117
+ return {
118
+ exitCode: 2,
119
+ text: `${command}: the step ${options.id} passes no arguments to a tool, so it refuses "-- ${options.args.join(" ")}"; the steps that take them: ${taking.length === 0 ? "none here" : taking.join(", ")}`,
120
+ };
121
+ }
122
+ return run(`${command}${options.only ? " --only" : ""}`, prepared, {
123
+ quick: false,
124
+ verbose: options.verbose,
125
+ env: options.env,
126
+ catalog: options.catalog,
127
+ target: { id: options.id, only: options.only, args: options.args },
128
+ });
129
+ }