@maniumek/suwgate 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.shared.md CHANGED
@@ -8,11 +8,17 @@ repository's own `AGENTS.md` adds what is only its own, and wins where it says o
8
8
 
9
9
  - For people: a recipe in `justfile` with a one-line description; `just` lists them. A recipe only calls a script or a command,
10
10
  and a script answers `--help` with a usage text printed by the script, never with header comments.
11
- - While working, `suwgate check --quick`, and `suwgate step <step> [-- <tool args>]` runs one step (`suwgate step` lists them);
12
- `suwgate check` before calling a change done. `AGENTS.md` says how this repository runs suwgate.
13
- - Test last: finish every change of the task, then run the full gate once and push once, so CI runs once. After a red run, fix all
14
- it shows, rerun only the tests that failed, and the full gate once when they pass. Quick checks of the part you change (its unit
15
- tests, the type checker, one step) are fine while building.
11
+ - A task ends in one of two: a pull request with its PR proof, or a page that clears up what is unclear (a spec, a plan, an
12
+ explanation). The owner reads pages and approves pull requests; nobody watches CI.
13
+ - While building, on a feature branch: `suwgate check --quick` runs after every turn, and `suwgate step <step> [-- <tool args>]` runs
14
+ one step (`suwgate step` lists them). The full gate runs only in CI: an agent never runs `suwgate check` itself. `AGENTS.md` says
15
+ how this repository runs suwgate.
16
+ - Done building? `/suwagent:ship`: it simplifies the change, runs `suwgate ship` (the quick gate and the changed e2e tests, which
17
+ writes the ship record), pushes, opens the pull request, waits for CI, fixes a red run and writes the PR proof. A push or a pull
18
+ request without a ship record for its commit is refused; a person without the plugin runs `suwgate ship` before pushing.
19
+ - What the PR proof shows, by the kind of change: a refactor, optimisation, performance or stability change none ("behaviour
20
+ unchanged"); a UI change screenshots and video, before and after; a behaviour change one scenario, before and after; a new
21
+ feature the behaviour after.
16
22
  - KISS and YAGNI first: a repository grows only when a real need shows up; one developer maintains it after hours. When in doubt,
17
23
  leave it out, and say in the change what was left out and why.
18
24
  - Plan a change by listing what it makes obsolete, and delete that first, in the same change.
@@ -41,8 +47,10 @@ cannot see:
41
47
 
42
48
  - Set ids with `vdoc.py ids`, never by hand: a dropped id is never reused, an id is never renumbered.
43
49
  - A criterion no automated check can prove is a wrong criterion: ask the owner, never keep it unguarded.
44
- - A criterion gets the lightest check that can fail for it: a plain unit test before anything that needs a server, a browser or a
45
- screenshot, which cover only what nothing lighter can.
50
+ - A criterion is guarded by a test at the public boundary: the UI through a headless browser (a real browser only for how it looks),
51
+ the HTTP API, the CLI, or the public API of a library. That test is also what the PR proof records. A promise only a unit test
52
+ can reach is not a product criterion: it leaves the spec, and its unit test stays, without an id. Unit tests are the quick
53
+ checks of the quick gate. A repository makes this loud with `boundaryOnly` of the `criteria-ran` step once its criteria moved.
46
54
  - A criterion that promises something for every member of a set that grows (every event, role, page, component) is guarded by
47
55
  structure, not by examples: a type derived from the set's source, so a new member is a compile error until it is handled, or a
48
56
  test that walks every member, from the source or the rendered structure. A test that names the members it checks lets the next
package/README.md CHANGED
@@ -103,7 +103,7 @@ Every subcommand answers `--help`. The `dev` section and what each command does:
103
103
 
104
104
  <picture>
105
105
  <source media="(prefers-color-scheme: dark)" srcset="docs/visual/board/img/readme/ci-dark.png">
106
- <img alt="CI, releases and dependencies. Reusable workflows, pinned by commit: gate.yml (proof, gate, smoke, stamp; tools installed with checksums; consumer: a kit tested in a real app); release-npm.yml (changesets: the Version Packages pull request, then build and pack; npm trusted publishing); release-nuget.yml (full history, dotnet pack in Release, the artifact nupkg; NuGet trusted publishing). Self-hosted fallback: private repositories move to local runners when the month's Actions minutes run out: CI_RUNNER=suw-local, set and cleared by a timer. Renovate for every repository: once a week (new pull requests on Monday before 6:00 Warsaw time); two pull requests (minor and patch in one, majors in the other); merged on green (Renovate merges once the checks pass, a red one stays open); holds follow peers (TypeScript held to what typescript-eslint accepts, moved by pull request)." src="docs/visual/board/img/readme/ci-light.png" width="100%">
106
+ <img alt="CI, releases and dependencies. Reusable workflows, pinned by commit: gate.yml (proof, gate, smoke, stamp; tools installed with checksums; consumer: a kit tested in a real app); release-npm.yml (changesets: publish the version a merged branch moved, then build and pack; npm trusted publishing); release-nuget.yml (full history, dotnet pack in Release, the artifact nupkg; NuGet trusted publishing). Self-hosted fallback: private repositories move to local runners when the month's Actions minutes run out: CI_RUNNER=suw-local, set and cleared by a timer. Renovate for every repository: once a week (new pull requests on Monday before 6:00 Warsaw time); two pull requests (minor and patch in one, majors in the other); merged on green (Renovate merges once the checks pass, a red one stays open); holds follow peers (TypeScript held to what typescript-eslint accepts, moved by pull request). Left to people: the minimum SDK in global.json, PostgreSQL majors, Langfuse's stack, hash-pinned Python requirements." src="docs/visual/board/img/readme/ci-light.png" width="100%">
107
107
  </picture>
108
108
 
109
109
  A repository's whole `ci.yml` can be one job:
@@ -206,12 +206,13 @@ The schema ships in the package (`schema/suwgate.schema.json`); VS Code checks t
206
206
  <details>
207
207
  <summary>The settings of the steps</summary>
208
208
 
209
- | Step | Setting | What it does |
210
- | :------------- | :------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
211
- | `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`) |
212
- | `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 |
213
- | `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 |
214
- | `api-version` | `breaking: never` | every breaking change fails; the default, `major`, lets one through with a new major version |
209
+ | Step | Setting | What it does |
210
+ | :------------- | :------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
211
+ | `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`) |
212
+ | `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 |
213
+ | `criteria-ran` | `boundaryOnly: true` | opt-in: a criterion id may be named only by a test at the public boundary; a unit test (`web test (vitest)`, `unit test (vitest)`, or a `criteria.json` kind with `"unit": true`) that names one fails |
214
+ | `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 |
215
+ | `api-version` | `breaking: never` | every breaking change fails; the default, `major`, lets one through with a new major version |
215
216
 
