werkmeister-core 0.90.4 → 0.90.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # sandbox-core
2
2
 
3
+ ## 0.90.6
4
+
5
+ ### Patch Changes
6
+
7
+ - fa318f9: Faster starts and prompt exits. `dockerode` (about 300 modules, ~0.2 s of CPU) loads on the first Docker call instead of at start, so a command that never reaches the Engine no longer pays for it. A command that is not installed (a missing `gh`, say) no longer holds the process open for its whole timeout after failing. The MCP proxy exits when its client closes stdin, instead of waiting two seconds to be signalled.
8
+
9
+ ## 0.90.5
10
+
11
+ ### Patch Changes
12
+
13
+ - c1088f8: The fixture's fake `gh` and `docker` (`with-fixture-workspace`, `withFixtureWorkspace`, `withFakeGh`) are POSIX shell scripts that read their world from plain files, not Node scripts reading `world.json`. A call took ~100 ms to start Node; a fixture flow makes dozens, so the fixture-workspace tests run up to 2x faster. Their output, exit codes and call logs are unchanged.
14
+
3
15
  ## 0.90.4
4
16
 
5
17
  ## 0.90.3
package/dist/docker.d.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * `depends_on: service_healthy`, profiles, BuildKit, `.env` interpolation — is a
11
11
  * project to reimplement, not a refactor.
12
12
  */
13
- import Dockerode, { type DockerOptions } from "dockerode";
13
+ import type Dockerode from "dockerode";
14
+ import type { DockerOptions } from "dockerode";
14
15
  /**
15
16
  * Where the daemon is.
16
17
  *
package/dist/docker.js CHANGED
@@ -16,9 +16,9 @@ import * as os from "node:os";
16
16
  import * as path from "node:path";
17
17
  import { PassThrough, Readable } from "node:stream";
18
18
  import { StringDecoder } from "node:string_decoder";
19
- import Dockerode from "dockerode";
20
19
  import * as tar from "tar-fs";
21
20
  import { BLUE, CYAN, GREEN, MAGENTA, RESET, YELLOW } from "./colors.js";
21
+ import { loadDockerode } from "./dockerode_load.js";
22
22
  import { ProcError, run } from "./proc.js";
23
23
  /**
24
24
  * Where the daemon is.
@@ -125,7 +125,7 @@ export function endpointOptions(host) {
125
125
  let client = null;
126
126
  /** The shared client. The endpoint is resolved once, on first use. */
127
127
  export function docker() {
128
- return (client ??= new Dockerode(resolveEndpoint()));
128
+ return (client ??= new (loadDockerode())(resolveEndpoint()));
129
129
  }
130
130
  /**
131
131
  * A compose project's containers, found by the labels compose stamps on them.
@@ -0,0 +1,2 @@
1
+ import type Dockerode from "dockerode";
2
+ export declare function loadDockerode(): typeof Dockerode;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * dockerode, loaded on first use. Its graph is about 300 CommonJS modules (~0.2 s of CPU at
3
+ * start), and most processes that import docker.ts never reach the Engine.
4
+ *
5
+ * A bundler cannot follow this require: the CLI leaves dockerode external, so it resolves at
6
+ * run time, and the VS Code extension's esbuild.mjs swaps this module for a static import.
7
+ */
8
+ import { createRequire } from "node:module";
9
+ export function loadDockerode() {
10
+ return createRequire(import.meta.url)("dockerode");
11
+ }
@@ -1,10 +1,10 @@
1
1
  /**
2
- * The one set of fakes for fixtures and core tests (SW-427): a fake `gh` and `docker` that read one
3
- * `world.json` and log each call. `seedFixture` and `withFakeGh` both write them, so a gh verb added
2
+ * The one set of fakes for fixtures and core tests (SW-427): a fake `gh` and `docker` that read their
3
+ * world from plain files beside them and log each call. `seedFixture` and `withFakeGh` both write them, so a gh verb added
4
4
  * here reaches every test. They stay generated text, not files in a folder: the CLI bundles core,
5
5
  * so a folder read at runtime would be missing from the published build.
6
6
  */
