werkmeister-core 0.0.0 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister-core",
3
- "version": "0.0.0",
3
+ "version": "0.89.0",
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>;
@@ -1,173 +0,0 @@
1
- /**
2
- * The local `claude` CLI as a subprocess: locating it under Claude Desktop's
3
- * minimal PATH, running `claude -p`, and pulling a tagged result or a JSON
4
- * object out of what it prints. Shared by sandbox.ts and the issue trackers
5
- * (whose Atlassian-MCP fallback is a `claude -p` run).
6
- */
7
- import { spawn } from "node:child_process";
8
- import { writeFileSync } from "node:fs";
9
- import fs from "node:fs/promises";
10
- import os from "node:os";
11
- import path from "node:path";
12
- import { stripVTControlCharacters } from "node:util";
13
- import { envVar, isFixture } from "./config.js";
14
- import { SandboxError, WORKSPACE_ERROR_CODE } from "./errors.js";
15
- export function stripAnsi(s) {
16
- return stripVTControlCharacters(s);
17
- }
18
- export async function isExecutable(p) {
19
- try {
20
- await fs.access(p, fs.constants.X_OK);
21
- return true;
22
- }
23
- catch {
24
- return false;
25
- }
26
- }
27
- /**
28
- * Env for a child `werkmeister` process. The wrapper has to find a `node` runtime
29
- * (and `docker`, `git`, `gh` downstream of it), which the stripped PATH a
30
- * GUI-launched process inherits often can't — prepend the usual tool dirs.
31
- * Those dirs beat a fake earlier on PATH, so fake gh/docker through {@link toolBin}'s overrides.
32
- *
33
- * Exported for the same reason as {@link sandbox.resolveSandboxBin}: callers that spawn // name-check: ignore
34
- * the CLI themselves need this env, not a hand-rolled approximation of it.
35
- */
36
- export function childEnv() {
37
- const extra = [
38
- path.join(os.homedir(), ".local", "bin"),
39
- path.join(os.homedir(), ".cargo", "bin"),
40
- "/opt/homebrew/bin",
41
- "/usr/local/bin",
42
- "/usr/bin",
43
- "/bin",
44
- ];
45
- const current = process.env.PATH ? process.env.PATH.split(path.delimiter) : [];
46
- const merged = [...new Set([...extra, ...current])].join(path.delimiter);
47
- return { ...process.env, PATH: merged };
48
- }
49
- /** `gh`, or $WERKMEISTER_GH_BIN (tests point it at a fake); under WERKMEISTER_FIXTURE a stub that fails (SW-177). */
50
- export const ghBin = () => envVar("GH_BIN") || (isFixture() ? fixtureGhStub() : "gh");
51
- /** `docker`, or $WERKMEISTER_DOCKER_BIN (tests and fixture exercises point it at a fake; SW-208). */
52
- export const dockerBin = () => envVar("DOCKER_BIN") || "docker";
53
- /** *bin*, with `gh` and `docker` resolved through their overrides: childEnv()'s PATH would beat a fake (SW-148, SW-208). */
54
- export const toolBin = (bin) => bin === "gh" ? ghBin() : bin === "docker" ? dockerBin() : bin;
55
- let ghStub = null;
56
- function fixtureGhStub() {
57
- if (ghStub)
58
- return ghStub;
59
- const file = path.join(os.tmpdir(), `werkmeister-fixture-gh-${process.pid}`);
60
- writeFileSync(file, '#!/bin/sh\necho "gh called under WERKMEISTER_FIXTURE: $*" >&2\nexit 1\n', {
61
- mode: 0o755,
62
- });
63
- ghStub = file;
64
- return file;
65
- }
66
- /**
67
- * Locate the `claude` CLI, robust to Claude Desktop's minimal PATH. Order:
68
- * $CLAUDE_BIN → the usual install locations → bare `claude` (resolved against
69
- * the augmented PATH in {@link childEnv}).
70
- */
71
- export async function resolveClaudeBin() {
72
- const candidates = [
73
- process.env.CLAUDE_BIN,
74
- path.join(os.homedir(), ".local", "bin", "claude"),
75
- path.join(os.homedir(), ".claude", "local", "claude"),
76
- "/opt/homebrew/bin/claude",
77
- "/usr/local/bin/claude",
78
- ].filter((p) => Boolean(p));
79
- for (const c of candidates) {
80
- if (await isExecutable(c))
81
- return c;
82
- }
83
- return "claude"; // Node resolves this against childEnv().PATH below.
84
- }
85
- /**
86
- * Run a binary, capturing stdout/stderr, with stdin CLOSED so `claude -p`
87
- * doesn't stall 3s waiting for piped input. Rejects on spawn error or timeout.
88
- * `"gh"` and `"docker"` resolve through {@link toolBin}.
89
- */
90
- export function runCapture(bin, args, cwd = os.homedir()) {
91
- return new Promise((resolve, reject) => {
92
- const child = spawn(toolBin(bin), args, {
93
- cwd,
94
- env: childEnv(),
95
- stdio: ["ignore", "pipe", "pipe"],
96
- });
97
- let stdout = "";
98
- let stderr = "";
99
- const timer = setTimeout(() => {
100
- child.kill("SIGKILL");
101
- reject(new SandboxError("The `claude` CLI timed out after 120s.", WORKSPACE_ERROR_CODE));
102
- }, 120_000);
103
- child.stdout.on("data", (d) => (stdout += d.toString()));
104
- child.stderr.on("data", (d) => (stderr += d.toString()));
105
- child.on("error", (e) => {
106
- clearTimeout(timer);
107
- reject(e);
108
- });
109
- child.on("close", (code) => {
110
- clearTimeout(timer);
111
- resolve({ stdout, stderr, code });
112
- });
113
- });
114
- }
115
- /** Pull the rewrite out of the model's tagged output; fall back to the whole text. */
116
- export function extractResult(out) {
117
- const m = out.match(/<result>\s*([\s\S]*?)\s*<\/result>/i);
118
- return (m ? m[1] : out).trim();
119
- }
120
- /**
121
- * Slice a `{…}` (possibly fenced) JSON object out of free-form model output.
122
- * The outermost braces win when they parse, so a fence inside a JSON string
123
- * value (a starting prompt with a ```bash block) isn't mistaken for the answer.
124
- */
125
- export function extractJson(out) {
126
- const slice = (s) => {
127
- const start = s.indexOf("{");
128
- const end = s.lastIndexOf("}");
129
- return start !== -1 && end > start ? s.slice(start, end + 1) : null;
130
- };
131
- const whole = slice(out);
132
- if (whole) {
133
- try {
134
- JSON.parse(whole);
135
- return whole;
136
- }
137
- catch {
138
- // fall through to a fenced block
139
- }
140
- }
141
- const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(out);
142
- return fenced ? slice(fenced[1]) : whole;
143
- }
144
- /**
145
- * One `claude -p` run, the tagged `<result>` body or null on any failure.
146
- * `tools` adds --dangerously-skip-permissions: the Atlassian MCP tools are
147
- * deferred, so --allowedTools cannot pre-approve them in headless mode.
148
- */
149
- export async function askClaude(prompt, opts = {}) {
150
- try {
151
- const args = opts.tools ? ["-p", prompt, "--dangerously-skip-permissions"] : ["-p", prompt];
152
- const res = await runCapture(await resolveClaudeBin(), args);
153
- if (res.code !== 0)
154
- return null;
155
- return extractResult(stripAnsi(res.stdout));
156
- }
157
- catch {
158
- return null;
159
- }
160
- }
161
- /** {@link askClaude}, then the JSON object in its answer; null when there is none. */
162
- export async function askClaudeJson(prompt, opts = {}) {
163
- const out = await askClaude(prompt, opts);
164
- const json = out === null ? null : extractJson(out);
165
- if (!json)
166
- return null;
167
- try {
168
- return JSON.parse(json);
169
- }
170
- catch {
171
- return null;
172
- }
173
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * CLAUDE.md / routing-table / werkmeister-context builders — extracted from
3
- * init-workspace per DEBT-03 (it was the largest file in the codebase,
4
- * mixing workspace discovery,
5
- * input resolution, interactive prompting, CLAUDE.md generation, and compose
6
- * orchestration).
7
- *
8
- * This module owns pure string-rendering logic for the workspace-facing
9
- * markdown artifacts: the workspace `CLAUDE.md`, its routing table, and
10
- * `.werkmeister/werkmeister-context.md`.
11
- */
12
- import { type ArchetypeRegistry, type ReposConfig, type ServicesConfig } from "./config.js";
13
- import type { IssueRef } from "./strategies/types.js";
14
- /**
15
- * The public hostname to point the reader at, and the cookie's domain scope.
16
- *
17
- * Derived from the ingress config + `feature_router:` blocks rather than
18
- * hardcoded: the routed host set is per-machine, so a literal would send every
19
- * workspace to a host that may not exist. Prefers a service this feature
20
- * actually runs, else any routed service. Returns null when nothing is routed
21
- * (or the config can't be read) so callers omit the URL instead of inventing one.
22
- */
23
- export declare function resolveProxyHost(serviceNames: string[]): {
24
- host: string;
25
- domain: string;
26
- } | null;
27
- /**
28
- * Build the routing table for CLAUDE.md.
29
- *
30
- * Per-repo routing rows are only emitted when `{repo}/CLAUDE.md` actually
31
- * exists — pointing at a file that isn't there is worse than no row at all.
32
- * Everything about the running feature (URL, cookie, ports, lifecycle, health
33
- * checks) is one row: it all lives in werkmeister-context.md.
34
- */
35
- export declare function buildRoutingTable(repos: Array<[string, string]>, workspaceRoot: string, hasFeature: boolean): string;
36
- /**
37
- * Render the "Standards routing" block (jit-context-system.md §5.3).
38
- *
39
- * The compiled, inspectable projection of services.yaml `standards:` +
40
- * workspace.yml `standards_override` — the ICM Layer-1 table. The
41
- * `w9r-<key>-standard` skills it references are generated from
42
- * docs/standards/ and projected into the workspace's `.claude/skills/` by
43
- * init-workspace (`workspace_skills.ts`); `w9r-implement`/`w9r-research`/
44
- * `w9r-test`/`w9r-review` are the phase-entry skills that read this table (docs/jit-context-system.md §5.2 — the
45
- * CLAUDE.md-table → entry-skill chain is the measured 15/15 PREVENTIVE
46
- * mechanism). *workType* selects which By-phase rows render and adds the Work type / Gate lines; an empty or unknown type renders all five rows and no gate (`DEFAULT_PLAN`).
47
- */
48
- export declare function buildStandardsRoutingSection(active: string[], modules: Record<string, Record<string, any>>, repoNames: string[], workType?: string): string;
49
- /** Render the workspace CLAUDE.md content. */
50
- export declare function buildClaudeMd(workspaceName: string, workspaceRoot: string, repos: Array<[string, string]>, task: string, meta: Record<string, string>, standardsSection?: string | null, issue?: IssueRef | null): string;
51
- /**
52
- * Render .werkmeister/werkmeister-context.md — how to validate, then (when they apply)
53
- * ports, service topology, lifecycle commands, health checks.
54
- *
55
- * `candidates` is the workspace's services (selected, else its repos'); routing
56
- * and Caddy sections appear only for those with a URL.
57
- */
58
- export declare function buildSandboxContextMd(feature: string, slot: number, portStart: number, portEnd: number, localServices: string[], servicesConfig: ServicesConfig, testPath?: string, archetypes?: ArchetypeRegistry | null, candidates?: string[], autoStop?: boolean, tempHome?: string, reposConfig?: ReposConfig): string;