216
217
  </details>
217
218
 
package/dist/cli.js CHANGED
@@ -5,13 +5,16 @@ import { check, step } from "./gate/check.js";
5
5
  import { dev, realEnvironment } from "./dev/index.js";
6
6
  import { loadConfig } from "./gate/config.js";
7
7
  import { PROFILES } from "./gate/contract.js";
8
- import { repositoryRoot } from "./gate/repository.js";
8
+ import { changedFiles, repositoryRoot } from "./gate/repository.js";
9
9
  import { guards, SHARED_RULES, writeSharedRules } from "./guards/index.js";
10
10
  import { discoverApiIn, dotnetGuards, stepsFor, verdict } from "./profiles/index.js";
11
+ import { guardPr } from "./session/guardPr.js";
11
12
  import { guardEdit } from "./session/guardEdit.js";
12
13
  import { preCommit, runTool } from "./session/preCommit.js";
14
+ import { prePush } from "./session/prePush.js";
15
+ import { ship } from "./session/ship.js";
13
16
  import { stop } from "./session/stop.js";
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 agents-shared | suwgate --help | --version
17
+ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verbose] [-- <args>]] | suwgate hook <guard-edit|guard-pr|stop|pre-commit|pre-push> | suwgate ship | suwgate dev <command> | suwgate agents-shared | suwgate --help | --version
15
18
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
16
19
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
17
20
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
@@ -24,8 +27,13 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
24
27
  suwgate hook guard-edit Claude Code PreToolUse hook: refuses an agent's edit of the gate and of generated files
25
28
  (ALLOW_GATE_EDIT=1 lifts the gate part for one session); only files of its own project
26
29
  (CLAUDE_PROJECT_DIR, else the git checkout it runs in), with the lists of its profiles
30
+ suwgate hook guard-pr Claude Code PreToolUse hook for Bash: refuses gh pr create and the commands of
31
+ settings.hooks.prCommands while the HEAD tree has no ship record, and --no-verify always
27
32
  suwgate hook stop Claude Code Stop hook: runs the quick gate unless nothing changed since it last passed
