@capybara-hq/plugin-tools 0.0.0-stage → 0.1.0-rc.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 (73) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +105 -2
  4. package/bin/capybara-plugin.mjs +12 -0
  5. package/dist/check/applied-migrations.d.ts +28 -0
  6. package/dist/check/applied-migrations.js +65 -0
  7. package/dist/check/cli.d.ts +16 -0
  8. package/dist/check/cli.js +69 -0
  9. package/dist/check/deps.d.ts +23 -0
  10. package/dist/check/deps.js +207 -0
  11. package/dist/check/index.d.ts +15 -0
  12. package/dist/check/index.js +14 -0
  13. package/dist/check/migrations.d.ts +11 -0
  14. package/dist/check/migrations.js +93 -0
  15. package/dist/check/plugin-pack.d.ts +17 -0
  16. package/dist/check/plugin-pack.js +56 -0
  17. package/dist/check/plugin-permissions.d.ts +22 -0
  18. package/dist/check/plugin-permissions.js +392 -0
  19. package/dist/check/plugin-state.d.ts +19 -0
  20. package/dist/check/plugin-state.js +181 -0
  21. package/dist/check/plugin-versions.d.ts +13 -0
  22. package/dist/check/plugin-versions.js +56 -0
  23. package/dist/check/release-metadata.d.ts +13 -0
  24. package/dist/check/release-metadata.js +80 -0
  25. package/dist/check/report.d.ts +8 -0
  26. package/dist/check/report.js +17 -0
  27. package/dist/check/run.d.ts +36 -0
  28. package/dist/check/run.js +60 -0
  29. package/dist/check/source.d.ts +53 -0
  30. package/dist/check/source.js +153 -0
  31. package/dist/check/sync-versions-cli.d.ts +10 -0
  32. package/dist/check/sync-versions-cli.js +44 -0
  33. package/dist/check/test-imports.d.ts +20 -0
  34. package/dist/check/test-imports.js +158 -0
  35. package/dist/check/tool-design.d.ts +13 -0
  36. package/dist/check/tool-design.js +227 -0
  37. package/dist/cli.d.ts +1 -0
  38. package/dist/cli.js +48 -0
  39. package/dist/discover.d.ts +21 -0
  40. package/dist/discover.js +69 -0
  41. package/dist/index.d.ts +10 -0
  42. package/dist/index.js +10 -0
  43. package/dist/integrity.d.ts +2 -0
  44. package/dist/integrity.js +3 -0
  45. package/dist/marketplace/cli.d.ts +20 -0
  46. package/dist/marketplace/cli.js +80 -0
  47. package/dist/marketplace/file.d.ts +2 -0
  48. package/dist/marketplace/file.js +2 -0
  49. package/dist/marketplace/index.d.ts +2 -0
  50. package/dist/marketplace/index.js +2 -0
  51. package/dist/marketplace/marketplace.d.ts +57 -0
  52. package/dist/marketplace/marketplace.js +245 -0
  53. package/dist/pack/bootstrap.d.ts +25 -0
  54. package/dist/pack/bootstrap.js +70 -0
  55. package/dist/pack/cli.d.ts +20 -0
  56. package/dist/pack/cli.js +109 -0
  57. package/dist/pack/index.d.ts +4 -0
  58. package/dist/pack/index.js +4 -0
  59. package/dist/pack/npm.d.ts +66 -0
  60. package/dist/pack/npm.js +177 -0
  61. package/dist/pack/pack.d.ts +44 -0
  62. package/dist/pack/pack.js +518 -0
  63. package/dist/release/cli.d.ts +30 -0
  64. package/dist/release/cli.js +93 -0
  65. package/dist/release/index.d.ts +4 -0
  66. package/dist/release/index.js +4 -0
  67. package/dist/release/publish-plan.d.ts +68 -0
  68. package/dist/release/publish-plan.js +117 -0
  69. package/dist/release/publish.d.ts +91 -0
  70. package/dist/release/publish.js +274 -0
  71. package/dist/release/semver.d.ts +11 -0
  72. package/dist/release/semver.js +44 -0
  73. package/package.json +61 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Capybara
