werkmeister-core 0.0.0 → 0.89.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/CHANGELOG.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # sandbox-core
2
2
 
3
+ ## 0.89.1
4
+
3
5
  ## 0.89.0
4
6
 
5
7
  ### Minor Changes
@@ -501,7 +501,7 @@ or visit https://${proxy.host}/__werkmeister and select \`${feature}\` — the s
501
501
  How to exercise a change to each service in this workspace.${onDemand.length
502
502
  ? ` A plain \`werkmeister feature up\` skips the on-demand ones, ${onDemand.map((s) => `\`${s}\``).join(", ")}: start one with \`werkmeister feature up --service <name>\`.`
503
503
  : ""}${tempHome
504
- ? ` Each test command runs through \`.werkmeister/bin/with-temp-home\`, which gives it a fresh temporary HOME and deletes it on exit: never hand-roll \`HOME=…\`. Start every exercise command with the script itself, never with env assignments or a \`cd\`, so one permission rule matches it: \`${tempHome} <test command>\`. A command that needs an env var takes it after the script (\`${tempHome} env WERKMEISTER_ROOT=… <cmd>\`); no rule pre-approves that form, so it asks. Put \`--no-wait\` first (\`${tempHome} --no-wait <cmd>\`) to skip its host-load wait; the allow rules below cover that form too. That wait lasts up to 90 s; if load is still over then, the script exits 75 without running the command (retry later). It prints only on stderr, so a foreground call shows nothing until it ends and its only child is \`werkmeister internal wait-load\`: that is the wait, not a hang. The allow rule that covers them is \`Bash(${tempHome} <test command>:*)\` for each test command below: run those for a test without a prompt. A test command of more than one command (an \`&&\` chain, a \`{ …; }\` group, \`||\`, \`;\` or a pipe) is shown as \`${tempHome} sh -c '…'\`, so every part runs under the temp HOME, and its rule allows that exact line: run it as shown, with no extra arguments. Neither \`node --test\` through the script nor the script alone is allowed, since both run any file (SW-510). The temp HOME only keeps a run from writing to the real one by accident; it is not an isolation boundary. A pre-approved test command or built CLI still runs whatever the worktree holds, a test written in this run included, and that code can reach absolute paths, the caller's env, the network, docker and gh (SW-522).`
504
+ ? ` Each test command runs through \`.werkmeister/bin/with-temp-home\`, which gives it a fresh temporary HOME and deletes it on exit: never hand-roll \`HOME=…\`. Start every exercise command with the script itself, never with env assignments or a \`cd\`, so one permission rule matches it: \`${tempHome} <test command>\`. A command that needs an env var takes it after the script (\`${tempHome} env WERKMEISTER_ROOT=… <cmd>\`); no rule pre-approves that form, so it asks. Put \`--no-wait\` first (\`${tempHome} --no-wait <cmd>\`) to skip its host-load and free-memory wait; the allow rules below cover that form too. That wait lasts up to 90 s; if load or memory is still over its limit then, the script exits 75 without running the command (retry later). It prints only on stderr, so a foreground call shows nothing until it ends and its only child is \`werkmeister internal wait-load\`: that is the wait, not a hang. The allow rule that covers them is \`Bash(${tempHome} <test command>:*)\` for each test command below: run those for a test without a prompt. A test command of more than one command (an \`&&\` chain, a \`{ …; }\` group, \`||\`, \`;\` or a pipe) is shown as \`${tempHome} sh -c '…'\`, so every part runs under the temp HOME, and its rule allows that exact line: run it as shown, with no extra arguments. Neither \`node --test\` through the script nor the script alone is allowed, since both run any file (SW-510). The temp HOME only keeps a run from writing to the real one by accident; it is not an isolation boundary. A pre-approved test command or built CLI still runs whatever the worktree holds, a test written in this run included, and that code can reach absolute paths, the caller's env, the network, docker and gh (SW-522).`
505
505
  : ""}${linted
506
506
  ? " A test command ending in `&& <lint>` also runs the repo's lint, the same command the PR gate's lint row runs, so a format error fails here and not first at `werkmeister pr open`."
507
507
  : ""}
