werkmeister 0.87.2 → 0.87.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.
Files changed (127) hide show
  1. package/dist/budget-BLK2WAB7.js +4 -0
  2. package/dist/cache-HYS5M4AY.js +4 -0
  3. package/dist/chunk-22YIK2BP.js +40 -0
  4. package/dist/chunk-2IE5JCIK.js +4 -0
  5. package/dist/chunk-47HAXWC4.js +4 -0
  6. package/dist/chunk-7D4A3HVZ.js +5 -0
  7. package/dist/chunk-7I5GWJOR.js +45 -0
  8. package/dist/chunk-7YUHPLUW.js +5 -0
  9. package/dist/chunk-A5QL5RDB.js +4 -0
  10. package/dist/chunk-AEDQ3BHS.js +24 -0
  11. package/dist/chunk-ANDUBI2O.js +23 -0
  12. package/dist/chunk-ATYTAZNX.js +4 -0
  13. package/dist/chunk-AXXV337U.js +18 -0
  14. package/dist/chunk-C4J3VWL3.js +26 -0
  15. package/dist/chunk-CBTQBN4M.js +110 -0
  16. package/dist/chunk-CVIURF6M.js +180 -0
  17. package/dist/chunk-CVK35MQA.js +4 -0
  18. package/dist/chunk-CVMWX5W5.js +146 -0
  19. package/dist/chunk-DL73WFKY.js +4 -0
  20. package/dist/chunk-DMZPGI56.js +13 -0
  21. package/dist/chunk-DNDCV7NJ.js +6 -0
  22. package/dist/chunk-EHWLRQV7.js +410 -0
  23. package/dist/chunk-EOBOW6TP.js +48 -0
  24. package/dist/chunk-FUA5NLXY.js +57 -0
  25. package/dist/chunk-GMROWN6L.js +10 -0
  26. package/dist/chunk-GMYAKGU2.js +4 -0
  27. package/dist/chunk-GUFHPPBN.js +4 -0
  28. package/dist/chunk-H3J3PJGY.js +7 -0
  29. package/dist/chunk-HKKHKLTS.js +11 -0
  30. package/dist/chunk-I3QYJM3C.js +4 -0
  31. package/dist/chunk-I7X6WZIM.js +4 -0
  32. package/dist/chunk-IFSWSRJW.js +5 -0
  33. package/dist/chunk-JPAIPFJZ.js +6 -0
  34. package/dist/chunk-JYCKRH6K.js +68 -0
  35. package/dist/chunk-K6GRVJQO.js +4 -0
  36. package/dist/chunk-N72DCINT.js +82 -0
  37. package/dist/chunk-NX6LSFJH.js +4 -0
  38. package/dist/chunk-OC7PYYEG.js +145 -0
  39. package/dist/chunk-OSW5G2B6.js +82 -0
  40. package/dist/chunk-OTPRXRNK.js +23 -0
  41. package/dist/chunk-P3NAQKV7.js +6 -0
  42. package/dist/chunk-PLREOZEU.js +4 -0
  43. package/dist/chunk-Q2CVZANF.js +42 -0
  44. package/dist/chunk-QAQMYRCU.js +4 -0
  45. package/dist/chunk-QEYZ7HOT.js +36 -0
  46. package/dist/chunk-QO5K65QU.js +5 -0
  47. package/dist/chunk-QVMMQ5JU.js +41 -0
  48. package/dist/chunk-RJQTC65O.js +33 -0
  49. package/dist/chunk-RO5NEK3B.js +4 -0
  50. package/dist/chunk-RS7NMSUP.js +4 -0
  51. package/dist/chunk-S62C4SVE.js +4 -0
  52. package/dist/chunk-SNY4QE2J.js +137 -0
  53. package/dist/chunk-SUWACJLK.js +5 -0
  54. package/dist/chunk-TCABDYVJ.js +4 -0
  55. package/dist/chunk-U4733O5I.js +13 -0
  56. package/dist/chunk-U4RIK7SI.js +15 -0
  57. package/dist/chunk-USRMIMWS.js +11 -0
  58. package/dist/chunk-UTVZKLGU.js +89 -0
  59. package/dist/chunk-UU5QPEC3.js +9 -0
  60. package/dist/chunk-VNP6M5VF.js +294 -0
  61. package/dist/chunk-WITTY5DQ.js +4 -0
  62. package/dist/chunk-X7GPCYQ7.js +4 -0
  63. package/dist/chunk-XGIW27EP.js +4 -0
  64. package/dist/chunk-XMARLDYZ.js +11 -0
  65. package/dist/chunk-XS5OH4RT.js +9 -0
  66. package/dist/chunk-YSPELKLM.js +8 -0
  67. package/dist/chunk-ZQOM25KE.js +31 -0
  68. package/dist/chunk-ZUSETSI2.js +4 -0
  69. package/dist/chunk-ZYR6KZ3U.js +4 -0
  70. package/dist/clean-XPY5QAR2.js +8 -0
  71. package/dist/close_out-3G6LG5CE.js +8 -0
  72. package/dist/code-LB6A5M22.js +4 -0
  73. package/dist/config-NTIS2QLB.js +4 -0
  74. package/dist/connect-MNBVLTKZ.js +11 -0
  75. package/dist/daemon-3A47MBS2.js +4 -0
  76. package/dist/dashboard.js +20 -1898
  77. package/dist/detect-QMRHHFXH.js +13 -0
  78. package/dist/down-WKZSBYCI.js +17 -0
  79. package/dist/fixture-OLAE2KUV.js +14 -0
  80. package/dist/form-cli.js +3 -1507
  81. package/dist/hooks-ULLFLRUW.js +4 -0
  82. package/dist/hooks_gen-GKZVUPMO.js +4 -0
  83. package/dist/infra-A3C7FDNR.js +4 -0
  84. package/dist/init_workspace-TU76APJQ.js +4 -0
  85. package/dist/intercept-SOU6VA2K.js +7 -0
  86. package/dist/issue-XC7UEFIP.js +5 -0
  87. package/dist/lib/agent_state.js +1 -6
  88. package/dist/lib/gate.js +1 -2
  89. package/dist/lib/pr_guard.js +1 -1
  90. package/dist/list_workspaces-4FBP4CIS.js +7 -0
  91. package/dist/logs-GFJHTAOE.js +6 -0
  92. package/dist/main.js +42 -1852
  93. package/dist/mcp-proxy.js +12 -229
  94. package/dist/mcp.js +30 -1930
  95. package/dist/migrate-PB3PLOPH.js +8 -0
  96. package/dist/notes-BT4GAPYP.js +4 -0
  97. package/dist/open-ZM2OEFSN.js +6 -0
  98. package/dist/optimize-2IZXOEM6.js +11 -0
  99. package/dist/pause-UPYUR576.js +4 -0
  100. package/dist/pr-UT66UXR7.js +5 -0
  101. package/dist/proxy_reload-PXGCYXTX.js +6 -0
  102. package/dist/registry-BYQSBFX2.js +4 -0
  103. package/dist/remove-E3D5UE6C.js +7 -0
  104. package/dist/remove_workspace-HH5DY2PQ.js +8 -0
  105. package/dist/restart-WACF24Q5.js +8 -0
  106. package/dist/resume-WUHWDN5P.js +8 -0
  107. package/dist/safari-LADKSYXB.js +8 -0
  108. package/dist/sandbox-KCOIOWUC.js +4 -0
  109. package/dist/services-HGBYH2BF.js +6 -0
  110. package/dist/setup-IHMHWCWE.js +5 -0
  111. package/dist/skills-AGQ43EYJ.js +4 -0
  112. package/dist/slots-FUNR4X2E.js +4 -0
  113. package/dist/standards-R42OMGAN.js +4 -0
  114. package/dist/start_args-5VUTUZJK.js +4 -0
  115. package/dist/starting_prompt-VSXMHUES.js +4 -0
  116. package/dist/stats-SBCCNRRR.js +4 -0
  117. package/dist/status-YRBJF4LX.js +13 -0
  118. package/dist/stop-UOWK5NZB.js +9 -0
  119. package/dist/telepresence-KGO67FZ6.js +4 -0
  120. package/dist/test-IGAOSBIZ.js +6 -0
  121. package/dist/tokens-2IJEBSSK.js +6 -0
  122. package/dist/up-LO6N5V5M.js +11 -0
  123. package/dist/v4-IBDIQBRV.js +4 -0
  124. package/dist/wait_load-LVY5WRZP.js +4 -0
  125. package/dist/werkmeister-workspaces.vsix +0 -0
  126. package/dist/workspace-LDQAAZM6.js +4 -0
  127. package/package.json +3 -3