28
33
  suwgate hook pre-commit git pre-commit hook: gitleaks on the staged changes, then the quick gate
34
+ suwgate hook pre-push git pre-push hook: refuses a push of a branch whose tree has no ship record
35
+ suwgate ship needs a clean working tree: runs the quick gate and the e2e tests whose files changed on the
36
+ branch, then records the tree (the pre-push and guard-pr hooks let a push of it through)
29
37
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
30
38
  the local stack of the repository (the dev section of suwgate.yml), and the images of the
31
39
  sibling repositories it runs, rebuilt from their checkouts when stale, the API contract and types regenerated
@@ -139,6 +147,30 @@ async function main(argv) {
139
147
  console.error(verdict.message);
140
148
  return verdict.exitCode;
141
149
  }
150
+ if (command === "ship" && hook === undefined) {
151
+ const root = repositoryRoot(process.cwd()) ?? process.cwd();
152
+ const verdict = await ship(root, {
153
+ changedFiles: () => changedFiles(root),
154
+ quickCheck: () => runCheck(root, true, false),
155
+ e2e: (files) => step({ cwd: root, id: "e2e", only: false, args: files, verbose: false, env: process.env, catalog }),
156
+ });
157
+ (verdict.exitCode === 0 ? console.log : console.error)(verdict.message);
158
+ return verdict.exitCode;
159
+ }
160
+ if (command === "hook" && rest.length === 0 && hook === "pre-push") {
161
+ const root = repositoryRoot(process.cwd()) ?? process.cwd();
162
+ const verdict = prePush(readInput(), root);
163
+ if (verdict.message !== "")
164
+ console.error(verdict.message);
165
+ return verdict.exitCode;
166
+ }
167
+ if (command === "hook" && rest.length === 0 && hook === "guard-pr") {
168
+ const root = process.env["CLAUDE_PROJECT_DIR"] ?? repositoryRoot(process.cwd()) ?? process.cwd();
169
+ const verdict = guardPr(readInput(), root, editHookProject(root).settings.prCommands ?? []);
170
+ if (verdict.message !== "")
171
+ console.error(verdict.message);
172
+ return verdict.exitCode;
173
+ }
142
174
  if (command === "hook" && rest.length === 0 && (hook === "guard-edit" || hook === "stop")) {
143
175
  const root = process.env["CLAUDE_PROJECT_DIR"] ?? repositoryRoot(process.cwd()) ?? process.cwd();
144
176
  const verdict = hook === "guard-edit"
@@ -70,6 +70,10 @@ export const hooks = {
70
70
  },
71
71
  },
72
72
  recordings: { ...stringList, description: "Globs of recorded tests: a file git tracks there is not edited by an agent." },
73
+ prCommands: {
74
+ ...stringList,
75
+ description: "More commands (whole words, e.g. just pr) that the guard-pr hook refuses until the HEAD tree has a ship record, besides gh pr create; a git push is checked by the pre-push hook.",
76
+ },
73
77
  migrations: { ...stringList, description: "Globs of migration scripts: one that exists is never edited, a new one is added." },
74
78
  },
75
79
  },
@@ -4,6 +4,7 @@ interface Kind {
4
4
  kind: string;
5
5
  paths: string[];
6
6
  how: string;
7
+ unit?: boolean;
7
8
  }