2
+ Copyright 2026 Meta-1 (Tianjin Yuanyilian Technology Co., Ltd.)
package/README.md CHANGED
@@ -1,3 +1,106 @@
1
- # Temporary Holding Version
1
+ # @capybara-hq/plugin-tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The toolchain for [Capybara](https://github.com/capybara-hq/core) plugins: the `capybara-plugin`
4
+ CLI packs plugins into plugin tgz files, runs the plugin checks, keeps a marketplace manifest and
5
+ publishes a workspace to npm.
6
+ Capybara's own repositories use it (core for its scripts and test extensions, the plugins
7
+ repository for the official plugins); any plugin repository can.
8
+
9
+ ```bash
10
+ npm install --save-dev @capybara-hq/plugin-tools
11
+ ```
12
+
13
+ ## Commands
14
+
15
+ ```bash
16
+ capybara-plugin pack [<dir>...] [--all <root>] [--out <dir>]
17
+ capybara-plugin pack --bootstrap <manifest> [--root <dir>] [--out <dir>] [--registry <url>]
18
+ [--npm-token <token>]
19
+ capybara-plugin check [--root <dir>] [--plugins <glob>] [--base <ref>]
20
+ capybara-plugin sync-versions [--root <dir>] [--plugins <glob>]
21
+ capybara-plugin marketplace --write|--check [--base <rev>] [--root <dir>] [--file <path>]
22
+ [--plugins <glob>]
23
+ capybara-plugin release [--dry-run] [--provenance] [--out <dir>] [--auto] [--root <dir>]
24
+ [--plugins <pattern>]... [--marketplace <file>]
25
+ ```
26
+
27
+ - **pack**: a plugin directory (`package.json` + `.capybara-plugin/plugin.json`, an optional
28
+ extension in `src/index.ts`, `skills/`, `connectors/`, `migrations/`, `ui/`) becomes a
29
+ byte-reproducible plugin tgz: the extension bundled by esbuild into single-file ESM, its static
30
+ manifest written into `plugin.json`, LICENSE / NOTICE and the bundled dependencies' notices
31
+ included. A plugin with an extension gets `"main"` and `"exports": { ".": "./dist/index.mjs" }`,
32
+ so once installed it resolves by package name (a test loads `@capybara-hq/plugin-model-fake`
33
+ from npm). `--all <root>` packs every plugin of a repository; `--bootstrap` packs the entries of
34
+ a bootstrap manifest (workspace entries from the repository, npm entries downloaded from
35
+ `--registry`, default `CAPYBARA_PACKAGES__NPM_REGISTRY` or the public registry, with
36
+ `--npm-token` / `CAPYBARA_PACKAGES__NPM_TOKEN` sent to the registry origin only, tarballs capped
37
+ at 50 MiB) and checks them against their pinned sha512 and their `package.json` name and version.
38
+ Output: `artifacts/plugins`.
39
+ - **check**: every plugin check, on the plugins under `<root>/plugins/*` (or `--plugins <glob>`, or
40
+ the root itself when it is a plugin): the dependency boundary (a plugin depends only on
41
+ `@capybara-hq/plugin-sdk` and third-party packages), extension state under multiple replicas (no
42
+ timers, no module-level mutable state), the permission manifest (hooks, UI, storage, HTTP,
43
+ secrets, tools), packing into a valid plugin package, the tool design rules (English
44
+ descriptions, actionable errors), the migrations (naming, idempotent, no unmarked destructive
45
+ statements), the plugin tests' imports (`plugin-test-imports`: a file under `<plugin>/test` uses
46
+ only `@capybara-hq/plugin-sdk`, `@capybara-hq/testing`, `@capybara-hq/plugin-model-fake`, the
47
+ plugin itself and files inside the plugin, by import, package-name string or path) and the
48
+ release metadata (`plugin-release-metadata`: a public plugin has a `description`, a `license`, an
49
+ https `homepage` and `repository` `{ type: "git", url: <the root package.json's
50
+ repository.url>, directory: <its dir> }`; `example-*` plugins are private). `--base <ref>` also fails when the diff edits, deletes or renames an applied
51
+ migration. No plugin found is an error. A plugin may list `@capybara-hq/plugin-tools` (like
52
+ `@capybara-hq/testing`) in its devDependencies.
53
+ - **sync-versions**: after `changeset version` (which bumps only `package.json`), copies each
54
+ plugin's version into its `.capybara-plugin/plugin.json` and its extension manifest
55
+ (`src/index.ts`, ` version: "x"`), which the packer requires equal.
56
+ - **marketplace**: `--write` appends to `.capybara-plugin/marketplace.json` (`--file`) one npm entry
57
+ per public plugin version it does not list yet (`name`, `version`, `summary`, `homepage`,
58
+ `permissions`, `source.npm` with the sha512 of a reproducible pack), formatted as Biome formats
59
+ it; `--check` fails when an entry is missing (`marketplace-missing`) or the file does not parse
60
+ (`marketplace-invalid`). A version already listed is not compared with the tree: once
61
+ published, its bytes are the release gate's business. `--check --base <rev>` (pull requests)
62
+ also requires the entries at `<rev>` to stay unchanged and first, in order
63
+ (`marketplace-append-only`), and the entries added since to match their packs
64
+ (`marketplace-integrity`). Entries of versions no longer in the tree are kept.
65
+ - **release**: publishes every non-private workspace package whose version is not on npm yet:
66
+ plugins (the packages under `plugins/`) as their plugin tgz, libraries through `pnpm pack`, with
67
+ the dist-tag rule (prerelease `next`, backport `release-<major>.<minor>`, else `latest`), then
68
+ writes the plugins' `SHA512SUMS` and `integrity.json`. `--auto` is the push-to-main mode
69
+ (committed tree only, never the first release). The workspace packages are the directories with a
70
+ `package.json` in `packages/*`, `apps/*`, `plugins/*` and `tools/*` under `--root`; none found is
71
+ an error. `--plugins <pattern>` (repeatable) plans only the matching plugins (libraries are unaffected; a pattern matching none is an error);
72
+ `--marketplace <file>` (default `.capybara-plugin/marketplace.json` under the root when it
73
+ exists) packs every planned plugin and checks its sha512 against that version's entry before the
74
+ first publish; a mismatch or a missing entry stops the run with nothing published
75
+ (`release.integrity_mismatch`).
76
+
77
+ Relative paths, the default root and the output directories resolve against the current directory
78
+ of the process: in a package script that is the package's directory, so `"pack": "capybara-plugin
79
+ pack ."` in a plugin's `package.json` packs that plugin. `capybara-plugin <command> --help` prints
80
+ one command's usage.
81
+
82
+ ## Testing plugins against the published kernel
83
+
84
+ A plugin's kernel-level tests load the plugin by path (`plugins/<name>/src/index.ts`, imports
85
+ written `./x.js`) into a kernel installed from npm. Vitest externalizes `node_modules`, so the
86
+ kernel's `import()` would run in plain Node, which does not map `./x.js` to `./x.ts`. Inline the
87
+ core packages in `vitest.config.ts` (the pattern is matched against the resolved file path, not
88
+ the package name):
89
+
90
+ ```ts
91
+ export default defineConfig({
92
+ test: { server: { deps: { inline: [/\/node_modules\/@capybara-hq\//] } } },
93
+ });
94
+ ```
95
+
96
+ ## Library
97
+
98
+ The same code as functions: `packPlugin`, `packBootstrap`, `pluginChecks` / `runChecks` and each
99
+ check (`checkDeps`, `checkPluginState`, `checkPluginPermissions`, `checkPluginPack`,
100
+ `checkToolDesign`, `checkMigrations`, `checkAppliedMigrations`, `checkPluginTestImports`,
101
+ `checkPluginReleaseMetadata`), `syncPluginVersions` (after `changeset version`),
102
+ `syncMarketplace`, `planPublish`, `distTagFor`, `runPublish` and `integrityOf`. The subpaths
103
+ `@capybara-hq/plugin-tools/pack`, `/release` and `/source` load without the kernel.
104
+
105
+ - How plugins are written: [.agents/skills/writing-plugins](https://github.com/capybara-hq/core/tree/main/.agents/skills/writing-plugins).
106
+ - The repository: [capybara-hq/core](https://github.com/capybara-hq/core).
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ // The `capybara-plugin` bin: runs the compiled CLI (dist/cli.js, built by `tsc -b`). In this
3
+ // repository, the root scripts (pnpm pack-plugin, pack-plugins, pack-bootstrap, release) run the
4
+ // TypeScript sources through tsx instead.
5
+ import { existsSync } from "node:fs";
6
+
7
+ const dist = new URL("../dist/cli.js", import.meta.url);
8
+ if (!existsSync(dist)) {
9
+ process.stderr.write("capybara-plugin: dist/cli.js not found; build the package first\n");
10
+ process.exit(1);
11
+ }
12
+ await import(dist.href);
@@ -0,0 +1,28 @@
1
+ import type { Finding } from "./source.js";
2
+ /** Whether a repo-relative POSIX path is a migration file the check guards. */
3
+ export type MigrationFilePredicate = (path: string) => boolean;
4
+ /**
5
+ * A {@link MigrationFilePredicate} for migration directories given as globs relative to the
6
+ * repository root (`plugins/*\/migrations`, `packages/kernel/src/migrations`, `migrations` for a
7
+ * single-plugin repository): a `*.sql` file directly inside a matching directory. Globs also match
8
+ * directories that no longer exist, so deleting a whole plugin's migrations is still reported.
9
+ */
10
+ export declare function migrationFileMatcher(dirGlobs: string[]): MigrationFilePredicate;
11
+ /**
12
+ * PR check: an applied migration is never edited, deleted or renamed. The migrator records each
13
+ * file by name and checksum: an edited file stops `capybara migrate` (checksum mismatch) on every
14
+ * database that already ran it, a renamed one is out of order there, and a deleted one leaves those
15
+ * databases on a different schema than fresh ones. Fresh test databases pass either way, so only a
16
+ * diff check catches it. Adding new files is fine.
17
+ *
18
+ * `nameStatus` is the output of `git diff --name-status -M <base>...HEAD`: an `M`, `D` or `T`
19
+ * entry on a migration (`isMigration`), or an `R` entry whose source is a migration, is reported.
20
+ * `A` and `C` (a new file) are not.
21
+ */
22
+ export declare function checkAppliedMigrations(nameStatus: string, isMigration: MigrationFilePredicate): Finding[];
23
+ /**
24
+ * Runs {@link checkAppliedMigrations} on `<base>...HEAD` (changes since the merge base) in `cwd`.
25
+ * Paths are relative to `cwd` (`git diff --relative`), so `cwd` may be a subdirectory of the
26
+ * repository; finding files are relative to `cwd` too.
27
+ */
28
+ export declare function diffAppliedMigrations(cwd: string, base: string, isMigration: MigrationFilePredicate): Finding[];
@@ -0,0 +1,65 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { globToRegExp } from "../discover.js";
3
+ /**
4
+ * A {@link MigrationFilePredicate} for migration directories given as globs relative to the
5
+ * repository root (`plugins/*\/migrations`, `packages/kernel/src/migrations`, `migrations` for a
6
+ * single-plugin repository): a `*.sql` file directly inside a matching directory. Globs also match
7
+ * directories that no longer exist, so deleting a whole plugin's migrations is still reported.
8
+ */
9
+ export function migrationFileMatcher(dirGlobs) {
10
+ const dirs = dirGlobs.map(globToRegExp);
11
+ return (path) => {
12
+ if (!path.endsWith(".sql"))
13
+ return false;
14
+ const slash = path.lastIndexOf("/");
15
+ const dir = slash < 0 ? "" : path.slice(0, slash);
16
+ return dirs.some((re) => re.test(dir));
17
+ };
18
+ }
19
+ /**
20
+ * PR check: an applied migration is never edited, deleted or renamed. The migrator records each
21
+ * file by name and checksum: an edited file stops `capybara migrate` (checksum mismatch) on every
22
+ * database that already ran it, a renamed one is out of order there, and a deleted one leaves those
23
+ * databases on a different schema than fresh ones. Fresh test databases pass either way, so only a
24
+ * diff check catches it. Adding new files is fine.
25
+ *
26
+ * `nameStatus` is the output of `git diff --name-status -M <base>...HEAD`: an `M`, `D` or `T`
27
+ * entry on a migration (`isMigration`), or an `R` entry whose source is a migration, is reported.
28
+ * `A` and `C` (a new file) are not.
29
+ */
30
+ export function checkAppliedMigrations(nameStatus, isMigration) {
31
+ const findings = [];
32
+ for (const line of nameStatus.split("\n")) {
33
+ if (line === "")
34
+ continue;
35
+ const [status = "", from = ""] = line.split("\t");
36
+ const kind = status[0];
37
+ if (kind === "A" || kind === "C")
38
+ continue;
39
+ if (!isMigration(from))
40
+ continue;
41
+ const what = kind === "D"
42
+ ? "deleted"
43
+ : kind === "R"
44
+ ? "renamed"
45
+ : kind === "T"
46
+ ? "changed type"
47
+ : "edited";
48
+ findings.push({
49
+ file: from,
50
+ line: 1,
51
+ rule: "applied-migration-edited",
52
+ message: `migration ${what}: applied migrations are immutable (the migrator records them by name and checksum); restore it and add a new migration instead`,
53
+ });
54
+ }
55
+ return findings;
56
+ }
57
+ /**
58
+ * Runs {@link checkAppliedMigrations} on `<base>...HEAD` (changes since the merge base) in `cwd`.
59
+ * Paths are relative to `cwd` (`git diff --relative`), so `cwd` may be a subdirectory of the
60
+ * repository; finding files are relative to `cwd` too.
61
+ */
62
+ export function diffAppliedMigrations(cwd, base, isMigration) {
63
+ const out = execFileSync("git", ["diff", "--name-status", "--no-ext-diff", "--relative", "-M", `${base}...HEAD`], { cwd, encoding: "utf8" });
64
+ return checkAppliedMigrations(out, isMigration);
65
+ }
@@ -0,0 +1,16 @@
1
+ export declare const CHECK_USAGE = "capybara-plugin check [--root <dir>] [--plugins <glob>] [--base <ref>]";
2
+ /**
3
+ * `capybara-plugin check`: runs every plugin-scoped check on the plugins of a repository.
4
+ *
5
+ * - `--root <dir>`: the repository (default: the current directory);
6
+ * - `--plugins <glob>`: the plugin directories, relative to the root (`*` within one segment);
7
+ * default `plugins/*` when `<root>/plugins` exists, else the root itself when it holds
8
+ * `.capybara-plugin/plugin.json`;
9
+ * - `--base <ref>`: also fail when `<ref>...HEAD` edits, deletes or renames a migration of a plugin
10
+ * (applied migrations are immutable); for pull requests.
11
+ *
12
+ * Finding no plugin is an error: an empty scan would pass without checking anything.
13
+ *
14
+ * Relative paths resolve against `cwd` (the current directory). Returns the exit code.
15
+ */
16
+ export declare function checkCommand(args: string[], cwd: string): Promise<number>;
@@ -0,0 +1,69 @@
1
+ import { join, relative, resolve } from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ import { discoverPlugins, pluginsGlobOf } from "../discover.js";
4
+ import { diffAppliedMigrations, migrationFileMatcher } from "./applied-migrations.js";
5
+ import { pluginChecks, runChecks } from "./run.js";
6
+ export const CHECK_USAGE = "capybara-plugin check [--root <dir>] [--plugins <glob>] [--base <ref>]";
7
+ /**
8
+ * `capybara-plugin check`: runs every plugin-scoped check on the plugins of a repository.
9
+ *
10
+ * - `--root <dir>`: the repository (default: the current directory);
11
+ * - `--plugins <glob>`: the plugin directories, relative to the root (`*` within one segment);
12
+ * default `plugins/*` when `<root>/plugins` exists, else the root itself when it holds
13
+ * `.capybara-plugin/plugin.json`;
14
+ * - `--base <ref>`: also fail when `<ref>...HEAD` edits, deletes or renames a migration of a plugin
15
+ * (applied migrations are immutable); for pull requests.
16
+ *
17
+ * Finding no plugin is an error: an empty scan would pass without checking anything.
18
+ *
19
+ * Relative paths resolve against `cwd` (the current directory). Returns the exit code.
20
+ */
21
+ export async function checkCommand(args, cwd) {
22
+ const { values } = parseArgs({
23
+ args,
24
+ options: {
25
+ help: { type: "boolean", short: "h", default: false },
26
+ root: { type: "string" },
27
+ plugins: { type: "string" },
28
+ base: { type: "string" },
29
+ },
30
+ });
31
+ if (values.help) {
32
+ console.log(`usage: ${CHECK_USAGE}`);
33
+ return 0;
34
+ }
35
+ const root = values.root === undefined ? cwd : resolve(cwd, values.root);
36
+ let plugins;
37
+ try {
38
+ plugins = discoverPlugins(root, values.plugins);
39
+ }
40
+ catch (e) {
41
+ console.error(e instanceof Error ? e.message : String(e));
42
+ return 2;
43
+ }
44
+ if (plugins.length === 0) {
45
+ console.error(`${relative(cwd, root) || "."}: no plugin found (${values.plugins ?? "plugins/* or .capybara-plugin/plugin.json"}); the checks would check nothing`);
46
+ return 1;
47
+ }
48
+ console.log(`checking ${plugins.length} plugin(s): ${plugins.map((p) => relative(root, p) || ".").join(", ")}`);
49
+ const checks = pluginChecks({ root, plugins });
50
+ const base = values.base;
51
+ if (base !== undefined) {
52
+ const glob = pluginsGlobOf(root, values.plugins);
53
+ const isMigration = migrationFileMatcher([glob === "." ? "migrations" : `${glob}/migrations`]);
54
+ checks.push({
55
+ name: "Applied migrations",
56
+ run: () => diffAppliedMigrations(root, base, isMigration).map((f) => ({
57
+ ...f,
58
+ file: join(root, f.file),
59
+ })),
60
+ });
61
+ }
62
+ const failed = await runChecks(checks, root);
63
+ if (failed > 0) {
64
+ console.error(`\n${failed} check(s) failed`);
65
+ return 1;
66
+ }
67
+ console.log("\nAll plugin checks passed");
68
+ return 0;
69
+ }
@@ -0,0 +1,23 @@
1
+ import { type Finding } from "./source.js";
2
+ export type { Finding };
3
+ /**
4
+ * The dependency boundary check.
5
+ * - pluginDirs: each plugin directory (source imports and package.json); a violation is
6
+ * plugin-imports-kernel (a path leaving the plugin directory: plugin-imports-outside);
7
+ * - sdkDirs: the packages/plugin-sdk directory; any @capybara-hq/* package or path leaving the
8
+ * package directory is sdk-imports-internal.
9
+ *
10
+ * Covers: import / export from / export * / import type / dynamic import("literal or concatenated
11
+ * literals") / require("…") / import x = require() / import("x") types; package.json dependencies /
12
+ * peerDependencies / devDependencies / optionalDependencies (name and value, so npm: / workspace:
13
+ * aliases too) / bundleDependencies / link:|file:|portal: leaving the directory / imports and exports
14
+ * map values; `#xxx` imports in the sources after expanding the imports map, and dependency aliases;
15
+ * file: URLs and absolute paths count as leaving the directory.
16
+ * Allowed in devDependencies and test files: @capybara-hq/testing and @capybara-hq/plugin-tools.
17
+ * Also allowed there: `@capybara-hq/plugin-model-fake` (plugin tests drive agent runs with it).
18
+ *
19
+ * Known gaps: non-literal dynamic specifiers (`import(x)`); indirect require through a variable,
20
+ * `module.require` or `createRequire(...)`; `import.meta.resolve`; paths built at run time to read
21
+ * files; nested package.json files and TS `paths` mappings.
22
+ */
23
+ export declare function checkDeps(pluginDirs: string[], sdkDirs?: string[]): Finding[];