werkmeister-core 0.94.1 → 0.94.3

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,23 @@
1
1
  # sandbox-core
2
2
 
3
+ ## 0.94.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 31dd7fd: Shared infra made from an old checkout path is detected. A container made from another checkout's compose file is named, with `werkmeister infra up` as the fix, by `feature up`, `infra proxy-reload`, `feature status` and `infra status`. `infra up` now recreates those containers too, including one whose only drift is the files it was made from. Caddy counts as unhealthy when its `/__werkmeister` picker page is missing from its mount, which used to 404 on every routed host.
8
+ - 879f709: `feature stop --via-daemon` (the SessionEnd auto-stop) calls the daemon even when the CLI can't find its own daemon build for the build header. The lookup failure used to throw before the request, and the error was dropped, so the stop did nothing and exited 0. It now sends no header, and any daemon error other than "not running" is printed.
9
+
10
+ ## 0.94.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 2896765: Two repos in one workspace that use the same `node_modules_volume` name now get `<repo>-<name>` volumes instead of sharing one; a workspace with one such repo keeps its volume. `clean` recognises the scoped names.
15
+ - 444af37: When the branch is behind `origin/<base>`, the `pr gate` base row names the files base changed that the branch also touches, with "rebase, recheck the spec and tests that name them, rerun". The row's pass or fail is unchanged.
16
+ - 598dbde: `workspace new` with no free slot prints the next step once: init's "container step did not run" banner is dropped when create called it; the slot warning and the "Workspace created at …" line stay.
17
+ - 633fcce: `workspace new` no longer takes services from a command or log quoted in the issue: it ignores code blocks, indented lines and command-shaped `{{…}}`/backtick spans, maps a named code path (`packages/werkmeister-core/src`) to its service, and reads the starting prompt only when the issue names none.
18
+ - 4aa1aad: `pr adopt` over an approved PR file that was never opened fills in its url, merge sha and status and keeps its body, instead of writing a follow-up file.
19
+ - 2bcf30b: Templates and workspace skills are read from the checkout the code runs from when `WERKMEISTER_ROOT` is only config.yaml's `paths.werkmeister_root` (the value env.sh exports into every shell), so a workspace worktree's build renders its own templates. The daemon, Caddy and shared-infra paths still follow `WERKMEISTER_ROOT`, and any other value still wins everywhere.
20
+
3
21
  ## 0.94.1
4
22
 
5
23
  ### Patch Changes
package/dist/caddy.js CHANGED
@@ -7,7 +7,7 @@
7
7
  import * as fs from "node:fs";
8
8
  import { Colors } from "./colors.js";
9
9
  import { stopOrRestart } from "./compose.js";
10
- import { composeInvocation, INFRA_PROJECT } from "./compose_infra.js";
10
+ import { composeInvocation, INFRA_PROJECT, warnStaleInfra } from "./compose_infra.js";
11
11
  import { sharedProxySkipReason, stateInfraRoot } from "./config.js";
12
12
  import { copyFileToContainer, execCapture, projectContainers } from "./docker.js";
13
13
  import { ProcError, run } from "./proc.js";
@@ -297,6 +297,8 @@ export async function reloadCaddy() {
297
297
  info(`Caddy reload skipped (${skip})`);
298
298
  return true;
299
299
  }
300
+ // A reload only copies the Caddyfile: it can't fix a container still mounting a moved checkout (SW-610).
301
+ await warnStaleInfra();
300
302
  const hostCaddyfile = `${stateInfraRoot()}/proxy/Caddyfile`;
301
303
  info("Copying Caddyfile into Caddy container...");