7
- /** What the fakes answer. Absent fields take the defaults in FAKE_JS. */
7
+ /** What the fakes answer. Absent fields take the defaults in FAKE_SH. */
8
8
  export interface FakeWorld {
9
9
  /** `gh issue view` prints it as JSON; null or absent exits 1 ("could not resolve"). */
10
10
  issue?: unknown;
@@ -1,6 +1,6 @@
1
1
  /**
2
- * The one set of fakes for fixtures and core tests (SW-427): a fake `gh` and `docker` that read one
3
- * `world.json` and log each call. `seedFixture` and `withFakeGh` both write them, so a gh verb added
2
+ * The one set of fakes for fixtures and core tests (SW-427): a fake `gh` and `docker` that read their
3
+ * world from plain files beside them and log each call. `seedFixture` and `withFakeGh` both write them, so a gh verb added
4
4
  * here reaches every test. They stay generated text, not files in a folder: the CLI bundles core,
5
5
  * so a folder read at runtime would be missing from the published build.
6
6
  */
@@ -12,82 +12,90 @@ import * as path from "node:path";
12
12
  // Only the gate's `ps --format {{.Names}}\t{{.State}}` sees running containers; every other `ps`
13
13
  // (-q/-aq by label) finds none, so no teardown of a pre-rename project runs on a fake hit. Only the
14
14
  // scheduler's exact feature-label `ps -q` and its NanoCpus `inspect` see `containers` (SW-685).
15
- const FAKE_JS = `import { spawnSync } from "node:child_process";
16
- import * as fs from "node:fs";
17
- const [, , tool, dir, ...args] = process.argv;
18
- const worldFile = dir + "/world.json";
19
- const world = JSON.parse(fs.readFileSync(worldFile, "utf8"));
20
- // A gate exec logs as \`exec <container> <row command>\`: the inlined with-temp-home script is ~1.5 KB a row (SW-511).
21
- const logged = tool === "docker" && args[0] === "exec" ? ["exec", args[1], args.at(-1)] : args;
22
- fs.appendFileSync(dir + "/" + (tool === "gh" ? "calls" : "docker-calls"), logged.join(" ").replace(/\\n/g, " ") + "\\n");
23
- const out = (s) => process.stdout.write(s);
24
- const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); };
25
- const verb = args.slice(0, 2).join(" ");
26
- const labels = world.labels ?? [];
27
- if (tool === "gh") {
28
- switch (verb) {
29
- case "auth status":
30
- process.stderr.write((world.auth ?? 0) === 0 ? " ✓ Logged in to github.com account octo (keyring)\\n" : "You are not logged into any GitHub hosts.\\n");
31
- process.exit(world.auth ?? 0);
32
- case "api user": out("octo\\n"); break;
33
- // The gate's merge row (SW-457): any other \`gh api\` path still falls through to unhandled.
34
- case "api " + args[1]:
35
- if (!args[1].includes("/rules/branches/")) fail("fake gh: unhandled: " + args.join(" "));
36
- out(JSON.stringify(world.rules ?? []) + "\\n");
37
- break;
38
- case "search prs": out("[]\\n"); break;
39
- case "pr list": break;
40
- case "pr create": out((world.prUrl ?? "https://github.com/o/app/pull/1") + "\\n"); break;
41
- case "pr view": {
42
- const state = world.prState ?? "OPEN";
43
- out(JSON.stringify({
44
- url: args[2], number: 1, title: "fixture", state, headRefName: "me/demo", baseRefName: "main", headRefOid: "",
45
- mergeCommit: state === "MERGED" ? { oid: "0".repeat(40) } : null, mergeable: "MERGEABLE", reviewDecision: "",
46
- latestReviews: [], reviews: [], comments: [], files: [], statusCheckRollup: [],
47
- }) + "\\n");
48
- break;
49
- }
50
- case "repo view": process.exit(world.repoView ?? 0);
51
- case "label create":
52
- if (!labels.includes(args[2])) fs.writeFileSync(worldFile, JSON.stringify({ ...world, labels: [...labels, args[2]] }));
53
- break;
54
- case "issue edit":
55
- if (args[5] === "--add-label" && !labels.includes(args[6])) fail("'" + args[6] + "' not found");
56
- break;
57
- case "issue view":
58
- if (world.issue == null) fail("could not resolve");
59
- out(JSON.stringify(world.issue) + "\\n");
60
- break;
61
- case "issue list": out(JSON.stringify(world.issues ?? []) + "\\n"); break;
62
- case "project item-list": out(JSON.stringify({ items: world.items ?? [] }) + "\\n"); break;
63
- case "issue close": case "issue comment": break;
64
- default: fail("fake gh: unhandled: " + args.join(" "));
65
- }
66
- } else {
67
- switch (args[0]) {
68
- case "ps":
69
- if (args.some((a) => a.includes("{{.Names}}"))) out((world.running ?? []).map((c) => c + "\\trunning\\n").join(""));
70
- else if (args.join(" ") === "ps -q --filter label=com.werkmeister.feature") out((world.containers ?? []).map((_, i) => "c" + i + "\\n").join(""));
71
- break;
72
- case "inspect":
73
- out(args[1] === "--format" && args[2].includes("NanoCpus") ? (world.containers ?? []).map((l) => l + "\\n").join("") : "false\\n");
74
- break;
75
- case "exec":
76
- if (world.execCwd) process.exit(spawnSync("sh", ["-c", args.at(-1)], { cwd: world.execCwd, stdio: "inherit" }).status ?? 1);
77
- break;
78
- case "stop": case "compose": case "network": break;
79
- default: fail("fake docker: unhandled: " + args.join(" "));
80
- }
81
- }
15
+ // POSIX sh, not node: a fixture flow makes dozens of gh/docker calls and a node start was ~100 ms
16
+ // each. The world is plain files next to the script (writeFakes), so there is no JSON to parse.
17
+ const FAKE_SH = `get() { v=$2; [ -f "$dir/$1" ] && IFS= read -r v < "$dir/$1"; printf '%s' "$v"; }
18
+ show() { IFS= read -r v < "$dir/$1"; printf '%s\\n' "$v"; }
19
+ out() { printf '%s\\n' "$1"; }
20
+ fail() { printf '%s\\n' "$1" >&2; exit 1; }
21
+ if [ "$tool" = gh ]; then log=calls; else log=docker-calls; fi
22
+ # A gate exec logs as \`exec <container> <row command>\`: the inlined with-temp-home script is ~1.5 KB a row (SW-511).
23
+ if [ "$tool" = docker ] && [ "$1" = exec ]; then for last; do :; done; line="exec $2 $last"; else line="$*"; fi
24
+ case "$line" in *'
25
+ '*) line=$(printf '%s' "$line" | tr '\\n' ' ') ;; esac
26
+ printf '%s\\n' "$line" >> "$dir/$log"
27
+ if [ "$tool" = gh ]; then
28
+ case "$1 $2" in
29
+ "auth status")
30
+ a=$(get auth 0)
31
+ if [ "$a" = 0 ]; then out ' ✓ Logged in to github.com account octo (keyring)' >&2; else out 'You are not logged into any GitHub hosts.' >&2; fi
32
+ exit "$a" ;;
33
+ "api user") out octo ;;
34
+ "api "*)
35
+ # The gate's merge row (SW-457): any other \`gh api\` path still falls through to unhandled.
36
+ case "$2" in */rules/branches/*) show rules.json ;; *) fail "fake gh: unhandled: $*" ;; esac ;;
37
+ "search prs") out '[]' ;;
38
+ "pr list") ;;
39
+ "pr create") out "$(get prUrl https://github.com/o/app/pull/1)" ;;
40
+ "pr view")
41
+ state=$(get prState OPEN)
42
+ merge=null
43
+ [ "$state" = MERGED ] && merge='{"oid":"0000000000000000000000000000000000000000"}'
44
+ url=
45
+ [ $# -ge 3 ] && url=$(printf '%s' "$3" | sed 's/\\\\/\\\\\\\\/g; s/"/\\\\"/g; s/^/"url":"/; s/$/",/')
46
+ out "{\${url}\\"number\\":1,\\"title\\":\\"fixture\\",\\"state\\":\\"$state\\",\\"headRefName\\":\\"me/demo\\",\\"baseRefName\\":\\"main\\",\\"headRefOid\\":\\"\\",\\"mergeCommit\\":$merge,\\"mergeable\\":\\"MERGEABLE\\",\\"reviewDecision\\":\\"\\",\\"latestReviews\\":[],\\"reviews\\":[],\\"comments\\":[],\\"files\\":[],\\"statusCheckRollup\\":[]}" ;;
47
+ "repo view") exit "$(get repoView 0)" ;;
48
+ "label create") grep -Fxq -- "$3" "$dir/labels" || printf '%s\\n' "$3" >> "$dir/labels" ;;
49
+ "issue edit")
50
+ if [ "$6" = --add-label ] && ! grep -Fxq -- "$7" "$dir/labels"; then fail "'$7' not found"; fi ;;
51
+ "issue view") [ -f "$dir/issue.json" ] || fail "could not resolve"; show issue.json ;;
52
+ "issue list") show issues.json ;;
53
+ "project item-list") show items.json ;;
54
+ "issue close"|"issue comment") ;;
55
+ *) fail "fake gh: unhandled: $*" ;;
56
+ esac
57
+ else
58
+ case "$1" in
59
+ ps)
60
+ case "$*" in
61
+ *'{{.Names}}'*) while IFS= read -r c; do printf '%s\\trunning\\n' "$c"; done < "$dir/running" ;;
62
+ "ps -q --filter label=com.werkmeister.feature") i=0; while IFS= read -r c; do printf 'c%s\\n' "$i"; i=$((i + 1)); done < "$dir/containers" ;;
63
+ esac ;;
64
+ inspect)
65
+ if [ "$2" = --format ] && case "$3" in *NanoCpus*) true ;; *) false ;; esac; then cat "$dir/containers"; else out false; fi ;;
66
+ exec)
67
+ if [ -f "$dir/execCwd" ]; then cd -P "$(cat "$dir/execCwd")" 2>/dev/null || exit 1; sh -c "$last"; exit $?; fi ;;
68
+ stop|compose|network) ;;
69
+ *) fail "fake docker: unhandled: $*" ;;
70
+ esac
71
+ fi
82
72
  `;
83
- const shim = (dir, tool) => `#!/bin/sh\nexec '${process.execPath}' '${path.join(dir, "fake.mjs")}' ${tool} '${dir}' "$@"\n`;
73
+ /** Newline-terminated lines, or nothing for an empty list. */
74
+ const lines = (xs) => xs.map((x) => `${x}\n`).join("");
84
75
  /** Write the fakes and *world* into *dir* (created if missing); returns where they are. */