@@ -0,0 +1,180 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{a as U,b as N,f as Q}from"./chunk-ZQOM25KE.js";import{c as q,d as V,e as X,g as Y,j as K}from"./chunk-S62C4SVE.js";import{N as Z,O as ee,u as J}from"./chunk-RJQTC65O.js";import{a as A,b as te}from"./chunk-ATYTAZNX.js";import{I as re}from"./chunk-XMARLDYZ.js";import{r as G}from"./chunk-C4J3VWL3.js";import{D as W,S as z}from"./chunk-OC7PYYEG.js";import{a as h,f as E}from"./chunk-K6GRVJQO.js";E();import*as oe from"node:fs";import*as ne from"node:path";E();function se(t){let n=t.url?`[${t.ref}](${t.url})`:t.ref,i=t.title?`: ${t.title}`:"",a=t.fetchedAt?`Copy taken ${t.fetchedAt.slice(0,10)}: \`.werkmeister/issue.md\`.`:"No stored copy; run `werkmeister workspace init --refresh-issue`.";return["## Issue","",`${n}${i}. ${a}`,"Before each stage, re-read the live issue for newer direction: `werkmeister issue view`","Its status moves by itself (In Progress \u2192 In Review \u2192 Done): `docs/workspace-lifecycle.md` \xA7 Issue status in the werkmeister repo.",""].join(`
4
+ `)}h(se,"renderIssueRef");function ye(t){try{let n=G(),i=A(void 0,n),a=t.find(s=>i[s]?.hostname),r=a?i[a].hostname:Object.values(i).map(s=>s.hostname).filter(Boolean).sort()[0];return r?{host:r,domain:n.local_domain.replace(/^\.+/,"")}:null}catch{return null}}h(ye,"resolveProxyHost");function F(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}h(F,"isDict");function ve(t,n,i){let a=[];for(let[r]of t){let s=!1;try{s=oe.statSync(ne.join(n,r,"CLAUDE.md")).isFile()}catch{}s&&a.push(`| Working in ${r} | ${r}/CLAUDE.md |`)}return i&&a.push("| Running or validating the change \u2014 test commands, how to validate, ports, lifecycle | .werkmeister/werkmeister-context.md |"),t.length>1&&a.push("| Cross-repo contract change | .werkmeister/notes/ (`contract` notes) |"),a.push("| Open or create a PR (including `/create-pr`), merge, close out | .werkmeister/pr-rules.md |"),a.length===0?"":`| Task | Read |
5
+ |------|------|
6
+ `+a.join(`
7
+ `)}h(ve,"buildRoutingTable");function be(t){return t.path==="spike"?"No implement, review, or PR phase. Deliverable: `finding` notes. Anything built is throwaway.":t.gate===null?"Gate: none \u2014 `w9r-implement` loads the standards.":t.gate.status?`Gate: no source edit until a \`${t.gate.note}\` note in \`.werkmeister/notes/\` reads \`status: ${t.gate.status}\`. Write it at the end of research, after the user approves the design; the flip *is* the approval \u2014 do not ask again.`:`Gate: no source edit until a \`${t.gate.note}\` note in \`.werkmeister/notes/\` names the root cause.`}h(be,"gateLine");function Ue(t,n,i,a=""){let r=Q(n),s=[];for(let u of t){let C=n[u]??{},p;r.includes(u)?p="any code edit":p=(C.applies_to||[]).map(w=>`\`${w}\``).join(", ")||"\u2014",s.push(`| ${u} | \`w9r-${u}-standard\` | ${p} |`)}let g=i.length>0?i.join(", "):"none discovered",y=N(U(),"","tree"),f=y?`
8
+ > Module source: ${y}`:"",R=["`ponytail`",...r.map(u=>`\`w9r-${u}-standard\``)].join(" + "),d=ee(a),v={research:"| research / planning | `w9r-research` | nothing \u2014 spawns the read-only `w9r-researcher` agent |",implement:`| implementing (before the first code edit) | \`w9r-implement\` | universal base (${R}) + rows matching the files you edit |`,test:"| testing | `w9r-test` | nothing \u2014 spawns the matching `w9r-tester-<archetype>` agent(s) |",review:"| review (before reading any diff or PR) | `w9r-review` | the standards covering files in the diff |",pr:"| PR / finishing | `w9r-pr` | `.werkmeister/pr-rules.md` \u2014 PRs open only via `werkmeister pr open` |"},k=d===Z?"":`**Work type:** ${a.trim().toLowerCase()} (${d.path} path) \u2014 phases: ${d.phases.join(" \u2192 ")}.
9
+ ${be(d)}
10
+
11
+ `;return`## Standards routing
12
+
13
+ > Compiled from services.yaml + .werkmeister/workspace.yml (\`standards_override\`) \u2014 regenerated by \`werkmeister workspace init\`. Do not hand-edit.${f}
14
+
15
+ **Active in this workspace** (repos: ${g}):
16
+
17
+ | Standard | Skill | Loads on |
18
+ |----------|-------|----------|
19
+ ${s.join(`
20
+ `)}
21
+
22
+ ${k}**By phase** \u2014 invoke the entry skill before starting the phase:
23
+
24
+ | Phase | Invoke first | Loads |
25
+ |-------|--------------|-------|
26
+ ${d.phases.map(u=>v[u]).join(`
27
+ `)}
28
+
29
+ `}h(Ue,"buildStandardsRoutingSection");function Ne(t,n,i,a,r,s=null,g=null){let y=i.map(([b,I])=>`- ${b}/ \u2014 branch: ${I}`).join(`
30
+ `),f=!!(r.FEATURE??"").trim(),R=ve(i,n,f),d=R?`
31
+ ## Routing
32
+
33
+ ${R}
34
+
35
+ ## Context Budget
36
+
37
+ Load only what the routing table points to for your current task. Target: \u2264 3 context files per step unless a repo's CLAUDE.md explicitly requires more.
38
+ `:"",v=i.length,k=v>1?"This is a multi-repo workspace. Repositories:":"This is a single-repo workspace. Repository:",C=`## Notes
39
+
40
+ Working notes live in [.werkmeister/notes/](.werkmeister/notes/) \u2014 \`NNN-<type>-<slug>.md\`. Types and rules: docs/notes-conventions.md in the werkmeister repo.
41
+
42
+ Read relevant notes first; skip \`status: superseded\`. \`decision\` notes are binding and override task-level instincts \u2014 on conflict, raise it to the user rather than picking a side.
43
+ ${v>1?"\nRecord contract changes (API schema, shared types, event contracts) as `contract` notes **before** switching repos; read them when entering the receiving repo.\n":""}`,p=g?null:J(r),w=p?p[1]?`${a} \u2014 [${p[0]}](${p[1]})`:`${a} \u2014 ${p[0]}`:a,x=(r.DESCRIPTION??"").trim(),m=`## Current Task
44
+
45
+ ${w}
46
+
47
+ ${x||"<!-- Replace this comment with 1-2 sentences describing what this feature does and the user-visible outcome. -->"}
48
+ ${g?`
49
+ ${se(g)}`:""}`,$;if(s!==null)$=s;else{let b=N(U(),"","tree");$=`## Code Standards
50
+
51
+ Follow the canonical cross-repo code standards (comment rubric, per-repo quirks)`+(b?`: ${b}`:".")+`
52
+
53
+ `}return`# Workspace: ${t}
54
+
55
+ ${m}
56
+ ## Layout
57
+
58
+ ${k}
59
+
60
+ ${y}
61
+ ${d}
62
+ ${$}${C}
63
+ ## Issues
64
+
65
+ Hit a bug, or need to log a feature or task, in the \`werkmeister\` tool or a repo's code? If this workspace's changes caused a bug, fix it here; otherwise file an issue (bug | feature | task) where it belongs (the werkmeister repo, or this machine's issue tracker) and report the URL. Rules, labels and templates: [.werkmeister/issues-report.md](.werkmeister/issues-report.md).
66
+ `}h(Ne,"buildClaudeMd");function Te(t,n,i,a){let r=q(n,i[n],a),s=V(i[n]);return s?`- \`${n}\`: no tests (registry: ${s})`:r?`- \`${n}\`: \`${X(t,n,r)}\``:`- \`${n}\`: no test command registered (add \`test:\` to its registry entry)`}h(Te,"testCommandLine");function Fe(t,n,i,a,r,s,g="",y=null,f=r,R=!1,d="",v={}){let k=[],u=new Set;try{k=te(s);for(let e of Object.values(A(s)))e.hostname&&!e.remoteUpstream&&u.add(e.hostname)}catch{k=[]}let C="answers only while a feature runs its service",p=k.length?`These hosts are routed through Caddy:
67
+
68
+ `+k.map(e=>`- \`https://${e}\`${u.has(e)?` \u2014 ${C}`:""}`).join(`
69
+ `):"No services declare a `feature_router:` block, so Caddy terminates no public hosts for this workspace.",w=[],x=[],S=new Set;try{let e=A(s),o=h(l=>l.map(c=>e[c]?.hostname).filter(c=>!!c).sort(),"hostsOf");w=o(r),x=o(f),S=new Set(f.filter(l=>e[l]?.hostname))}catch{w=[]}let m=r.length>0,$=S.size>0,b=h(e=>v[e]?.lint,"lintOf"),I=h(e=>e.test?`\`${Y(d,e.test,b(e.repo))}\``:"\u2014","testCell"),O=K(f,s,y,S),ae=[...new Set(O.map(e=>e.repo))].map(e=>{let{format:o,release_check:l,ship:c}=v[e]??{},T=[o&&`- Format: \`${o}\` \u2014 ${o.includes("{files}")?"`{files}` replaced with the files you touched":"run as written, from the repo root"}`,c==="tag"&&l&&`- Release check: \`${l}\` \u2014 the PR gate's release row; commit the release entry it looks for`].filter(Boolean);return T.length?`
70
+
71
+ Repo commands for ${e}:
72
+ ${T.join(`
73
+ `)}`:""}).join(""),ie=O.some(e=>e.test&&b(e.repo)),ce=`| Service | Repo | Path in repo | Test command | Validation |
74
+ |---------|------|--------------|--------------|------------|
75
+ `+O.map(e=>`| \`${e.service}\` | ${e.repo} | \`${e.path}\` | ${I(e)} | ${e.validate} |`).join(`
76
+ `),le=h(e=>{let o=s[e]??{};return F(o)&&o.k8s_forward_port!==null&&o.k8s_forward_port!==void 0?Number(o.k8s_forward_port):null},"k8sPort"),L=[],_=null;for(let e of[...r].sort()){let o=s[e]??{};if(!F(o))continue;let l=o.port_offset??0,c=re(n,l);_===null&&S.has(e)&&(_=c);let T=o.internal_port??3e3,$e=`${e.toUpperCase().replace(/-/g,"_")}_URL`;L.push(`| \`${e}\` | local | \`${o.path??"."}\` | \`${t}-${e}\` | ${c} | \`${$e}=http://${e}:${T}\` |`)}for(let e of Object.keys(s).sort()){if(r.includes(e)||!m&&!f.includes(e))continue;let o=s[e]??{};if(!F(o))continue;let l=`${e.toUpperCase().replace(/-/g,"_")}_URL`,c=W(e,o);if(c){L.push(`| \`${e}\` | baseline | \`${o.path??"."}\` | \u2014 | \u2014 | \`${l}=http://${c.host}:${c.port}\` |`);continue}let T=le(e);T&&L.push(`| \`${e}\` | k8s | \`${o.path??"."}\` | \u2014 | \u2014 | \`${l}=http://k8s-forwards:${T}\` |`)}let B;L.length>0?B=`| Service | Location | Path in repo | Container | Host Port | In-cluster URL (env var) |
77
+ |---------|----------|--------------|-----------|-----------|--------------------------|
78
+ `+L.join(`
79
+ `):B="_No services configured._";let D;if(r.length>0){let e=[...r].sort(),o=e.map(c=>`\`${t}-${c}\``).join(", "),l=e[0];D=`### Container Commands
80
+
81
+ Container naming pattern: \`${t}-<service>\` \u2014 ${o}
82
+
83
+ \`\`\`bash
84
+ docker logs <container> -f # follow logs
85
+ docker logs <container> --tail 50 # last 50 lines
86
+ docker exec -it <container> sh # shell in
87
+
88
+ # Or via compose (run from workspace root):
89
+ docker compose ps
90
+ docker compose logs -f ${l}
91
+ docker compose restart ${l}
92
+ \`\`\`
93
+
94
+ ### Test commands
95
+
96
+ The registry's \`test:\` for each service (or its archetype's), run in its container \u2014 the worktree is mounted at \`/app\` with its \`node_modules\`; the host checkout has none. The pre-PR gate runs these (\`werkmeister pr gate\`).
97
+
98
+ ${e.map(c=>Te(t,c,s,y??z())).join(`
99
+ `)}
100
+
101
+ `}else D="";let P,H=h(e=>u.has(e)?`# ${e} ${C}
102
+ `:"","noteFor");if(_!==null){let e=`# Direct to a local service (bypass Caddy \u2014 isolates routing vs app issues):
103
+ curl -s -o /dev/null -w "HTTP %{http_code} | Size: %{size_download}\\n" "http://localhost:${_}/"
104
+
105
+ `,o=w.length?`# Through Caddy (verifies full proxy routing):
106
+ `+w.map(c=>H(c)+`curl -sk -b "X-Feature=${t}" -o /dev/null -w "HTTP %{http_code} | Size: %{size_download}\\n" "https://${c}/"
107
+ `).join("")+`
108
+ `:"",l=`# Container status:
109
+ docker ps --format "table {{.Names}}\\t{{.Status}}\\t{{.Ports}}" | grep ${t}`;P=o+e+l}else m?P=`# Container status:
110
+ docker ps --format "table {{.Names}}\\t{{.Status}}\\t{{.Ports}}" | grep ${t}`:P=`# Through Caddy (all traffic routes to k8s):
111
+ `+x.map(e=>H(e)+`curl -sk -o /dev/null -w "HTTP %{http_code} | Size: %{size_download}\\n" "https://${e}/"
112
+ `).join("").trimEnd();let j=ye(r),he=j?`
113
+ **Feature URL:** https://${j.host}/${g.replace(/^\/+/,"")}
114
+
115
+ Set the routing cookie in the browser (DevTools console):
116
+
117
+ \`\`\`js
118
+ document.cookie = "X-Feature=${t}; domain=.${j.domain}; path=/; SameSite=Lax";
119
+ \`\`\`
120
+
121
+ or visit https://${j.host}/__werkmeister and select \`${t}\` \u2014 the selector is served on every routed host and the cookie applies to each host sharing the base domain.
122
+ `:"",M=f.filter(e=>!r.includes(e)).sort(),de=`## How to validate
123
+
124
+ How to exercise a change to each service in this workspace.${M.length?` A plain \`werkmeister feature up\` skips the on-demand ones, ${M.map(e=>`\`${e}\``).join(", ")}: start one with \`werkmeister feature up --service <name>\`.`:""}${d?` Each test command runs through \`.werkmeister/bin/with-temp-home\`, which gives it a fresh temporary HOME and deletes it on exit: never hand-roll \`HOME=\u2026\`. Start every exercise command with the script itself, never with env assignments or a \`cd\`, so one permission rule matches it: \`${d} <test command>\`. A command that needs an env var takes it after the script (\`${d} env WERKMEISTER_ROOT=\u2026 <cmd>\`); no rule pre-approves that form, so it asks. Put \`--no-wait\` first (\`${d} --no-wait <cmd>\`) to skip its host-load wait; the allow rules below cover that form too. That wait lasts up to 90 s; if load is still over then, the script exits 75 without running the command (retry later). It prints only on stderr, so a foreground call shows nothing until it ends and its only child is \`werkmeister internal wait-load\`: that is the wait, not a hang. The allow rule that covers them is \`Bash(${d} <test command>:*)\` for each test command below: run those for a test without a prompt. A test command of more than one command (an \`&&\` chain, a \`{ \u2026; }\` group, \`||\`, \`;\` or a pipe) is shown as \`${d} sh -c '\u2026'\`, so every part runs under the temp HOME, and its rule allows that exact line: run it as shown, with no extra arguments. Neither \`node --test\` through the script nor the script alone is allowed, since both run any file (SW-510). The temp HOME only keeps a run from writing to the real one by accident; it is not an isolation boundary. A pre-approved test command or built CLI still runs whatever the worktree holds, a test written in this run included, and that code can reach absolute paths, the caller's env, the network, docker and gh (SW-522).`:""}${ie?" A test command ending in `&& <lint>` also runs the repo's lint, the same command the PR gate's lint row runs, so a format error fails here and not first at `werkmeister pr open`.":""}
125
+
126
+ ${ce}${ae}
127
+
128
+ `,ue=m?`## Slot & Port Range
129
+
130
+ - **Slot:** ${n}
131
+ - **Port range:** ${i}\u2013${a}
132
+
133
+ `:"",pe=m?`## Container Lifecycle
134
+
135
+ Run from anywhere in the workspace \u2014 \`werkmeister\` reads \`FEATURE\` from \`.env\` at the workspace root.
136
+
137
+ \`\`\`bash
138
+ werkmeister feature up # start containers + configure Caddy proxy
139
+ werkmeister feature stop # stop (slot preserved, fast resume)
140
+ werkmeister feature restart # restart all containers
141
+ werkmeister feature down # tear down + release slot
142
+ werkmeister feature down -v # tear down + remove volumes (node_modules, caches)
143
+ \`\`\`
144
+ ${R?"\n**Auto-stop is on** (`auto_stop: true` in `.werkmeister/workspace.yml`): when a Claude session here ends and no other session is open in this workspace, a SessionEnd hook runs `werkmeister internal session-end`, which stops this feature's containers (slot and volumes kept \u2014 `werkmeister feature up` resumes). Shared infra is never stopped.\n":""}
145
+ > **Fallback:** If \`werkmeister\` CLI is unavailable, \`docker compose up -d --build\` / \`docker compose down\` from the workspace root works equivalently. Prefer \`werkmeister\` \u2014 it also manages slot allocation and Caddy proxy regeneration.
146
+
147
+ `:"",me=m||L.length>0?`## Services
148
+
149
+ Every container gets each service's URL injected as an env var (the last column). Local services resolve to the Docker DNS alias on the per-feature network; baseline services resolve to their \`baseline_upstream\`; k8s-forwarded services resolve via the shared \`k8s-forwards\` container.
150
+
151
+ ${B}
152
+
153
+ `:"",fe=[...w,...x].some(e=>u.has(e))?"If every host resets TLS (curl exit 35) while `w9r-caddy` is healthy, check `~/.werkmeister/infra/proxy/features.json` first: `[]` means nothing is routed and it is not an outage.\n\n":"",we=$||m?`## Quick Health Checks
154
+
155
+ ${fe}\`\`\`bash
156
+ ${P}
157
+ \`\`\`
158
+
159
+ `:"",ke=$?`## Proxy Routing
160
+
161
+ ${p}
162
+
163
+ Set \`X-Feature=${t}\` (cookie or header) to route to this workspace's local containers; otherwise traffic falls through to the k8s port-forwards.
164
+ ${he}
165
+ `:"";return`<!--
166
+ AUTO-GENERATED FILE \u2014 DO NOT EDIT BY HAND.
167
+ Source: ~/.werkmeister/services.yaml + ports.yaml
168
+ + .werkmeister/workspace.yml (feature, services, slot)
169
+ Generator: packages/werkmeister-core/src/harness/claude/claude_md.ts :: buildSandboxContextMd
170
+ Regen: werkmeister workspace init (or \`werkmeister feature up\` after slot changes)
171
+ To change ports/health endpoints/services, edit services.yaml / ports.yaml.
172
+ To change which services run locally, edit .werkmeister/workspace.yml and rerun.
173
+ -->
174
+
175
+ # Werkmeister Context: ${t}
176
+
177
+ ${de}${ue}${pe}${me}${D}${we}${ke}${$||m?`## Troubleshooting
178
+
179
+ ${$?"### Feature missing from `/__werkmeister` selector\n\nThe dropdown is populated from `~/.werkmeister/infra/proxy/features.json` (a static file served by Caddy), which is regenerated alongside the Caddyfile. It can drift from the live container labels (`com.werkmeister.feature` \u2014 the source of truth) if a slot is allocated without a proxy regen.\n\nDiagnose \u2014 compare what's labeled vs. what the UI shows:\n```bash\ndocker ps -a --filter label=com.werkmeister.feature --format '{{ .Label \"com.werkmeister.feature\" }}' | sort -u\njq '[.[].name]' \"$HOME/.werkmeister/infra/proxy/features.json\"\n```\n\nResync:\n```bash\nwerkmeister infra proxy-reload # regenerates Caddyfile + features.json, reloads Caddy\n```\n\n### Caddy returns `content-length: 0` but direct service hit works\n\nCaddy routing issue, not an app issue. Try `werkmeister infra proxy-reload` first; if Caddy is still misrouting, check `docker logs w9r-caddy --tail 50`.\n\n":""}${m?"### Containers expected per the table above are missing from `docker ps`\n\n`werkmeister feature up` may have partially failed. Re-run from the workspace root:\n```bash\nwerkmeister feature up # idempotent \u2014 starts missing containers\ndocker compose logs -f # watch startup if something crashes\n```\n":""}`:""}`}h(Fe,"buildSandboxContextMd");export{se as a,Ue as b,Ne as c,Fe as d};
180
+ //# sourceMappingURL=chunk-CVIURF6M.js.map
@@ -0,0 +1,4 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{c as i,d as n,f as s}from"./chunk-QEYZ7HOT.js";import{a as o,f as t}from"./chunk-K6GRVJQO.js";t();import*as c from"node:fs";function a(){if(process.stdin.isTTY)return"";try{return c.readFileSync(0,"utf8")}catch{return""}}o(a,"readStdinTask");async function d(e){try{await s(e,void 0,{readStdinTask:a,build:e.build!==!1})}catch(r){throw r instanceof n&&(console.log(r.message),process.exit(1)),r instanceof i&&process.exit(1),r}}o(d,"run");export{a,d as b};
4
+ //# sourceMappingURL=chunk-CVK35MQA.js.map
@@ -0,0 +1,146 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{h as Ze}from"./chunk-7YUHPLUW.js";import{b as ne}from"./chunk-22YIK2BP.js";import{h as te}from"./chunk-ZQOM25KE.js";import{c as Xe,e as Ye,f as Ve,g as Qe,i as ze}from"./chunk-S62C4SVE.js";import{C as oe,D as se,F as et,G as re,Z as tt,b as T,c as F,ca as ie,d as We,e as Je,f as Ke,g as qe,i as I}from"./chunk-RJQTC65O.js";import{a as Re,b as U,e as Ue,h as Fe,j as Le,k as g}from"./chunk-H3J3PJGY.js";import{c as Ge,e as He}from"./chunk-USRMIMWS.js";import{b as R,c as je}from"./chunk-47HAXWC4.js";import{b as Be,c as k}from"./chunk-WITTY5DQ.js";import{G as Ie,M as Pe,R as De,S as Me,j as be,k as Ne,l as C,t as $e}from"./chunk-OC7PYYEG.js";import{b as Te}from"./chunk-RO5NEK3B.js";import{a as r,f as u}from"./chunk-K6GRVJQO.js";u();import*as m from"node:fs";import*as f from"node:path";u();var Jt=["mcp__plugin_werkmeister_werkmeister__"],ae=r(e=>Jt.map(t=>`${t}${e}`),"pluginTool"),Gt=["werkmeister","w9r"],A=r(e=>Gt.map(t=>`Bash(${t} ${e})`),"cli"),L=["Bash(git -c:*)","Bash(git config:*)",...["--config","--exec-path","--template"].flatMap(e=>[`Bash(git ${e}*)`,`Bash(git * ${e}*)`]),"Bash(git --git-dir*)","Bash(node:*)","Bash(python3:*)",...["proxy-reload","down","remove","remove-workspace","clean","setup","registry","connect","intercept","notes graduate","up infra","restart infra","stop infra","infra proxy-reload","feature down","infra down","feature drop","machine clean","machine setup","infra connect","infra intercept","workspace new","ws new","infra up","infra restart","infra stop","daemon install","daemon uninstall","daemon restart"].flatMap(e=>A(`${e}:*`)),...["stop","kill","rm","rmi","compose down","system prune","volume rm","network rm"].map(e=>`Bash(docker ${e}:*)`),...["npm","pnpm"].flatMap(e=>["publish","link","unlink","install -g","install --global","i -g","i --global","uninstall -g","uninstall --global"].map(t=>`Bash(${e} ${t}:*)`)),...["add -g","add --global","remove -g","remove --global"].map(e=>`Bash(pnpm ${e}:*)`),"Bash(gh pr merge:*)",...["kube-switch","up","stop","restart","down","create-workspace","create-workspace-form","pr-approve","ask-pr-review","claude-send","claude-resume","connect","proxy-reload","remove-service","intercept"].flatMap(ae)];u();import*as O from"node:fs";import*as J from"node:path";u();var W={id:"mcp",instructionsFile:"AGENTS.md",skillsDir:".agents/skills",hooks:{available:!1,reason:"a generic MCP harness has no hooks adapter; use harness: codex for Codex"},agents:!1,notice:r(()=>`
4
+ ## Harness
5
+
6
+ This workspace was generated for the \`mcp\` harness. Werkmeister's tools come from the MCP server \`werkmeister\` at ${je()}/mcp (how to register it: docs/harnesses.md in the werkmeister repo). Hooks are unavailable on this harness: werkmeister's session-start context, standards gate, PR guard and agent state do not run here (Codex: use \`harness: codex\`). Open PRs only with \`werkmeister pr open\`.
7
+ `,"notice")};var le=".codex/hooks.json",ce=".codex/config.toml",P="WERKMEISTER_MCP_TOKEN=$(cat .werkmeister/token) codex",nt="# Generated by werkmeister (harness: codex). Do not hand-edit; rerun `werkmeister workspace init`.",ot={...W,id:"codex",hooks:{available:!0},notice:r(()=>`
8
+ ## Harness
9
+
10
+ This workspace was generated for the \`codex\` harness. Werkmeister's tools come from the MCP server \`werkmeister\` registered in \`${ce}\`, and its session-start context, standards gate, PR guard and agent state run as Codex hooks from \`${le}\`. Codex loads both only once this folder is trusted and \`/hooks\` has approved each hook (docs/harnesses.md in the werkmeister repo). Start Codex as \`${P}\`, so the server sees this workspace's token. Open PRs only with \`werkmeister pr open\`.
11
+ `,"notice")};function Ht(){return[nt,"[mcp_servers.werkmeister]",`url = "http://127.0.0.1:${R()}/mcp"`,"# The daemon refuses a call without a token; the workspace token scopes the pre-approved tools to this workspace.",'bearer_token_env_var = "WERKMEISTER_MCP_TOKEN"',"# codex exec refuses non-read-only MCP tools unless pre-approved; the 300 s default cut off a first `up` (SW-188).",'default_tools_approval_mode = "approve"',"tool_timeout_sec = 1800",""].join(`
12
+ `)}r(Ht,"codexConfigToml");function st(e){let t=J.join(e,ce);return O.existsSync(t)&&O.readFileSync(t,"utf8").split(`
13
+ `,1)[0]!==nt?(C(`${ce} was not written by werkmeister; left as is (add [mcp_servers.werkmeister], docs/harnesses.md)`),t):(O.mkdirSync(J.dirname(t),{recursive:!0}),O.writeFileSync(t,Ht()),t)}r(st,"writeCodexConfig");u();u();u();import{execFile as Kt}from"node:child_process";import G from"node:fs/promises";import ue from"node:os";import H from"node:path";import{promisify as qt}from"node:util";var Xt=qt(Kt);async function pe(){if($e())return Fe();let e=[process.env.CODEX_BIN,H.join(ue.homedir(),".local","bin","codex"),"/opt/homebrew/bin/codex","/usr/local/bin/codex"].filter(t=>!!t);for(let t of e)if(await U(t))return t;return"codex"}r(pe,"resolveCodexBin");var Yt={type:"object",properties:{result:{type:"string"}},required:["result"],additionalProperties:!1};async function rt(e,t){let n=await pe(),o=await G.mkdtemp(H.join(ue.tmpdir(),"werkmeister-codex-ask-")),s=H.join(o,"schema.json"),a=H.join(o,"out.json");try{await G.writeFile(s,JSON.stringify(Yt));let i=Xt(n,["exec","--skip-git-repo-check","--ephemeral","-C",ue.homedir(),"--output-schema",s,"-o",a,"-s","read-only","--",e],{env:Ue(),timeout:12e4,maxBuffer:16*1024*1024});i.child.stdin?.end(),await i;let c;try{c=JSON.parse(await G.readFile(a,"utf-8"))}catch{throw new k("Codex returned no text.")}return String(c.result??"")}catch(i){if(i instanceof k)throw i;let c=i;if(c.code==="ENOENT")throw new k("Could not find the `codex` CLI. Set CODEX_BIN to its path, or install Codex.");if(c.killed||c.signal==="SIGTERM")throw new k("The `codex` CLI timed out after 120s.");let l=Re(String(c.stderr??"")).trim().split(`
14
+ `).slice(-2).join(" ");throw new k(`codex exec failed${l?`: ${l}`:""}`)}finally{await G.rm(o,{recursive:!0,force:!0})}}r(rt,"runExec");async function de(e,t={}){let n=We(await rt(e,t));if(!n)throw new k("Codex returned no text.");return n}r(de,"askCodexStrict");function it(e,t={}){return de(e,t).catch(()=>null)}r(it,"askCodex");async function at(e,t={}){try{let n=Je(await rt(e,t)),o=n?JSON.parse(n):null;return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}r(at,"askCodexJson");function ct(e,t,n){return`cd ${g(e)} && codex exec --skip-git-repo-check -s read-only -- "$(cat ${g(t)})"$'\\n\\n'${g(n)}`}r(ct,"codexReconcileCommand");u();u();import{createReadStream as Vt}from"node:fs";import D from"node:fs/promises";import Qt from"node:os";import b from"node:path";import zt from"node:readline";function Zt(){return b.join(process.env.CODEX_HOME||b.join(Qt.homedir(),".codex"),"sessions")}r(Zt,"codexSessionsRoot");var me=new Map;async function en(e){if(me.has(e))return me.get(e)??null;let t=null,n=zt.createInterface({input:Vt(e,"utf-8"),crlfDelay:1/0});try{for await(let o of n){let s=JSON.parse(o)?.payload;typeof s?.id=="string"&&typeof s?.cwd=="string"&&(t={id:s.id,cwd:s.cwd});break}}catch{}finally{n.close()}return t&&me.set(e,t),t}r(en,"readMeta");async function N(e){let t=Zt(),n;try{n=await D.readdir(t,{recursive:!0})}catch{return[]}let o=[...new Set([e,await D.realpath(e).catch(()=>e)])],s=r(i=>o.some(c=>i===c||i.startsWith(c+b.sep)),"owns"),a=[];for(let i of n){if(!b.basename(i).startsWith("rollout-")||!i.endsWith(".jsonl"))continue;let c=b.join(t,i),l=await en(c);if(!(!l||!s(l.cwd)))try{a.push({file:c,id:l.id,cwd:l.cwd,mtime:(await D.stat(c)).mtime})}catch{}}return a.sort((i,c)=>c.mtime.getTime()-i.mtime.getTime())}r(N,"codexSessionsIn");function ut(e,t){return t&&e.find(n=>n.id===t)||e[0]||null}r(ut,"pick");var tn=/^(# AGENTS\.md instructions for|<environment_context>|<user_instructions>)/;function lt(e,t){return Array.isArray(e)?e.filter(n=>n?.type===t&&typeof n.text=="string").map(n=>n.text).join(`
15
+ `).trim():""}r(lt,"textOf");var nn=r(e=>String(e??"").trim().split(`
16
+ `)[0].slice(0,120),"firstLine");function $(e){let t=[];for(let n of e.split(`
17
+ `)){if(!n.trim())continue;let o;try{o=JSON.parse(n)}catch{continue}let s=o.payload;if(o.type!=="response_item"||!s)continue;let a=typeof o.timestamp=="string"?o.timestamp:null;if(s.type==="message"&&s.role==="user"){let i=lt(s.content,"input_text");i&&!tn.test(i)&&t.push({role:"user",text:i,timestamp:a})}else if(s.type==="message"&&s.role==="assistant"){let i=lt(s.content,"output_text");i&&t.push({role:"assistant",text:i,timestamp:a})}else if(s.type==="function_call"||s.type==="custom_tool_call"){let i=nn(s.type==="function_call"?s.arguments:s.input);t.push({role:"tool",text:i?`${s.name}: ${i}`:String(s.name),timestamp:a})}}return t}r($,"parseCodexLines");async function pt(e,t){return(await N(e)).find(n=>n.id===t)?.cwd??null}r(pt,"codexSessionStartDir");async function dt(e,t){let n=await N(e),o=ut(n,t);return{workspacePath:e,projectDir:o?b.dirname(o.file):null,sessionFile:o?.file??null,sessionId:o?.id??null,sessionCount:n.length,updatedAt:o?.mtime.toISOString()??null}}r(dt,"codexSessionSourceIn");async function mt(e,t=20,n){let o=await N(e),s=ut(o,n);if(!s)return{sessionId:null,workspacePath:e,messages:[],sessionCount:0,updatedAt:null};let a;try{a=await D.readFile(s.file,"utf-8")}catch(i){throw new k(`Could not read session file: ${i.message}`)}return{sessionId:s.id,workspacePath:e,messages:Ke($(a),t),sessionCount:o.length,updatedAt:s.mtime.toISOString()}}r(mt,"codexTranscriptIn");async function fe(e,t){let n=await D.readFile(e,"utf-8").catch(()=>""),o=$(n).find(s=>s.role==="user");return o?o.text.replace(/\s+/g," ").slice(0,80):t.slice(0,8)}r(fe,"codexSessionTitle");async function ft(e){let t=await N(e);return Promise.all(t.map(async(n,o)=>({sessionId:n.id,title:await fe(n.file,n.id),updatedAt:n.mtime.toISOString(),isNewest:o===0})))}r(ft,"codexListSessionsIn");function on(e,t,n,o=!1){return["exec",...t?["resume",t]:[],"--skip-git-repo-check",...o?["--json"]:[],...n?["-m",n]:[],"-c",'sandbox_mode="workspace-write"',"--",e]}r(on,"codexSendArgs");async function ht(e,t,n,o,s,a={}){let i=on(n,o,s,!!a.wait);return await F(e,await pe(),i,t,!!a.wait)===null?null:{denied:[]}}r(ht,"codexStartTurn");function xt(e,t,n){return qe(e,t,n,$)}r(xt,"codexSignal");function wt(e,t,n){return[P,...e?["resume"]:[],...t?["-m",g(t)]:[],...e?[g(e)]:[],...n?[g(n)]:[]].join(" ")}r(wt,"codexResumeCommand");u();import sn from"node:fs/promises";function rn(e){let t=null,n="unknown",o=null,s=null,a=0;for(let c of e.split(`
18
+ `)){if(!c.trim())continue;let l;try{l=JSON.parse(c)}catch{continue}typeof l.timestamp=="string"&&((!o||l.timestamp<o)&&(o=l.timestamp),(!s||l.timestamp>s)&&(s=l.timestamp));let d=l.payload;l.type==="turn_context"&&typeof d?.model=="string"&&(n=d.model),l.type==="event_msg"&&d?.type==="token_count"&&d.info?.total_token_usage&&(t=d.info.total_token_usage,a++)}let i=new Map;if(t){let c=t.cached_input_tokens??0;i.set(n,{input:(t.input_tokens??0)-c,output:t.output_tokens??0,cacheCreation:t.cache_write_input_tokens??0,cacheRead:c})}return{byModel:i,firstTurn:o,lastTurn:s,turns:a,models:[...i.keys()]}}r(rn,"reduceCodexSession");async function yt(e,t){let n=[];for(let o of await N(t)){let s=await sn.readFile(o.file,"utf-8").catch(()=>null);s!==null&&n.push({sessionId:o.id,title:await fe(o.file,o.id),updatedAt:o.mtime.toISOString(),reduction:rn(s)})}return tt(e,n)}r(yt,"codexUsageForDir");var gt={id:"codex",ask:it,askJson:at,askOrThrow:de,sendTurn:ht,turnStatus:T,transcript:mt,sessionSource:dt,sessionStartDir:pt,listSessions:ft,parseSession:$,agentSignal:xt,usage:yt,resumeCommand:wt,reconcileCommand:ct};u();u();import an from"node:os";import cn from"node:path";async function he(){let e=[process.env.OPENCODE_BIN,cn.join(an.homedir(),".opencode","bin","opencode"),"/opt/homebrew/bin/opencode","/usr/local/bin/opencode"].filter(t=>!!t);for(let t of e)if(await U(t))return t;return"opencode"}r(he,"resolveOpencodeBin");var St=r(e=>e?.includes("/")?["--model",e]:[],"modelArgs");function ln(e,t,n,o={}){return["run","--format","json",...St(n),...t?["--session",t]:[],...o.unattended?["--auto"]:[],e]}r(ln,"opencodeSendArgs");async function kt(e,t,n,o,s,a={}){let i=ln(n,o,s,{unattended:!!a.unattended});return await F(e,await he(),i,t,!!a.wait)===null?null:{denied:[]}}r(kt,"startTurn");async function _t(e,t,n){let o=n?.updatedAt??null,s=T(e).state,a=r((c,l=o,d=null)=>({signal:{state:s,agent:c,at:l,question:d},lastActivity:o}),"signal");if(s==="running")return a("working");let i=He(Ge(t));return(s==="done"||s==="failed")&&i?.agent==="working"?a(s==="done"?"done":"idle",i.at):i?a(i.agent,i.at,i.question):a("idle")}r(_t,"sessionSignal");function Et(e,t,n){return["opencode",...St(t).map(g),...e?["--session",g(e)]:[],...n?["--prompt",g(n)]:[]].join(" ")}r(Et,"opencodeResumeCommand");u();import At from"node:fs/promises";var xe=r(e=>typeof e=="number"?new Date(e).toISOString():null,"iso");async function vt(e,t){let{stdout:n,code:o}=await Le(await he(),e,t);if(o!==0)throw new Error(`opencode ${e[0]} exited ${o}`);return JSON.parse(n)}r(vt,"opencodeJson");async function we(e){let t=await At.realpath(e).catch(()=>e),n;try{n=await vt(["session","list","--format","json"],e)}catch{return[]}return Array.isArray(n)?(await Promise.all(n.map(async s=>{let a=typeof s?.directory=="string"?s.directory:"";return a&&(a===e||await At.realpath(a).catch(()=>a)===t)?s:null}))).filter(s=>s&&typeof s.id=="string").map(s=>({sessionId:s.id,title:String(s.title??""),updatedAt:xe(s.updated)??xe(s.created)??""})).sort((s,a)=>a.updatedAt.localeCompare(s.updatedAt)):[]}r(we,"sessionsIn");async function ye(e){return(await we(e)).map((t,n)=>({...t,isNewest:n===0}))}r(ye,"listSessionsIn");async function ge(e,t){let n=await we(e),o=t?n.find(s=>s.sessionId===t):n[0];return{workspacePath:e,projectDir:null,sessionFile:null,sessionId:o?.sessionId??t??null,sessionCount:n.length,updatedAt:o?.updatedAt??null}}r(ge,"sessionSourceIn");function un(e){let t=e?.state?.input??{},n=String(t.command??t.path??t.filePath??"").split(`
19
+ `)[0],o=String(e?.name??"tool");return n?`${o}: ${n.slice(0,120)}`:o}r(un,"toolRow");function pn(e){let t=e?.type;if(t!=="user"&&t!=="assistant")return[];let n=xe(e.time?.created),o=Array.isArray(e.content)?e.content:[],s=(t==="user"?String(e.text??""):o.filter(i=>i?.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
20
+ `)).trim(),a=s?[{role:t,text:s,timestamp:n}]:[];for(let i of o)i?.type==="tool"&&a.push({role:"tool",text:un(i),timestamp:n});return a}r(pn,"messageRows");async function Ct(e,t=20,n){let o=await ge(e,n),s=[];if(o.sessionId)try{s=((await vt(["session","export",o.sessionId],e))?.messages??[]).flatMap(pn).slice(-t)}catch{}return{sessionId:o.sessionId,workspacePath:e,messages:s,sessionCount:o.sessionCount,updatedAt:o.updatedAt}}r(Ct,"transcriptIn");var Ot={input:0,output:0,cacheCreation:0,cacheRead:0};async function Tt(e,t){let n=(await we(t)).map(o=>({...o,firstTurn:null,lastTurn:null,turns:0,models:[],totals:{...Ot},estUsd:null}));return{name:e,totals:{...Ot},estUsd:null,byModel:[],sessions:n}}r(Tt,"usageForDir");var bt=r(e=>{throw new k(`${e} is not supported on the opencode harness.`)},"unsupported"),Nt={id:"opencode",ask:r(async()=>null,"ask"),askJson:r(async()=>null,"askJson"),askOrThrow:r(async()=>bt("A headless question"),"askOrThrow"),sendTurn:kt,turnStatus:T,transcript:Ct,sessionSource:r((e,t)=>ge(e,t),"sessionSource"),sessionStartDir:r(async(e,t)=>(await ye(e)).some(n=>n.sessionId===t)?e:null,"sessionStartDir"),listSessions:ye,parseSession:r(()=>[],"parseSession"),agentSignal:_t,usage:Tt,resumeCommand:Et,reconcileCommand:r(()=>bt("PR reconcile"),"reconcileCommand")};u();u();import M from"node:fs";import Se from"node:path";var dn=".opencode/plugins/werkmeister.js",mn=`// Managed by werkmeister (SW-385): rewritten by workspace init and feature up; edits are lost.
21
+ import { spawn } from "node:child_process";
22
+
23
+ const EDIT_TOOLS = new Set(["edit", "write", "patch", "apply_patch", "multiedit"]);
24
+
25
+ function run(cmd, payload) {
26
+ return new Promise((resolve) => {
27
+ let out = "";
28
+ let child;
29
+ try {
30
+ child = spawn("werkmeister", ["internal", cmd], { stdio: ["pipe", "pipe", "ignore"] });
31
+ } catch {
32
+ return resolve("");
33
+ }
34
+ child.on("error", () => resolve(""));
35
+ child.stdout.on("data", (d) => (out += d));
36
+ child.on("close", () => resolve(out));
37
+ child.stdin.on("error", () => {});
38
+ child.stdin.end(JSON.stringify(payload));
39
+ });
40
+ }
41
+
42
+ // A PreToolUse deny, or a UserPromptSubmit block (a paused or queued workspace).
43
+ function denial(stdout) {
44
+ for (const line of stdout.split("\\n")) {
45
+ try {
46
+ const o = JSON.parse(line);
47
+ const h = o && o.hookSpecificOutput;
48
+ if (h && h.permissionDecision === "deny") return h.permissionDecisionReason || "Blocked by werkmeister.";
49
+ if (o && o.decision === "block") return o.reason || "Blocked by werkmeister.";
50
+ } catch {}
51
+ }
52
+ return null;
53
+ }
54
+
55
+ async function prompt(cwd, sessionId) {
56
+ const reason = denial(await run("agent-state", { hook_event_name: "UserPromptSubmit", session_id: sessionId, cwd }));
57
+ if (reason) throw new Error(reason);
58
+ }
59
+
60
+ async function before(cwd, sessionId, tool, args) {
61
+ args = args || {};
62
+ const base = { hook_event_name: "PreToolUse", session_id: sessionId, cwd };
63
+ const checks = [];
64
+ if ((tool === "apply_patch" || tool === "patch") && typeof args.patchText === "string") {
65
+ // The gate reads each path out of the patch, as it does for Codex.
66
+ const named = { ...base, tool_name: "apply_patch", tool_input: { command: args.patchText } };
67
+ checks.push(["gate", named], ["agent-state", named]);
68
+ } else if (EDIT_TOOLS.has(tool)) {
69
+ const input = { ...args, file_path: args.filePath || args.file_path || args.path };
70
+ const named = { ...base, tool_name: tool === "write" ? "Write" : "Edit", tool_input: input };
71
+ checks.push(["gate", named], ["agent-state", named]);
72
+ } else if (tool === "shell" || tool === "bash") {
73
+ const named = { ...base, tool_name: "Bash", tool_input: { command: String(args.command || "") } };
74
+ checks.push(["pr-guard", named], ["agent-state", named]);
75
+ } else {
76
+ const named = { ...base, tool_name: tool, tool_input: args };
77
+ if (tool.endsWith("create_pull_request")) checks.push(["pr-guard", named]);
78
+ checks.push(["agent-state", named]);
79
+ }
80
+ for (const [cmd, payload] of checks) {
81
+ const reason = denial(await run(cmd, payload));
82
+ if (reason) throw new Error(reason);
83
+ }
84
+ }
85
+
86
+ const state = (cwd, sessionId, event, extra) =>
87
+ run("agent-state", { hook_event_name: event, session_id: sessionId, cwd, ...extra });
88
+
89
+ // 2.2.5 events (V2): a turn runs from session.execution.started to .succeeded (.failed by
90
+ // analogy with session.tool.failed, not yet seen).
91
+ // The others are V1's names; 2.2.5 sends no session-created or session-ended event.
92
+ function onEvent(cwd, ev) {
93
+ const p = (ev && (ev.properties || ev.data)) || ev || {};
94
+ const id = p.sessionID || (p.info && p.info.id);
95
+ if (!id) return;
96
+ switch (ev.type) {
97
+ case "session.execution.succeeded":
98
+ case "session.execution.failed":
99
+ return state(cwd, id, "Stop");
100
+ case "session.created":
101
+ return state(cwd, id, "SessionStart");
102
+ case "session.idle":
103
+ return state(cwd, id, "Stop");
104
+ case "session.status":
105
+ return p.status && p.status.type === "idle" ? state(cwd, id, "Stop") : undefined;
106
+ case "permission.asked":
107
+ case "permission.updated":
108
+ return state(cwd, id, "Notification", {
109
+ notification_type: "permission_prompt",
110
+ message: String(p.title || p.permission || "Permission needed"),
111
+ });
112
+ case "session.deleted":
113
+ return state(cwd, id, "SessionEnd");
114
+ }
115
+ }
116
+
117
+ export default {
118
+ id: "werkmeister",
119
+ async setup(ctx) {
120
+ const cwd = ctx.location.directory;
121
+ await ctx.tool.hook("execute.before", (e) => before(cwd, e.sessionID, e.tool, e.input));
122
+ await ctx.tool.hook("execute.after", (e) => state(cwd, e.sessionID, "PostToolUse", { tool_name: e.tool }));
123
+ await ctx.session.hook("prompt", (e) => prompt(cwd, e.sessionID));
124
+ const stop = new AbortController();
125
+ (async () => {
126
+ try {
127
+ for await (const ev of ctx.event.subscribe({ signal: stop.signal })) await onEvent(cwd, ev);
128
+ } catch {}
129
+ })();
130
+ return () => stop.abort();
131
+ },
132
+ async server({ directory }) {
133
+ return {
134
+ "tool.execute.before": (input, output) => before(directory, input.sessionID, input.tool, output.args),
135
+ "tool.execute.after": (input) => state(directory, input.sessionID, "PostToolUse", { tool_name: input.tool }),
136
+ "chat.message": (input) => prompt(directory, input.sessionID),
137
+ event: ({ event }) => onEvent(directory, event),
138
+ };
139
+ },
140
+ };
141
+ `,fn=Object.fromEntries(L.flatMap(e=>{let t=/^Bash\((.+):\*\)$/.exec(e);return t?[[`${t[1]}*`,"deny"]]:[]}));function $t(e){let t=Se.join(e,dn);M.mkdirSync(Se.dirname(t),{recursive:!0}),M.writeFileSync(t,mn);let n=Se.join(e,"opencode.json"),o={$schema:"https://opencode.ai/config.json"};if(M.existsSync(n))try{if(o=JSON.parse(M.readFileSync(n,"utf8")),!o||typeof o!="object"||Array.isArray(o))throw new Error}catch{return C("opencode.json is not plain JSON; left it as is. Add the werkmeister MCP server by hand."),t}o.mcp={...o.mcp,werkmeister:{type:"remote",url:`http://127.0.0.1:${R()}/mcp`,headers:{Authorization:"Bearer {file:.werkmeister/token}"}}};let s=o.permission?.bash;return o.permission={...o.permission,bash:{...typeof s=="string"?{"*":s}:s,...fn}},M.writeFileSync(n,`${JSON.stringify(o,null,2)}
142
+ `),t}r($t,"writeOpencodeHooks");var hn="session-start context, auto-stop",It={id:"opencode",instructionsFile:"AGENTS.md",skillsDir:".agents/skills",hooks:{available:"own",write:$t,missing:hn},agents:!1,questionTool:"question",notice:r(()=>"\n## Harness\n\nThis workspace was generated for OpenCode. Werkmeister's MCP server is registered in `opencode.json`, and `.opencode/plugins/werkmeister.js` runs the standards gate, the PR guard and agent state. Session-start context and auto-stop do not run on OpenCode: nothing injects the notes when a session starts, and quitting does not stop the containers. A `model:` in workspace.yml applies to headless turns only in OpenCode's `provider/model` form. Open PRs only with `werkmeister pr open`.\n","notice")};var xn={id:"claude",instructionsFile:"CLAUDE.md",skillsDir:".claude/skills",hooks:{available:!0},agents:!0,questionTool:"AskUserQuestion",notice:r(()=>"","notice")},wn={claude:xn,mcp:W,codex:ot,opencode:It};function Pt(e){let t=e==null?"":String(e).trim();if(!t)return I[0];if(I.includes(t))return t;throw new Be(`Unknown harness '${t}' in workspace.yml \u2014 expected one of: ${I.join(", ")}`,"UNKNOWN_HARNESS")}r(Pt,"parseHarnessId");function ke(e){return wn[Pt(re(e,"harness"))]}r(ke,"harnessLayoutFor");var yn={claude:ie,mcp:ie,codex:gt,opencode:Nt};function gn(e){try{return Pt(re(e,"harness"))}catch{return I[0]}}r(gn,"harnessIdOf");function Us(e){return yn[gn(e)]}r(Us,"harnessFor");function Fs(e){let{id:t,hooks:n}=ke(e);return n.available===!0?!0:(n.available==="own"?(Ne(`Wrote ${n.write(e)}`),C(`hooks: partial on ${t} (${n.missing} do not run)`)):C(`hooks: unavailable on ${t} (${n.reason})`),!1)}r(Fs,"hooksAvailable");var q="werkmeister notes context",X="werkmeister internal gate",Y="werkmeister internal pr-guard",K="werkmeister internal session-end",V="werkmeister internal agent-state",Sn={[X]:"werkmeister hooks gate",[Y]:"werkmeister hooks pr-guard",[K]:"werkmeister stop --if-idle",[V]:"werkmeister hooks agent-state"},kn="werkmeister skills check >/dev/null 2>&1 || werkmeister skills sync >/dev/null 2>&1",_n=`command -v werkmeister >/dev/null 2>&1 && { ${kn}; ${q}; } || true`,En=`command -v werkmeister >/dev/null 2>&1 && ${X} || true`,An=`command -v werkmeister >/dev/null 2>&1 && ${Y} || true`,On=`command -v werkmeister >/dev/null 2>&1 && ${K} >/dev/null 2>&1 || true`,vn=`command -v werkmeister >/dev/null 2>&1 && ${V} || true`,Cn=`command -v werkmeister >/dev/null 2>&1 && WERKMEISTER_HOOK_HARNESS=codex ${V} || true`,Tn=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","Notification","Stop","SessionEnd","PermissionRequest","PermissionDenied","PostToolUseFailure","SubagentStart","SubagentStop","StopFailure"],bn=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","Stop","SessionEnd"],Nn=10,$n=3,B=r(e=>ke(e).id==="codex","isCodex");function In(){return{hooks:[{type:"command",command:_n}]}}r(In,"buildSessionStartEntry");function Pn(e=!1){return{matcher:e?"apply_patch":"Edit|Write",hooks:[{type:"command",command:En}]}}r(Pn,"buildPreToolUseGateEntry");function jt(){return{matcher:"Bash|mcp__.*create_pull_request",hooks:[{type:"command",command:An}]}}r(jt,"buildPrGuardEntry");function Dn(e=!1){return{hooks:[{type:"command",command:On,timeout:e?$n:Nn}]}}r(Dn,"buildSessionEndEntry");function Mn(e=!1){return{hooks:[{type:"command",command:e?Cn:vn}]}}r(Mn,"buildAgentStateEntry");var Bn=r((e,t)=>[t,Sn[t]].some(n=>n!==void 0&&(e.includes(n)||e.includes(n.replace(/^werkmeister /,"sandbox ")))),"isManagedCommand");function Rt(e,t=q){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e.hooks;return Array.isArray(n)?n.some(o=>typeof o=="object"&&o!==null&&!Array.isArray(o)&&Bn(String(o.command??""),t)):!1}r(Rt,"_isManaged");function jn(e,t,n,o){let s=t in e?e[t]:[];if(!Array.isArray(s))return!1;let a=s.filter(i=>!Rt(i,o));return a.push(n),e[t]=a,!0}r(jn,"_mergeEvent");function Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}r(Ae,"_isDict");function j(e){return B(e)?f.join(e,le):f.join(e,".claude","settings.json")}r(j,"_settingsPath");function Oe(e){if(!m.existsSync(e))return{};try{let t=JSON.parse(m.readFileSync(e,"utf8"));return Ae(t)?t:null}catch{return null}}r(Oe,"_readSettings");function Q(e,t){if(Object.keys(t).length){m.mkdirSync(f.dirname(e),{recursive:!0}),m.writeFileSync(e,JSON.stringify(t,null,2)+`
143
+ `);return}m.rmSync(e,{force:!0});try{m.rmdirSync(f.dirname(e))}catch{}}r(Q,"_saveSettings");function z(e,t){let n=j(e),o=Oe(n);if(o===null)return n;"hooks"in o||(o.hooks={});let s=o.hooks;if(typeof s!="object"||s===null||Array.isArray(s))return n;for(let[a,i,c]of t)if(!jn(s,a,i,c))return n;return Q(n,o),n}r(z,"_writeManaged");function er(e){return z(e,[["SessionStart",In(),q],["PreToolUse",Pn(B(e)),X],["PreToolUse",jt(),Y]])}r(er,"writeWorkspaceHooks");function Dt(e){let t=B(e);return z(e,(t?bn:Tn).map(n=>[n,Mn(t),V]))}r(Dt,"writeAgentStateHooks");function tr(e){return z(e,[["PreToolUse",jt(),Y]])}r(tr,"writePrGuardHook");function nr(e){return Ut(e,[["SessionStart",q],["PreToolUse",X]])}r(nr,"removeWorkspaceHooks");function Mt(e,t){return t?z(e,[["SessionEnd",Dn(B(e)),K]]):(Ut(e,[["SessionEnd",K]]),j(e))}r(Mt,"writeAutoStopHook");function Ut(e,t){let n=j(e),o;try{o=JSON.parse(m.readFileSync(n,"utf8"))}catch{return[]}let s=o?.hooks;if(typeof s!="object"||s===null||Array.isArray(s))return[];let a=[];for(let[i,c]of t){let l=s[i];if(!Array.isArray(l))continue;let d=l.filter(h=>!Rt(h,c));for(let h of l)d.includes(h)||a.push(...h.hooks.map(p=>String(p.command)));d.length?s[i]=d:delete s[i]}return a.length?(Object.keys(s).length||delete o.hooks,Q(n,o),a):[]}r(Ut,"_removeManaged");var Rn=["Bash(git diff:*)","Bash(git status:*)","Bash(git ls-files:*)"],Bt=["Bash(git:*)",...["pr view","pr checks","pr diff","pr list","issue view","run view","run list"].map(e=>`Bash(gh ${e}:*)`),...["up","restart","feature up","feature restart"].flatMap(A),...A("feature up --service:*"),...["status","feature status","infra status","pr","issue view","issue start","init-workspace","workspace init","skills","standards","notes context"].flatMap(e=>A(`${e}:*`)),"Bash(docker ps:*)","Bash(claude plugin validate:*)","Bash(claude plugin test:*)",...["issue","issue-statuses","status","workspace-prs","kube-context","k8s-forwards-status"].flatMap(ae)];function Un(e,t){return e?[...Bt,...["up","restart","feature up","feature restart"].flatMap(n=>A(`${n} ${e}`)),...A(`feature up ${e} --service:*`),...["logs","test","services","feature logs","feature test","feature services"].flatMap(n=>A(`${n} ${e}:*`)),...t.flatMap(n=>[`Bash(docker logs ${e}-${n}:*)`,`Bash(docker restart ${e}-${n})`])]:Bt}r(Un,"autonomousRules");var Ft=r(e=>f.join(Te(e),"claude-permissions.json"),"permissionsRecord");function Fn(e,t,n,o,s="",a=[],i=[],c={}){let l=[],d=r(p=>p.split(/\s*&&\s*/).filter(Boolean),"segments");for(let p of[...t,...i]){let S=Xe(p,n[p],o);if(!S||(t.includes(p)&&(l.push(`Bash(${Ye(e,p,S)})`),Ve(S)&&l.push(...d(S).map(y=>`Bash(${y}:*)`))),!s))continue;let w=c[String(n[p]?.repo??"")]?.lint,_=Qe(s,S,w);l.push(_.startsWith(`${s} sh -c '`)?`Bash(${_})`:`Bash(${_}:*)`)}if(s)for(let p of a)l.push(`Bash(${s} ${p}:*)`);s&&a.length&&l.push(`Bash(${f.join(f.dirname(s),"with-fixture-workspace")}:*)`);let h=`Bash(${s} `;return s&&l.push(...l.filter(p=>p.startsWith(h)).map(p=>`${h}--no-wait ${p.slice(h.length)}`)),[...new Set([...l,...Rn])]}r(Fn,"buildAllowRules");function Ln(e){let t;try{t=m.readFileSync(f.join(e,".env"),"utf8")}catch{return{}}let n={};for(let o of t.split(`
144
+ `)){let s=o.indexOf("=");s>0&&(n[o.slice(0,s).trim()]=o.slice(s+1).trim())}return n}r(Ln,"_readEnv");function Wn(e,t=oe(e)){let n=Ln(e),o=n.FEATURE??"",s=(n.SERVICES??"").split(",").map(y=>y.trim()).filter(Boolean),a=ne(e),i=Lt(e),c=te(e).map(y=>f.basename(y)),l=[],d={};try{(c.length||s.length)&&(d=De(),l=ze(c,d))}catch{}let h=l.filter(y=>!s.includes(y)),p=s.length>0||h.length>0,S=Fn(p?o:"",s,p?Pe():{},p?Me():{},a,i,h,d);if(!t)return S;let w=Ie(),_=c.flatMap(y=>Ze(v=>m.existsSync(f.join(w,y,v))).map(v=>`Bash(${v})`));return[...new Set([...S,...Un(o,s),..._])]}r(Wn,"workspaceAllowRules");function Lt(e){return te(e).map(t=>f.join(t,"apps","cli","werkmeister")).filter(t=>m.existsSync(t))}r(Lt,"builtCliWrappers");function Jn(e){let t=ne(e),n=[`Bash(${t} env WERKMEISTER_ROOT=* node --test:*)`,`Bash(${t} --no-wait env WERKMEISTER_ROOT=* node --test:*)`],o=Lt(e);if(!o.length)return n;let s=f.join(f.dirname(t),"with-fixture-workspace");return[`Bash(${s} --exec-runs:*)`,`Bash(${s} --no-wait --exec-runs:*)`,...o.flatMap(a=>[`Bash(${t} ${a} internal fixture --exec-runs:*)`,`Bash(${t} --no-wait ${a} internal fixture --exec-runs:*)`]),...n]}r(Jn,"workspaceAskRules");function Gn(e,t=oe(e)){return t?L:[]}r(Gn,"workspaceDenyRules");var _e=r(e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],"_strings");function ve(e){try{let t=JSON.parse(m.readFileSync(e,"utf8"));return Ae(t)?{allow:_e(t.allow),deny:_e(t.deny),ask:_e(t.ask),model:typeof t.model=="string"?t.model:null}:{allow:[],deny:[],ask:[],model:null}}catch{return{allow:[],deny:[],ask:[],model:null}}}r(ve,"_readRecord");function Ee(e,t){let n={...t.allow.length?{allow:t.allow}:{},...t.deny.length?{deny:t.deny}:{},...t.ask.length?{ask:t.ask}:{},...t.model?{model:t.model}:{}},o=ve(e);JSON.stringify(t)!==JSON.stringify(o)&&(Object.keys(n).length?(m.mkdirSync(f.dirname(e),{recursive:!0}),m.writeFileSync(e,`${JSON.stringify(n,null,2)}
145
+ `)):m.rmSync(e,{force:!0}))}r(Ee,"_writeRecord");function Wt(e,t,n=[],o=[]){let s=j(e),a=Oe(s);if(a===null)return s;let i=a.permissions??{};if(!Ae(i))return s;let c={allow:t,deny:n,ask:o},l=["allow","deny","ask"];if(l.some(w=>!Array.isArray(i[w]??[])))return s;let d=Ft(e),h=ve(d),p={...h},S=!1;for(let w of l){let _=i[w]??[],y=new Set(h[w]),v=[...new Set(c[w])],Z=_.filter(E=>!(typeof E=="string"&&y.has(E)&&!v.includes(E))),ee=v.filter(E=>!Z.includes(E));if(p[w]=v.filter(E=>y.has(E)||ee.includes(E)),Z.length===_.length&&!ee.length)continue;S=!0;let Ce=[...Z,...ee];Ce.length?i[w]=Ce:delete i[w]}return S&&(Object.keys(i).length?a.permissions=i:delete a.permissions,Q(s,a)),Ee(d,p),s}r(Wt,"writeWorkspacePermissions");function or(e){return Wt(e,[],[],[])}r(or,"removeWorkspacePermissions");function Hn(e,t){let n=j(e),o=Oe(n);if(o===null)return n;let s=Ft(e),a=ve(s),i=o.model;return i!==void 0&&i!==a.model?(Ee(s,{...a,model:null}),n):(i!==(t??void 0)&&(t?o.model=t:delete o.model,Q(n,o)),Ee(s,{...a,model:t}),n)}r(Hn,"writeWorkspaceModel");function sr(e){if(B(e)){Mt(e,se(e)),Dt(e),st(e),be(`codex: trust this folder in Codex, approve its hooks with /hooks, and start it as \`${P}\` (docs/harnesses.md \xA7 Codex)`);return}Wt(e,Wn(e),Gn(e),Jn(e)),Hn(e,et(e)),Mt(e,se(e)),Dt(e)}r(sr,"writeWorkspaceSettings");export{L as a,P as b,Pt as c,ke as d,gn as e,Us as f,Fs as g,_n as h,En as i,An as j,On as k,vn as l,Cn as m,Tn as n,bn as o,In as p,Pn as q,jt as r,Dn as s,Mn as t,er as u,Dt as v,tr as w,nr as x,Mt as y,Rn as z,Bt as A,Un as B,Fn as C,Wn as D,Jn as E,Gn as F,Wt as G,or as H,Hn as I,sr as J};
146
+ //# sourceMappingURL=chunk-CVMWX5W5.js.map
@@ -0,0 +1,4 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{a as n,f as o}from"./chunk-K6GRVJQO.js";o();function u(t){return t.listenerCount("SIGINT")>1}n(u,"claimed");var r=new AbortController;function s(){return r.signal}n(s,"interruptSignal");function d(t=process,i=()=>{},l=e=>process.exit(e)){let e=!1;r=new AbortController,t.on("SIGINT",()=>{if(r.abort(),u(t)&&!e){e=!0;return}i(),l(130)})}n(d,"installDefaultInterrupt");export{s as a,d as b};
4
+ //# sourceMappingURL=chunk-DL73WFKY.js.map
@@ -0,0 +1,13 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{a as o,c as w,f as u}from"./chunk-K6GRVJQO.js";var $=w(s=>{"use strict";u();var y=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,c=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,E=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,v=/\\([\u000b\u0020-\u00ff])/g,h=/([\\"])/g,d=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;s.format=g;s.parse=T;function g(r){if(!r||typeof r!="object")throw new TypeError("argument obj is required");var e=r.parameters,t=r.type;if(!t||!d.test(t))throw new TypeError("invalid type");var f=t;if(e&&typeof e=="object")for(var a,p=Object.keys(e).sort(),n=0;n<p.length;n++){if(a=p[n],!E.test(a))throw new TypeError("invalid parameter name");f+="; "+a+"="+m(e[a])}return f}o(g,"format");function T(r){if(!r)throw new TypeError("argument string is required");var e=typeof r=="object"?l(r):r;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var t=e.indexOf(";"),f=t!==-1?e.slice(0,t).trim():e.trim();if(!d.test(f))throw new TypeError("invalid media type");var a=new _(f.toLowerCase());if(t!==-1){var p,n,i;for(y.lastIndex=t;n=y.exec(e);){if(n.index!==t)throw new TypeError("invalid parameter format");t+=n[0].length,p=n[1].toLowerCase(),i=n[2],i.charCodeAt(0)===34&&(i=i.slice(1,-1),i.indexOf("\\")!==-1&&(i=i.replace(v,"$1"))),a.parameters[p]=i}if(t!==e.length)throw new TypeError("invalid parameter format")}return a}o(T,"parse");function l(r){var e;if(typeof r.getHeader=="function"?e=r.getHeader("content-type"):typeof r.headers=="object"&&(e=r.headers&&r.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}o(l,"getcontenttype");function m(r){var e=String(r);if(E.test(e))return e;if(e.length>0&&!c.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(h,"\\$1")+'"'}o(m,"qstring");function _(r){this.parameters=Object.create(null),this.type=r}o(_,"ContentType")});export{$ as a};
4
+ /*! Bundled license information:
5
+
6
+ content-type/index.js:
7
+ (*!
8
+ * content-type
9
+ * Copyright(c) 2015 Douglas Christopher Wilson
10
+ * MIT Licensed
11
+ *)
12
+ */
13
+ //# sourceMappingURL=chunk-DMZPGI56.js.map
@@ -0,0 +1,6 @@
1
+ import { createRequire as __sandboxCreateRequire } from "node:module";
2
+ const require = __sandboxCreateRequire(import.meta.url);
3
+ import{c as N}from"./chunk-U4RIK7SI.js";import{a as D}from"./chunk-GUFHPPBN.js";import{j as Y,k as B,o as G,q as $,r as O}from"./chunk-USRMIMWS.js";import{d as Q,e as z,l as J}from"./chunk-47HAXWC4.js";import{n as E}from"./chunk-C4J3VWL3.js";import{b as K}from"./chunk-WITTY5DQ.js";import{a as pt,j as A,l as W,n as C,s as H,w as U}from"./chunk-OC7PYYEG.js";import{b as F}from"./chunk-RO5NEK3B.js";import{a as s,e as mt,f as h}from"./chunk-K6GRVJQO.js";h();import*as f from"node:fs";import*as V from"node:os";import*as I from"node:path";import{setTimeout as lt}from"node:timers/promises";var dt=s(()=>I.join(F(V.homedir()),"locks"),"lockDir"),ht=.1;function yt(t){let e;try{e=Number.parseInt(f.readFileSync(t,"utf8").trim(),10)}catch{return!1}if(!Number.isInteger(e)||e<=0)return!0;try{return process.kill(e,0),!1}catch(r){return r.code==="ESRCH"}}s(yt,"holderIsDead");function wt(t){try{let e=f.openSync(t,"wx");return f.writeSync(e,String(process.pid)),f.closeSync(e),!0}catch(e){if(e.code==="EEXIST"){if(yt(t))try{f.unlinkSync(t)}catch{}return!1}throw e}}s(wt,"tryAcquire");async function _(t,e,{timeout:r}={}){let o=dt();f.mkdirSync(o,{recursive:!0});let n=I.join(o,`${t}.lock`),i=r!==void 0?performance.now()+r*1e3:null;for(;!wt(n);){if(i!==null&&performance.now()>=i)throw new Error(`Timed out after ${r}s waiting for lock '${t}' (${n}). The previous holder may have crashed without releasing it; if no werkmeister process is running, it is safe to delete this file and retry.`);await lt(ht*1e3)}try{return await e()}finally{try{f.unlinkSync(n)}catch{}}}s(_,"sandboxLock");h();var St={"":1,b:1,k:1024,m:1048576,g:1073741824,t:1099511627776};function j(t){if(typeof t=="number")return t;let e=/^\s*(\d+(?:\.\d+)?)\s*([bkmgt]?)b?\s*$/i.exec(t);if(!e)throw new Error(`Not a size: '${t}'`);return Math.round(Number(e[1])*(St[e[2].toLowerCase()]??1))}s(j,"parseSize");var X=["idle","human-check","working"];function Z(t,e,r,o){if(!o.services&&e.some(a=>a.feature===o.feature))return{kind:"admit"};if(o.cost.memory>t.memory||o.cost.cpus>t.cpus)return{kind:"never-fits",cost:o.cost};let n=e.reduce((a,u)=>({memory:a.memory+u.cost.memory,cpus:a.cpus+u.cost.cpus}),{memory:0,cpus:0}),i=s(a=>n.memory-a.memory+o.cost.memory<=t.memory&&n.cpus-a.cpus+o.cost.cpus<=t.cpus,"fits"),c=r.indexOf(o.feature),m=c===-1?r.length===0:c===0;if(i({memory:0,cpus:0})&&(o.byPerson||m))return{kind:"admit"};if(t.preempt&&(o.byPerson||o.services&&m)){let u=(o.byPerson?X:X.slice(0,2)).flatMap(b=>e.filter(x=>x.rank===b&&!x.busy&&x.feature!==o.feature&&(x.cost.memory||x.cost.cpus))),l=[],S={memory:0,cpus:0};for(let b of u)if(l.push(b.feature),S.memory+=b.cost.memory,S.cpus+=b.cost.cpus,i(S))return{kind:"preempt",victims:l}}return{kind:"wait",position:c===-1?r.length+1:c+1}}s(Z,"admit");function Dt(t,e,r,o){for(let[n,i]of e)if(i===t)return n;if(o!==null&&o>=1&&o<=r&&!e.has(o))return o;for(let n=1;n<=r;n++)if(!e.has(n))return n;return null}s(Dt,"pickSlot");h();var tt=mt(pt(),1);import{createHash as bt}from"node:crypto";import*as d from"node:fs";import*as q from"node:net";import*as L from"node:os";import*as p from"node:path";import{setTimeout as xt}from"node:timers/promises";var R=30,et=s(()=>p.join(U(),"scheduler"),"stateDir"),ot=s(()=>p.join(et(),"leases.json"),"leasesPath"),rt=s(()=>p.join(et(),"queue.json"),"queuePath");function nt(t,e,r){try{let o=JSON.parse(d.readFileSync(t,"utf8"));return e(o)?o:r}catch{return r}}s(nt,"readJson");function st(t,e){d.mkdirSync(p.dirname(t),{recursive:!0}),B(t,e)}s(st,"writeJson");var y=s(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),"isDict");function gt(){let t=nt(ot(),y,{}),e={};for(let[r,o]of Object.entries(t))y(o)&&Number.isInteger(o.slot)&&(e[r]={slot:o.slot,workspace:String(o.workspace??"")});return e}s(gt,"readLeases");function Zt(t){st(ot(),t)}s(Zt,"writeLeases");function g(){return nt(rt(),t=>Array.isArray(t),[]).map(String)}s(g,"readQueue");function M(t){st(rt(),t)}s(M,"writeQueue");function qt(t){return _("scheduler",async()=>M(g().filter(e=>e!==t)),{timeout:R})}s(qt,"dequeue");function te(t,e){return _("scheduler",async()=>{let r=g().filter(o=>o!==t);$(e,{position:r.length+1,reason:"preempted"}),M([...r,t])},{timeout:R})}s(te,"enqueue");async function ee(t=()=>N().info()){let e=E().budget,r=y(e)?e:{},o={};if(r.memory===void 0||r.cpus===void 0)try{o=await t()}catch{}let n=r.memory!==void 0?j(r.memory):o.MemTotal?o.MemTotal-2**30:1/0,i=r.cpus!==void 0?Number(r.cpus):o.NCPU??1/0;return{memory:n,cpus:i,preempt:r.preempt!==!1}}s(ee,"loadBudget");function it(t){let e=E().budget,r=y(e)?Number(e.host_load??Number.NaN):Number.NaN;return Number.isFinite(r)&&r>=0?r:2*t}s(it,"hostLoadLimit");var P=15e3,w=9e4,kt=6e4,Nt=s(()=>({load:L.loadavg(),cores:L.availableParallelism()}),"readHostLoad"),ct={hostLoad:Nt,sleep:s(t=>xt(t),"sleep")},v=s(t=>Number((t/6e4).toFixed(1)),"minutes");async function _t(t=ct,e=process.platform,r="with-temp-home; --no-wait skips"){if(e==="darwin"||H("NO_WAIT"))return"";let{load:o,cores:n}=t.hostLoad(),i=it(n);if(i===0||o[0]<=i)return"";A(`waiting up to ${v(w)} min for host load ${o[0].toFixed(1)} to fall to ${i} (budget.host_load) before ${r}`);for(let c=P;c<=w;c+=P){if(await t.sleep(P),{load:o}=t.hostLoad(),o[0]<=i)return`waited ${c/1e3} s for host load`;c%kt===0&&c<w&&A(`still waiting for host load: ${o[0].toFixed(1)} over ${i}, ${c/1e3} s so far, up to ${v(w-c)} min left`)}return`ran with host load ${o[0].toFixed(1)} over ${i}; the ${v(w)} min host-load wait is spent`}s(_t,"waitForHostLoadNow");async function oe(t,e,r=ct,o=process.platform){let n=Object.entries(k(t)).filter(([u,l])=>e?e.includes(u):!l?.profiles).filter(([,u])=>u?.labels?.["com.werkmeister.role"]==="setup").map(([u])=>u);if(!n.length)return;let i=n.join(", ");if(!(await _t(r,o,`starting ${i}; WERKMEISTER_NO_WAIT=1 skips`)).startsWith("ran with"))return;let{load:m,cores:a}=r.hostLoad();throw new K(`host load ${m[0].toFixed(1)} is over ${it(a)} (budget.host_load) after the ${v(w)} min wait; ${i} not started. Retry when load falls, or set WERKMEISTER_NO_WAIT=1 to start anyway.`,"HOST_LOAD")}s(oe,"waitForSetupLoad");function k(t,e=p.join(t,D)){try{let r=tt.parse(d.readFileSync(e,"utf8"));return y(r?.services)?r.services:{}}catch{return{}}}s(k,"composeServices");function vt(t,e){let r={memory:0,cpus:0};for(let[o,n]of Object.entries(k(t))){if(!y(n)||(e?!e.includes(o):n.profiles))continue;let i=n.deploy?.resources,c=i?.reservations?.memory;c!==void 0&&(r.memory+=j(c)),r.cpus+=Number(i?.limits?.cpus??0)||0}return r}s(vt,"featureCost");var at=s(t=>{let e=t?.depends_on;return Array.isArray(e)?e.map(String):y(e)?Object.keys(e):[]},"dependsOn");function re(t,e){return[e,...at(k(t)[e])]}s(re,"serviceStarts");async function ne(t,e){let r=k(p.dirname(t),t),o=at(r[e]);if(!o.length||!o.every(n=>Lt(r[n])))return!1;for(let n of o){let i=r[n]?.container_name,c=i?await N().getContainer(String(i)).inspect().then(m=>m.State,()=>null):null;if(c?.Status!=="exited"||c.ExitCode!==0)return!1}return!0}s(ne,"setupsCurrent");function Lt(t){if(t?.labels?.["com.werkmeister.role"]!=="setup")return!1;let e=/^node:(\d+)/.exec(String(t.image??""))?.[1],r=(t.volumes??[]).map(String).find(c=>c.endsWith(":/app"));if(!e||!r)return!1;let o=r.slice(0,-5),n=Buffer.concat(["package-lock.json","pnpm-lock.yaml"].flatMap(c=>{try{return[d.readFileSync(p.join(o,c))]}catch{return[]}})),i=`${bt("sha256").update(n).digest("hex")} v${e}`;try{return d.readFileSync(p.join(o,".turbo/.werkmeister-install-hash"),"utf8").trim()===i}catch{return!1}}s(Lt,"installStamped");var At=6e4;function Et(t){let e=gt();return t.filter(r=>{let o=e[r]?.workspace;if(!o||!G(o)?.services)return!0;let n=d.statSync(Y(o),{throwIfNoEntry:!1})?.mtimeMs??0;return Date.now()-n<At?!0:(O(o),!1)})}s(Et,"withoutDeadWaiters");function se(t,e,r,o,n,i){let c=vt(e,i?.services);return!c.memory&&!c.cpus?Promise.resolve({kind:"admit"}):_("scheduler",async()=>{let m=g(),a=Et(m),u=Z(n,o,a,{feature:t,cost:c,byPerson:r,services:i?.services}),l=a;return u.kind==="wait"?($(e,{position:u.position,reason:"waiting for capacity",...i}),a.includes(t)||(l=[...a,t])):(l=a.filter(S=>S!==t),O(e)),l.join(`
4
+ `)!==m.join(`
5
+ `)&&M(l),u},{timeout:R})}s(se,"requestAdmission");function $t(t,e){let r=[];for(let[o,n]of Object.entries(k(t)))if(!(!y(n)||(e?!e.includes(o):n.profiles)))for(let i of n.ports??[]){let c=Number.parseInt(String(i).split(":").slice(-2)[0]??"",10);Number.isInteger(c)&&r.push(c)}return r}s($t,"publishedPorts");function Ot(t){return new Promise(e=>{let r=q.createServer();r.once("error",o=>e(o.code==="EADDRINUSE")),r.listen(t,"0.0.0.0",()=>r.close(()=>e(!1)))})}s(Ot,"bound");async function ie(t,e,r){let o=new Map;try{for(let i of await N().listContainers()){let c=(i.Names[0]??"").replace(/^\//,""),m=i.Labels?.["com.werkmeister.feature"]??"";for(let a of i.Ports??[])a.PublicPort&&o.set(a.PublicPort,{name:c,feature:m})}}catch{}let n=[];for(let i of $t(e,r)){let c=o.get(i);c?.feature!==t&&(c||await Ot(i))&&n.push({port:i,holder:c?.name??"a host process"})}return n}s(ie,"portHolders");h();var ft=!1,ut=!1;function le(){ft=!0}s(le,"ownScheduler");async function Tt(t,e,r,o){if(ft||!Q())return r();try{let{data:n,text:i}=await J("scheduler",{op:t,...e},{timeoutMs:o});return i&&C(i),n.value}catch(n){if(!(n instanceof z))throw n;return ut||W(`${n.message} Scheduling in this process instead.`),ut=!0,r()}}s(Tt,"schedulerOp");function de(){return Tt("queue",{},async()=>g())}s(de,"waitingQueue");export{_ as a,Dt as b,gt as c,Zt as d,g as e,qt as f,te as g,ee as h,it as i,Nt as j,_t as k,oe as l,re as m,ne as n,se as o,ie as p,le as q,Tt as r,de as s};
6
+ //# sourceMappingURL=chunk-DNDCV7NJ.js.map