@kana-ai/edgar-ext-docker 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kana.ai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @kana-ai/edgar-ext-docker
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 Docker extension of EDGAR. Its environment `compose` starts a service's Docker Compose stack before each `check` stage of the service, checks that the stack is healthy, and removes the stack after the checks. A service names it as `docker__compose`.
4
+
5
+ ## Steps
6
+
7
+ The engine runs the four steps around the checks of a `check` stage: `stop`, `prepare`, `start`, `health`, then the checks, then `stop` again, also after a failed step. Each step runs `docker compose` in the run's checkout, where the Compose file of the service is.
8
+
9
+ | Step | What it runs | Fails when |
10
+ | --------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
11
+ | `prepare` | `docker compose config --format json --no-env-resolution`, then `docker compose build` | The Compose file breaks a rule below. |
12
+ | `start` | `docker compose up --detach --wait --wait-timeout <wait_seconds>` | The Compose file breaks a rule below, or a container is not healthy within `wait_seconds`. |
13
+ | `health` | `docker compose ps --all --format json` | A container is not running and healthy. A one-off job, such as a migration, may end with 0. |
14
+ | `stop` | `docker compose down --volumes --remove-orphans --rmi local` | Docker does not answer. A stack that is not up is already stopped, so `stop` is safe to repeat. |
15
+
16
+ Each stack is its own Compose project, `edgar-<service>-<run>`, so two runs never share a container, a network or a volume. One stack of a service is up at a time. A health check in the Compose file says when the service is ready, for example a `curl` of its address. `start` waits for it.
17
+
18
+ The Compose file comes from the run's checkout, and a stage can change it on its branch, so `prepare` and `start` each read the file as `docker compose config --no-env-resolution` writes it, with each `env_file` kept as its path, and refuse what gives a container more than its own share of the machine. The rules are a list of what a stack may use, so a key that is not on it, including one that Compose adds later, is refused:
19
+
20
+ - At the top of the file: `services`, `networks`, `volumes`, `configs`, `secrets` and `name`.
21
+ - In a service: `image`, `build`, `command`, `entrypoint`, `environment`, `env_file`, `ports`, `expose`, `volumes`, `healthcheck`, `depends_on`, `deploy`, `mem_limit`, `cpus`, `pids_limit`, `networks`, `working_dir`, `user`, `restart`, `labels`, `tmpfs`, `init`, `stop_grace_period`, `stop_signal`, `hostname`, `extra_hosts`, `read_only`, `shm_size`, `configs` and `secrets`. So `privileged`, `cap_add`, `devices`, `security_opt`, `network_mode`, `pid`, `ipc`, `cgroup_parent`, `gpus`, `volumes_from` and the rest are refused.
22
+ - In `build`: `context`, `dockerfile`, `args`, `target` and `cache_from`. So `network`, `privileged`, `entitlements`, `ssh`, `secrets` and `additional_contexts` are refused.
23
+ - In `deploy`: `resources`, with `limits` (`cpus`, `memory`, `pids`) and `reservations` (`cpus`, `memory`), and `placement`, which Compose writes for every service with a `deploy` section and which only a swarm reads.
24
+ - A key that starts with `x-` is an extension field, which Compose never reads, and passes at every level.
25
+
26
+ On top of the list:
27
+
28
+ - A port that binds an address other than `127.0.0.1` is refused. A port with no host port, such as `"80"`, is published on a random port of every address, so it is refused too. Write it as `"127.0.0.1:8080:80"`, or `"127.0.0.1::80"` for a random port of `127.0.0.1`.
29
+ - A service with no memory limit or no CPU limit is refused. Set `deploy.resources.limits` (or `mem_limit` and `cpus`).
30
+ - Every network of the stack is `internal: true`, the default network too, except one network named `edge`. Only a service that publishes a port may join `edge`, so a database or a worker has no way out of the machine. A service that publishes a port must join `edge`, since Docker publishes no port of a container that is only on internal networks.
31
+ - A mount is a `bind`, a `volume` or a `tmpfs`.
32
+ - A network or a volume is the stack's own: `external: true` is refused, and so is a `name` other than the one Compose gives it, `edgar-<service>-<run>_<key>`, since a name reaches the network or the volume of another project. A driver other than `bridge` for a network and `local` for a volume is refused too.
33
+ - A config or a secret is the stack's own and comes from a file: `external: true` and `environment`, which reads a variable of the process that runs Compose, are refused.
34
+ - Each path of the machine that the file mounts or reads (a bind mount, an `env_file`, a build context and its Dockerfile, a named volume that binds a folder, the file of a config or a secret) must have its real path inside the checkout. The real path follows every link, so a link in the checkout to `/var/run/docker.sock` is refused.
35
+
36
+ An example stack that follows the rules: an API that it builds and that publishes a port, on `edge` and on the internal default network, and the database it waits for, on the internal network only:
37
+
38
+ ```yaml
39
+ services:
40
+ api:
41
+ build: .
42
+ ports: ["127.0.0.1:8080:8080"]
43
+ env_file: [test.env]
44
+ networks: [default, edge]
45
+ healthcheck: { test: ["CMD", "curl", "-f", "http://127.0.0.1:8080/health"], interval: 5s }
46
+ depends_on: { db: { condition: service_healthy } }
47
+ deploy: { resources: { limits: { cpus: "1", memory: 512M } } }
48
+ db:
49
+ image: postgres:17
50
+ environment: { POSTGRES_PASSWORD: test }
51
+ healthcheck: { test: ["CMD", "pg_isready"], interval: 5s }
52
+ deploy: { resources: { limits: { cpus: "1", memory: 1G } } }
53
+ networks:
54
+ default: { internal: true }
55
+ edge: {}
56
+ ```
57
+
58
+ A file that breaks a rule fails the stage as `refused`, with each break named, and nothing is built or started.
59
+
60
+ The engine gives each step 600 seconds. `wait_seconds` is at most 540, so `start` ends with the name of the container that is not up before the step's own limit stops it.
61
+
62
+ ## Enable and approve
63
+
64
+ 1. Add the package to the project, enable it, and name the stack of each service in `edgar/edgar.toml`:
65
+
66
+ ```toml
67
+ [extensions]
68
+ enabled = ["docker"]
69
+
70
+ [extensions.docker.stacks.api]
71
+ file = "docker-compose.yml" # the default, relative to the checkout
72
+ wait_seconds = 300 # the default
73
+
74
+ [services.api]
75
+ environment = { provider = "docker__compose" }
76
+ ```
77
+
78
+ 2. Approve its capabilities. The manifest declares `sandbox:read` and `sandbox:write`, no secret and no network:
79
+
80
+ ```sh
81
+ edgar extensions approve docker
82
+ ```
83
+
84
+ The environment needs a Docker daemon that the sandbox reaches. Whoever enables it gives each run that daemon. The rules above check the stack that the environment's steps start. They do not check a command of a role that reaches the same daemon, as each command does with `[sandbox] kind = "none"`, and access to a Docker daemon is the same as root on the machine that runs the daemon. So use this environment with `kind = "none"` only on a machine for development or tests. Only the services on the network `edge` can reach outside the machine.
85
+
86
+ The steps need a Docker Compose release whose `config` has `--no-env-resolution`. With an older one, each step fails and nothing starts.
87
+
88
+ `edgar check` refuses the project when `docker` is not on `PATH`, because the extension declares it in `executables.requires`. The sandbox must reach the Docker daemon: with `[sandbox] kind = "none"` the steps use the machine's Docker. A secret of the stack goes in the service's own environment, never in the Compose file or its `.env`.
@@ -0,0 +1,5 @@
1
+ import { type Capability } from "@kana-ai/edgar-sdk";
2
+ /** The steps run `docker compose` in the checkout of the run, where the service's Compose file is. */
3
+ export declare const access: readonly Capability[];
4
+ /** The `compose` environment: a service's Docker Compose stack, up while the stage's checks run. */
5
+ export declare const composeEnvironment: import("@kana-ai/edgar-sdk").Environment;
@@ -0,0 +1,113 @@
1
+ import { z } from "zod";
2
+ import { defineEnvironment, defineTool, done, err, ok, permanentFailure, } from "@kana-ai/edgar-sdk";
3
+ import { container, composeConfig, stepInput, stepOutput } from "#schemas/compose";
4
+ import { config } from "#schemas/config";
5
+ import { compose, json, project, realPaths, rows } from "#stack/compose";
6
+ import { hostPaths, notUp, refusals } from "#stack/rules";
7
+ /** The steps run `docker compose` in the checkout of the run, where the service's Compose file is. */
8
+ export const access = ["sandbox:read", "sandbox:write"];
9
+ /** The stack of the step's service and its Compose project, or the failure when the input or the `[extensions.docker]` table does not read, or the table names no stack for the service. */
10
+ function stackOf(raw, ctx) {
11
+ const input = stepInput.safeParse(raw);
12
+ if (!input.success)
13
+ return err(permanentFailure("invalid_input", input.error.message));
14
+ const settings = config.safeParse(ctx.config ?? {});
15
+ if (!settings.success)
16
+ return err(permanentFailure("invalid", "the [extensions.docker] table does not match its schema", {
17
+ cause: settings.error.issues.map((issue) => issue.message).join("; "),
18
+ }));
19
+ const { service, run } = input.data;
20
+ const stack = Object.hasOwn(settings.data.stacks, service)
21
+ ? settings.data.stacks[service]
22
+ : undefined;
23
+ if (stack === undefined)
24
+ return err(permanentFailure("invalid", `[extensions.docker] stacks has no stack for the service \`${service}\``));
25
+ return ok({ stack, name: project(service, String(run)) });
26
+ }
27
+ /** A step of the environment as a tool: it reads its stack, runs `step` and answers the Compose project. */
28
+ function stepTool(description, step) {
29
+ return defineTool({
30
+ description,
31
+ input: stepInput,
32
+ output: stepOutput,
33
+ capabilities: access,
34
+ execute: async (raw, ctx) => {
35
+ const found = stackOf(raw, ctx);
36
+ if (!found.ok)
37
+ return found.error;
38
+ const ran = await step(found.value.stack, found.value.name, ctx);
39
+ return ran.ok ? done({ project: found.value.name }) : ran.error;
40
+ },
41
+ });
42
+ }
43
+ /** Reads the Compose file as `docker compose config --no-env-resolution` writes it, with each env file kept as its path so the rules judge it, and refuses it when it breaks a rule of `refusals`. Both `prepare` and `start` run it, so a file is judged again right before Docker starts it. */
44
+ async function checked(stack, name, ctx) {
45
+ const read = await compose(ctx, stack, name, [
46
+ "config",
47
+ "--format",
48
+ "json",
49
+ "--no-env-resolution",
50
+ ]);
51
+ if (!read.ok)
52
+ return read;
53
+ const parsed = composeConfig.safeParse(json(read.value));
54
+ if (!parsed.success)
55
+ return err(permanentFailure("tool_error", "docker compose config printed no Compose file"));
56
+ const paths = await realPaths(ctx, hostPaths(parsed.data));
57
+ if (!paths.ok)
58
+ return paths;
59
+ const broken = refusals(parsed.data, name, paths.value.checkout, paths.value.real);
60
+ return broken.length === 0
61
+ ? ok(undefined)
62
+ : err(permanentFailure("refused", `the Compose file of the stack breaks a rule: ${broken.join("; ")}`));
63
+ }
64
+ /** Refuses a Compose file that breaks a rule, then builds the images that the file builds. */
65
+ const prepare = async (stack, name, ctx) => {
66
+ const check = await checked(stack, name, ctx);
67
+ if (!check.ok)
68
+ return check;
69
+ const built = await compose(ctx, stack, name, ["build", "--quiet"]);
70
+ return built.ok ? ok(undefined) : built;
71
+ };
72
+ /** Refuses a Compose file that breaks a rule, then starts the stack and waits until each container runs and each health check passes. */
73
+ const start = async (stack, name, ctx) => {
74
+ const check = await checked(stack, name, ctx);
75
+ if (!check.ok)
76
+ return check;
77
+ const wait = String(stack.wait_seconds);
78
+ const up = await compose(ctx, stack, name, ["up", "--detach", "--wait", "--wait-timeout", wait]);
79
+ return up.ok ? ok(undefined) : up;
80
+ };
81
+ /** Checks that each container of the stack is up, as `notUp` says. */
82
+ const health = async (stack, name, ctx) => {
83
+ const listed = await compose(ctx, stack, name, ["ps", "--all", "--format", "json"]);
84
+ if (!listed.ok)
85
+ return listed;
86
+ const containers = z.array(container).safeParse(rows(listed.value));
87
+ if (!containers.success || containers.data.length === 0)
88
+ return err(permanentFailure("tool_error", "docker compose ps listed no container"));
89
+ const down = notUp(containers.data);
90
+ return down.length === 0
91
+ ? ok(undefined)
92
+ : err(permanentFailure("tool_error", `the stack is not up: ${down.join("; ")}`));
93
+ };
94
+ /** Removes the stack's containers, networks, volumes and the images it built. A stack that is not up is already stopped. */
95
+ const stop = async (stack, name, ctx) => {
96
+ const removed = await compose(ctx, stack, name, [
97
+ "down",
98
+ "--volumes",
99
+ "--remove-orphans",
100
+ "--rmi",
101
+ "local",
102
+ "--timeout",
103
+ "30",
104
+ ]);
105
+ return removed.ok ? ok(undefined) : removed;
106
+ };
107
+ /** The `compose` environment: a service's Docker Compose stack, up while the stage's checks run. */
108
+ export const composeEnvironment = defineEnvironment({
109
+ prepare: stepTool("Check the stack's Compose file and build its images", prepare),
110
+ start: stepTool("Start the stack and wait until it is healthy", start),
111
+ health: stepTool("Check that each container of the stack is up", health),
112
+ stop: stepTool("Remove the stack's containers, networks, volumes and built images", stop),
113
+ });
@@ -0,0 +1,3 @@
1
+ /** The Docker extension: the environment `compose`, which brings a service's Docker Compose stack up for its checks and removes it after. A service names it with `environment = { provider = "docker__compose" }`. */
2
+ declare const _default: import("@kana-ai/edgar-sdk").Extension;
3
+ export default _default;
@@ -0,0 +1,18 @@
1
+ import { defineExtension } from "@kana-ai/edgar-sdk";
2
+ import { access, composeEnvironment } from "#environment/steps";
3
+ import { config } from "#schemas/config";
4
+ /** The Docker extension: the environment `compose`, which brings a service's Docker Compose stack up for its checks and removes it after. A service names it with `environment = { provider = "docker__compose" }`. */
5
+ export default defineExtension({
6
+ name: "docker",
7
+ config,
8
+ capabilities: [...access],
9
+ environments: { compose: composeEnvironment },
10
+ executables: {
11
+ requires: [
12
+ {
13
+ name: "docker",
14
+ reason: "The environment compose runs docker compose in the sandbox of the run.",
15
+ },
16
+ ],
17
+ },
18
+ });
@@ -0,0 +1,77 @@
1
+ import { z } from "zod";
2
+ /** The part of `docker compose config --format json` that the rules read. Compose writes each path of the file as an absolute path of the machine. Every other key is kept, so the rules see it and refuse it. */
3
+ export declare const composeConfig: z.ZodObject<{
4
+ services: z.ZodRecord<z.ZodString, z.ZodObject<{
5
+ ports: z.ZodOptional<z.ZodArray<z.ZodObject<{
6
+ host_ip: z.ZodOptional<z.ZodString>;
7
+ published: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
8
+ target: z.ZodOptional<z.ZodNumber>;
9
+ }, z.core.$loose>>>;
10
+ mem_limit: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
11
+ cpus: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
12
+ deploy: z.ZodOptional<z.ZodObject<{
13
+ resources: z.ZodOptional<z.ZodObject<{
14
+ limits: z.ZodOptional<z.ZodObject<{
15
+ cpus: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
16
+ memory: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
17
+ }, z.core.$loose>>;
18
+ reservations: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
19
+ }, z.core.$loose>>;
20
+ }, z.core.$loose>>;
21
+ volumes: z.ZodOptional<z.ZodArray<z.ZodObject<{
22
+ type: z.ZodString;
23
+ source: z.ZodOptional<z.ZodString>;
24
+ }, z.core.$loose>>>;
25
+ networks: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
26
+ env_file: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
27
+ path: z.ZodString;
28
+ }, z.core.$loose>]>>]>>;
29
+ build: z.ZodOptional<z.ZodObject<{
30
+ context: z.ZodOptional<z.ZodString>;
31
+ dockerfile: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$loose>>;
33
+ }, z.core.$loose>>;
34
+ networks: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodObject<{
35
+ external: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{}, z.core.$loose>]>>;
36
+ name: z.ZodOptional<z.ZodString>;
37
+ internal: z.ZodOptional<z.ZodBoolean>;
38
+ driver: z.ZodOptional<z.ZodString>;
39
+ driver_opts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
40
+ }, z.core.$loose>>>>;
41
+ volumes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodObject<{
42
+ external: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{}, z.core.$loose>]>>;
43
+ name: z.ZodOptional<z.ZodString>;
44
+ internal: z.ZodOptional<z.ZodBoolean>;
45
+ driver: z.ZodOptional<z.ZodString>;
46
+ driver_opts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
47
+ }, z.core.$loose>>>>;
48
+ configs: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
49
+ file: z.ZodOptional<z.ZodString>;
50
+ environment: z.ZodOptional<z.ZodString>;
51
+ external: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{}, z.core.$loose>]>>;
52
+ }, z.core.$loose>>>;
53
+ secrets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
54
+ file: z.ZodOptional<z.ZodString>;
55
+ environment: z.ZodOptional<z.ZodString>;
56
+ external: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{}, z.core.$loose>]>>;
57
+ }, z.core.$loose>>>;
58
+ }, z.core.$loose>;
59
+ /** One container of `docker compose ps --format json`. */
60
+ export declare const container: z.ZodObject<{
61
+ Service: z.ZodString;
62
+ State: z.ZodString;
63
+ Health: z.ZodOptional<z.ZodString>;
64
+ ExitCode: z.ZodOptional<z.ZodNumber>;
65
+ }, z.core.$loose>;
66
+ /** The input of each step, as the engine sends it: the service, its slot and the run. */
67
+ export declare const stepInput: z.ZodObject<{
68
+ service: z.ZodString;
69
+ slot: z.ZodNumber;
70
+ run: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
71
+ }, z.core.$loose>;
72
+ /** The output of each step: the Compose project of the stack. */
73
+ export declare const stepOutput: z.ZodObject<{
74
+ project: z.ZodString;
75
+ }, z.core.$strip>;
76
+ export type ComposeConfig = z.output<typeof composeConfig>;
77
+ export type Container = z.output<typeof container>;
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ const port = z.looseObject({
3
+ host_ip: z.string().optional(),
4
+ published: z.union([z.string(), z.number()]).optional(),
5
+ target: z.number().optional(),
6
+ });
7
+ const limits = z.looseObject({
8
+ cpus: z.union([z.string(), z.number()]).optional(),
9
+ memory: z.union([z.string(), z.number()]).optional(),
10
+ });
11
+ const mount = z.looseObject({ type: z.string(), source: z.string().optional() });
12
+ const envFile = z.union([z.string(), z.looseObject({ path: z.string() })]);
13
+ const service = z.looseObject({
14
+ ports: z.array(port).optional(),
15
+ mem_limit: z.union([z.string(), z.number()]).optional(),
16
+ cpus: z.union([z.string(), z.number()]).optional(),
17
+ deploy: z
18
+ .looseObject({
19
+ resources: z
20
+ .looseObject({ limits: limits.optional(), reservations: z.looseObject({}).optional() })
21
+ .optional(),
22
+ })
23
+ .optional(),
24
+ volumes: z.array(mount).optional(),
25
+ networks: z.record(z.string(), z.unknown()).optional(),
26
+ env_file: z.union([z.string(), z.array(envFile)]).optional(),
27
+ build: z
28
+ .looseObject({ context: z.string().optional(), dockerfile: z.string().optional() })
29
+ .optional(),
30
+ });
31
+ const part = z
32
+ .looseObject({
33
+ external: z.union([z.boolean(), z.looseObject({})]).optional(),
34
+ name: z.string().optional(),
35
+ internal: z.boolean().optional(),
36
+ driver: z.string().optional(),
37
+ driver_opts: z.record(z.string(), z.string()).optional(),
38
+ })
39
+ .nullable();
40
+ const source = z.looseObject({
41
+ file: z.string().optional(),
42
+ environment: z.string().optional(),
43
+ external: z.union([z.boolean(), z.looseObject({})]).optional(),
44
+ });
45
+ /** The part of `docker compose config --format json` that the rules read. Compose writes each path of the file as an absolute path of the machine. Every other key is kept, so the rules see it and refuse it. */
46
+ export const composeConfig = z.looseObject({
47
+ services: z.record(z.string(), service),
48
+ networks: z.record(z.string(), part).optional(),
49
+ volumes: z.record(z.string(), part).optional(),
50
+ configs: z.record(z.string(), source).optional(),
51
+ secrets: z.record(z.string(), source).optional(),
52
+ });
53
+ /** One container of `docker compose ps --format json`. */
54
+ export const container = z.looseObject({
55
+ Service: z.string(),
56
+ State: z.string(),
57
+ Health: z.string().optional(),
58
+ ExitCode: z.number().optional(),
59
+ });
60
+ /** The input of each step, as the engine sends it: the service, its slot and the run. */
61
+ export const stepInput = z.looseObject({
62
+ service: z.string().min(1),
63
+ slot: z.number().int().min(1),
64
+ run: z.union([z.string().min(1), z.number().int()]),
65
+ });
66
+ /** The output of each step: the Compose project of the stack. */
67
+ export const stepOutput = z.object({ project: z.string() });
@@ -0,0 +1,16 @@
1
+ import { z } from "zod";
2
+ /** The seconds the engine gives each step of an environment, and so its `docker compose` command. */
3
+ export declare const STEP_SECONDS = 600;
4
+ /** One stack of `[extensions.docker] stacks`: its Compose file, relative to the checkout of the service, and the most seconds `start` waits for each container to be running and healthy. The wait ends a minute before the step's own limit, so `start` says which container is not up. */
5
+ export declare const stack: z.ZodObject<{
6
+ file: z.ZodDefault<z.ZodString>;
7
+ wait_seconds: z.ZodDefault<z.ZodNumber>;
8
+ }, z.core.$strict>;
9
+ /** The extension's `[extensions.docker]` table: a stack for each service, by the service's name. */
10
+ export declare const config: z.ZodObject<{
11
+ stacks: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
12
+ file: z.ZodDefault<z.ZodString>;
13
+ wait_seconds: z.ZodDefault<z.ZodNumber>;
14
+ }, z.core.$strict>>>;
15
+ }, z.core.$strict>;
16
+ export type Stack = z.output<typeof stack>;
@@ -0,0 +1,15 @@
1
+ import { z } from "zod";
2
+ /** The seconds the engine gives each step of an environment, and so its `docker compose` command. */
3
+ export const STEP_SECONDS = 600;
4
+ /** One stack of `[extensions.docker] stacks`: its Compose file, relative to the checkout of the service, and the most seconds `start` waits for each container to be running and healthy. The wait ends a minute before the step's own limit, so `start` says which container is not up. */
5
+ export const stack = z.strictObject({
6
+ file: z.string().min(1).default("docker-compose.yml"),
7
+ wait_seconds: z
8
+ .number()
9
+ .int()
10
+ .min(1)
11
+ .max(STEP_SECONDS - 60)
12
+ .default(300),
13
+ });
14
+ /** The extension's `[extensions.docker]` table: a stack for each service, by the service's name. */
15
+ export const config = z.strictObject({ stacks: z.record(z.string().min(1), stack).default({}) });
@@ -0,0 +1,17 @@
1
+ import { type Ctx, type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import type { Stack } from "#schemas/config";
3
+ /** The Compose project of the stack of `service` for `run`: one project per stack, so two runs never share a container, a network or a volume. Compose allows lowercase letters, digits, `-` and `_`. */
4
+ export declare function project(service: string, run: string): string;
5
+ /** The arguments of `docker` for one `docker compose` command of a stack. */
6
+ export declare function composeArgs(stack: Stack, name: string, command: readonly string[]): readonly string[];
7
+ /** Runs one `docker compose` command of a stack in the run's checkout; its standard output, or the failure with the end of its standard error. */
8
+ export declare function compose<S extends string>(ctx: Ctx<S>, stack: Stack, name: string, command: readonly string[]): Promise<Result<string, Failure>>;
9
+ /** A JSON text as a value; `undefined` when it does not parse. */
10
+ export declare function json(text: string): unknown;
11
+ /** The containers of `docker compose ps --format json`, which prints one object per line, or one array in older versions. */
12
+ export declare function rows(text: string): readonly unknown[];
13
+ /** The real path of the run's checkout and of each of `paths`, with every link followed, as `readlink -f` gives them in the checkout. A link inside the checkout can point outside it, so a path is judged by where it ends. The failure when one does not resolve. */
14
+ export declare function realPaths<S extends string>(ctx: Ctx<S>, paths: readonly string[]): Promise<Result<{
15
+ readonly checkout: string;
16
+ readonly real: ReadonlyMap<string, string>;
17
+ }, Failure>>;
@@ -0,0 +1,47 @@
1
+ import { attempt, err, ok, permanentFailure, portFailure, unwrapOr, } from "@kana-ai/edgar-sdk";
2
+ /** The Compose project of the stack of `service` for `run`: one project per stack, so two runs never share a container, a network or a volume. Compose allows lowercase letters, digits, `-` and `_`. */
3
+ export function project(service, run) {
4
+ return `edgar-${service}-${run}`.toLowerCase().replaceAll(/[^a-z0-9_-]+/g, "-");
5
+ }
6
+ /** The arguments of `docker` for one `docker compose` command of a stack. */
7
+ export function composeArgs(stack, name, command) {
8
+ return ["compose", "--project-name", name, "--file", stack.file, ...command];
9
+ }
10
+ /** Runs one `docker compose` command of a stack in the run's checkout; its standard output, or the failure with the end of its standard error. */
11
+ export async function compose(ctx, stack, name, command) {
12
+ const ran = await ctx.sandbox.exec("docker", composeArgs(stack, name, command));
13
+ if (!ran.ok)
14
+ return err(portFailure(ran.error));
15
+ if (ran.value.exit_code === 0)
16
+ return ok(ran.value.stdout);
17
+ return err(permanentFailure("tool_error", `docker compose ${command.join(" ")} failed`, {
18
+ cause: `exit ${String(ran.value.exit_code)}: ${ran.value.stderr.trim().slice(-2000)}`,
19
+ }));
20
+ }
21
+ /** A JSON text as a value; `undefined` when it does not parse. */
22
+ export function json(text) {
23
+ return unwrapOr(attempt(() => JSON.parse(text), () => undefined), undefined);
24
+ }
25
+ /** The containers of `docker compose ps --format json`, which prints one object per line, or one array in older versions. */
26
+ export function rows(text) {
27
+ const whole = json(text.trim());
28
+ if (Array.isArray(whole))
29
+ return whole;
30
+ return text
31
+ .split("\n")
32
+ .filter((line) => line.trim() !== "")
33
+ .map((line) => json(line));
34
+ }
35
+ /** The real path of the run's checkout and of each of `paths`, with every link followed, as `readlink -f` gives them in the checkout. A link inside the checkout can point outside it, so a path is judged by where it ends. The failure when one does not resolve. */
36
+ export async function realPaths(ctx, paths) {
37
+ const ran = await ctx.sandbox.exec("readlink", ["-f", "--", ".", ...paths]);
38
+ if (!ran.ok)
39
+ return err(portFailure(ran.error));
40
+ const lines = ran.value.stdout.split("\n").filter((line) => line !== "");
41
+ const [checkout, ...real] = lines;
42
+ if (ran.value.exit_code !== 0 || checkout === undefined || real.length !== paths.length)
43
+ return err(permanentFailure("refused", "a path of the Compose file does not resolve", {
44
+ cause: `exit ${String(ran.value.exit_code)}: ${ran.value.stderr.trim().slice(-2000)}`,
45
+ }));
46
+ return ok({ checkout, real: new Map(paths.map((path, at) => [path, real[at] ?? ""])) });
47
+ }
@@ -0,0 +1,11 @@
1
+ import type { ComposeConfig, Container } from "#schemas/compose";
2
+ /** The address each entry of `ports` must bind, so a stack is never reachable from outside the machine. */
3
+ export declare const LOOPBACK = "127.0.0.1";
4
+ /** The one network of a stack that may reach outside the machine. Every other network is `internal: true`. */
5
+ export declare const EDGE = "edge";
6
+ /** Each path of the machine that the Compose file mounts or reads: bind mounts, `env_file`s, build contexts and Dockerfiles, named volumes that bind a folder, and the files of configs and secrets. */
7
+ export declare function hostPaths(config: ComposeConfig): readonly string[];
8
+ /** What the Compose file of the stack's Compose `project` breaks of the rules: `topRefusals`, `serviceRefusals` of each service, and each path of `hostPaths` whose real path, in `real`, is outside `checkout`, the real path of the run's checkout. Empty when the file follows them. */
9
+ export declare function refusals(config: ComposeConfig, project: string, checkout: string, real: ReadonlyMap<string, string>): readonly string[];
10
+ /** Each container that is not up: one that runs with a health check that is not `healthy` yet, or one that stopped with an exit code other than 0. A one-off job, such as a migration, that ended with 0 is up. */
11
+ export declare function notUp(containers: readonly Container[]): readonly string[];
@@ -0,0 +1,180 @@
1
+ /** The address each entry of `ports` must bind, so a stack is never reachable from outside the machine. */
2
+ export const LOOPBACK = "127.0.0.1";
3
+ /** The one network of a stack that may reach outside the machine. Every other network is `internal: true`. */
4
+ export const EDGE = "edge";
5
+ /** The keys a stack may use, at the top of the file and in each service. Any other key, and any key that Compose adds later, is refused, since a key that is not known is a key that is not judged. */
6
+ const TOP = new Set(["services", "networks", "volumes", "configs", "secrets", "name"]);
7
+ const SERVICE = new Set([
8
+ "image",
9
+ "build",
10
+ "command",
11
+ "entrypoint",
12
+ "environment",
13
+ "env_file",
14
+ "ports",
15
+ "expose",
16
+ "volumes",
17
+ "healthcheck",
18
+ "depends_on",
19
+ "deploy",
20
+ "mem_limit",
21
+ "cpus",
22
+ "pids_limit",
23
+ "networks",
24
+ "working_dir",
25
+ "user",
26
+ "restart",
27
+ "labels",
28
+ "tmpfs",
29
+ "init",
30
+ "stop_grace_period",
31
+ "stop_signal",
32
+ "hostname",
33
+ "extra_hosts",
34
+ "read_only",
35
+ "shm_size",
36
+ "configs",
37
+ "secrets",
38
+ ]);
39
+ const BUILD = new Set(["context", "dockerfile", "args", "target", "cache_from"]);
40
+ const DEPLOY = new Set(["resources", "placement"]);
41
+ const RESOURCES = new Set(["limits", "reservations"]);
42
+ const LIMITS = new Set(["cpus", "memory", "pids"]);
43
+ const RESERVATIONS = new Set(["cpus", "memory"]);
44
+ const MOUNTS = new Set(["bind", "volume", "tmpfs"]);
45
+ /** Each key of `value` that `allowed` does not hold, as `<prefix><key>`. An `x-` key is an extension field, which Compose keeps and never reads. */
46
+ function unknownKeys(value, allowed, prefix = "") {
47
+ return Object.keys(value ?? {})
48
+ .filter((key) => !allowed.has(key) && !key.startsWith("x-"))
49
+ .map((key) => `${prefix}${key}`);
50
+ }
51
+ /** The file paths of a service's `env_file`, in either form Compose writes. */
52
+ function envFiles(service) {
53
+ const files = service.env_file;
54
+ if (files === undefined)
55
+ return [];
56
+ return (typeof files === "string" ? [files] : files).map((file) => typeof file === "string" ? file : file.path);
57
+ }
58
+ /** The Dockerfile of a build as a path of the machine. Compose keeps a relative one relative to the build context. */
59
+ function dockerfile(build) {
60
+ const file = build?.dockerfile;
61
+ if (file === undefined)
62
+ return [];
63
+ if (file.startsWith("/"))
64
+ return [file];
65
+ return build?.context?.startsWith("/") === true ? [`${build.context}/${file}`] : [];
66
+ }
67
+ /** Each path of the machine that the Compose file mounts or reads: bind mounts, `env_file`s, build contexts and Dockerfiles, named volumes that bind a folder, and the files of configs and secrets. */
68
+ export function hostPaths(config) {
69
+ const services = Object.values(config.services).flatMap((service) => [
70
+ ...(service.volumes ?? []).flatMap((mount) => mount.type === "bind" && mount.source !== undefined ? [mount.source] : []),
71
+ ...envFiles(service),
72
+ ...(service.build?.context?.startsWith("/") === true ? [service.build.context] : []),
73
+ ...dockerfile(service.build),
74
+ ]);
75
+ const devices = Object.values(config.volumes ?? {}).flatMap((volume) => {
76
+ const device = volume?.driver_opts?.["device"];
77
+ return device === undefined ? [] : [device];
78
+ });
79
+ const files = [
80
+ ...Object.values(config.configs ?? {}),
81
+ ...Object.values(config.secrets ?? {}),
82
+ ].flatMap(({ file }) => (file === undefined ? [] : [file]));
83
+ return [...new Set([...services, ...devices, ...files])];
84
+ }
85
+ /** What a service breaks of the rules: each key that a stack may not use, at any level that the rules know, each mount that is not a bind, a volume or a tmpfs, each entry of `ports` that binds an address other than `127.0.0.1`, with a host port or without one, joining the network `edge` with no published port, a published port off `edge`, where Docker never publishes it, and each missing memory or CPU limit. */
86
+ function serviceRefusals(name, service) {
87
+ const resources = service.deploy?.resources;
88
+ const keys = [
89
+ ...unknownKeys(service, SERVICE),
90
+ ...unknownKeys(service.build, BUILD, "build."),
91
+ ...unknownKeys(service.deploy, DEPLOY, "deploy."),
92
+ ...unknownKeys(resources, RESOURCES, "deploy.resources."),
93
+ ...unknownKeys(resources?.limits, LIMITS, "deploy.resources.limits."),
94
+ ...unknownKeys(resources?.reservations, RESERVATIONS, "deploy.resources.reservations."),
95
+ ].map((key) => `service \`${name}\` uses \`${key}\`, which a stack may not use`);
96
+ const mounts = (service.volumes ?? [])
97
+ .filter((mount) => !MOUNTS.has(mount.type))
98
+ .map((mount) => `service \`${name}\` mounts a \`${mount.type}\`, which a stack may not use`);
99
+ const open = (service.ports ?? [])
100
+ .filter((port) => port.host_ip !== LOOPBACK)
101
+ .map((port) => `service \`${name}\` publishes ${port.published === undefined ? `container port ${String(port.target)}` : `port ${String(port.published)}`} on ${port.host_ip ?? "every address"}; bind it to ${LOOPBACK}`);
102
+ const onEdge = Object.hasOwn(service.networks ?? {}, EDGE);
103
+ const publishes = (service.ports ?? []).length > 0;
104
+ const edge = onEdge && !publishes
105
+ ? [
106
+ `service \`${name}\` joins the network \`${EDGE}\` but publishes no port; only a service that publishes a port may reach outside the machine`,
107
+ ]
108
+ : publishes && !onEdge
109
+ ? [
110
+ `service \`${name}\` publishes a port but is not on the network \`${EDGE}\`, so the port never answers; add \`${EDGE}\` to its networks`,
111
+ ]
112
+ : [];
113
+ const memory = service.mem_limit ?? resources?.limits?.memory;
114
+ const cpus = service.cpus ?? resources?.limits?.cpus;
115
+ const capped = [
116
+ ...(memory === undefined ? ["memory"] : []),
117
+ ...(cpus === undefined ? ["CPU"] : []),
118
+ ].map((what) => `service \`${name}\` has no ${what} limit; set \`deploy.resources.limits\``);
119
+ return [...keys, ...mounts, ...open, ...edge, ...capped];
120
+ }
121
+ /** What the top of the file breaks: a key a stack may not use, a network other than `edge` that is not `internal: true`, a network or a volume from outside the stack, with a name other than the one Compose gives it in `project`, which would reach a network or a volume of another project, or with a driver other than the local one, and a config or a secret from outside the stack or from a variable of the process that runs Compose. */
122
+ function topRefusals(config, project) {
123
+ const keys = unknownKeys(config, TOP).map((key) => `the Compose file uses \`${key}\`, which a stack may not use`);
124
+ const parts = [
125
+ ["network", config.networks, "bridge"],
126
+ ["volume", config.volumes, "local"],
127
+ ].flatMap(([kind, all, driver]) => Object.entries(all ?? {}).flatMap(([name, part]) => [
128
+ ...(part?.external === undefined || part.external === false
129
+ ? []
130
+ : [`the ${kind} \`${name}\` is outside the stack`]),
131
+ ...(part?.name === undefined || part.name === `${project}_${name}`
132
+ ? []
133
+ : [`the ${kind} \`${name}\` uses the name \`${part.name}\`, which is not the stack's own`]),
134
+ ...(part?.driver === undefined || part.driver === driver
135
+ ? []
136
+ : [`the ${kind} \`${name}\` uses the driver \`${part.driver}\``]),
137
+ ]));
138
+ const outward = Object.entries(config.networks ?? {})
139
+ .filter(([name, part]) => name !== EDGE && part?.internal !== true)
140
+ .map(([name]) => `the network \`${name}\` reaches outside the machine; set \`internal: true\`, since only the network \`${EDGE}\` may`);
141
+ const sources = [
142
+ ["config", config.configs],
143
+ ["secret", config.secrets],
144
+ ].flatMap(([kind, all]) => Object.entries(all ?? {}).flatMap(([name, source]) => [
145
+ ...(source.external === undefined || source.external === false
146
+ ? []
147
+ : [`the ${kind} \`${name}\` is outside the stack`]),
148
+ ...(source.environment === undefined
149
+ ? []
150
+ : [
151
+ `the ${kind} \`${name}\` reads the variable ${source.environment} of the process that runs Compose`,
152
+ ]),
153
+ ]));
154
+ return [...keys, ...parts, ...outward, ...sources];
155
+ }
156
+ /** What the Compose file of the stack's Compose `project` breaks of the rules: `topRefusals`, `serviceRefusals` of each service, and each path of `hostPaths` whose real path, in `real`, is outside `checkout`, the real path of the run's checkout. Empty when the file follows them. */
157
+ export function refusals(config, project, checkout, real) {
158
+ const outside = hostPaths(config).flatMap((path) => {
159
+ const resolved = real.get(path);
160
+ if (resolved === undefined)
161
+ return [`the path ${path} does not resolve`];
162
+ return resolved === checkout || resolved.startsWith(`${checkout}/`)
163
+ ? []
164
+ : [`the path ${path} is outside the checkout`];
165
+ });
166
+ const services = Object.entries(config.services).flatMap(([name, service]) => serviceRefusals(name, service));
167
+ return [...topRefusals(config, project), ...services, ...outside];
168
+ }
169
+ /** Each container that is not up: one that runs with a health check that is not `healthy` yet, or one that stopped with an exit code other than 0. A one-off job, such as a migration, that ended with 0 is up. */
170
+ export function notUp(containers) {
171
+ return containers.flatMap(({ Service, State, Health, ExitCode }) => {
172
+ if (State === "running" && (Health === undefined || Health === "" || Health === "healthy"))
173
+ return [];
174
+ if (State === "exited" && ExitCode === 0)
175
+ return [];
176
+ const health = Health === undefined || Health === "" ? "" : `, ${Health}`;
177
+ const code = State === "exited" ? `, exit ${String(ExitCode)}` : "";
178
+ return [`\`${Service}\` is ${State}${health}${code}`];
179
+ });
180
+ }
@@ -0,0 +1,57 @@
1
+ {
2
+ "contract": 1,
3
+ "name": "docker",
4
+ "version": "0.1.1",
5
+ "config_schema": "schemas/config.json",
6
+ "secrets": [],
7
+ "capabilities": ["sandbox:read", "sandbox:write"],
8
+ "tools": [],
9
+ "webhooks": [],
10
+ "workflows": [],
11
+ "roles": [],
12
+ "skills": [],
13
+ "tracker": null,
14
+ "environments": [
15
+ {
16
+ "name": "compose",
17
+ "prepare": {
18
+ "description": "Check the stack's Compose file and build its images",
19
+ "input_schema": "schemas/environment.compose.prepare.in.json",
20
+ "output_schema": "schemas/environment.compose.prepare.out.json",
21
+ "secrets": [],
22
+ "capabilities": ["sandbox:read", "sandbox:write"]
23
+ },
24
+ "start": {
25
+ "description": "Start the stack and wait until it is healthy",
26
+ "input_schema": "schemas/environment.compose.start.in.json",
27
+ "output_schema": "schemas/environment.compose.start.out.json",
28
+ "secrets": [],
29
+ "capabilities": ["sandbox:read", "sandbox:write"]
30
+ },
31
+ "health": {
32
+ "description": "Check that each container of the stack is up",
33
+ "input_schema": "schemas/environment.compose.health.in.json",
34
+ "output_schema": "schemas/environment.compose.health.out.json",
35
+ "secrets": [],
36
+ "capabilities": ["sandbox:read", "sandbox:write"]
37
+ },
38
+ "stop": {
39
+ "description": "Remove the stack's containers, networks, volumes and built images",
40
+ "input_schema": "schemas/environment.compose.stop.in.json",
41
+ "output_schema": "schemas/environment.compose.stop.out.json",
42
+ "secrets": [],
43
+ "capabilities": ["sandbox:read", "sandbox:write"]
44
+ }
45
+ }
46
+ ],
47
+ "hooks": [],
48
+ "executables": {
49
+ "requires": [
50
+ {
51
+ "name": "docker",
52
+ "reason": "The environment compose runs docker compose in the sandbox of the run."
53
+ }
54
+ ],
55
+ "provides": []
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@kana-ai/edgar-ext-docker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "EDGAR extension for Docker: a service's Docker Compose stack as the environment that its checks run against.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kana-ai/edgar",
9
+ "directory": "packages/extensions/ext-docker"
10
+ },
11
+ "files": [
12
+ "dist/src",
13
+ "edgar-extension.json",
14
+ "schemas"
15
+ ],
16
+ "type": "module",
17
+ "imports": {
18
+ "#*": "./dist/src/*.js"
19
+ },
20
+ "exports": {
21
+ ".": "./dist/src/index.js"
22
+ },
23
+ "dependencies": {
24
+ "@kana-ai/edgar-sdk": "0.1.1",
25
+ "zod": "4.6.7"
26
+ },
27
+ "devDependencies": {
28
+ "@kana-ai/edgar-contracts": "0.1.1",
29
+ "@types/node": "24.19.2",
30
+ "oxfmt": "0.76.0",
31
+ "oxlint": "1.91.0",
32
+ "oxlint-tsgolint": "7.0.2005",
33
+ "typescript": "7.0.2"
34
+ },
35
+ "scripts": {
36
+ "build": "edgar-extension-build src/index.ts",
37
+ "check-types": "tsc --noEmit",
38
+ "lint": "oxlint --type-aware --deny-warnings",
39
+ "format:check": "oxfmt --check",
40
+ "test": "node --test"
41
+ }
6
42
  }
@@ -0,0 +1,32 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "stacks": {
6
+ "default": {},
7
+ "type": "object",
8
+ "propertyNames": {
9
+ "type": "string",
10
+ "minLength": 1
11
+ },
12
+ "additionalProperties": {
13
+ "type": "object",
14
+ "properties": {
15
+ "file": {
16
+ "default": "docker-compose.yml",
17
+ "type": "string",
18
+ "minLength": 1
19
+ },
20
+ "wait_seconds": {
21
+ "default": 300,
22
+ "type": "integer",
23
+ "minimum": 1,
24
+ "maximum": 540
25
+ }
26
+ },
27
+ "additionalProperties": false
28
+ }
29
+ }
30
+ },
31
+ "additionalProperties": false
32
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "service": {
6
+ "type": "string",
7
+ "minLength": 1
8
+ },
9
+ "slot": {
10
+ "type": "integer",
11
+ "minimum": 1,
12
+ "maximum": 9007199254740991
13
+ },
14
+ "run": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string",
18
+ "minLength": 1
19
+ },
20
+ {
21
+ "type": "integer",
22
+ "minimum": -9007199254740991,
23
+ "maximum": 9007199254740991
24
+ }
25
+ ]
26
+ }
27
+ },
28
+ "required": ["service", "slot", "run"],
29
+ "additionalProperties": {}
30
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "project": {
6
+ "type": "string"
7
+ }
8
+ },
9
+ "required": ["project"]
10
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "service": {
6
+ "type": "string",
7
+ "minLength": 1
8
+ },
9
+ "slot": {
10
+ "type": "integer",
11
+ "minimum": 1,
12
+ "maximum": 9007199254740991
13
+ },
14
+ "run": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string",
18
+ "minLength": 1
19
+ },
20
+ {
21
+ "type": "integer",
22
+ "minimum": -9007199254740991,
23
+ "maximum": 9007199254740991
24
+ }
25
+ ]
26
+ }
27
+ },
28
+ "required": ["service", "slot", "run"],
29
+ "additionalProperties": {}
30
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "project": {
6
+ "type": "string"
7
+ }
8
+ },
9
+ "required": ["project"]
10
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "service": {
6
+ "type": "string",
7
+ "minLength": 1
8
+ },
9
+ "slot": {
10
+ "type": "integer",
11
+ "minimum": 1,
12
+ "maximum": 9007199254740991
13
+ },
14
+ "run": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string",
18
+ "minLength": 1
19
+ },
20
+ {
21
+ "type": "integer",
22
+ "minimum": -9007199254740991,
23
+ "maximum": 9007199254740991
24
+ }
25
+ ]
26
+ }
27
+ },
28
+ "required": ["service", "slot", "run"],
29
+ "additionalProperties": {}
30
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "project": {
6
+ "type": "string"
7
+ }
8
+ },
9
+ "required": ["project"]
10
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "service": {
6
+ "type": "string",
7
+ "minLength": 1
8
+ },
9
+ "slot": {
10
+ "type": "integer",
11
+ "minimum": 1,
12
+ "maximum": 9007199254740991
13
+ },
14
+ "run": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string",
18
+ "minLength": 1
19
+ },
20
+ {
21
+ "type": "integer",
22
+ "minimum": -9007199254740991,
23
+ "maximum": 9007199254740991
24
+ }
25
+ ]
26
+ }
27
+ },
28
+ "required": ["service", "slot", "run"],
29
+ "additionalProperties": {}
30
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "properties": {
5
+ "project": {
6
+ "type": "string"
7
+ }
8
+ },
9
+ "required": ["project"]
10
+ }