8
9
  interface Extras {
9
10
  specs?: string;
@@ -20,6 +21,7 @@ export interface ToolPin {
20
21
  commit: string;
21
22
  sha256: string;
22
23
  }
24
+ export declare function criteriaExtras(text: string | null): Extras;
23
25
  export declare function criteriaConfig(context: StepContext, extras: Extras): CriteriaConfig;
24
26
  export declare function criteria(pin: ToolPin): (context: StepContext) => string | Skip;
25
27
  export declare const criteriaStep: Step;
@@ -52,14 +52,24 @@ function webKinds(context) {
52
52
  const directory = prefix(context, "web");
53
53
  return [
54
54
  { kind: "e2e test (playwright)", paths: [`${directory}src/**/*.e2e.ts`], how: 'the id in the title: test("<id>: …")' },
55
- { kind: "web test (vitest)", paths: [`${directory}src/**/*.test.ts`, `${directory}src/**/*.test.tsx`], how: TITLE },
55
+ {
56
+ kind: "web test (vitest)",
57
+ paths: [`${directory}src/**/*.test.ts`, `${directory}src/**/*.test.tsx`],
58
+ how: TITLE,
59
+ unit: true,
60
+ },
56
61
  ...scripts(directory),
57
62
  ];
58
63
  }
59
64
  function libraryKinds(context) {
60
65
  const directory = prefix(context, "library");
61
66
  return [
62
- { kind: "unit test (vitest)", paths: [`${directory}src/**/*.test.ts`, `${directory}src/**/*.test.tsx`], how: TITLE },
67
+ {
68
+ kind: "unit test (vitest)",
69
+ paths: [`${directory}src/**/*.test.ts`, `${directory}src/**/*.test.tsx`],
70
+ how: TITLE,
71
+ unit: true,
72
+ },
63
73
  {
64
74
  kind: "story test (vitest, Chromium)",
65
75
  paths: [`${directory}src/**/*.stories.tsx`],
@@ -84,13 +94,30 @@ function merged(kinds) {
84
94
  const byName = new Map();
85
95
  for (const kind of kinds) {
86
96
  const known = byName.get(kind.kind);
87
- byName.set(kind.kind, known === undefined ? { ...kind } : { ...known, paths: [...new Set([...known.paths, ...kind.paths])] });
97
+ byName.set(kind.kind, known === undefined
98
+ ? { ...kind }
99
+ : {
100
+ ...known,
101
+ paths: [...new Set([...known.paths, ...kind.paths])],
102
+ ...(known.unit === true || kind.unit === true ? { unit: true } : {}),
103
+ });
88
104
  }
89
105
  return [...byName.values()];
90
106
  }
91
107
  function defaultKinds(context) {
92
108
  return merged(context.profiles.flatMap((profile) => KINDS_BY_PROFILE[profile](context)));
93
109
  }
110
+ function vdocConfig(config) {
111
+ return { ...config, kinds: config.kinds.map(({ unit: _unit, ...kind }) => kind) };
112
+ }
113
+ export function criteriaExtras(text) {
114
+ try {
115
+ return text === null ? {} : JSON.parse(text);
116
+ }
117
+ catch {
118
+ return {};
119
+ }
120
+ }
94
121
  export function criteriaConfig(context, extras) {
95
122
  return {
96
123
  specs: extras.specs ?? "docs/visual/spec",
@@ -148,7 +175,7 @@ export function criteria(pin) {
148
175
  return script([
149
176
  `mkdir -p ${quoted(path.dirname(config))}`,
150
177
  `cat >${quoted(config)} <<'SUWGATE_CRITERIA'`,
151
- JSON.stringify(criteriaConfig(context, extras), null, 2),
178
+ JSON.stringify(vdocConfig(criteriaConfig(context, extras)), null, 2),
152
179
  "SUWGATE_CRITERIA",
153
180
  `python3 ${quoted(tool)} criteria --root ${quoted(context.root)} --config ${quoted(config)}`,
154
181
  ]);
@@ -7,12 +7,14 @@ interface TestSource {
7
7
  patterns: string[];
8
8
  skipped?: string;
9
9
  excludeTraits?: string[];
10
+ unit?: boolean;
10
11
  }
11
12
  export interface CriteriaRanInput {
12
13
  root: string;
13
14
  run: string;
14
15
  specs: string[];
15
16
  sources: TestSource[];
17
+ boundaryOnly?: boolean;
16
18
  }
17
19
  export declare function criterionIds(spec: string): string[];
18
20
  export declare function names(text: string, id: string, format: ReportFormat): boolean;
@@ -1,10 +1,20 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { CRITERIA_FILE, criteriaConfig } from "./criteria.js";
4
+ import { CRITERIA_FILE, criteriaConfig, criteriaExtras } from "./criteria.js";
5
5
  import { excludedTraits } from "./dotnet.js";
6
6
  import { readRun } from "./reports.js";
7
- import { quoted, read, tracked, verdictCommand } from "./shell.js";
7
+ import { quoted, read, settingsOf, tracked, verdictCommand } from "./shell.js";
8
+ const CRITERIA_RAN_SETTINGS = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ properties: {
12
+ boundaryOnly: {
13
+ description: "Refuse an acceptance criterion id named by a unit test (the kinds marked unit: web test (vitest), unit test (vitest), or a criteria.json kind with unit: true): the criterion is guarded at the public boundary (an e2e, API, CLI or consumer test). Default false.",
14
+ type: "boolean",
15
+ },
16
+ },
17
+ };
8
18
  const REPORTED = {
9
19
  "test (xunit)": { step: "dotnet-test", format: "xunit" },
10
20
  "web test (vitest)": { step: "unit-tests", format: "vitest" },
@@ -87,27 +97,34 @@ export function criteriaRan(input) {
87
97
  source,
88
98
  files: listed(input.root, source.patterns).map((file) => ({ file, text: readFileSync(path.join(input.root, file), "utf8") })),
89
99
  }));
90
- return ids.flatMap((id) => {
91
- const naming = texts.flatMap(({ source, files }) => files
92
- .filter((file) => names(file.text, id, source.format))
93
- .map((file) => ({ source, file: file.file, outside: outsideTheGate(file.text, id, source.excludeTraits ?? []) })));
94
- const checked = naming.filter((entry) => entry.source.skipped === undefined);
95
- if (checked.length === 0)
96
- return [];
97
- if (checked.every((entry) => entry.outside)) {
98
- const traits = [...new Set(checked.flatMap((entry) => entry.source.excludeTraits ?? []))].join(", ");
99
- return [
100
- `${id}: named only by tests outside the gate (${traits}, excludeTraits of dotnet-test in suwgate.yml): ${checked.map((entry) => entry.file).join(", ")}. The gate never runs them, so nothing in it proves the criterion: add a test the gate runs that names it, with a stand-in for the outside service (a fake model or server), and keep the outside test for the real one`,
101
- ];
102
- }
103
- if (checked.some((entry) => proven(runs.get(entry.source.step)?.passed ?? [], id)))
104
- return [];
105
- const unreported = [...new Set(checked.filter((entry) => runs.get(entry.source.step) === null).map((entry) => entry.source.step))];
106
- const why = unreported.length > 0 ? `${unreported.join(", ")} wrote no report` : "skipped, filtered out, or failed";
100
+ return ids.flatMap((id) => [...(input.boundaryOnly === true ? unitFindings(texts, id) : []), ...ranFindings(texts, runs, id)]);
101
+ }
102
+ function unitFindings(texts, id) {
103
+ return texts
104
+ .filter(({ source }) => source.unit === true)
105
+ .flatMap(({ source, files }) => files.filter((file) => names(file.text, id, source.format)))
106
+ .map((file) => `${file.file}: ${id} is named by a unit test: guard the criterion at the public boundary (an e2e, API, CLI or consumer test) and drop the id here, or move the promise out of the spec and keep this test without an id`);
107
+ }
108
+ function ranFindings(texts, runs, id) {
109
+ const naming = texts.flatMap(({ source, files }) => files
110
+ .filter((file) => names(file.text, id, source.format))
111
+ .map((file) => ({ source, file: file.file, outside: outsideTheGate(file.text, id, source.excludeTraits ?? []) })));
112
+ const checked = naming.filter((entry) => entry.source.skipped === undefined);
113
+ if (checked.length === 0)
114
+ return [];
115
+ if (checked.every((entry) => entry.outside)) {
116
+ const traits = [...new Set(checked.flatMap((entry) => entry.source.excludeTraits ?? []))].join(", ");
107
117
  return [
108
- `${id}: named by ${checked.map((entry) => `${entry.file} (${entry.source.step})`).join(", ")}, but no test naming it ran and passed in this gate run (${why}): make that test run and pass, or skip its step in suwgate.yml (steps.skip) with a reason`,
118
+ `${id}: named only by tests outside the gate (${traits}, excludeTraits of dotnet-test in suwgate.yml): ${checked.map((entry) => entry.file).join(", ")}. The gate never runs them, so nothing in it proves the criterion: add a test the gate runs that names it, with a stand-in for the outside service (a fake model or server), and keep the outside test for the real one`,
109
119
  ];
110
- });
120
+ }
121
+ if (checked.some((entry) => proven(runs.get(entry.source.step)?.passed ?? [], id)))
122
+ return [];
123
+ const unreported = [...new Set(checked.filter((entry) => runs.get(entry.source.step) === null).map((entry) => entry.source.step))];
124
+ const why = unreported.length > 0 ? `${unreported.join(", ")} wrote no report` : "skipped, filtered out, or failed";
125
+ return [
126
+ `${id}: named by ${checked.map((entry) => `${entry.file} (${entry.source.step})`).join(", ")}, but no test naming it ran and passed in this gate run (${why}): make that test run and pass, or skip its step in suwgate.yml (steps.skip) with a reason`,
127
+ ];
111
128
  }
112
129
  function specsFolder(context) {
113
130
  const text = read({ ...context, cwd: context.root }, CRITERIA_FILE);
@@ -124,7 +141,7 @@ export function criteriaRanInput(context) {
124
141
  const specs = tracked(root, [`${specsFolder(context)}/*.html`]);
125
142
  if (specs.length === 0)
126
143
  return null;
127
- const sources = criteriaConfig(context, {}).kinds.flatMap((kind) => {
144
+ const sources = criteriaConfig(context, criteriaExtras(read(root, CRITERIA_FILE))).kinds.flatMap((kind) => {
128
145
  const reported = REPORTED[kind.kind];
129
146
  if (reported === undefined)
130
147
  return [];
@@ -133,12 +150,14 @@ export function criteriaRanInput(context) {
133
150
  ...reported,
134
151
  report: path.posix.join(reported.step, REPORT_FILE[reported.format]),
135
152
  patterns: kind.paths,
153
+ ...(kind.unit === true ? { unit: true } : {}),
136
154
  ...(context.skippedSteps.includes(reported.step) ? { skipped: "skipped in suwgate.yml" } : {}),
137
155
  ...(reported.format === "xunit" && excludedTraits(context).length > 0 ? { excludeTraits: excludedTraits(context) } : {}),
138
156
  },
139
157
  ];
140
158
  });
141
- return { root: context.root, specs, sources };
159
+ const boundaryOnly = settingsOf(context, "criteria-ran").boundaryOnly === true;
160
+ return { root: context.root, specs, sources, ...(boundaryOnly ? { boundaryOnly } : {}) };
142
161
  }
143
162
  export const criteriaRanStep = {
144
163
  id: "criteria-ran",
@@ -148,5 +167,6 @@ export const criteriaRanStep = {
148
167
  const input = criteriaRanInput(context);
149
168
  return input === null ? null : verdictCommand(`criteria "\${SUWGATE_RUN:-/no-run-folder}" ${quoted(JSON.stringify(input))}`);
150
169
  },
170
+ settingsSchema: CRITERIA_RAN_SETTINGS,
151
171
  limitSeconds: 60,
152
172
  };
@@ -4,7 +4,11 @@ const CHANGESET = script([
4
4
  'base=""',
5
5
  "if git rev-parse --verify -q origin/master >/dev/null; then base=origin/master; elif git rev-parse --verify -q master >/dev/null; then base=master; fi",
6
6
  'if [ -z "$base" ] || [ "$(git rev-parse HEAD 2>/dev/null)" = "$(git rev-parse "$base")" ]; then echo "on $base itself or no master yet: nothing to compare with"; exit 0; fi',
7
- 'pnpm exec changeset status --since "$base"',
7
+ "pending=\"$(find .changeset -maxdepth 1 -name '*.md' ! -name README.md 2>/dev/null | sort)\"",
8
+ 'if [ -n "$pending" ]; then echo "$pending" >&2; echo "version these changesets in this branch: pnpm exec changeset version, then commit package.json and CHANGELOG.md; the merge publishes, with no Version Packages pull request" >&2; exit 1; fi',
9
+ 'version() { node -p \'JSON.parse(require("fs").readFileSync(0, "utf8")).version\'; }',
10
+ 'if [ "$(git show "$base:./package.json" | version)" != "$(version < package.json)" ]; then echo "the version moved since $base: the merge publishes it"; exit 0; fi',
11
+ 'pnpm exec changeset status --since "$base" || { echo "add a changeset (pnpm exec changeset), version it (pnpm exec changeset version) and commit package.json and CHANGELOG.md" >&2; exit 1; }',
8
12
  ]);
9
13
  const PUBLINT = script([
10
14
  'work="$(mktemp -d)"',
@@ -127,7 +131,7 @@ export const librarySteps = [
127
131
  },
128
132
  {
129
133
  id: "changeset",
130
- title: "a changeset for a change of the package since master (changeset status)",
134
+ title: "a change of the package since master carries its new version and CHANGELOG entry (changeset version, changeset status)",
131
135
  profile: "library",
132
136
  needs: ["pnpm"],
133
137
  after,
@@ -29,9 +29,10 @@ export declare function e2eTests<Config extends PlaywrightConfig>(config: Config
29
29
  reporter: ReporterDescription[];
30
30
  use: {
31
31
  baseURL?: string;
32
+ video?: "on";
32
33
  locale: string;
33
34
  trace: "retain-on-failure";
34
- screenshot: "only-on-failure";
35
+ screenshot: "on" | "only-on-failure";
35
36
  };
36
37
  };
37
38
  export declare function visualTests({ port }?: {
@@ -16,7 +16,13 @@ export function e2eTests(config) {
16
16
  projects: [{ name: "chromium", use: { browserName: "chromium", viewport: { width: 1440, height: 900 } } }],
17
17
  ...config,
18
18
  reporter: withGateReport(config.reporter ?? "list"),
19
- use: { locale: "en-US", trace: "retain-on-failure", screenshot: "only-on-failure", ...config.use },
19
+ use: {
20
+ locale: "en-US",
21
+ trace: "retain-on-failure",
22
+ screenshot: ci() ? "on" : "only-on-failure",
23
+ ...(ci() ? { video: "on" } : {}),
24
+ ...config.use,
25
+ },
20
26
  };
21
27
  }
22
28
  export function visualTests({ port = 6007 } = {}) {
@@ -6,6 +6,7 @@ export interface EditHookSettings {
6
6
  }[];
7
7
  recordings?: string[];
8
8
  migrations?: string[];
9
+ prCommands?: string[];
9
10
  }
10
11
  export interface EditHookProject {
11
12
  root: string;
@@ -0,0 +1,5 @@
1
+ export interface GuardPrVerdict {
2
+ exitCode: 0 | 2;
3
+ message: string;
4
+ }
5
+ export declare function guardPr(input: string, root: string, prCommands: readonly string[]): GuardPrVerdict;
@@ -0,0 +1,42 @@
1
+ import { homedir } from "node:os";
2
+ import path from "node:path";
3
+ import { hasShipRecord, treeOf } from "./shipRecord.js";
4
+ const BUILT_IN = ["gh pr create"];
5
+ const SKIPPED_HOOKS = /(?<![\w-])git\s+(?:\S+\s+)*?(?:push|commit)\b[^;&|]*\s--no-verify(?![\w-])/;
6
+ const NO_RECORD = "No ship record for this commit: run /suwagent:ship first; it simplifies, checks the changed tests, then pushes and opens the pull request.";
7
+ function callOf(input, root) {
8
+ try {
9
+ const parsed = JSON.parse(input);
10
+ const command = parsed.tool_input?.command;
11
+ return { command: typeof command === "string" ? command : "", cwd: typeof parsed.cwd === "string" ? parsed.cwd : root };
12
+ }
13
+ catch {
14
+ return { command: "", cwd: root };
15
+ }
16
+ }
17
+ const CD = /(?:^|[;&|(]\s*)cd\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/g;
18
+ function directoryOf(call) {
19
+ const last = [...call.command.matchAll(CD)].at(-1)?.[1];
20
+ if (last === undefined)
21
+ return call.cwd;
22
+ const unquoted = last.replace(/^(["'])(.*)\1$/, "$2").replace(/^~(?=\/|$)/, homedir());
23
+ return path.resolve(call.cwd, unquoted);
24
+ }
25
+ function pattern(words) {
26
+ const escaped = words
27
+ .trim()
28
+ .split(/\s+/)
29
+ .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
30
+ return new RegExp(`(?<![\\w-])${escaped.join("\\s+")}(?![\\w-])`);
31
+ }
32
+ const SKIPPING = "An agent never skips git hooks: drop --no-verify. A push needs a ship record: run /suwagent:ship, which pushes for you.";
33
+ export function guardPr(input, root, prCommands) {
34
+ const call = callOf(input, root);
35
+ if (SKIPPED_HOOKS.test(call.command))
36
+ return { exitCode: 2, message: SKIPPING };
37
+ const guarded = [...BUILT_IN, ...prCommands].filter((words) => words.trim() !== "").some((words) => pattern(words).test(call.command));
38
+ const directory = directoryOf(call);
39
+ if (!guarded || hasShipRecord(directory, treeOf(directory, "HEAD")))
40
+ return { exitCode: 0, message: "" };
41
+ return { exitCode: 2, message: NO_RECORD };
42
+ }
@@ -0,0 +1,5 @@
1
+ export interface PrePushVerdict {
2
+ exitCode: 0 | 1;
3
+ message: string;
4
+ }
5
+ export declare function prePush(input: string, root: string): PrePushVerdict;
@@ -0,0 +1,14 @@
1
+ import { hasShipRecord, treeOf } from "./shipRecord.js";
2
+ const NO_COMMIT = /^0+$/;
3
+ export function prePush(input, root) {
4
+ const refused = [];
5
+ for (const line of input.split("\n")) {
6
+ const [localRef, localSha] = line.trim().split(/\s+/);
7
+ if (localRef === undefined || localSha === undefined || !localRef.startsWith("refs/heads/") || NO_COMMIT.test(localSha))
8
+ continue;
9
+ if (!hasShipRecord(root, treeOf(root, localSha))) {
10
+ refused.push(`pre-push: ${localRef} has no ship record for its tree: run /suwagent:ship (an agent) or \`suwgate ship\`, then push again; push refused`);
11
+ }
12
+ }
13
+ return { exitCode: refused.length === 0 ? 0 : 1, message: refused.join("\n") };
14
+ }
@@ -0,0 +1,16 @@
1
+ export interface ShipVerdict {
2
+ exitCode: 0 | 1;
3
+ message: string;
4
+ }
5
+ export interface ShipSteps {
6
+ changedFiles: () => readonly string[];
7
+ quickCheck: () => Promise<{
8
+ exitCode: number;
9
+ text: string;
10
+ }>;
11
+ e2e: (files: readonly string[]) => Promise<{
12
+ exitCode: number;
13
+ text: string;
14
+ }>;
15
+ }
16
+ export declare function ship(root: string, steps: ShipSteps): Promise<ShipVerdict>;
@@ -0,0 +1,30 @@
1
+ import { isClean, treeOf, writeShipRecord } from "./shipRecord.js";
2
+ const SHOWN_LINES = 80;
3
+ function tail(text) {
4
+ return text.trimEnd().split("\n").slice(-SHOWN_LINES).join("\n");
5
+ }
6
+ export async function ship(root, steps) {
7
+ if (!isClean(root)) {
8
+ return {
9
+ exitCode: 1,
10
+ message: "ship: the working tree has uncommitted or untracked changes: commit your work first, ship records the committed tree",
11
+ };
12
+ }
13
+ const quick = await steps.quickCheck();
14
+ if (quick.exitCode !== 0) {
15
+ return { exitCode: 1, message: `${tail(quick.text)}\nship: the quick gate is red (above): fix it, commit, and run ship again` };
16
+ }
17
+ const tests = steps.changedFiles().filter((file) => file.endsWith(".e2e.ts"));
18
+ if (tests.length > 0) {
19
+ const e2e = await steps.e2e(tests);
20
+ if (e2e.exitCode !== 0) {
21
+ return {
22
+ exitCode: 1,
23
+ message: `${tail(e2e.text)}\nship: the changed e2e tests are red (above): fix them, commit, and run ship again`,
24
+ };
25
+ }
26
+ }
27
+ const tree = treeOf(root, "HEAD");
28
+ writeShipRecord(root, tree);
29
+ return { exitCode: 0, message: `ship record written for tree ${tree}` };
30
+ }
@@ -0,0 +1,4 @@
1
+ export declare function treeOf(root: string, revision: string): string;
2
+ export declare function hasShipRecord(root: string, tree: string): boolean;
3
+ export declare function writeShipRecord(root: string, tree: string): void;
4
+ export declare function isClean(root: string): boolean;
@@ -0,0 +1,27 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ function git(root, args) {
5
+ try {
6
+ return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7
+ }
8
+ catch {
9
+ return "";
10
+ }
11
+ }
12
+ function recordFile(root) {
13
+ return path.resolve(root, git(root, ["rev-parse", "--git-path", "suwgate-ship"]));
14
+ }
15
+ export function treeOf(root, revision) {
16
+ return git(root, ["rev-parse", `${revision}^{tree}`]);
17
+ }
18
+ export function hasShipRecord(root, tree) {
19
+ const file = recordFile(root);
20
+ return tree !== "" && existsSync(file) && readFileSync(file, "utf8").trim() === tree;
21
+ }
22
+ export function writeShipRecord(root, tree) {
23
+ writeFileSync(recordFile(root), `${tree}\n`);
24
+ }
25
+ export function isClean(root) {
26
+ return git(root, ["status", "--porcelain"]) === "";
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "One quality gate for every repository: suwgate check runs the steps of the repository's profiles and its guards, configured in suwgate.yml",
5
5
  "license": "MIT",
6
6
  "author": "Manomenu",
@@ -85,7 +85,7 @@
85
85
  "knip": "^6.46.1",
86
86
  "prettier": "^3.10.1",
87
87
  "publint": "0.3.25",
88
- "typescript": "5.9.3",
88
+ "typescript": "6.0.3",
89
89
  "typescript-eslint": "^8.73.0",
90
90
  "vitest": "5.1.1"
91
91
  },