302
304
  if (!(await cpCaddyfileToContainer(hostCaddyfile))) {
@@ -11,6 +11,7 @@
11
11
  * all call this, and `infra.ts` already imports `k8s.ts`, so putting it in
12
12
  * `infra.ts` would make a cycle.
13
13
  */
14
+ import type Dockerode from "dockerode";
14
15
  /** The Compose project name for shared infra (shared-infra.yml's `name:`). */
15
16
  export declare const INFRA_PROJECT = "w9r-infra";
16
17
  /**
@@ -31,3 +32,34 @@ export declare function composeInvocation(): {
31
32
  env: NodeJS.ProcessEnv;
32
33
  cwd: string;
33
34
  };
35
+ /** An infra container left over from another checkout (SW-610). */
36
+ export interface StaleInfraContainer {
37
+ name: string;
38
+ service: string;
39
+ reason: string;
40
+ }
41
+ /**
42
+ * Why *c* no longer matches the shipped compose file at *composeFile*, or null.
43
+ * Compose stamps the files it ran with; after a checkout moves, a container made
44
+ * from the old path keeps its relative bind mounts (the Caddy picker UI) pointed
45
+ * there, and `feature up` / `proxy-reload` never recreate it. The label, not the
46
+ * bind sources: a missing source comes back as an empty dir on restart, and from
47
+ * a container the host's paths don't exist at all.
48
+ */
49
+ export declare function staleInfraReason(c: Pick<Dockerode.ContainerInfo, "Labels">, composeFile: string): string | null;
50
+ /**
51
+ * The shared-infra containers {@link staleInfraReason} flags. Never throws: empty when
52
+ * docker is unreachable or there is no machine config to say where the compose file is.
53
+ */
54
+ export declare function staleInfraContainers(): Promise<StaleInfraContainer[]>;
55
+ /** One warning per stale infra container, naming the command that recreates it. */
56
+ export declare function warnStaleInfra(): Promise<void>;
57
+ /**
58
+ * Split *stale* into the services `up` can recreate (those in *started*, this run's list)
59
+ * and leftovers whose service this checkout's file no longer has: naming one to
60
+ * `compose up` fails every run, or turns on a profile that is off.
61
+ */
62
+ export declare function recreatePlan(stale: StaleInfraContainer[], started: string[]): {
63
+ recreate: string[];
64
+ leftover: StaleInfraContainer[];
65
+ };
@@ -14,8 +14,11 @@
14
14
  import * as fs from "node:fs";
15
15
  import * as path from "node:path";
16
16
  import { baselineOverridePath } from "./baseline.js";
17
- import { infraRoot, loadConfig, stateInfraRoot } from "./config.js";
17
+ import { infraRoot, isFixture, loadConfig, stateInfraRoot } from "./config.js";
18
+ import { docker } from "./docker.js";
19
+ import { insideContainer } from "./global_config.js";
18
20
  import { generateK8sForwards, overrideFilePath } from "./k8s_forwards.js";
21
+ import { warn } from "./reporter.js";
19
22
  /** The Compose project name for shared infra (shared-infra.yml's `name:`). */
20
23
  export const INFRA_PROJECT = "w9r-infra";
21
24
  /**
@@ -73,3 +76,62 @@ export function composeInvocation() {
73
76
  cwd: path.dirname(stateInfraRoot()),
74
77
  };
75
78
  }
79
+ /**
80
+ * Why *c* no longer matches the shipped compose file at *composeFile*, or null.
81
+ * Compose stamps the files it ran with; after a checkout moves, a container made
82
+ * from the old path keeps its relative bind mounts (the Caddy picker UI) pointed
83
+ * there, and `feature up` / `proxy-reload` never recreate it. The label, not the
84
+ * bind sources: a missing source comes back as an empty dir on restart, and from
85
+ * a container the host's paths don't exist at all.
86
+ */
87
+ export function staleInfraReason(c, composeFile) {
88
+ const from = c.Labels?.["com.docker.compose.project.config_files"]?.split(",")[0];
89
+ return from && path.resolve(from) !== path.resolve(composeFile) ? `created from ${from}` : null;
90
+ }
91
+ /**
92
+ * The shared-infra containers {@link staleInfraReason} flags. Never throws: empty when
93
+ * docker is unreachable or there is no machine config to say where the compose file is.
94
+ */
95
+ export async function staleInfraContainers() {
96
+ // A workspace container's checkout is /app, so every host-made label differs, and a
97
+ // recreate from there would mount /app paths the host lacks (SW-554). Fixtures never start infra.
98
+ if (insideContainer() && !isFixture())
99
+ return [];
100
+ let list;
101
+ let composeFile;
102
+ try {
103
+ list = await docker().listContainers({
104
+ all: true,
105
+ filters: { label: [`com.docker.compose.project=${INFRA_PROJECT}`] },
106
+ });
107
+ composeFile = composeInvocation().argv[3];
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ return list.flatMap((c) => {
113
+ const reason = staleInfraReason(c, composeFile);
114
+ const name = c.Names?.[0]?.replace(/^\//, "") ?? c.Id.slice(0, 12);
115
+ return reason
116
+ ? [{ name, service: c.Labels?.["com.docker.compose.service"] ?? "", reason }]
117
+ : [];
118
+ });
119
+ }
120
+ /** One warning per stale infra container, naming the command that recreates it. */
121
+ export async function warnStaleInfra() {
122
+ for (const s of await staleInfraContainers()) {
123
+ warn(`${s.name} was ${s.reason}, not this checkout: run \`werkmeister infra up\` to recreate it`);
124
+ }
125
+ }
126
+ /**
127
+ * Split *stale* into the services `up` can recreate (those in *started*, this run's list)
128
+ * and leftovers whose service this checkout's file no longer has: naming one to
129
+ * `compose up` fails every run, or turns on a profile that is off.
130
+ */
131
+ export function recreatePlan(stale, started) {
132
+ const known = stale.filter((s) => started.includes(s.service));
133
+ return {
134
+ recreate: [...new Set(known.map((s) => s.service))],
135
+ leftover: stale.filter((s) => !started.includes(s.service)),
136
+ };
137
+ }
package/dist/config.d.ts CHANGED
@@ -385,6 +385,8 @@ export declare function getVolumeBaseNames(): string[];
385
385
  *
386
386
  * The walk-up is what a bundled consumer cannot do — a `.vsix` has no monorepo
387
387
  * around it — which is why `WERKMEISTER_ROOT` ranks first rather than as a fallback.
388
+ * Machine-wide paths (the daemon's plist entry, Caddy, shared infra) hang off this,
389
+ * so it stays on that order; templates and skills read {@link sourceInfraRoot}.
388
390
  */
389
391
  export declare function sandboxRoot(): string;
390
392
  /**
@@ -404,6 +406,13 @@ export declare function installedCliPackage(pathEnv?: string): string | null;
404
406
  * {@link stateInfraRoot}. Nothing writes here at runtime.
405
407
  */
406
408
  export declare function infraRoot(): string;
409
+ /**
410
+ * The `infra/` the templates and skills are read from: {@link infraRoot}, except that a
411
+ * `WERKMEISTER_ROOT` equal to config.yaml's `paths.werkmeister_root` (env.sh's export into
412
+ * every shell) yields to the checkout this code runs from, so a worktree's build renders its
413
+ * own templates. Reads only: nothing machine-wide is placed from it.
414
+ */
415
+ export declare function sourceInfraRoot(): string;
407
416
  /**
408
417
  * `~/.werkmeister/infra`: the generated runtime files for the shared infra — the
409
418
  * Caddyfile, features.json, the pinned kubeconfig, the forwards table and the
package/dist/config.js CHANGED
@@ -559,6 +559,9 @@ function registryVolumeBases() {
559
559
  const nodeModulesVol = def["node_modules_volume"];
560
560
  if (typeof nodeModulesVol === "string" && nodeModulesVol) {
561
561
  bases.add(nodeModulesVol);
562
+ // SW-110: a clash between repos names it `<repo>-<vol>` (repoScopedNodeModules).
563
+ if (typeof def["repo"] === "string" && def["repo"])
564
+ bases.add(`${def["repo"]}-${nodeModulesVol}`);
562
565
  }
563
566
  const extraVolumes = def["extra_volumes"];
564
567
  if (!Array.isArray(extraVolumes)) {
@@ -593,6 +596,30 @@ export function getVolumeBaseNames() {
593
596
  // ---------------------------------------------------------------------------
594
597
  // Where the CLI checkout is
595
598
  // ---------------------------------------------------------------------------
599
+ /** The `apps/cli` of the checkout this module sits in, found by walking up; null outside one. */
600
+ function ownCheckoutCli() {
601
+ let dir = import.meta.dirname;
602
+ for (let i = 0; i < 8; i++) {
603
+ const cli = path.join(dir, "apps", "cli");
604
+ if (fs.existsSync(cli))
605
+ return cli;
606
+ const parent = path.dirname(dir);
607
+ if (parent === dir)
608
+ break;
609
+ dir = parent;
610
+ }
611
+ return null;
612
+ }
613
+ /** config.yaml's `paths.werkmeister_root`, the value env.sh exports; null when unset or unreadable. */
614
+ function storedWerkmeisterRoot() {
615
+ try {
616
+ const stored = loadConfig().paths?.werkmeister_root;
617
+ return typeof stored === "string" && stored ? path.resolve(expandUser(stored)) : null;
618
+ }
619
+ catch {
620
+ return null;
621
+ }
622
+ }
596
623
  /**
597
624
  * The CLI package directory (`<checkout>/apps/cli`) — the root of everything
598
625
  * that ships as CODE: `infra/`, `dist/`, the `werkmeister` wrapper.
@@ -605,6 +632,8 @@ export function getVolumeBaseNames() {
605
632
  *
606
633
  * The walk-up is what a bundled consumer cannot do — a `.vsix` has no monorepo
607
634
  * around it — which is why `WERKMEISTER_ROOT` ranks first rather than as a fallback.
635
+ * Machine-wide paths (the daemon's plist entry, Caddy, shared infra) hang off this,
636
+ * so it stays on that order; templates and skills read {@link sourceInfraRoot}.
608
637
  */
609
638
  export function sandboxRoot() {
610
639
  // SW-239: an unpinned test silently builds or writes in main's checkout (or turbo's walk-up).
@@ -614,16 +643,9 @@ export function sandboxRoot() {
614
643
  const override = envVar("ROOT");
615
644
  if (override)
616
645
  return path.resolve(expandUser(override));
617
- let dir = import.meta.dirname;
618
- for (let i = 0; i < 8; i++) {
619
- const cli = path.join(dir, "apps", "cli");
620
- if (fs.existsSync(cli))
621
- return cli;
622
- const parent = path.dirname(dir);
623
- if (parent === dir)
624
- break;
625
- dir = parent;
626
- }
646
+ const own = ownCheckoutCli();
647
+ if (own)
648
+ return own;
627
649
  const installed = installedCliPackage();
628
650
  if (installed)
629
651
  return installed;
@@ -675,6 +697,18 @@ export function installedCliPackage(pathEnv = process.env.PATH ?? "") {
675
697
  export function infraRoot() {
676
698
  return path.join(sandboxRoot(), "infra");
677
699
  }
700
+ /**
701
+ * The `infra/` the templates and skills are read from: {@link infraRoot}, except that a
702
+ * `WERKMEISTER_ROOT` equal to config.yaml's `paths.werkmeister_root` (env.sh's export into
703
+ * every shell) yields to the checkout this code runs from, so a worktree's build renders its
704
+ * own templates. Reads only: nothing machine-wide is placed from it.
705
+ */
706
+ export function sourceInfraRoot() {
707
+ const root = sandboxRoot();
708
+ const own = ownCheckoutCli();
709
+ const useOwn = own !== null && own !== root && root === storedWerkmeisterRoot();
710
+ return path.join(useOwn ? own : root, "infra");
711
+ }
678
712
  /**
679
713
  * `~/.werkmeister/infra`: the generated runtime files for the shared infra — the
680
714
  * Caddyfile, features.json, the pinned kubeconfig, the forwards table and the
@@ -173,6 +173,15 @@ let staleWarned = false;
173
173
  export function expectDaemonBuild(get) {
174
174
  expectedBuild = get;
175
175
  }
176
+ // The header is a hint: a lookup that throws (no checkout to find, SW-718) sends none rather than dropping the call.
177
+ function buildToSend() {
178
+ try {
179
+ return expectedBuild?.() ?? null;
180
+ }
181
+ catch {
182
+ return null;
183
+ }
184
+ }
176
185
  function checkBuild(onDisk, res) {
177
186
  const loaded = res.headers.get(BUILD_HEADER);
178
187
  if (staleWarned || !onDisk || !loaded || loaded === onDisk)
@@ -241,7 +250,7 @@ export async function daemonStatus() {
241
250
  */
242
251
  export async function callTool(name, args = {}, opts = {}) {
243
252
  const timeout = AbortSignal.timeout(opts.timeoutMs ?? 120_000);
244
- const build = expectedBuild?.() ?? null;
253
+ const build = buildToSend();
245
254
  const res = await send(`${daemonUrl()}/api/tool`, {
246
255
  method: "POST",
247
256
  headers: {
@@ -36,6 +36,13 @@ export declare function loadWorkspaceEnvVars(workspaceRoot: string): Record<stri
36
36
  * start one for a repo with no container running.
37
37
  */
38
38
  export declare function onDemandServices(servicesConfig: Record<string, unknown>, localServices: string[], workspaceRoot: string): string[];
39
+ /**
40
+ * SW-110: two checked-out repos whose fragments share a `node_modules_volume`
41
+ * name would mount one volume, and one repo's install breaks the other's tree.
42
+ * On such a clash the name gets the repo (`<repo>-<vol>`); otherwise it is
43
+ * kept, so a workspace keeps its installed volume. Returns copies.
44
+ */
45
+ export declare function repoScopedNodeModules([services, setups]: [ServicesConfig, ServicesConfig], workspaceRoot: string): [ServicesConfig, ServicesConfig];
39
46
  /**
40
47
  * Generate `<workspace>/compose.yml` for *feature*.
41
48
  *
package/dist/generate.js CHANGED
@@ -18,7 +18,7 @@ import { candidateServiceNames } from "./archetypes.js";
18
18
  import { applyCaches } from "./build_caches.js";
19
19
  import { projectName } from "./compose.js";
20
20
  import { COMPOSE_FILE, migrateWorkspaceCompose } from "./compose_file.js";
21
- import { baselineUpstream, containerOf, DEFAULT_CPUS, DEFAULT_SETUP_CPUS, dotDir, IDLE_SERVICE_TYPES, infraRoot, loadArchetypes, loadCaches, loadPorts, loadReposConfig, loadServices, loadSetupServices, resolveWorkspace, SHARED_VOLUME_MARKER, sandboxRoot, stateInfraRoot, } from "./config.js";
21
+ import { baselineUpstream, containerOf, DEFAULT_CPUS, DEFAULT_SETUP_CPUS, dotDir, IDLE_SERVICE_TYPES, loadArchetypes, loadCaches, loadPorts, loadReposConfig, loadServices, loadSetupServices, resolveWorkspace, SHARED_VOLUME_MARKER, sandboxRoot, sourceInfraRoot, stateInfraRoot, } from "./config.js";
22
22
  import { loadFeatureRouters } from "./feature_routing.js";
23
23
  import { refuseInsideContainer } from "./global_config.js";
24
24
  import { buildSandboxContextMd } from "./harness/claude/claude_md.js";
@@ -177,7 +177,7 @@ function installArrayAppend() {
177
177
  /** Create and return a nunjucks `Environment` (jinja2-parity settings). */
178
178
  function getNunjucksEnv() {
179
179
  installArrayAppend();
180
- const templatesDir = path.join(infraRoot(), "templates");
180
+ const templatesDir = path.join(sourceInfraRoot(), "templates");
181
181
  if (!fs.existsSync(templatesDir) || !fs.statSync(templatesDir).isDirectory()) {
182
182
  fs.mkdirSync(templatesDir, { recursive: true });
183
183
  }
@@ -440,6 +440,32 @@ export function onDemandServices(servicesConfig, localServices, workspaceRoot) {
440
440
  .map(([name]) => name)
441
441
  .sort();
442
442
  }
443
+ /**
444
+ * SW-110: two checked-out repos whose fragments share a `node_modules_volume`
445
+ * name would mount one volume, and one repo's install breaks the other's tree.
446
+ * On such a clash the name gets the repo (`<repo>-<vol>`); otherwise it is
447
+ * kept, so a workspace keeps its installed volume. Returns copies.
448
+ */
449
+ export function repoScopedNodeModules([services, setups], workspaceRoot) {
450
+ const here = (def) => isDict(def) &&
451
+ Boolean(def["repo"]) &&
452
+ Boolean(def["node_modules_volume"]) &&
453
+ fs.existsSync(path.join(workspaceRoot, String(def["repo"])));
454
+ const reposOf = new Map();
455
+ for (const def of [...Object.values(services), ...Object.values(setups)]) {
456
+ if (!here(def))
457
+ continue;
458
+ const vol = String(def["node_modules_volume"]);
459
+ reposOf.set(vol, (reposOf.get(vol) ?? new Set()).add(String(def["repo"])));
460
+ }
461
+ const scope = (defs) => Object.fromEntries(Object.entries(defs).map(([name, def]) => [
462
+ name,
463
+ here(def) && (reposOf.get(String(def["node_modules_volume"]))?.size ?? 0) > 1
464
+ ? { ...def, node_modules_volume: `${def["repo"]}-${def["node_modules_volume"]}` }
465
+ : def,
466
+ ]));
467
+ return [scope(services), scope(setups)];
468
+ }
443
469
  /**
444
470
  * Render the compose file for *feature* without writing it.
445
471
  *
@@ -451,7 +477,7 @@ export function onDemandServices(servicesConfig, localServices, workspaceRoot) {
451
477
  function renderFeatureCompose(feature, slot, localServices, config, workspaceOverride, source) {
452
478
  const [registryServices, portsConfig] = resolveServicesAndPorts(config);
453
479
  const [workspaceRoot, outPath] = resolveComposeOutPath(feature, workspaceOverride);
454
- const [servicesConfig, cachedSetups] = applyCaches(registryServices, config && "setup_services" in config ? (config["setup_services"] ?? {}) : loadSetupServices(), config && "archetypes" in config ? (config["archetypes"] ?? {}) : loadArchetypes(), config && "caches" in config ? (config["caches"] ?? {}) : loadCaches(), workspaceRoot);
480
+ const [servicesConfig, cachedSetups] = repoScopedNodeModules(applyCaches(registryServices, config && "setup_services" in config ? (config["setup_services"] ?? {}) : loadSetupServices(), config && "archetypes" in config ? (config["archetypes"] ?? {}) : loadArchetypes(), config && "caches" in config ? (config["caches"] ?? {}) : loadCaches(), workspaceRoot), workspaceRoot);
455
481
  const devLinks = loadDevLinks(workspaceRoot);
456
482
  const header = composeHeader(feature, source);
457
483
  // Try template first
package/dist/infra.js CHANGED
@@ -21,10 +21,11 @@ import * as net from "node:net";
21
21
  import * as os from "node:os";
22
22
  import * as path from "node:path";
23
23
  import { baselineSpecs, generateBaselineOverride } from "./baseline.js";
24
+ import { CADDY_CONTAINER } from "./caddy.js";
24
25
  import { stopOrRestart, takeDownProject } from "./compose.js";
25
- import { composeInvocation, INFRA_PROJECT, infraProfiles, LEGACY_INFRA_PROJECT, } from "./compose_infra.js";
26
+ import { composeInvocation, INFRA_PROJECT, infraProfiles, LEGACY_INFRA_PROJECT, recreatePlan, staleInfraContainers, } from "./compose_infra.js";
26
27
  import { isFixture, sandboxHome } from "./config.js";
27
- import { projectContainers } from "./docker.js";
28
+ import { execCapture, projectContainers } from "./docker.js";
28
29
  import { generateCaddyfile } from "./generate.js";
29
30
  import { configureGitHooksPath } from "./git_hooks.js";
30
31
  import { checkPortForwardHealth, ensurePortForwardsHealthy, refreshKubeconfig } from "./k8s.js";
@@ -145,13 +146,13 @@ export async function startSharedInfra(signal) {
145
146
  return false;
146
147
  }
147
148
  takeDownProject(LEGACY_INFRA_PROJECT, "the pre-rename shared infra");
148
- const services = [
149
+ const started = [
149
150
  "k8s-forwards",
150
151
  "caddy",
151
152
  ...infraProfiles(),
152
153
  ...baselineSpecs().map((s) => `baseline-${s.service}`),
153
- ].join(", ");
154
- info(`Starting shared infrastructure (${services})...`);
154
+ ];
155
+ info(`Starting shared infrastructure (${started.join(", ")})...`);
155
156
  try {
156
157
  const result = await runAsync([...argv, "up", "-d", "--build"], {
157
158
  capture: true,
@@ -163,6 +164,20 @@ export async function startSharedInfra(signal) {
163
164
  error(`docker compose failed:\n${result.stderr.trim()}`);
164
165
  return false;
165
166
  }
167
+ // `up` recreates a container whose resolved binds changed, not one whose only drift is
168
+ // the compose files it was made from (w9r-k8s-forwards after a checkout move, SW-610).
169
+ const { recreate, leftover } = recreatePlan(await staleInfraContainers(), started);
170
+ for (const s of leftover) {
171
+ warn(`${s.name} was ${s.reason}, and this checkout has no such service: remove it with \`docker rm -f ${s.name}\``);
172
+ }
173
+ if (recreate.length) {
174
+ info(`Recreating ${recreate.join(", ")} from this checkout...`);
175
+ const again = await runAsync([...argv, "up", "-d", "--no-deps", "--force-recreate", ...recreate], { capture: true, signal, env, cwd });
176
+ if (again.status !== 0) {
177
+ error(`docker compose failed:\n${again.stderr.trim()}`);
178
+ return false;
179
+ }
180
+ }
166
181
  success("Shared infrastructure started");
167
182
  return true;
168
183
  }
@@ -178,6 +193,8 @@ export async function startSharedInfra(signal) {
178
193
  throw e;
179
194
  }
180
195
  }
196
+ /** The page Caddy serves for `/__werkmeister` (generate.ts's `root * /werkmeister/proxy/ui`). */
197
+ const PICKER_PAGE = "/werkmeister/proxy/ui/index.html";
181
198
  function checkPort(host, port, timeoutSec) {
182
199
  return new Promise((resolve) => {
183
200
  const sock = net.createConnection({ host, port });
@@ -209,6 +226,11 @@ async function checkInfraHealth() {
209
226
  for (const c of (await projectContainers(INFRA_PROJECT, undefined, { all: false })) ?? []) {
210
227
  services[c.service || c.name] = c.health === "healthy" || (c.state === "running" && !c.health);
211
228
  }
229
+ // Running is not serving: an empty picker mount 404s /__werkmeister on every host (SW-610).
230
+ if (services["caddy"]) {
231
+ const picker = await execCapture(CADDY_CONTAINER, ["test", "-s", PICKER_PAGE]).catch(() => null);
232
+ services["caddy"] = picker?.exitCode === 0;
233
+ }
212
234
  // Fallback: check key ports if the daemon listed nothing
213
235
  if (!Object.keys(services).length) {
214
236
  const portChecks = [
package/dist/lifecycle.js CHANGED
@@ -1391,8 +1391,10 @@ export function classifyVolumes(volumes, baseNames, live) {
1391
1391
  const activeVolumes = [];
1392
1392
  const orphanedVolumes = [];
1393
1393
  for (const vol of volumes) {
1394
- const feature = featureFromVolume(vol, baseNames);
1395
- (feature && live.has(feature) ? activeVolumes : orphanedVolumes).push(vol);
1394
+ // SW-110: `fix-shop-node-modules` is live feature `fix-shop` under `node-modules`, or `fix` under
1395
+ // `shop-node-modules`. Any reading that leaves a live feature keeps it: a wrong one deletes node_modules.
1396
+ const isLive = baseNames.some((b) => vol.endsWith(`-${b}`) && live.has(vol.slice(0, -b.length - 1)));
1397
+ (isLive ? activeVolumes : orphanedVolumes).push(vol);
1396
1398
  }
1397
1399
  return { activeVolumes, orphanedVolumes };
1398
1400
  }
@@ -853,12 +853,24 @@ testsOnly = false) {
853
853
  "-q",
854
854
  `refs/remotes/origin/${branch}`,
855
855
  ])).code === 0;
856
+ // SW-191: base commits in files this branch touches made a spec or test route stale mid-run. Warns only.
857
+ const names = async (range) => {
858
+ const r = await deps.run("git", ["-C", dir, "diff", "--name-only", range]);
859
+ return r.code ? [] : r.stdout.split("\n").filter(Boolean);
860
+ };
861
+ const theirs = count > 0 ? new Set(await names(`HEAD...origin/${base}`)) : new Set();
862
+ const overlap = theirs.size
863
+ ? (await names(`origin/${base}...HEAD`)).filter((f) => theirs.has(f))
864
+ : [];
865
+ const also = overlap.length
866
+ ? `; origin/${base} also changed ${overlap.join(", ")} — rebase onto origin/${base}, recheck the spec and tests that name them, rerun`
867
+ : "";
856
868
  add("base", behind.code === 0 && (count === 0 || pushed), behind.code
857
869
  ? `cannot check against origin/${base}: ${(behind.stderr || behind.stdout).trim()}`
858
870
  : pushed
859
- ? `${commits}; ${branch} is already pushed, so \`pr watch\` flags a conflict and rule 5's \`--force-with-lease\` hand-off applies`
871
+ ? `${commits}; ${branch} is already pushed, so \`pr watch\` flags a conflict and rule 5's \`--force-with-lease\` hand-off applies${also}`
860
872
  : count
861
- ? `${commits} — \`git -C ${file.dir} rebase origin/${base}\` (keeps one commit per ticket), rerun the tests, then rerun`
873
+ ? `${commits} — \`git -C ${file.dir} rebase origin/${base}\` (keeps one commit per ticket), rerun the tests, then rerun${also}`
862
874
  : `up to date with origin/${base}`);
863
875
  const status = await deps.run("git", ["-C", dir, "status", "--porcelain"]);
864
876
  add("clean", status.code === 0 && status.stdout.trim() === "", status.code
@@ -2448,6 +2460,7 @@ export async function adoptPr(ws, opts, deps = defaultDeps()) {
2448
2460
  };
2449
2461
  let fm;
2450
2462
  let title;
2463
+ let unopened = null;
2451
2464
  if (opts.noPr !== undefined) {
2452
2465
  if (!opts.noPr.trim())
2453
2466
  throw new WorkspaceError("--no-pr needs a reason.");
@@ -2473,12 +2486,17 @@ export async function adoptPr(ws, opts, deps = defaultDeps()) {
2473
2486
  const tracked = readPrFiles(ws).find((f) => f.fm["url"] === pr.url);
2474
2487
  if (tracked)
2475
2488
  throw new WorkspaceError(`${pr.url} is already tracked in ${path.basename(tracked.path)}.`);
2489
+ const merged = pr.state === "MERGED";
2490
+ const existing = fs.existsSync(file) ? parsePrFile(file) : null;
2491
+ // SW-735: a PR file never opened (no url) is this PR's record: fill in its fields, keep its body.
2492
+ if (existing && !existing.fm["url"])
2493
+ unopened = existing;
2476
2494
  // The worktree's first PR file is taken: adopt as a follow-up named by PR number (SW-103).
2477
- const followUp = fs.existsSync(file);
2495
+ const followUp = Boolean(existing) && !unopened;
2478
2496
  if (followUp)
2479
2497
  file = path.join(dir, `pr-${repo}-${/\/pull\/(\d+)/.exec(pr.url)?.[1]}.md`);
2480
- taken();
2481
- const merged = pr.state === "MERGED";
2498
+ if (!unopened)
2499
+ taken();
2482
2500
  fm = {
2483
2501
  ...(followUp ? { worktree: repo } : {}),
2484
2502
  repo: /github\.com\/([^/]+\/[^/]+)\/pull\//.exec(pr.url)?.[1] ?? "",
@@ -2493,7 +2511,10 @@ export async function adoptPr(ws, opts, deps = defaultDeps()) {
2493
2511
  title = pr.title;
2494
2512
  }
2495
2513
  // Through the YAML library: a hand-written `release: @scope/pkg@1.0` is invalid YAML.
2496
- fs.writeFileSync(file, `---\n${YAML.stringify(fm)}---\n# ${title}\n\nAdopted with \`werkmeister pr adopt\`: the work landed outside this workspace.\n`);
2514
+ if (unopened)
2515
+ writePrFields(unopened, fm);
2516
+ else
2517
+ fs.writeFileSync(file, `---\n${YAML.stringify(fm)}---\n# ${title}\n\nAdopted with \`werkmeister pr adopt\`: the work landed outside this workspace.\n`);
2497
2518
  const lines = [`${path.basename(file, ".md").replace(/^pr-/, "")}: adopted as ${fm["status"]}`];
2498
2519
  if (fm["status"] !== "closed")
2499
2520
  lines.push(...(await refreshPrStatus(ws, deps)).lines);
package/dist/sandbox.js CHANGED
@@ -960,19 +960,32 @@ export async function distillIssue(issue, distill = (p) => harness().ask(p)) {
960
960
  : { fields, warning: "the answer held no usable fields" };
961
961
  }
962
962
  /**
963
- * The registered services in *repos* whose id the issue spells out as a whole
964
- * word: matched, not model-picked, so an unattended create stays deterministic.
965
- */
966
- function servicesNamedIn(issue, repos) {
963
+ * The registered services in *repos* that *text* names: by id as a whole word,
964
+ * or by the service's `path` (`packages/x`, `packages/x/src/y.ts`). Matched, not
965
+ * model-picked: on the issue text an unattended create is deterministic; the
966
+ * starting-prompt fallback is only as stable as the brief it reads. Quoted commands and
967
+ * logs are evidence, not a choice (SW-707): code blocks, indented lines and code
968
+ * spans holding whitespace are dropped first; a one-word span like `{{api}}` stays.
969
+ */
970
+ function servicesNamedIn(text, repos) {
967
971
  const wanted = new Set(repos.map((r) => r.trim()).filter(Boolean));
968
- // Jira wiki markup escapes hyphens (`smart\-app`).
969
- const text = [issue.title, issue.body, ...issue.comments.map((c) => c.body)]
970
- .join("\n")
971
- .replace(/\\/g, "");
972
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
973
+ const prose = text
974
+ .replace(/\\/g, "") // Jira wiki markup escapes hyphens (`smart\-app`).
975
+ .replace(/\{(code|noformat)[^}]*\}[\s\S]*?\{\1\}/g, "")
976
+ .replace(/```[\s\S]*?```/g, "")
977
+ .replace(/^(?: {4}|\t).*$/gm, "")
978
+ // One span at a time: a pattern spanning two spans would eat the prose between them.
979
+ .replace(/\{\{[^}]*\}\}|`[^`\n]*`/g, (m) => (/\s/.test(m) ? "" : m));
972
980
  return Object.entries(loadServices())
973
981
  .filter(([, def]) => wanted.has(String(def?.repo ?? "")))
982
+ .filter(([id, def]) => {
983
+ const p = String(def?.path ?? "").replace(/^\.?\/+|\/+$/g, "");
984
+ return (new RegExp(`(?<![\\w./-])${esc(id)}(?![\\w/-])`).test(prose) ||
985
+ // A one-segment path (`docs`) is too often a plain word.
986
+ (p.includes("/") && new RegExp(`(?<![\\w.-])${esc(p)}(?![\\w.-])`).test(prose)));
987
+ })
974
988
  .map(([id]) => id)
975
- .filter((id) => new RegExp(`(?<![\\w./-])${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w/-])`).test(text))
976
989
  .sort();
977
990
  }
978
991
  /** Resolve inputs, fetch the issue (failing the create), then fill an empty task, services, description and starting_prompt from it. */
@@ -1017,22 +1030,31 @@ export async function prepareCreate(formData, opts = {}) {
1017
1030
  const blankOnPurpose = rawServices !== null &&
1018
1031
  rawServices !== undefined &&
1019
1032
  (Array.isArray(rawServices) ? rawServices : [rawServices]).every((v) => !String(v).trim());
1020
- if (!resolved.services && resolved.repos && !blankOnPurpose) {
1021
- const named = servicesNamedIn(issue, resolved.repos.split(","));
1022
- if (named.length) {
1023
- resolved.services = named.join(",");
1024
- info(`Services taken from the issue text: ${resolved.services} (pass --services "" for none)`);
1025
- }
1026
- }
1027
1033
  if (opts.distill !== false && (!resolved.description || !resolved.starting_prompt)) {
1028
1034
  const { fields, warning } = await distillIssue(issue, opts.distill ?? ((p) => harness().ask(p)));
1029
- // Only the prose: a model-picked feature or services would make unattended creates nondeterministic.
1035
+ // Only the prose, never a model-picked feature or services list; the services step below may
1036
+ // still match names in this starting prompt when the issue text names none (SW-707).
1030
1037
  for (const k of ["description", "starting_prompt"])
1031
1038
  if (!resolved[k] && fields[k])
1032
1039
  resolved[k] = fields[k];
1033
1040
  if (warning)
1034
1041
  warn(`description/starting_prompt not filled from the issue: ${warning}`);
1035
1042
  }
1043
+ if (!resolved.services && resolved.repos && !blankOnPurpose) {
1044
+ const repos = resolved.repos.split(",");
1045
+ const issueText = [issue.title, issue.body, ...issue.comments.map((c) => c.body)].join("\n");
1046
+ let named = servicesNamedIn(issueText, repos);
1047
+ let from = "the issue text";
1048
+ // SW-707: the issue may name a service only as evidence; the brief's "service X" is the next signal.
1049
+ if (!named.length && resolved.starting_prompt) {
1050
+ named = servicesNamedIn(resolved.starting_prompt, repos);
1051
+ from = "the starting prompt";
1052
+ }
1053
+ if (named.length) {
1054
+ resolved.services = named.join(",");
1055
+ info(`Services taken from ${from}: ${resolved.services} (pass --services "" for none)`);
1056
+ }
1057
+ }
1036
1058
  return { resolved, issue };
1037
1059
  }
1038
1060
  // Creation is workspace_init's, called in-process (it used to be a `workspace new` child; note 087).
@@ -76,6 +76,8 @@ export interface InitWorkspaceOptions {
76
76
  * outlive it on the real docker daemon, holding a slot.
77
77
  */
78
78
  build?: boolean;
79
+ /** Skip the no-slot banner: `workspace new` prints its own next step after it. */
80
+ quietNoSlot?: boolean;
79
81
  }
80
82
  /**
81
83
  * Write the issue copy when one is handed over or a refresh is asked for, then
@@ -756,9 +756,10 @@ export async function initWorkspace(args, workspaceRootOverride, opts = {}) {
756
756
  }
757
757
  }
758
758
  if (!containers) {
759
- warn(`Workspace initialised, but the container step did not run: no slot, so ${COMPOSE_FILE} was not (re)generated ` +
760
- "(see the slot warning above). `werkmeister feature up` fails until you free a slot " +
761
- "and rerun `werkmeister workspace init`.");
759
+ if (!opts.quietNoSlot)
760
+ warn(`Workspace initialised, but the container step did not run: no slot, so ${COMPOSE_FILE} was not (re)generated ` +
761
+ "(see the slot warning above). `werkmeister feature up` fails until you free a slot " +
762
+ "and rerun `werkmeister workspace init`.");
762
763
  return { containers };
763
764
  }
764
765
  raw(`\n${Colors.BOLD}Workspace initialised.${Colors.RESET} ` +
@@ -778,7 +779,7 @@ export async function initWorkspace(args, workspaceRootOverride, opts = {}) {
778
779
  async function runInitWorkspace(workspaceDir, featureSlug, resolved, opts) {
779
780
  info(`Running: werkmeister workspace init (feature: ${featureSlug})`);
780
781
  try {
781
- return await initWorkspace({ ...resolved, feature: featureSlug, force: opts.force }, workspaceDir, opts);
782
+ return await initWorkspace({ ...resolved, feature: featureSlug, force: opts.force }, workspaceDir, { ...opts, quietNoSlot: true });
782
783
  }
783
784
  catch (exc) {
784
785
  // A WorkspaceInitError has already emitted its own `[err]` line — the
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import * as fs from "node:fs";
26
26
  import * as path from "node:path";
27
- import { infraRoot } from "./config.js";
27
+ import { sourceInfraRoot } from "./config.js";
28
28
  import { loadManifest } from "./gate.js";
29
29
  import { harnessLayoutFor } from "./harness/layout.js";
30
30
  import { info, success } from "./reporter.js";
@@ -37,7 +37,7 @@ import { loadConfigFile, loadSandboxServiceConfigs, planFor } from "./workspace_
37
37
  const _MANAGED_PREFIXES = ["w9r-", "sb-"];
38
38
  /** The hand-authored entry-skill sources: infra/skills/<name>/SKILL.md. */
39
39
  export function skillsSourceDir() {
40
- return path.join(infraRoot(), "skills");
40
+ return path.join(sourceInfraRoot(), "skills");
41
41
  }
42
42
  function isDir(p) {
43
43
  return fs.existsSync(p) && fs.statSync(p).isDirectory();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister-core",
3
- "version": "0.94.1",
3
+ "version": "0.94.3",
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.",