@@ -76,6 +76,11 @@ export interface Deps {
76
76
  load: number[];
77
77
  cores: number;
78
78
  };
79
+ /** Bytes available and total, read once before the gate starts anything (SW-620). */
80
+ hostMemory: () => {
81
+ free: number;
82
+ total: number;
83
+ };
79
84
  sleep: (ms: number) => Promise<void>;
80
85
  /** One idle-reaper pass over every workspace (SW-39). */
81
86
  reapIdle: () => Promise<{
@@ -28,7 +28,7 @@ import { loadNote } from "./resources.js";
28
28
  import { commitAndPush, listRepoWorktrees, listWorkspaces, removeWorkspace, resolveSessionSource, resolveWorkspaceDir, sendToClaudeSession, sessionStartDir, WorkspaceError, worktreeSources,
29
29
  // biome-ignore lint/suspicious/noImportCycles: pr_lifecycle↔sandbox.ts↔usage_snapshot; SW-411
30
30
  } from "./sandbox.js";
31
- import { portHolders, readHostLoad, waitForHostLoadNow } from "./scheduler_state.js";
31
+ import { lowMemory, portHolders, readHostLoad, readHostMemory, waitForHostLoadNow, } from "./scheduler_state.js";
32
32
  import { getServicePort } from "./slots.js";
33
33
  import { repoDirs } from "./standards.js";
34
34
  import { TEMP_HOME_SCRIPT } from "./temp_home.js";
@@ -91,6 +91,7 @@ export function defaultDeps() {
91
91
  stop: stopWorkspace,
92
92
  prWatch: () => prWatchScheduleState(),
93
93
  hostLoad: readHostLoad,
94
+ hostMemory: readHostMemory,
94
95
  sleep: (ms) => delay(ms),
95
96
  reapIdle: async () => {
96
97
  const minutes = idleStopMinutes();
@@ -571,7 +572,8 @@ testsOnly = false) {
571
572
  ...(!ok && capacityShort && NO_CONTAINER.test(detail) && { retry: true }),
572
573
  });
573
574
  const startFailed = (name, e, prefix = "") => {
574
- const capacity = e.code === "NO_CAPACITY";
575
+ // HOST_LOAD: a setup start that waited out load or low memory is the host, not the change (SW-620).
576
+ const capacity = ["NO_CAPACITY", "HOST_LOAD"].includes(e.code ?? "");
575
577
  if (capacity)
576
578
  capacityShort = true;
577
579
  checks.push({
@@ -884,6 +886,18 @@ testsOnly = false) {
884
886
  }
885
887
  return true;
886
888
  };
889
+ // Admission prices reservations, not the host's live memory: Claude Code stops an idle background
890
+ // gate when the Mac runs low, before any row runs, so exit 75 before starting anything (SW-620).
891
+ const memory = lowMemory(deps.hostMemory);
892
+ if (memory) {
893
+ checks.push({
894
+ name: "memory",
895
+ ok: false,
896
+ detail: `low memory: ${memory}; no container started and no row run. Retry later.`,
897
+ retry: true,
898
+ });
899
+ return done();
900
+ }
887
901
  // Running containers come from compose.yml, rendered from the machine registry; a
888
902
  // touched service whose branch settings render differently runs from compose.gate.yml (SW-118).
889
903
  let changed = [];
@@ -1112,7 +1126,7 @@ export function failedRowExcerpt(output, tail) {
1112
1126
  }
1113
1127
  export function formatGate(dir, g) {
1114
1128
  return [
1115
- `${dir}: gate ${g.ok ? "passed" : g.retry ? "retry later (no capacity)" : "FAILED"}`,
1129
+ `${dir}: gate ${g.ok ? "passed" : g.retry ? `retry later (${g.checks.some((c) => c.name === "memory" && !c.ok) ? "low memory" : "no capacity"})` : "FAILED"}`,
1116
1130
  ...g.checks.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.name}: ${c.detail.replace(/\n/g, "\n ")}`),
1117
1131
  ];
1118
1132
  }
@@ -39,11 +39,30 @@ export declare function loadBudget(info?: () => Promise<{
39
39
  }>): Promise<Budget>;
40
40
  /** 1-min host load above which with-temp-home and a setup start wait (SW-209, SW-542, SW-630): `budget.host_load`, else 2 × cores; 0 is off. */
41
41
  export declare function hostLoadLimit(cores: number): number;
42
+ /** % of memory available under which the gate and with-temp-home hold off (SW-620): `budget.free_memory`, else 15; 0 is off. */
43
+ export declare function freeMemoryLimit(): number;
44
+ /**
45
+ * Bytes available and total. On macOS os.freemem() counts only untouched pages (0.08 of 16 GiB on a
46
+ * healthy host), so it reads kern.memorystatus_level, the % the kernel calls available (SW-620).
47
+ */
48
+ export declare function readHostMemory(platform?: NodeJS.Platform): {
49
+ free: number;
50
+ total: number;
51
+ };
52
+ /** "N% free, under budget.free_memory M%" when memory is low, else ""; unreadable memory is not low. */
53
+ export declare function lowMemory(hostMemory?: () => {
54
+ free: number;
55
+ total: number;
56
+ }): string;
42
57
  export interface HostLoadDeps {
43
58
  hostLoad: () => {
44
59
  load: number[];
45
60
  cores: number;
46
61
  };
62
+ hostMemory: () => {
63
+ free: number;
64
+ total: number;
65
+ };
47
66
  sleep: (ms: number) => Promise<unknown>;
48
67
  }
49
68
  export declare const readHostLoad: () => {
@@ -52,16 +71,18 @@ export declare const readHostLoad: () => {
52
71
  };
53
72
  /**
54
73
  * The wait of `werkmeister internal wait-load`, which the generated with-temp-home runs first (SW-224):
55
- * up to 90 s for the 1-minute load to fall under the limit, saying so up front and printing progress
56
- * each minute (SW-262); the note for the wrapper's stderr, or "". The gate stopped waiting in SW-542.
57
- * Not on macOS: its loadavg counts idle daemons in R state (450-550 on a quiet host) and never the
58
- * Linux VM that runs the tests, so it is no signal to wait on and the wait was pure delay (SW-556).
74
+ * up to 90 s for the 1-minute load to fall under the limit and free memory to rise over its own (SW-620),
75
+ * saying so up front and printing progress each minute (SW-262); the note for the wrapper's stderr, or "".
76
+ * A spent wait's note starts "ran with". The gate stopped waiting in SW-542.
77
+ * Load not on macOS: its loadavg counts idle daemons in R state (450-550 on a quiet host) and never the
78
+ * Linux VM that runs the tests, so it is no signal to wait on (SW-556). Its memory is: Claude Code
79
+ * stops an idle background shell when the Mac runs low (SW-620).
59
80
  */
60
81
  export declare function waitForHostLoadNow(deps?: HostLoadDeps, platform?: NodeJS.Platform, before?: string): Promise<string>;
61
82
  /**
62
83
  * Before compose starts a setup one-shot among *services* (undefined: what a whole `up` starts),
63
- * wait on host load as with-temp-home does, and fail with the load once the wait is spent (SW-630):
64
- * a setup install started at load ~413 ran 78 min, past compose's 20 min `--wait`, and ended 137.
84
+ * wait on host load and free memory as with-temp-home does, and fail once the wait is spent (SW-630,
85
+ * SW-620): a setup install started at load ~413 ran 78 min, past compose's 20 min `--wait`, and ended 137.
65
86
  *
66
87
  * Throws `HOST_LOAD`.
67
88
  */
@@ -11,6 +11,7 @@
11
11
  * What is running, and what it costs, is never stored: `lifecycle.ts` reads it
12
12
  * from Docker on every decision, because `up` exits once containers start.
13
13
  */
14
+ import { execFileSync } from "node:child_process";
14
15
  import { createHash } from "node:crypto";
15
16
  import * as fs from "node:fs";
16
17
  import * as net from "node:net";
@@ -115,43 +116,106 @@ export function hostLoadLimit(cores) {
115
116
  const v = isDict(cfg) ? Number(cfg["host_load"] ?? Number.NaN) : Number.NaN;
116
117
  return Number.isFinite(v) && v >= 0 ? v : 2 * cores;
117
118
  }
119
+ /** % of memory available under which the gate and with-temp-home hold off (SW-620): `budget.free_memory`, else 15; 0 is off. */
120
+ export function freeMemoryLimit() {
121
+ const cfg = loadGlobalConfig()["budget"];
122
+ const v = isDict(cfg) ? Number(cfg["free_memory"] ?? Number.NaN) : Number.NaN;
123
+ return Number.isFinite(v) && v >= 0 ? v : 15;
124
+ }
125
+ /**
126
+ * Bytes available and total. On macOS os.freemem() counts only untouched pages (0.08 of 16 GiB on a
127
+ * healthy host), so it reads kern.memorystatus_level, the % the kernel calls available (SW-620).
128
+ */
129
+ export function readHostMemory(platform = process.platform) {
130
+ const total = os.totalmem();
131
+ if (platform !== "darwin")
132
+ return { free: os.freemem(), total };
133
+ const level = Number(execFileSync("sysctl", ["-n", "kern.memorystatus_level"], { encoding: "utf8" }));
134
+ return { free: (total * level) / 100, total };
135
+ }
136
+ /** "N% free, under budget.free_memory M%" when memory is low, else ""; unreadable memory is not low. */
137
+ export function lowMemory(hostMemory = readHostMemory) {
138
+ const limit = freeMemoryLimit();
139
+ if (limit === 0)
140
+ return "";
141
+ let pct;
142
+ try {
143
+ const { free, total } = hostMemory();
144
+ pct = (100 * free) / total;
145
+ }
146
+ catch {
147
+ return "";
148
+ }
149
+ return Number.isFinite(pct) && pct < limit
150
+ ? `${pct.toFixed(0)}% free, under budget.free_memory ${limit}%`
151
+ : "";
152
+ }
118
153
  const LOAD_POLL_MS = 15_000;
119
154
  // with-temp-home's own wait: under an agent's default 2 min Bash timeout, so the call can't time out before its command starts (SW-469).
120
155
  const WRAPPER_LOAD_WAIT_MS = 90_000;
121
156
  const LOAD_PROGRESS_MS = 60_000;
122
157
  export const readHostLoad = () => ({ load: os.loadavg(), cores: os.availableParallelism() });
123
- const realHostLoad = { hostLoad: readHostLoad, sleep: (ms) => delay(ms) };
158
+ const realHostLoad = {
159
+ hostLoad: readHostLoad,
160
+ hostMemory: readHostMemory,
161
+ sleep: (ms) => delay(ms),
162
+ };
124
163
  const minutes = (ms) => Number((ms / 60_000).toFixed(1));
125
164
  /**
126
165
  * The wait of `werkmeister internal wait-load`, which the generated with-temp-home runs first (SW-224):
127
- * up to 90 s for the 1-minute load to fall under the limit, saying so up front and printing progress
128
- * each minute (SW-262); the note for the wrapper's stderr, or "". The gate stopped waiting in SW-542.
129
- * Not on macOS: its loadavg counts idle daemons in R state (450-550 on a quiet host) and never the
130
- * Linux VM that runs the tests, so it is no signal to wait on and the wait was pure delay (SW-556).
166
+ * up to 90 s for the 1-minute load to fall under the limit and free memory to rise over its own (SW-620),
167
+ * saying so up front and printing progress each minute (SW-262); the note for the wrapper's stderr, or "".
168
+ * A spent wait's note starts "ran with". The gate stopped waiting in SW-542.
169
+ * Load not on macOS: its loadavg counts idle daemons in R state (450-550 on a quiet host) and never the
170
+ * Linux VM that runs the tests, so it is no signal to wait on (SW-556). Its memory is: Claude Code
171
+ * stops an idle background shell when the Mac runs low (SW-620).
131
172
  */
132
173
  export async function waitForHostLoadNow(deps = realHostLoad, platform = process.platform, before = "with-temp-home; --no-wait skips") {
133
174
  // WERKMEISTER_NO_WAIT skips it inside the command too, not only in with-temp-home's shell (SW-425).
134
- if (platform === "darwin" || envVar("NO_WAIT"))
175
+ if (envVar("NO_WAIT"))
135
176
  return "";
136
- let { load, cores } = deps.hostLoad();
137
- const limit = hostLoadLimit(cores);
138
- if (limit === 0 || load[0] <= limit)
177
+ const read = () => {
178
+ const { load, cores } = deps.hostLoad();
179
+ const limit = platform === "darwin" ? 0 : hostLoadLimit(cores);
180
+ return {
181
+ load: load[0],
182
+ limit,
183
+ loadOver: limit !== 0 && load[0] > limit,
184
+ memory: lowMemory(deps.hostMemory),
185
+ };
186
+ };
187
+ let now = read();
188
+ if (!now.loadOver && !now.memory)
139
189
  return "";
140
- info(`waiting up to ${minutes(WRAPPER_LOAD_WAIT_MS)} min for host load ${load[0].toFixed(1)} to fall to ${limit} (budget.host_load) before ${before}`);
190
+ const waitedFor = [now.loadOver && "host load", now.memory && "free memory"]
191
+ .filter(Boolean)
192
+ .join(" and ");
193
+ info(`waiting up to ${minutes(WRAPPER_LOAD_WAIT_MS)} min for ${[
194
+ now.loadOver && `host load ${now.load.toFixed(1)} to fall to ${now.limit} (budget.host_load)`,
195
+ now.memory && `free memory to rise (${now.memory})`,
196
+ ]
197
+ .filter(Boolean)
198
+ .join(" and ")} before ${before}`);
199
+ const state = () => [
200
+ now.loadOver && `host load ${now.load.toFixed(1)} over ${now.limit}`,
201
+ now.memory && `low memory (${now.memory})`,
202
+ ]
203
+ .filter(Boolean)
204
+ .join(", ");
141
205
  for (let waited = LOAD_POLL_MS; waited <= WRAPPER_LOAD_WAIT_MS; waited += LOAD_POLL_MS) {
142
206
  await deps.sleep(LOAD_POLL_MS);
143
- ({ load } = deps.hostLoad());
144
- if (load[0] <= limit)
145
- return `waited ${waited / 1000} s for host load`;
207
+ now = read();
208
+ if (!now.loadOver && !now.memory)
209
+ return `waited ${waited / 1000} s for ${waitedFor}`;
146
210
  if (waited % LOAD_PROGRESS_MS === 0 && waited < WRAPPER_LOAD_WAIT_MS)
147
- info(`still waiting for host load: ${load[0].toFixed(1)} over ${limit}, ${waited / 1000} s so far, up to ${minutes(WRAPPER_LOAD_WAIT_MS - waited)} min left`);
211
+ info(`still waiting: ${state()}, ${waited / 1000} s so far, up to ${minutes(WRAPPER_LOAD_WAIT_MS - waited)} min left`);
148
212
  }
149
- return `ran with host load ${load[0].toFixed(1)} over ${limit}; the ${minutes(WRAPPER_LOAD_WAIT_MS)} min host-load wait is spent`;
213
+ return `ran with ${state()}; the ${minutes(WRAPPER_LOAD_WAIT_MS)} min host-load wait is spent`;
150
214
  }
151
215
  /**
152
216
  * Before compose starts a setup one-shot among *services* (undefined: what a whole `up` starts),
153
- * wait on host load as with-temp-home does, and fail with the load once the wait is spent (SW-630):
154
- * a setup install started at load ~413 ran 78 min, past compose's 20 min `--wait`, and ended 137.
217
+ * wait on host load and free memory as with-temp-home does, and fail once the wait is spent (SW-630,
218
+ * SW-620): a setup install started at load ~413 ran 78 min, past compose's 20 min `--wait`, and ended 137.
155
219
  *
156
220
  * Throws `HOST_LOAD`.
157
221
  */
@@ -167,9 +231,19 @@ export async function waitForSetupLoad(workspace, services, deps = realHostLoad,
167
231
  if (!note.startsWith("ran with"))
168
232
  return;
169
233
  const { load, cores } = deps.hostLoad();
170
- throw new SandboxError(`host load ${load[0].toFixed(1)} is over ${hostLoadLimit(cores)} (budget.host_load) after the ` +
171
- `${minutes(WRAPPER_LOAD_WAIT_MS)} min wait; ${what} not started. Retry when load falls, ` +
172
- "or set WERKMEISTER_NO_WAIT=1 to start anyway.", "HOST_LOAD");
234
+ const limit = hostLoadLimit(cores);
235
+ const memory = lowMemory(deps.hostMemory);
236
+ const over = [
237
+ platform !== "darwin" &&
238
+ limit !== 0 &&
239
+ load[0] > limit &&
240
+ `host load ${load[0].toFixed(1)} is over ${limit} (budget.host_load)`,
241
+ memory && `memory is low (${memory})`,
242
+ ]
243
+ .filter(Boolean)
244
+ .join(" and ");
245
+ throw new SandboxError(`${over || note} after the ${minutes(WRAPPER_LOAD_WAIT_MS)} min wait; ${what} not started. ` +
246
+ "Retry when load falls or memory frees, or set WERKMEISTER_NO_WAIT=1 to start anyway.", "HOST_LOAD");
173
247
  }
174
248
  function composeServices(workspace, composePath = path.join(workspace, COMPOSE_FILE)) {
175
249
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister-core",
3
- "version": "0.0.0",
3
+ "version": "0.89.1",
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.",
@@ -103,13 +103,6 @@
103
103
  "./workspace_skills": "./dist/workspace_skills.js",
104
104
  "./worktrees": "./dist/worktrees.js"
105
105
  },
106
- "scripts": {
107
- "build": "tsc",
108
- "typecheck": "tsc --noEmit",
109
- "docs:links": "typedoc",
110
- "docs:sdk": "typedoc --options typedoc.sdk.json",
111
- "test": "sh ./run-tests.sh"
112
- },
113
106
  "dependencies": {
114
107
  "@anthropic-ai/claude-agent-sdk": "^0.3.288",
115
108
  "@types/dockerode": "^4.0.1",
@@ -126,5 +119,12 @@
126
119
  "@types/nunjucks": "^3.2.6",
127
120
  "typedoc": "0.28.20",
128
121
  "typescript": "^5.9.3"
122
+ },
123
+ "scripts": {
124
+ "build": "tsc",
125
+ "typecheck": "tsc --noEmit",
126
+ "docs:links": "typedoc",
127
+ "docs:sdk": "typedoc --options typedoc.sdk.json",
128
+ "test": "sh ./run-tests.sh"
129
129
  }
130
- }
130
+ }
@@ -1,12 +0,0 @@
1
- /**
2
- * The bug-filing guide both context strategies write into a workspace: where a
3
- * bug goes — fixed here if this workspace's changes caused it, otherwise an
4
- * issue on the sandbox repo or in the machine's issue tracker
5
- * (`overrides.issue_tracker`: the Jira project, or the GitHub issues of the
6
- * registry repo it belongs to) — and the issue body. icm writes it to
7
- * `_shared/bug-report.md`, jit to `.sandbox/bug-report.md`; each strategy's
8
- * CLAUDE.md points at its copy.
9
- */
10
- import { type IssueTracker } from "./issue_tracker.js";
11
- export declare const SANDBOX_ISSUES_REPO = "jbbz-sandbox/sandbox";
12
- export declare function buildBugReportMd(workspaceName: string, jiraId?: string, tracker?: IssueTracker, repos?: string[]): string;
@@ -1,95 +0,0 @@
1
- /**
2
- * The bug-filing guide both context strategies write into a workspace: where a
3
- * bug goes — fixed here if this workspace's changes caused it, otherwise an
4
- * issue on the sandbox repo or in the machine's issue tracker
5
- * (`overrides.issue_tracker`: the Jira project, or the GitHub issues of the
6
- * registry repo it belongs to) — and the issue body. icm writes it to
7
- * `_shared/bug-report.md`, jit to `.sandbox/bug-report.md`; each strategy's
8
- * CLAUDE.md points at its copy.
9
- */
10
- import { loadJira } from "./global_config.js";
11
- import { githubIssueRepos, loadIssueTracker } from "./issue_tracker.js";
12
- export const SANDBOX_ISSUES_REPO = "jbbz-sandbox/sandbox";
13
- /** The app-code row of the "Where" table and the search step, per tracker. */
14
- function appCodeRouting(tracker, jiraId, repos) {
15
- if (tracker === "github") {
16
- const where = repos.length
17
- ? `the GitHub issues of the repo it belongs to — one of ${repos.map((r) => `\`${r}\``).join(", ")}`
18
- : "that repo's GitHub issues — find it with \`git -C <worktree> remote get-url origin\`";
19
- return [
20
- `| app code in a worktree | ${where} | \`gh issue create -R <owner>/<repo>\` |`,
21
- 'Search first: `gh issue list -R <owner>/<repo> --search "<keywords>" --state all`. If it exists, comment on it instead.',
22
- ];
23
- }
24
- const project = /^([A-Z][A-Z0-9]+)-\d+$/.exec(jiraId)?.[1];
25
- const base = (loadJira().base_url ?? "").trim().replace(/\/+$/, "");
26
- const where = `Jira${project ? `, project \`${project}\`` : " — ask the person which project"}${base ? ` (${base})` : ""}`;
27
- return [
28
- `| app code in a worktree | ${where} | the Atlassian MCP tools if connected; otherwise hand the person the title and body to file |`,
29
- `Search first: JQL \`${project ? `project = ${project} AND ` : ""}text ~ "<keywords>"\`. If it exists, comment on it instead. (Sandbox-tool bugs: \`gh issue list -R ${SANDBOX_ISSUES_REPO} --search "<keywords>" --state all\`.)`,
30
- ];
31
- }
32
- export function buildBugReportMd(workspaceName, jiraId = "", tracker = loadIssueTracker(), repos = tracker === "github" ? githubIssueRepos() : []) {
33
- const [appRow, searchStep] = appCodeRouting(tracker, jiraId.trim(), repos);
34
- return `# Filing a bug
35
-
36
- ## New or existing?
37
-
38
- Decide this first.
39
-
40
- - **New — this workspace's changes caused it** (the bug is in code changed on this branch, committed or not, and does not happen on the base branch): fix it here, in the current stage or phase. Do **not** file an issue.
41
- - **Existing — it was already there** (it happens on the base branch, or it is in code this workspace has not touched, including the \`sandbox\` tool itself): file it as an issue where it belongs (table below), then carry on. Fix it here only if the current task depends on it, and say so in the issue.
42
-
43
- Not sure? Check whether it happens on the base branch. If you still can't tell, ask the person — don't guess.
44
-
45
- Log an existing bug when you find it, even if the notes are rough. Each issue must stand alone: a later agent should be able to fix it without re-running this workspace or asking follow-up questions.
46
-
47
- ## Where (existing bugs only)
48
-
49
- | Bug is in | File at | Command |
50
- |---|---|---|
51
- | the \`sandbox\` tool: CLI, MCP tools, plugin skills, generated files (\`.sandbox/\`, \`docker-compose.yml\`, \`.env\`, \`CLAUDE.md\`, context files), containers, ports, Caddy routing, workspace init/teardown | https://github.com/${SANDBOX_ISSUES_REPO}/issues | \`gh issue create -R ${SANDBOX_ISSUES_REPO}\` |
52
- ${appRow}
53
-
54
- ## How
55
-
56
- 1. ${searchStep}
57
- 2. Title: one-line summary. Body: the template below (with \`gh\`, via \`--body-file\`).
58
- 3. Paste exact commands and error output — don't paraphrase.
59
- 4. Tell the person the issue URL, then resume what you were doing.
60
-
61
- ## Body template
62
-
63
- ~~~markdown
64
- - **Workspace:** ${workspaceName} (stage or phase you were in)
65
- - **Severity:** blocker | major | minor | papercut
66
- - **Area:** <e.g. CLI | MCP tool | plugin skill | generated files | containers | routing/Caddy | ports | docs | app code>
67
- - **Status:** open | worked-around
68
-
69
- **Ran**
70
- \`\`\`sh
71
- <exact command, MCP tool call, or skill invoked>
72
- \`\`\`
73
-
74
- **Expected**
75
- <what should have happened>
76
-
77
- **Actual**
78
- <what happened>
79
-
80
- **Evidence**
81
- \`\`\`text
82
- <error output, logs, file snippet — trimmed to the relevant part>
83
- \`\`\`
84
-
85
- **Repro steps** (if not obvious from "Ran")
86
- 1.
87
-
88
- **Workaround** (if any)
89
- <what you did to get unblocked; note any files hand-edited and the state left behind>
90
-
91
- **Suspected cause / where to look** (optional)
92
- <file or module, if you have a guess>
93
- ~~~
94
- `;
95
- }
@@ -1,54 +0,0 @@
1
- export declare function stripAnsi(s: string): string;
2
- export declare function isExecutable(p: string): Promise<boolean>;
3
- /**
4
- * Env for a child `werkmeister` process. The wrapper has to find a `node` runtime
5
- * (and `docker`, `git`, `gh` downstream of it), which the stripped PATH a
6
- * GUI-launched process inherits often can't — prepend the usual tool dirs.
7
- * Those dirs beat a fake earlier on PATH, so fake gh/docker through {@link toolBin}'s overrides.
8
- *
9
- * Exported for the same reason as {@link sandbox.resolveSandboxBin}: callers that spawn // name-check: ignore
10
- * the CLI themselves need this env, not a hand-rolled approximation of it.
11
- */
12
- export declare function childEnv(): NodeJS.ProcessEnv;
13
- /** `gh`, or $WERKMEISTER_GH_BIN (tests point it at a fake); under WERKMEISTER_FIXTURE a stub that fails (SW-177). */
14
- export declare const ghBin: () => string;
15
- /** `docker`, or $WERKMEISTER_DOCKER_BIN (tests and fixture exercises point it at a fake; SW-208). */
16
- export declare const dockerBin: () => string;
17
- /** *bin*, with `gh` and `docker` resolved through their overrides: childEnv()'s PATH would beat a fake (SW-148, SW-208). */
18
- export declare const toolBin: (bin: string) => string;
19
- /**
20
- * Locate the `claude` CLI, robust to Claude Desktop's minimal PATH. Order:
21
- * $CLAUDE_BIN → the usual install locations → bare `claude` (resolved against
22
- * the augmented PATH in {@link childEnv}).
23
- */
24
- export declare function resolveClaudeBin(): Promise<string>;
25
- /**
26
- * Run a binary, capturing stdout/stderr, with stdin CLOSED so `claude -p`
27
- * doesn't stall 3s waiting for piped input. Rejects on spawn error or timeout.
28
- * `"gh"` and `"docker"` resolve through {@link toolBin}.
29
- */
30
- export declare function runCapture(bin: string, args: string[], cwd?: string): Promise<{
31
- stdout: string;
32
- stderr: string;
33
- code: number | null;
34
- }>;
35
- /** Pull the rewrite out of the model's tagged output; fall back to the whole text. */
36
- export declare function extractResult(out: string): string;
37
- /**
38
- * Slice a `{…}` (possibly fenced) JSON object out of free-form model output.
39
- * The outermost braces win when they parse, so a fence inside a JSON string
40
- * value (a starting prompt with a ```bash block) isn't mistaken for the answer.
41
- */
42
- export declare function extractJson(out: string): string | null;
43
- /**
44
- * One `claude -p` run, the tagged `<result>` body or null on any failure.
45
- * `tools` adds --dangerously-skip-permissions: the Atlassian MCP tools are
46
- * deferred, so --allowedTools cannot pre-approve them in headless mode.
47
- */
48
- export declare function askClaude(prompt: string, opts?: {
49
- tools?: boolean;
50
- }): Promise<string | null>;
51
- /** {@link askClaude}, then the JSON object in its answer; null when there is none. */
52
- export declare function askClaudeJson(prompt: string, opts?: {
53
- tools?: boolean;
54
- }): Promise<Record<string, unknown> | null>;