85
76
  export function writeFakes(dir, world = {}) {
86
77
  fs.mkdirSync(dir, { recursive: true });
87
- fs.writeFileSync(path.join(dir, "world.json"), JSON.stringify(world));
88
- fs.writeFileSync(path.join(dir, "fake.mjs"), FAKE_JS);
78
+ const put = (name, body) => fs.writeFileSync(path.join(dir, name), body);
79
+ put("auth", String(world.auth ?? 0));
80
+ put("repoView", String(world.repoView ?? 0));
81
+ put("labels", lines(world.labels ?? []));
82
+ put("issues.json", JSON.stringify(world.issues ?? []));
83
+ put("items.json", JSON.stringify({ items: world.items ?? [] }));
84
+ put("rules.json", JSON.stringify(world.rules ?? []));
85
+ put("running", lines(world.running ?? []));
86
+ put("containers", lines(world.containers ?? []));
87
+ if (world.issue != null)
88
+ put("issue.json", JSON.stringify(world.issue));
89
+ if (world.prUrl !== undefined)
90
+ put("prUrl", world.prUrl);
91
+ if (world.prState !== undefined)
92
+ put("prState", world.prState);
93
+ if (world.execCwd)
94
+ put("execCwd", world.execCwd);
89
95
  for (const tool of ["gh", "docker"])
90
- fs.writeFileSync(path.join(dir, tool), shim(dir, tool), { mode: 0o755 });
96
+ fs.writeFileSync(path.join(dir, tool), `#!/bin/sh\ntool=${tool} dir='${dir}'\n${FAKE_SH}`, {
97
+ mode: 0o755,
98
+ });
91
99
  return {
92
100
  gh: path.join(dir, "gh"),
93
101
  docker: path.join(dir, "docker"),
package/dist/proc.js CHANGED
@@ -94,8 +94,12 @@ export function runAsync(cmd, opts = {}) {
94
94
  env: spawnEnv(cmd, opts.env),
95
95
  stdio,
96
96
  signal: opts.signal,
97
- timeout: opts.timeout !== undefined ? timeoutMs(opts.timeout) : undefined,
98
97
  });
98
+ // Not spawn's own `timeout`: Node leaves that timer running when the command is missing,
99
+ // and it holds the process open for the whole timeout after the ENOENT.
100
+ const timer = opts.timeout !== undefined
101
+ ? setTimeout(() => child.kill(), timeoutMs(opts.timeout))
102
+ : undefined;
99
103
  let stdout = "";
100
104
  let stderr = "";
101
105
  child.stdout?.on("data", (d) => (stdout += d.toString()));
@@ -119,6 +123,7 @@ export function runAsync(cmd, opts = {}) {
119
123
  };
120
124
  const aborted = () => opts.signal?.aborted === true;
121
125
  child.on("error", (e) => {
126
+ clearTimeout(timer);
122
127
  const code = e.code;
123
128
  if (aborted()) {
124
129
  fail(`Command aborted: ${cmd.join(" ")}`, -1, "ABORT_ERR");
@@ -131,11 +136,12 @@ export function runAsync(cmd, opts = {}) {
131
136
  fail(`Command failed to start: ${cmd.join(" ")} (${e.message})`, -1, code);
132
137
  });
133
138
  child.on("close", (status) => {
139
+ clearTimeout(timer);
134
140
  if (aborted()) {
135
141
  fail(`Command aborted: ${cmd.join(" ")}`, -1, "ABORT_ERR");
136
142
  return;
137
143
  }
138
- // Not aborted, so a kill can only be the timeout we passed to spawn. Asked of
144
+ // Not aborted, so a kill can only be the timeout above. Asked of
139
145
  // the child, not its exit shape: docker compose traps the SIGTERM and exits
140
146
  // 130 with no signal (SW-86).
141
147
  if (child.killed && opts.timeout !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister-core",
3
- "version": "0.90.4",
3
+ "version": "0.90.6",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "werkmeister's shared library. Its public API is werkmeister-core/sdk; every other entry point is internal.",