werkmeister-core 0.95.1 → 0.95.2

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,18 @@
1
1
  # sandbox-core
2
2
 
3
+ ## 0.95.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 27d6925: Autonomous workspaces narrow two CLI rules that reached past the workspace. `werkmeister pr:*` becomes `pr gate|open|status|new|adopt`, so `pr watch` (whose `--install` writes a launchd job) asks. `workspace init:*`/`init-workspace:*` become the bare form plus `--refresh-issue`, `--prune-context` and `--labels focus`, so `--feature <other>`, `--repos`, `--force` and `--autonomous` ask. Autonomous mode also denies Edit on `.env*`, `.werkmeister/workspace.yml`, `.werkmeister/claude-permissions.json` and `.werkmeister/token`, which the next wake's rules are read from (SW-625).
8
+ - cf3f368: Autonomous workspaces no longer pre-approve `Bash(git:*)`. They get an allow-list of the subcommands a run uses (status, diff, log, show, add, commit, restore, branch, rev-parse, ls-files, merge-base, rev-list, switch, checkout, symbolic-ref, `worktree list`), bare or as `git -C <repo>` for the workspace's own repos only, plus exact `fetch`, `fetch origin`, `fetch origin main`, `remote -v`, `remote get-url origin` and `rebase origin/main`/`--continue`/`--abort`. `grep` (whose pager option git also takes as `-lO` or `--open`), `rebase -x`, `bisect run`, `submodule foreach`, `difftool`, `push`, `init`, `clone`, `stash` and `-C <another workspace>` now ask; `--output` and `--no-index` (which write and read any path) and Edit on any `.git/` are denied (SW-626).
9
+ - 7fccb55: Rerunning `werkmeister workspace init` on an existing workspace now commits the regenerated contracts (CLAUDE.md, CONTEXT.md, `_shared/`, each stage's CONTEXT.md) on the record branch as their own commit, `chore: regenerate workspace contracts`, so they no longer ride along with the agent's next commit. Stage outputs and notes are left alone. A live session gets a nudge to re-read its contracts (SW-760).
10
+ - a8c988f: Run limits now allow `werkmeister issue create --relates <ticket>` for follow-ups a run finds, and `werkmeister feature up` when the exercise or a measurement needs the container, not only the gate. An autonomous workspace gets the matching allow rule, `issue create --relates <its issue>`, so a headless run files without a prompt; in an autonomous workspace `issue create` files only in its own issue's project and posts only a `--body-file` inside the workspace (no stdin, no path out of it) (SW-815).
11
+ - c8901fa: The reproduce contract's permission-rule step now also asks for a `git grep -F` of the exact old rule text across the whole repo, tests and `apps/` included, with each hit listed as a site the fix must update (SW-820).
12
+ - f643c98: Autonomous workspaces no longer pre-approve starting or restarting a service whose mounts give it the docker socket, the werkmeister home, the workspaces or repos root (or a parent), another workspace or a checkout under those roots (`feature up --service <svc>`, `docker restart <feature>-<svc>`), nor a whole-feature `feature up`/`restart` while such a service is selected: its `command:` often runs a package script the agent can edit. A new registry field, `unattended_start: <reason>`, keeps the rules for a service shown to run no such script. Only the machine registry's value counts, and only while the branch's fragment leaves the service's `command`, `image`, `build`, `entrypoint`, `archetype`, mounts and `environment` as the registry has them (SW-854).
13
+ - 0a604fa: Autonomous workspaces no longer pre-approve `werkmeister feature test|logs|services <feature>:*`. The prefix let an agent run `feature test <feature> -w <other> --scaffold`, which writes another workspace, and `feature test <feature> -- --config=<file>`, which runs any JS through Playwright. `feature services <feature>` and `feature logs <feature>` (with or without one of the workspace's own services) are now exact, plus their pre-SW-186 spellings. `feature test` has no rule and asks: even exact, it runs the workspace's own `playwright.config.*`, which the agent can write, with the real HOME. The threat model now records the `host.docker.internal` probe: a container has no network route to Docker, but it does reach the werkmeister daemon with its workspace's token (SW-855).
14
+ - ca7c8d2: `werkmeister-context.md` § Test commands now counts the mounts a service gets from the branch's own `.werkmeister/services.yaml` and the workspace's `dev_links`, as the allow rules already did. A service whose only `~/.werkmeister` or docker-socket mount comes from `dev_links` now prints its test under `with-temp-home` instead of a bare `docker exec` (SW-872).
15
+
3
16
  ## 0.95.1
4
17
 
5
18
  ### Patch Changes
@@ -15,10 +15,13 @@
15
15
  */
16
16
  import { type Archetype, type ArchetypeRegistry, type ReposConfig, type ServiceEntry, type ServicesConfig } from "./config.js";
17
17
  /**
18
- * True when one of *entry*'s host binds is a docker socket (any path ending `docker.sock`, e.g. OrbStack's)
19
- * or the werkmeister home, or a parent of either.
18
+ * True when one of *entry*'s host binds is a docker socket (any path ending `docker.sock`, e.g. OrbStack's),
19
+ * or the werkmeister home, the workspaces root or the repos root, or a parent of one. With *workspaceRoot*,
20
+ * also anything else under those roots: another workspace, or a checkout a dev-linked CLI runs from.
21
+ * SW-855: complete for docker (no TCP API on host.docker.internal), partial for the werkmeister daemon,
22
+ * which any container holding the workspace's token reaches on :3002 (docs/context-strategies.md).
20
23
  */
21
- export declare function hostAccess(entry: ServiceEntry | undefined): boolean;
24
+ export declare function hostAccess(entry: ServiceEntry | undefined, workspaceRoot?: string): boolean;
22
25
  /** True when *entry*'s container sees host path *p* at the same path (one of its binds covers it). */
23
26
  export declare function seesHostPath(entry: ServiceEntry | undefined, p: string): boolean;
24
27
  /**
@@ -115,3 +118,10 @@ export declare function presentArchetypes(repos: Array<[string, string]>, meta:
115
118
  * at workspace time rather than silently resolving.
116
119
  */
117
120
  export declare function validateServiceArchetypes(servicesConfig: ServicesConfig, archetypes: ArchetypeRegistry): string[];
121
+ /**
122
+ * SW-845: *registry* with each entry's `extra_volumes` widened to every bind compose mounts: the
123
+ * branch's own fragment and the workspace's `dev_links` too (both agent-editable), variables
124
+ * substituted as generate.ts does. Only the mounts: test commands stay the registry's.
125
+ * *branch* is registry_sync.ts's `workspaceServices(registry, workspaceRoot)`; importing it here is a cycle.
126
+ */
127
+ export declare function withComposeMounts(registry: ServicesConfig, workspaceRoot: string, branch: ServicesConfig): ServicesConfig;
@@ -15,7 +15,8 @@
15
15
  */
16
16
  import * as fs from "node:fs";
17
17
  import * as path from "node:path";
18
- import { expandUser, loadArchetypes, sandboxHome, } from "./config.js";
18
+ import { parse as parseYaml } from "yaml";
19
+ import { dotDir, expandUser, getReposRoot, loadArchetypes, sandboxHome, sandboxRoot, workspacesRoot, } from "./config.js";
19
20
  const realPath = (p) => {
20
21
  try {
21
22
  return fs.realpathSync(p);
@@ -31,12 +32,20 @@ const hostBinds = (entry) => (entry?.extra_volumes ?? [])
31
32
  .map((src) => realPath(expandUser(src)));
32
33
  const within = (p, dir) => p === dir || p.startsWith(`${dir}${path.sep}`) || dir === "/";
33
34
  /**
34
- * True when one of *entry*'s host binds is a docker socket (any path ending `docker.sock`, e.g. OrbStack's)
35
- * or the werkmeister home, or a parent of either.
35
+ * True when one of *entry*'s host binds is a docker socket (any path ending `docker.sock`, e.g. OrbStack's),
36
+ * or the werkmeister home, the workspaces root or the repos root, or a parent of one. With *workspaceRoot*,
37
+ * also anything else under those roots: another workspace, or a checkout a dev-linked CLI runs from.
38
+ * SW-855: complete for docker (no TCP API on host.docker.internal), partial for the werkmeister daemon,
39
+ * which any container holding the workspace's token reaches on :3002 (docs/context-strategies.md).
36
40
  */
37
- export function hostAccess(entry) {
38
- const targets = ["/var/run/docker.sock", sandboxHome()].map(realPath);
39
- return hostBinds(entry).some((host) => path.basename(host) === "docker.sock" || targets.some((t) => within(t, host)));
41
+ export function hostAccess(entry, workspaceRoot) {
42
+ const roots = [workspacesRoot(), getReposRoot()].map(realPath);
43
+ const targets = ["/var/run/docker.sock", sandboxHome(), ...roots].map(realPath);
44
+ // Both roots default to ~/workspace, so the workspace's own mount is under them.
45
+ const own = workspaceRoot && realPath(workspaceRoot);
46
+ return hostBinds(entry).some((host) => path.basename(host) === "docker.sock" ||
47
+ targets.some((t) => within(t, host)) ||
48
+ Boolean(own && roots.some((r) => within(host, r)) && !within(host, own)));
40
49
  }
41
50
  /** True when *entry*'s container sees host path *p* at the same path (one of its binds covers it). */
42
51
  export function seesHostPath(entry, p) {
@@ -260,3 +269,34 @@ export function validateServiceArchetypes(servicesConfig, archetypes) {
260
269
  }
261
270
  return errors;
262
271
  }
272
+ /**
273
+ * SW-845: *registry* with each entry's `extra_volumes` widened to every bind compose mounts: the
274
+ * branch's own fragment and the workspace's `dev_links` too (both agent-editable), variables
275
+ * substituted as generate.ts does. Only the mounts: test commands stay the registry's.
276
+ * *branch* is registry_sync.ts's `workspaceServices(registry, workspaceRoot)`; importing it here is a cycle.
277
+ */
278
+ export function withComposeMounts(registry, workspaceRoot, branch) {
279
+ // generate.ts's loadDevLinks reads the same field, but generate imports this module.
280
+ let devLinks = {};
281
+ try {
282
+ const yml = parseYaml(fs.readFileSync(path.join(dotDir(workspaceRoot), "workspace.yml"), "utf8"));
283
+ devLinks = yml?.["dev_links"] ?? {};
284
+ }
285
+ catch {
286
+ // No workspace.yml (or unreadable): no dev_links, as generate.ts reads it.
287
+ }
288
+ return Object.fromEntries(Object.entries(registry).map(([id, entry]) => {
289
+ const repo = path.join(workspaceRoot, String(branch[id]?.["repo"] ?? entry["repo"] ?? ""));
290
+ const specs = [
291
+ ...(entry.extra_volumes ?? []),
292
+ ...(branch[id]?.extra_volumes ?? []),
293
+ ...(devLinks[id] ?? []),
294
+ ].map((s) => {
295
+ const out = s.split("${WORKSPACE}").join(workspaceRoot).split("${REPO}").join(repo);
296
+ return out.includes("${WERKMEISTER_ROOT}")
297
+ ? out.split("${WERKMEISTER_ROOT}").join(sandboxRoot())
298
+ : out;
299
+ });
300
+ return [id, { ...entry, extra_volumes: specs }];
301
+ }));
302
+ }
package/dist/generate.js CHANGED
@@ -14,7 +14,7 @@ import * as path from "node:path";
14
14
  import { isDeepStrictEqual } from "node:util";
15
15
  import nunjucks from "nunjucks";
16
16
  import * as YAML from "yaml";
17
- import { candidateServiceNames } from "./archetypes.js";
17
+ import { candidateServiceNames, withComposeMounts } 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";
@@ -1428,7 +1428,9 @@ export async function generateWorkspaceCompose(feature, servicesStr, workspaceRo
1428
1428
  const [portStart, portEnd] = getPortRange(slot);
1429
1429
  success(`Compose ready (slot ${slot}, ports ${portStart}-${portEnd})`);
1430
1430
  const reposConfig = loadReposConfig();
1431
- const contextMd = buildSandboxContextMd(feature, slot, portStart, portEnd, localServices, servicesConfig, testPath, null, candidateServiceNames(repoNames, reposConfig, localServices), readAutoStop(workspaceRoot), tempHomeWrapper(workspaceRoot), reposConfig);
1431
+ const contextMd = buildSandboxContextMd(feature, slot, portStart, portEnd, localServices,
1432
+ // SW-872: the mounts compose gives (fragment, dev_links), as the allow rules count them.
1433
+ withComposeMounts(servicesConfig, workspaceRoot, workspaceServices(servicesConfig, workspaceRoot)), testPath, null, candidateServiceNames(repoNames, reposConfig, localServices), readAutoStop(workspaceRoot), tempHomeWrapper(workspaceRoot), reposConfig);
1432
1434
  const sandboxDir = dotDir(workspaceRoot);
1433
1435
  fs.mkdirSync(sandboxDir, { recursive: true });
1434
1436
  fs.writeFileSync(path.join(sandboxDir, "werkmeister-context.md"), contextMd);
@@ -17,9 +17,9 @@ export const cli = (rule) => CLI_NAMES.map((name) => `Bash(${name} ${rule})`);
17
17
  // shortcut: prefix rules — `npm install foo -g`, an agent-edited test script or a repo's own git
18
18
  // hook still runs (SW-522); a runner without host mounts is the upgrade if runs need a hard boundary.
19
19
  export const AUTONOMOUS_DENY = [
20
- // SW-560: `Bash(git:*)` is allowed, and an alias, pager, fsmonitor or hook set through config, or a
20
+ // SW-560: the git subcommands a run needs are allowed, and an alias, pager, fsmonitor or hook set through config, or a
21
21
  // git-* binary on --exec-path, runs any command. No `* -c *`/`* config *` forms: deny beats allow, and they
22
- // refuse `git commit -m "fix config"`; `git -C <dir> -c …` is SW-626's.
22
+ // refuse `git commit -m "fix config"`. SW-626: the allow rules name a subcommand right after `git` or `-C <repo>`, so `-C <dir> -c …` asks.
23
23
  "Bash(git -c:*)",
24
24
  "Bash(git config:*)",
25
25
  ...["--config", "--exec-path", "--template"].flatMap((flag) => [
@@ -27,6 +27,10 @@ export const AUTONOMOUS_DENY = [
27
27
  `Bash(git * ${flag}*)`,
28
28
  ]),
29
29
  "Bash(git --git-dir*)",
30
+ // SW-626: options of allowed subcommands that reach past the repo: diff/log/show write any path with
31
+ // `--output`, and `diff --no-index` reads any. git takes no abbreviation of either; `grep -O` and fetch's
32
+ // `--upload-pack` do (`-lO`, `--open`, `--upl`), so grep isn't allowed and fetch is exact instead.
33
+ ...["--output", "--no-index"].map((flag) => `Bash(git * ${flag}*)`),
30
34
  // SW-521: a registered test chain's bare `node --test` segment (buildAllowRules) runs any file
31
35
  // with the real HOME; npx and pnpm exec segments name their tool, so they stay allowed.
32
36
  "Bash(node:*)",
@@ -78,6 +82,17 @@ export const AUTONOMOUS_DENY = [
78
82
  ].map((cmd) => `Bash(${pm} ${cmd}:*)`)),
79
83
  ...["add -g", "add --global", "remove -g", "remove --global"].map((cmd) => `Bash(pnpm ${cmd}:*)`),
80
84
  "Bash(gh pr merge:*)",
85
+ // SW-625: the next wake's rules follow these (FEATURE, dev_links, the record), so the agent can't widen them.
86
+ // Only these files: the gate's logs are redirected into .werkmeister/ (pr-rules.md rule 3).
87
+ ...[
88
+ ".env*",
89
+ ".werkmeister/workspace.yml",
90
+ ".werkmeister/claude-permissions.json",
91
+ ".werkmeister/token",
92
+ ].map((f) => `Edit(/${f})`),
93
+ // SW-626: a repo's config (fsmonitor, aliases, hooksPath) and hooks run on the allowed git commands.
94
+ "Edit(/.git/**)",
95
+ "Edit(/**/.git/**)",
81
96
  ...[
82
97
  "kube-switch",
83
98
  "up",
@@ -89,12 +89,15 @@ export declare function removeWorkspaceHooks(workspaceRoot: string): string[];
89
89
  /** The SessionEnd auto-stop entry while *on*; otherwise remove it, keeping hand-added ones. */
90
90
  export declare function writeAutoStopHook(workspaceRoot: string, on: boolean): string;
91
91
  export declare const READ_ONLY_GIT_RULES: string[];
92
+ /** The git rules, bare or with `-C <dir>` for one of *dirs* (the workspace's own repos). */
93
+ export declare const gitRules: (dirs?: string[]) => string[];
92
94
  export declare const AUTONOMOUS_RULES: string[];
93
95
  /**
94
96
  * AUTONOMOUS_RULES plus the `werkmeister` and `docker` commands that name this feature or its containers.
95
97
  * *repoServices*: the workspace's repos' other services (on-demand ones), which only `feature up --service` starts.
98
+ * *hostMounted*: services whose start runs their `command:` with host mounts; none of their starts is pre-approved.
96
99
  */
97
- export declare function autonomousRules(feature: string, services: string[], repoServices?: string[]): string[];
100
+ export declare function autonomousRules(feature: string, services: string[], repoServices?: string[], hostMounted?: string[]): string[];
98
101
  /**
99
102
  * Allow rules for each local service's registered test command, then read-only
100
103
  * git. Each command gets the container form the agent is told to run, plus the
@@ -43,17 +43,18 @@
43
43
  */
44
44
  import * as fs from "node:fs";
45
45
  import * as path from "node:path";
46
- import { parse as parseYaml } from "yaml";
47
- import { candidateServiceNames, containerTestCommand, hostAccess, isPlainChain, serviceTestCommand, wrappedTestCommand, } from "../../archetypes.js";
48
- import { dotDir, getReposRoot, loadArchetypes, loadReposConfig, loadServices, sandboxRoot, } from "../../config.js";
46
+ import { isDeepStrictEqual } from "node:util";
47
+ import { candidateServiceNames, containerTestCommand, hostAccess, isPlainChain, serviceTestCommand, withComposeMounts, wrappedTestCommand, } from "../../archetypes.js";
48
+ import { dotDir, getReposRoot, loadArchetypes, loadReposConfig, loadServices, } from "../../config.js";
49
49
  import { frozenInstalls } from "../../fragment_detect/workspace.js";
50
50
  import { load as loadGlobalConfig } from "../../global_config.js";
51
51
  import { workspaceServices } from "../../registry_sync.js";
52
52
  import { info } from "../../reporter.js";
53
53
  import { repoDirs } from "../../standards.js";
54
54
  import { tempHomeWrapper } from "../../temp_home.js";
55
- // biome-ignore lint/suspicious/noImportCycles: jira→harness→…→issue_tracker (SW-188); SW-411
56
- import { readAutonomous, readAutoStop, readGrants, readModel } from "../../workspace_prompts.js";
55
+ // biome-ignore-start lint/suspicious/noImportCycles: jira→harness→…→issue_tracker (SW-188); SW-411
56
+ import { readAutonomous, readAutoStop, readGrants, readModel, readWorkspaceField, } from "../../workspace_prompts.js";
57
+ // biome-ignore-end lint/suspicious/noImportCycles: SW-188
57
58
  import { AUTONOMOUS_DENY, cli, pluginTool } from "../autonomous_deny.js";
58
59
  import { CODEX_HOOKS_FILE, CODEX_LAUNCH, writeCodexConfig } from "../codex/index.js";
59
60
  // biome-ignore lint/suspicious/noImportCycles: jira→harness→…→issue_tracker (SW-188); SW-411
@@ -345,26 +346,79 @@ export const READ_ONLY_GIT_RULES = [
345
346
  // `werkmeister:*`, `docker:*`, `npm:*`, `gh:*` or whole MCP server, which reached
346
347
  // the shared proxy, other features and the linked CLI. The PR guard is a
347
348
  // PreToolUse deny, so `gh pr create` stays blocked.
349
+ // SW-854: what decides the container a start runs; a branch that changes one loses `unattended_start`.
350
+ const START_FIELDS = [
351
+ "command",
352
+ "image",
353
+ "build",
354
+ "entrypoint",
355
+ "archetype",
356
+ "extra_volumes",
357
+ "environment",
358
+ ];
359
+ const WHOLE_FEATURE_STARTS = ["up", "restart", "feature up", "feature restart"];
360
+ // SW-626: the git a run needs, not `git:*`, which ran commands through `rebase -x`, `bisect run`,
361
+ // `submodule foreach`, `difftool -x` and `-C <other workspace>`. Push is `werkmeister pr open`'s.
362
+ const GIT_PREFIXES = [
363
+ "status",
364
+ "diff",
365
+ "log",
366
+ "show",
367
+ "add",
368
+ "commit",
369
+ "restore",
370
+ "branch",
371
+ "rev-parse",
372
+ "ls-files",
373
+ "merge-base",
374
+ "rev-list",
375
+ "switch",
376
+ "checkout",
377
+ "symbolic-ref",
378
+ "worktree list",
379
+ ];
380
+ // Exact: rebase's pr-rules.md rule 3 catch-up (any other rebase takes `-x <cmd>`); fetch takes any URL, path
381
+ // or `--upl=<cmd>`; `remote -v add|set-url` dispatches the subcommand after `-v`. No grep: the Grep tool covers it.
382
+ const GIT_EXACT = [
383
+ "rebase origin/main",
384
+ "rebase --continue",
385
+ "rebase --abort",
386
+ "fetch",
387
+ "fetch origin",
388
+ "fetch origin main",
389
+ "remote -v",
390
+ "remote get-url origin",
391
+ ];
392
+ /** The git rules, bare or with `-C <dir>` for one of *dirs* (the workspace's own repos). */
393
+ export const gitRules = (dirs = []) => ["", ...dirs.map((d) => `-C ${d} `)].flatMap((c) => [
394
+ ...GIT_PREFIXES.map((s) => `Bash(git ${c}${s}:*)`),
395
+ ...GIT_EXACT.map((s) => `Bash(git ${c}${s})`),
396
+ ]);
348
397
  export const AUTONOMOUS_RULES = [
349
- "Bash(git:*)",
398
+ ...gitRules(),
350
399
  // `werkmeister pr open` does the push and the PR; gh is read-only here.
351
400
  ...["pr view", "pr checks", "pr diff", "pr list", "issue view", "run view", "run list"].map((cmd) => `Bash(gh ${cmd}:*)`),
352
401
  // No-arg forms act on the cwd's FEATURE; `autonomousRules` adds the named ones.
353
402
  // Each pre-SW-186 spelling keeps its rule until the CLI drops it, beside its new one.
354
- ...["up", "restart", "feature up", "feature restart"].flatMap(cli),
403
+ ...WHOLE_FEATURE_STARTS.flatMap(cli),
355
404
  ...[
356
405
  "status",
357
406
  "feature status",
358
407
  "infra status",
359
- "pr",
408
+ // SW-625: no `pr watch`: `--install` writes a host launchd job, and a wake resumes every workspace.
409
+ "pr gate",
410
+ "pr open",
411
+ "pr status",
412
+ "pr new",
413
+ "pr adopt",
360
414
  "issue view",
361
415
  "issue start",
362
- "init-workspace",
363
- "workspace init",
364
416
  "skills",
365
417
  "standards",
366
418
  "notes context",
367
419
  ].flatMap((cmd) => cli(`${cmd}:*`)),
420
+ // SW-625: exact; `--feature <other>` repoints .env at another workspace's containers, `--repos`/`--force`/`--autonomous` reshape it.
421
+ ...["init-workspace", "workspace init"].flatMap((cmd) => ["", " --refresh-issue", " --prune-context", " --labels focus"].flatMap((flag) => cli(`${cmd}${flag}`))),
368
422
  "Bash(docker ps:*)",
369
423
  // Local build and test; no `npm install` or `pnpm add`, so a new dependency waits for a person.
370
424
  // SW-521: no `node`, `npx`, `pnpm exec` or `python3`, which run any file with the real HOME;
@@ -390,24 +444,34 @@ export const AUTONOMOUS_RULES = [
390
444
  /**
391
445
  * AUTONOMOUS_RULES plus the `werkmeister` and `docker` commands that name this feature or its containers.
392
446
  * *repoServices*: the workspace's repos' other services (on-demand ones), which only `feature up --service` starts.
447
+ * *hostMounted*: services whose start runs their `command:` with host mounts; none of their starts is pre-approved.
393
448
  */
394
- export function autonomousRules(feature, services, repoServices = []) {
449
+ export function autonomousRules(feature, services, repoServices = [], hostMounted = []) {
450
+ // SW-854: a start or restart runs the service's `command:`, often a package script the agent can edit.
451
+ const startable = (svc) => !hostMounted.includes(svc);
452
+ const wholeFeature = services.every(startable);
453
+ const base = wholeFeature
454
+ ? AUTONOMOUS_RULES
455
+ : AUTONOMOUS_RULES.filter((r) => !WHOLE_FEATURE_STARTS.flatMap(cli).includes(r));
395
456
  if (!feature)
396
- return AUTONOMOUS_RULES;
457
+ return base;
397
458
  return [
398
- ...AUTONOMOUS_RULES,
459
+ ...base,
399
460
  // Exact: `werkmeister feature restart <f> infra` and `docker restart <f>-a <other>` stay out.
400
- ...["up", "restart", "feature up", "feature restart"].flatMap((cmd) => cli(`${cmd} ${feature}`)),
461
+ ...(wholeFeature ? WHOLE_FEATURE_STARTS.flatMap((cmd) => cli(`${cmd} ${feature}`)) : []),
401
462
  // SW-132: one of its own services, the way the PR gate starts them. SW-843: exact, since a
402
463
  // trailing `<other>` or `-w <path>` would start another workspace's container.
403
- ...[...services, ...repoServices].flatMap((svc) => [`feature up --service ${svc}`, `feature up ${feature} --service ${svc}`].flatMap(cli)),
404
- ...["logs", "test", "services", "feature logs", "feature test", "feature services"].flatMap((cmd) => cli(`${cmd} ${feature}:*`)),
405
- // SW-560: no `docker exec <f>-<svc>:*`: any container reaches the host daemon over
406
- // host.docker.internal, and some mount the docker socket; its exact registered test still runs.
407
- ...services.flatMap((svc) => [
408
- `Bash(docker logs ${feature}-${svc}:*)`,
409
- `Bash(docker restart ${feature}-${svc})`,
410
- ]),
464
+ ...[...services, ...repoServices]
465
+ .filter(startable)
466
+ .flatMap((svc) => [`feature up --service ${svc}`, `feature up ${feature} --service ${svc}`].flatMap(cli)),
467
+ // SW-855: exact too. No `feature test` even exact: it runs the workspace's own `playwright.config.*`,
468
+ // which the agent can write, with the real HOME; its `-w <other> --scaffold` writes another workspace.
469
+ ...["logs", "services", "feature logs", "feature services"].flatMap((cmd) => cli(`${cmd} ${feature}`)),
470
+ ...services.flatMap((svc) => ["logs", "feature logs"].flatMap((cmd) => cli(`${cmd} ${feature} ${svc}`))),
471
+ // SW-560: no `docker exec <f>-<svc>:*`: some containers mount the docker socket, and any one that
472
+ // mounts the workspace reaches the werkmeister daemon with its token (SW-855); its exact registered test still runs.
473
+ ...services.map((svc) => `Bash(docker logs ${feature}-${svc}:*)`),
474
+ ...services.filter(startable).map((svc) => `Bash(docker restart ${feature}-${svc})`),
411
475
  ];
412
476
  }
413
477
  // Permission strings can't carry a marker the way hook commands do, so the rules
@@ -469,37 +533,6 @@ hostServices = [], reposConfig = {}) {
469
533
  .map((r) => `${wrapped}--no-wait ${r.slice(wrapped.length)}`));
470
534
  return [...new Set([...rules, ...READ_ONLY_GIT_RULES])];
471
535
  }
472
- /**
473
- * SW-845: *registry* with each entry's `extra_volumes` widened to every bind compose mounts: the
474
- * branch's own fragment and the workspace's `dev_links` too (both agent-editable), variables
475
- * substituted as generate.ts does. Only the mounts: test commands stay the registry's.
476
- */
477
- function withComposeMounts(registry, workspaceRoot) {
478
- const branch = workspaceServices(registry, workspaceRoot);
479
- // generate.ts's loadDevLinks reads the same field; importing it closes a cycle (generate → claude_md → jira → here).
480
- let devLinks = {};
481
- try {
482
- const yml = parseYaml(fs.readFileSync(path.join(dotDir(workspaceRoot), "workspace.yml"), "utf8"));
483
- devLinks = yml?.["dev_links"] ?? {};
484
- }
485
- catch {
486
- // No workspace.yml (or unreadable): no dev_links, as generate.ts reads it.
487
- }
488
- return Object.fromEntries(Object.entries(registry).map(([id, entry]) => {
489
- const repo = path.join(workspaceRoot, String(branch[id]?.["repo"] ?? entry["repo"] ?? ""));
490
- const specs = [
491
- ...(entry.extra_volumes ?? []),
492
- ...(branch[id]?.extra_volumes ?? []),
493
- ...(devLinks[id] ?? []),
494
- ].map((s) => {
495
- const out = s.split("${WORKSPACE}").join(workspaceRoot).split("${REPO}").join(repo);
496
- return out.includes("${WERKMEISTER_ROOT}")
497
- ? out.split("${WERKMEISTER_ROOT}").join(sandboxRoot())
498
- : out;
499
- });
500
- return [id, { ...entry, extra_volumes: specs }];
501
- }));
502
- }
503
536
  function _readEnv(workspaceRoot) {
504
537
  let text;
505
538
  try {
@@ -547,7 +580,10 @@ export function workspaceAllowRules(workspaceRoot, autonomous = readAutonomous(w
547
580
  }
548
581
  const extra = hostServices.filter((s) => !services.includes(s));
549
582
  const any = services.length > 0 || extra.length > 0;
550
- const rules = buildAllowRules(any ? feature : "", services, any ? withComposeMounts(loadServices(), workspaceRoot) : {}, any ? loadArchetypes() : {}, wrapper, builtClis, extra, reposConfig);
583
+ const loaded = any ? loadServices() : {};
584
+ const branch = any ? workspaceServices(loaded, workspaceRoot) : {};
585
+ const registry = any ? withComposeMounts(loaded, workspaceRoot, branch) : {};
586
+ const rules = buildAllowRules(any ? feature : "", services, registry, any ? loadArchetypes() : {}, wrapper, builtClis, extra, reposConfig);
551
587
  rules.push(...readGrants(workspaceRoot).flatMap(cli));
552
588
  if (!autonomous)
553
589
  return rules;
@@ -556,7 +592,27 @@ export function workspaceAllowRules(workspaceRoot, autonomous = readAutonomous(w
556
592
  // `yarnPath` would otherwise grant itself an install that runs its own file.
557
593
  const reposRoot = getReposRoot();
558
594
  const installs = repoNames.flatMap((name) => frozenInstalls((f) => fs.existsSync(path.join(reposRoot, name, f))).map((c) => `Bash(${c})`));
559
- return [...new Set([...rules, ...autonomousRules(feature, services, extra), ...installs])];
595
+ // `unattended_start` comes from the machine registry (synced from main), never the branch's fragment, and
596
+ // holds only while the branch runs the same container: its fragment's `command:`/`image:` win in compose (SW-337).
597
+ const unchanged = (svc) => START_FIELDS.every((k) => isDeepStrictEqual(loaded[svc]?.[k], branch[svc]?.[k]));
598
+ const hostMounted = Object.keys(registry).filter((svc) => hostAccess(registry[svc], workspaceRoot) &&
599
+ !(registry[svc]?.["unattended_start"] && unchanged(svc)));
600
+ // SW-626: `-C` only into the workspace's own repos, by absolute path or by name from the workspace root.
601
+ const repoGit = gitRules(repoDirs(workspaceRoot).flatMap((d) => [d, path.basename(d)])).filter((r) => r.startsWith("Bash(git -C "));
602
+ // SW-815: a follow-up the run finds, linked to this workspace's issue; `create` is Jira-only.
603
+ const issueId = String(readWorkspaceField(workspaceRoot, "issue_id") ?? "").trim();
604
+ const followUp = /^[A-Z][A-Z0-9_]*-\d+$/.test(issueId)
605
+ ? cli(`issue create --relates ${issueId}:*`)
606
+ : [];
607
+ return [
608
+ ...new Set([
609
+ ...rules,
610
+ ...autonomousRules(feature, services, extra, hostMounted),
611
+ ...repoGit,
612
+ ...installs,
613
+ ...followUp,
614
+ ]),
615
+ ];
560
616
  }
561
617
  function builtCliWrappers(workspaceRoot) {
562
618
  return repoDirs(workspaceRoot)
@@ -3,7 +3,7 @@
3
3
  * ▶ Start work, `werkmeister workspace prompt --args` (the next-wave skill) and an autonomous BRIEF.md.
4
4
  */
5
5
  export declare const INTERACTIVE_LINE = "This is an interactive run: check with me at each stage's human check.";
6
- export declare const GATE_LINE = "Run `werkmeister feature up` only when the gate needs it, and `werkmeister feature stop` this workspace's containers right after `werkmeister pr open` succeeds.";
6
+ export declare const GATE_LINE = "Run `werkmeister feature up` only when the gate, the exercise or a measurement needs the container, and `werkmeister feature stop` this workspace's containers right after `werkmeister pr open` succeeds.";
7
7
  /** What an autonomous run may not do, as markdown bullets. */
8
8
  export declare const RUN_LIMITS: string;
9
9
  /** Drop machine-writing run steps from a starting prompt and say they happen after merge instead. */
package/dist/run_start.js CHANGED
@@ -3,10 +3,10 @@
3
3
  * ▶ Start work, `werkmeister workspace prompt --args` (the next-wave skill) and an autonomous BRIEF.md.
4
4
  */
5
5
  export const INTERACTIVE_LINE = "This is an interactive run: check with me at each stage's human check.";
6
- export const GATE_LINE = "Run `werkmeister feature up` only when the gate needs it, and `werkmeister feature stop` this workspace's containers right after `werkmeister pr open` succeeds.";
6
+ export const GATE_LINE = "Run `werkmeister feature up` only when the gate, the exercise or a measurement needs the container, and `werkmeister feature stop` this workspace's containers right after `werkmeister pr open` succeeds.";
7
7
  /** What an autonomous run may not do, as markdown bullets. */
8
8
  export const RUN_LIMITS = [
9
- "Tests never call the real Jira or GitHub APIs; the tracker is mocked. The only real issue updates are the status moves `werkmeister issue start` and `werkmeister pr open` make for this ticket and its `group:` members; run both.",
9
+ "Tests never call the real Jira or GitHub APIs; the tracker is mocked. The only real issue updates are the status moves `werkmeister issue start` and `werkmeister pr open` make for this ticket and its `group:` members; run both. A follow-up the run finds is filed with `werkmeister issue create --relates <this ticket>` (SW-815); no other tracker writes.",
10
10
  "Never read or write the real `~/.werkmeister`; tests use a temporary HOME. To see the machine config's shape run `werkmeister machine config`: it masks secrets such as `jira.api_token`.",
11
11
  "No `npm link`, `npm`/`pnpm install -g`, `npm publish`, `werkmeister infra proxy-reload`, and no other workspaces.",
12
12
  'Where the ticket says "to confirm", use it as written unless the code shows a reason to change it, and record each choice in the stage output for PR review.',
@@ -350,7 +350,7 @@ const bugfix = [
350
350
  `When the proposed fix branches on a predicate, list each condition that makes it true and give each one a test. ${PREAPPROVED_INPUT}`,
351
351
  NAME_HISTORY_STEP,
352
352
  // SW-564: sw-521's root cause was a permission rule; step 4 listed the callers of one builder and missed two other sources of a matching rule.
353
- "When the root cause is a permission rule (allow, deny, ask), step 4 lists every source of a matching rule: each builder, each rule derived from a registered command (its `&&` segments included), rules recorded in existing workspaces and how a refresh or migrate removes them, and the list a headless wake passes (`--allowedTools` / `--disallowedTools`). The failing test probes each source.",
353
+ "When the root cause is a permission rule (allow, deny, ask), step 4 lists every source of a matching rule: each builder, each rule derived from a registered command (its `&&` segments included), rules recorded in existing workspaces and how a refresh or migrate removes them, and the list a headless wake passes (`--allowedTools` / `--disallowedTools`). The failing test probes each source. Also `git grep -F` the exact old rule text across the whole repo, tests and `apps/` included, and list each hit as a site the fix must update (SW-820).",
354
354
  `Write \`output/repro.md\`: steps 1–7, and a proposed fix in one paragraph under a \`status: proposed\` line.${noCommitPlan(v.group)} Check the proposed fix against the standards rows above and name any rule that already prescribes it. ${CRITERION_REACH}`,
355
355
  ],
356
356
  outputs: ["`output/repro.md`", "One failing test, uncommitted"],
@@ -153,6 +153,13 @@ export declare function initWorkspace(args: Record<string, unknown>, workspaceRo
153
153
  /** False when the workspace names a feature but no slot was free, so compose.yml was not generated. */
154
154
  containers: boolean;
155
155
  }>;
156
+ export declare const CONTRACTS_CHANGED_NUDGE = "`werkmeister workspace init` just regenerated this workspace's contracts (CLAUDE.md, CONTEXT.md, `_shared/`, the stage CONTEXT.md files; committed on the record branch as `chore: regenerate workspace contracts`). Re-read CLAUDE.md and the current stage's CONTEXT.md before going on: their rules now govern. An instruction the person gave you in chat still wins; if the two conflict, ask.";
157
+ /**
158
+ * SW-760: a rerun rewrites the contracts under any live session. Commit them alone on the record
159
+ * branch, so they don't ride along with the agent's next commit, and leave the session a nudge.
160
+ * Only the generated rule files: stage outputs and notes are the agent's.
161
+ */
162
+ export declare function recordRegeneratedContracts(workspaceRoot: string, owned: string[]): boolean;
156
163
  /**
157
164
  * Create a workspace from already-resolved inputs and initialise it. Returns
158
165
  * the workspace directory.
@@ -27,6 +27,7 @@ import * as fs from "node:fs";
27
27
  import * as os from "node:os";
28
28
  import * as path from "node:path";
29
29
  import * as YAML from "yaml";
30
+ import { writeNudge } from "./agent_state.js";
30
31
  import { presentArchetypes } from "./archetypes.js";
31
32
  import { Colors } from "./colors.js";
32
33
  import { ensureSharedVolumes, retireLegacyProject, workspaceComposeArgv } from "./compose.js";
@@ -43,6 +44,7 @@ import { harnessLayoutFor, parseHarnessId } from "./harness/layout.js";
43
44
  import { HARNESS_IDS } from "./harness/types.js";
44
45
  import { fetchIssueSnapshot, IssueFetchError, readIssueRef, writeIssueCopy, } from "./issue_snapshot.js";
45
46
  import { issueTracker, projectForIssue } from "./issue_tracker.js";
47
+ import { liveSessions } from "./lifecycle.js";
46
48
  import { defaultWorkspaceRepo, originMismatch, WORKSPACE_ROOT_REPO, workspaceRepoUrl, } from "./machine_setup.js";
47
49
  import { resolveWorkspaceMcpServers, validateArchetypeMcpServers, writeWorkspaceMcp, } from "./mcp_gen.js";
48
50
  import { modelTiers } from "./model_tiers.js";
@@ -659,6 +661,7 @@ export async function initWorkspace(args, workspaceRootOverride, opts = {}) {
659
661
  success(`Wrote ${writeFixtureWrapper(workspaceRoot)}`);
660
662
  // 5b–6c. The context layer — CLAUDE.md and everything the agent reads
661
663
  // beside it — belongs to the workspace's strategy (docs/context-strategies.md).
664
+ const rerun = fs.existsSync(path.join(workspaceRoot, "CLAUDE.md"));
662
665
  strategy.init({
663
666
  workspaceRoot,
664
667
  workspaceName,
@@ -679,6 +682,8 @@ export async function initWorkspace(args, workspaceRootOverride, opts = {}) {
679
682
  continue;
680
683
  reportLeftovers(workspaceRoot, strategyById(id), strategy, Boolean(args["prune_context"]));
681
684
  }
685
+ if (rerun)
686
+ recordRegeneratedContracts(workspaceRoot, strategy.ownedPaths());
682
687
  // 6d needs the present archetypes whichever strategy ran.
683
688
  const [servicesConfig, reposConfig] = loadSandboxServiceConfigs();
684
689
  const archetypes = loadArchetypes();
@@ -766,6 +771,29 @@ export async function initWorkspace(args, workspaceRootOverride, opts = {}) {
766
771
  "Open a new Claude Code session from the workspace root to pick up the context.\n\n");
767
772
  return { containers };
768
773
  }
774
+ export const CONTRACTS_CHANGED_NUDGE = "`werkmeister workspace init` just regenerated this workspace's contracts (CLAUDE.md, CONTEXT.md, `_shared/`, the stage CONTEXT.md files; committed on the record branch as `chore: regenerate workspace contracts`). Re-read CLAUDE.md and the current stage's CONTEXT.md before going on: their rules now govern. An instruction the person gave you in chat still wins; if the two conflict, ask.";
775
+ /**
776
+ * SW-760: a rerun rewrites the contracts under any live session. Commit them alone on the record
777
+ * branch, so they don't ride along with the agent's next commit, and leave the session a nudge.
778
+ * Only the generated rule files: stage outputs and notes are the agent's.
779
+ */
780
+ export function recordRegeneratedContracts(workspaceRoot, owned) {
781
+ const stageContracts = (dir) => fs.existsSync(path.join(workspaceRoot, dir))
782
+ ? fs
783
+ .readdirSync(path.join(workspaceRoot, dir))
784
+ .map((s) => path.join(dir, s, "CONTEXT.md"))
785
+ .filter((f) => fs.existsSync(path.join(workspaceRoot, f)))
786
+ : [];
787
+ const paths = owned
788
+ .flatMap((p) => (p === "stages" ? stageContracts(p) : [p]))
789
+ .filter((p) => !p.includes("*") && !p.endsWith("/notes"))
790
+ .filter((p) => fs.existsSync(path.join(workspaceRoot, p)));
791
+ if (!paths.length || !commitRecord(workspaceRoot, "chore: regenerate workspace contracts", paths))
792
+ return false;
793
+ if (liveSessions(workspaceRoot).length)
794
+ writeNudge(workspaceRoot, CONTRACTS_CHANGED_NUDGE);
795
+ return true;
796
+ }
769
797
  // ---------------------------------------------------------------------------
770
798
  // init-workspace hand-off
771
799
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "werkmeister-core",
3
- "version": "0.95.1",
3
+ "version": "0.95.2",
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.",