@lifeaitools/rdc-skills 0.24.37 → 0.24.39

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 (191) hide show
  1. package/.claude/settings.json +15 -15
  2. package/.claude-plugin/marketplace.json +21 -21
  3. package/.claude-plugin/plugin.json +1371 -1371
  4. package/.github/workflows/publish.yml +34 -34
  5. package/.github/workflows/self-test.yml +58 -58
  6. package/CHANGELOG.md +310 -310
  7. package/LICENSE +21 -21
  8. package/MANIFEST.md +221 -221
  9. package/README.md +377 -377
  10. package/README.sandbox.md +3 -3
  11. package/assets/watcher/viewer.html +164 -164
  12. package/bin/rdc-skills-mcp.mjs +316 -316
  13. package/commands/build.md +183 -183
  14. package/commands/collab.md +180 -180
  15. package/commands/deploy.md +152 -152
  16. package/commands/design.md +31 -31
  17. package/commands/edit.md +28 -28
  18. package/commands/fixit.md +124 -124
  19. package/commands/handoff.md +173 -173
  20. package/commands/help.md +95 -95
  21. package/commands/overnight.md +220 -220
  22. package/commands/plan.md +158 -158
  23. package/commands/preplan.md +131 -131
  24. package/commands/prototype.md +145 -145
  25. package/commands/release.md +49 -49
  26. package/commands/report.md +99 -99
  27. package/commands/review.md +120 -120
  28. package/commands/self-test.md +113 -113
  29. package/commands/status.md +86 -86
  30. package/commands/watch.md +98 -98
  31. package/commands/workitems.md +137 -137
  32. package/git-sha.json +1 -1
  33. package/guides/agent-bootstrap.md +295 -295
  34. package/guides/agents/backend.md +104 -104
  35. package/guides/agents/content.md +94 -94
  36. package/guides/agents/cs2.md +56 -56
  37. package/guides/agents/data.md +87 -87
  38. package/guides/agents/design.md +77 -77
  39. package/guides/agents/frontend.md +92 -92
  40. package/guides/agents/infrastructure.md +81 -81
  41. package/guides/agents/setup.md +281 -281
  42. package/guides/agents/verify.md +151 -151
  43. package/guides/agents/viz.md +106 -106
  44. package/guides/backend.md +146 -146
  45. package/guides/content.md +147 -147
  46. package/guides/cs2.md +190 -190
  47. package/guides/data.md +123 -123
  48. package/guides/design.md +116 -116
  49. package/guides/engineering-behavior.md +43 -43
  50. package/guides/escalation-protocol.md +125 -125
  51. package/guides/frontend.md +151 -151
  52. package/guides/history-md-spec.md +297 -297
  53. package/guides/infrastructure.md +179 -179
  54. package/guides/lessons-learned-spec.md +153 -153
  55. package/guides/output-contract.md +108 -108
  56. package/guides/publish-md-spec.md +289 -289
  57. package/guides/rdc-skills-startup.md +30 -30
  58. package/guides/verify.md +11 -11
  59. package/hooks/check-cwd.js +31 -31
  60. package/hooks/check-rdc-environment.js +164 -164
  61. package/hooks/check-services.js +6 -6
  62. package/hooks/check-stale-work-items.js +19 -19
  63. package/hooks/foreground-process-gate.js +128 -128
  64. package/hooks/gate-watchdog-selfcheck.js +257 -257
  65. package/hooks/hook-logger.js +25 -25
  66. package/hooks/lib/run-evidence-gate.mjs +241 -241
  67. package/hooks/no-stop-open-epics.js +127 -127
  68. package/hooks/post-tool-batch-gate.js +203 -203
  69. package/hooks/post-work-check.js +21 -21
  70. package/hooks/postcompact-log.js +13 -13
  71. package/hooks/precompact-log.js +13 -13
  72. package/hooks/rate-limit-retry.js +46 -46
  73. package/hooks/rdc-invocation-marker.js +157 -157
  74. package/hooks/rdc-output-contract-gate.js +94 -94
  75. package/hooks/require-work-item-on-commit.js +294 -294
  76. package/hooks/restart-brief.js +19 -19
  77. package/hooks/run-hidden-hook.ps1 +47 -47
  78. package/hooks/task-completed-gate.js +274 -274
  79. package/hooks/work-item-exit-gate.js +944 -944
  80. package/lib/catalog.mjs +236 -236
  81. package/lib/cloud-rewrite.mjs +155 -155
  82. package/package.json +56 -56
  83. package/rules/work-items-rpc.md +520 -520
  84. package/scaffold/templates/HISTORY.md.template +39 -39
  85. package/scaffold/templates/PUBLISH.md.template +21 -21
  86. package/scaffold/templates/brochure-studio-default.html +70 -70
  87. package/scripts/acceptance.mjs +502 -502
  88. package/scripts/fixtures/guides/bad-guide.md +15 -15
  89. package/scripts/fixtures/guides-clean/good-guide.md +16 -16
  90. package/scripts/install-rdc-skills.js +1289 -1289
  91. package/scripts/install.ps1 +202 -202
  92. package/scripts/install.sh +132 -132
  93. package/scripts/lib/assertions.mjs +287 -287
  94. package/scripts/lib/manifest-schema.mjs +754 -754
  95. package/scripts/lib/runner.mjs +465 -465
  96. package/scripts/lib/sandbox.mjs +435 -435
  97. package/scripts/prepack.mjs +32 -32
  98. package/scripts/rdc-brochure.mjs +464 -464
  99. package/scripts/rdc-design-cli.mjs +134 -134
  100. package/scripts/rebuild-mcp.mjs +107 -107
  101. package/scripts/self-test.mjs +1460 -1460
  102. package/scripts/stamp-git-sha.mjs +29 -29
  103. package/scripts/test-guide-validator.mjs +196 -196
  104. package/scripts/test-rdc-hooks.mjs +145 -145
  105. package/scripts/uninstall.ps1 +77 -77
  106. package/scripts/uninstall.sh +69 -69
  107. package/scripts/update.ps1 +43 -43
  108. package/scripts/update.sh +43 -43
  109. package/scripts/validate-place-histories.js +461 -461
  110. package/scripts/validate-publish-manifests.js +424 -424
  111. package/scripts/watch-init.mjs +100 -100
  112. package/skills/brochure/SKILL.md +107 -107
  113. package/skills/build/SKILL.md +563 -554
  114. package/skills/channel-formatter/SKILL.md +533 -533
  115. package/skills/co-develop/SKILL.md +196 -196
  116. package/skills/collab/SKILL.md +239 -239
  117. package/skills/convert/SKILL.md +140 -140
  118. package/skills/deploy/SKILL.md +541 -541
  119. package/skills/design/SKILL.md +211 -211
  120. package/skills/design/reference/ownership.md +16 -16
  121. package/skills/design/reference/rampa.md +92 -92
  122. package/skills/design/reference/studio-model.md +153 -153
  123. package/skills/edit/SKILL.md +98 -98
  124. package/skills/fixit/SKILL.md +165 -165
  125. package/skills/fs-mcp/SKILL.md +148 -148
  126. package/skills/handoff/SKILL.md +236 -200
  127. package/skills/help/SKILL.md +143 -143
  128. package/skills/housekeeping/SKILL.md +189 -189
  129. package/skills/lifeai-brochure-author/SKILL.md +340 -340
  130. package/skills/overnight/SKILL.md +251 -251
  131. package/skills/plan/SKILL.md +345 -314
  132. package/skills/preplan/SKILL.md +90 -90
  133. package/skills/prototype/SKILL.md +150 -150
  134. package/skills/rdc-brochurify/SKILL.md +245 -245
  135. package/skills/rdc-extract-verifier-rules/SKILL.md +191 -191
  136. package/skills/release/SKILL.md +140 -140
  137. package/skills/report/SKILL.md +100 -100
  138. package/skills/review/SKILL.md +152 -152
  139. package/skills/rpms-filemap/SKILL.cloud.md +111 -111
  140. package/skills/rpms-filemap/SKILL.md +111 -111
  141. package/skills/self-test/SKILL.md +132 -132
  142. package/skills/status/SKILL.md +99 -99
  143. package/skills/terminal-config/SKILL.md +62 -62
  144. package/skills/tests/MATRIX.md +54 -54
  145. package/skills/tests/README.md +47 -47
  146. package/skills/tests/rdc-brochure.test.json +34 -34
  147. package/skills/tests/rdc-build.test.json +36 -36
  148. package/skills/tests/rdc-channel-formatter.test.json +45 -45
  149. package/skills/tests/rdc-co-develop.test.json +29 -29
  150. package/skills/tests/rdc-collab.test.json +29 -29
  151. package/skills/tests/rdc-convert.test.json +35 -35
  152. package/skills/tests/rdc-deploy.test.json +30 -30
  153. package/skills/tests/rdc-design.test.json +27 -27
  154. package/skills/tests/rdc-edit.test.json +29 -29
  155. package/skills/tests/rdc-fixit.test.json +36 -36
  156. package/skills/tests/rdc-fs-mcp.test.json +36 -36
  157. package/skills/tests/rdc-handoff.test.json +28 -28
  158. package/skills/tests/rdc-help.test.json +29 -29
  159. package/skills/tests/rdc-housekeeping.test.json +31 -31
  160. package/skills/tests/rdc-lifeai-brochure-author.test.json +35 -35
  161. package/skills/tests/rdc-overnight.test.json +37 -37
  162. package/skills/tests/rdc-plan.test.json +27 -27
  163. package/skills/tests/rdc-preplan.test.json +31 -31
  164. package/skills/tests/rdc-prototype.test.json +28 -28
  165. package/skills/tests/rdc-rdc-brochurify.test.json +23 -23
  166. package/skills/tests/rdc-rdc-extract-verifier-rules.test.json +34 -34
  167. package/skills/tests/rdc-release.test.json +29 -29
  168. package/skills/tests/rdc-report.test.json +28 -28
  169. package/skills/tests/rdc-review.test.json +29 -29
  170. package/skills/tests/rdc-rpms-filemap.test.json +28 -28
  171. package/skills/tests/rdc-self-test.test.json +24 -24
  172. package/skills/tests/rdc-status.test.json +29 -29
  173. package/skills/tests/rdc-terminal-config.test.json +29 -29
  174. package/skills/tests/rdc-watch.test.json +24 -24
  175. package/skills/tests/rdc-workitems.test.json +27 -27
  176. package/skills/watch/SKILL.md +97 -97
  177. package/skills/workitems/SKILL.md +151 -151
  178. package/tests/acceptance.test.mjs +59 -59
  179. package/tests/channel-formatter.contract.test.mjs +251 -251
  180. package/tests/curl-surface.test.mjs +289 -289
  181. package/tests/harness-gates.test.mjs +325 -325
  182. package/tests/help-surface.test.mjs +61 -61
  183. package/tests/install-rdc-skills.test.mjs +49 -49
  184. package/tests/manifest-contract-fields.test.mjs +78 -78
  185. package/tests/mcp.test.mjs +271 -271
  186. package/tests/require-work-item-on-commit.test.mjs +162 -162
  187. package/tests/run-evidence-gate.test.mjs +82 -82
  188. package/tests/skill-test-matrix.test.mjs +66 -66
  189. package/tests/validate-skills.js +27 -27
  190. package/tests/work-item-exit-gate-l2.test.mjs +368 -368
  191. package/tests/work-item-exit-gate-l3.test.mjs +197 -197
@@ -1,435 +1,435 @@
1
- // sandbox.mjs — Tier 2 sandbox lifecycle primitives
2
- //
3
- // Provides isolated execution environments for rdc:* skill tests:
4
- // 1. Git worktrees — one per skill per run, on throwaway `test/*` branches
5
- // 2. Supabase test branches — one per run, shared across skills (budget)
6
- //
7
- // Consumers: scripts/self-test.mjs --tier2 (WP5, not yet written).
8
- // This module is side-effect-free at import time. The self-test at the
9
- // bottom exercises only pure helpers — no worktrees, no HTTP calls.
10
- //
11
- // See .rdc/plans/skill-self-test-tier-2.md (D1) for topology rationale.
12
-
13
- import { execSync } from "node:child_process";
14
- import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, appendFileSync } from "node:fs";
15
- import { dirname, join, resolve } from "node:path";
16
- import { fileURLToPath } from "node:url";
17
- import { randomBytes } from "node:crypto";
18
-
19
- const __dirname = dirname(fileURLToPath(import.meta.url));
20
- const REPO_ROOT = resolve(__dirname, "..", "..");
21
- const SANDBOX_ROOT = join(REPO_ROOT, ".rdc-sandbox");
22
- const SUPABASE_PROJECT_REF = "uvojezuorjgqzmhhgluu";
23
- const MAIN_DB_PROJECT_REF = "uvojezuorjgqzmhhgluu";
24
- const MAIN_DB_API_URL = `https://${MAIN_DB_PROJECT_REF}.supabase.co`;
25
- const SUPABASE_MGMT_API = "https://api.supabase.com";
26
- const CLAUTH_URL = "http://127.0.0.1:52437";
27
- const STALE_AGE_HOURS = 1;
28
-
29
- // ---------- path helpers ----------
30
-
31
- /** Forward-slash a path. Git accepts both on Windows; this keeps errors tidy. */
32
- function fwd(p) {
33
- return p.replace(/\\/g, "/");
34
- }
35
-
36
- /** Normalize a skill name for use in a git branch. Git forbids ':'. */
37
- function normalizeSkillForBranch(skillName) {
38
- return skillName.replace(/:/g, "-");
39
- }
40
-
41
- function worktreePath(runId, skillName) {
42
- return fwd(join(SANDBOX_ROOT, runId, normalizeSkillForBranch(skillName)));
43
- }
44
-
45
- function branchName(runId, skillName) {
46
- return `test/${normalizeSkillForBranch(skillName)}-${runId}`;
47
- }
48
-
49
- // ---------- shell ----------
50
-
51
- function sh(cmd, opts = {}) {
52
- try {
53
- return execSync(cmd, {
54
- stdio: ["ignore", "pipe", "pipe"],
55
- encoding: "utf8",
56
- cwd: REPO_ROOT,
57
- ...opts,
58
- });
59
- } catch (e) {
60
- const stderr = e.stderr?.toString?.() || "";
61
- const stdout = e.stdout?.toString?.() || "";
62
- const err = new Error(
63
- `command failed (exit ${e.status}): ${cmd}\nstderr: ${stderr.trim()}\nstdout: ${stdout.trim()}`,
64
- );
65
- err.exitCode = e.status;
66
- err.stderr = stderr;
67
- err.stdout = stdout;
68
- throw err;
69
- }
70
- }
71
-
72
- // ---------- sandbox root ----------
73
-
74
- /** Create (if needed) and return the sandbox root for a given project root. Idempotent. */
75
- export function createSandboxRoot(projectRoot = REPO_ROOT) {
76
- const sandboxRoot = join(projectRoot, ".rdc-sandbox");
77
- if (!existsSync(sandboxRoot)) {
78
- mkdirSync(sandboxRoot, { recursive: true });
79
- }
80
- return sandboxRoot;
81
- }
82
-
83
- /** Generate a run id: YYYY-MM-DD + 6 hex chars. */
84
- export function generateRunId() {
85
- const d = new Date();
86
- const date = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
87
- const rand = randomBytes(3).toString("hex");
88
- return `${date}-${rand}`;
89
- }
90
-
91
- // ---------- git worktrees ----------
92
-
93
- /**
94
- * Create a new worktree on a throwaway branch inside projectRoot.
95
- *
96
- * projectRoot MUST be the repo that claude --print will commit to — so that
97
- * commitsSince() and filesModifiedSince() in runner.mjs inspect the right repo.
98
- * In practice this is the regen-root working directory (process.cwd() when
99
- * self-test runs from regen-root).
100
- *
101
- * Worktrees live at <projectRoot>/.rdc-sandbox/<runId>/<skill-slug>/.
102
- */
103
- export function createWorktree(runId, skillName, projectRoot = REPO_ROOT) {
104
- const sandboxRoot = createSandboxRoot(projectRoot);
105
- const path = fwd(join(sandboxRoot, runId, normalizeSkillForBranch(skillName)));
106
- const branch = branchName(runId, skillName);
107
- if (existsSync(path)) {
108
- throw new Error(
109
- `worktree already exists for run=${runId} skill=${skillName} at ${path} — caller must decide retry policy`,
110
- );
111
- }
112
- mkdirSync(dirname(path), { recursive: true });
113
- try {
114
- sh(`git worktree add "${path}" -b "${branch}"`, { cwd: projectRoot });
115
- } catch (e) {
116
- throw new Error(
117
- `failed to create worktree for run=${runId} skill=${skillName} in ${projectRoot}: ${e.message}`,
118
- );
119
- }
120
- return { path, branch, projectRoot };
121
- }
122
-
123
- /**
124
- * Remove a worktree and its throwaway branch.
125
- * projectRoot must match the one passed to createWorktree. Safe to call if already gone.
126
- */
127
- export function removeWorktree(runId, skillName, projectRoot = REPO_ROOT) {
128
- const sandboxRoot = join(projectRoot, ".rdc-sandbox");
129
- const path = fwd(join(sandboxRoot, runId, normalizeSkillForBranch(skillName)));
130
- const branch = branchName(runId, skillName);
131
- if (existsSync(path)) {
132
- try {
133
- sh(`git worktree remove "${path}" --force`, { cwd: projectRoot });
134
- } catch {
135
- try { sh(`git worktree prune`, { cwd: projectRoot }); } catch {}
136
- }
137
- }
138
- try {
139
- sh(`git branch -D "${branch}"`, { cwd: projectRoot });
140
- } catch {
141
- // branch may already be gone or never created
142
- }
143
- }
144
-
145
- /** Scan .rdc-sandbox/ for worktree dirs older than STALE_AGE_HOURS. */
146
- export function listStaleWorktrees() {
147
- const stale = [];
148
- if (!existsSync(SANDBOX_ROOT)) return stale;
149
- const now = Date.now();
150
- let runDirs;
151
- try {
152
- runDirs = readdirSync(SANDBOX_ROOT);
153
- } catch {
154
- return stale;
155
- }
156
- for (const runId of runDirs) {
157
- const runPath = join(SANDBOX_ROOT, runId);
158
- let st;
159
- try { st = statSync(runPath); } catch { continue; }
160
- if (!st.isDirectory()) continue;
161
- let skills;
162
- try { skills = readdirSync(runPath); } catch { continue; }
163
- for (const skill of skills) {
164
- const p = join(runPath, skill);
165
- let sst;
166
- try { sst = statSync(p); } catch { continue; }
167
- if (!sst.isDirectory()) continue;
168
- const ageHours = (now - sst.mtimeMs) / (1000 * 60 * 60);
169
- if (ageHours >= STALE_AGE_HOURS) {
170
- stale.push({
171
- path: fwd(p),
172
- branch: `test/${skill}-${runId}`,
173
- ageHours: Math.round(ageHours * 10) / 10,
174
- });
175
- }
176
- }
177
- }
178
- return stale;
179
- }
180
-
181
- /** Remove all stale worktrees. Returns count removed. Safe on-start call. */
182
- export function cleanupStaleWorktrees() {
183
- const stale = listStaleWorktrees();
184
- let removed = 0;
185
- for (const w of stale) {
186
- try {
187
- sh(`git worktree remove "${w.path}" --force`);
188
- removed++;
189
- } catch (e) {
190
- console.error(`cleanup: failed to remove ${w.path}: ${e.message}`);
191
- }
192
- try { sh(`git branch -D "${w.branch}"`); } catch {}
193
- }
194
- try { sh(`git worktree prune`); } catch {}
195
- return removed;
196
- }
197
-
198
- // ---------- Supabase test branches ----------
199
-
200
- async function getSupabaseMgmtToken() {
201
- const res = await fetch(`${CLAUTH_URL}/get/supabase-management`);
202
- if (!res.ok) {
203
- throw new Error(`clauth daemon returned ${res.status} fetching supabase-management token`);
204
- }
205
- const body = await res.text();
206
- // clauth returns raw secret or JSON {value:...}; handle both
207
- try {
208
- const j = JSON.parse(body);
209
- return j.value || j.secret || j.token || body.trim();
210
- } catch {
211
- return body.trim();
212
- }
213
- }
214
-
215
- async function sleep(ms) {
216
- return new Promise((r) => setTimeout(r, ms));
217
- }
218
-
219
- /**
220
- * Fetch the anon/publishable key for a branch's own project ref.
221
- * Uses GET /v1/projects/{ref}/api-keys?reveal=true. Returns the first key
222
- * whose name/type indicates "anon" or "publishable". Throws on HTTP error.
223
- */
224
- async function fetchBranchAnonKey(projectRef, token) {
225
- const url = `${SUPABASE_MGMT_API}/v1/projects/${projectRef}/api-keys?reveal=true`;
226
- const res = await fetch(url, {
227
- headers: {
228
- Authorization: `Bearer ${token}`,
229
- Accept: "application/json",
230
- },
231
- });
232
- if (!res.ok) {
233
- throw new Error(`HTTP ${res.status}: ${await res.text()}`);
234
- }
235
- const body = await res.json();
236
- const keys = Array.isArray(body) ? body : body?.keys || [];
237
- // Prefer anon / publishable; avoid service_role.
238
- const pick = keys.find((k) => {
239
- const name = (k?.name || k?.type || "").toLowerCase();
240
- return name === "anon" || name === "publishable" || name.includes("anon") || name.includes("publishable");
241
- });
242
- if (!pick) {
243
- throw new Error(
244
- `no anon/publishable key found; got ${keys.length} keys: ${keys
245
- .map((k) => k?.name || k?.type || "?")
246
- .join(",")}`,
247
- );
248
- }
249
- return pick.api_key || pick.key || pick.value || null;
250
- }
251
-
252
- /**
253
- * Create a Supabase test branch via Management API.
254
- * Retries 3× with exponential backoff on 5xx. Throws on auth or final failure.
255
- */
256
- export async function createSupabaseTestBranch(runId) {
257
- const token = await getSupabaseMgmtToken();
258
- const url = `${SUPABASE_MGMT_API}/v1/projects/${SUPABASE_PROJECT_REF}/branches`;
259
- const body = JSON.stringify({ branch_name: `test-${runId}` });
260
-
261
- let lastErr;
262
- for (let attempt = 1; attempt <= 3; attempt++) {
263
- let res;
264
- try {
265
- res = await fetch(url, {
266
- method: "POST",
267
- headers: {
268
- "Authorization": `Bearer ${token}`,
269
- "Content-Type": "application/json",
270
- "Accept": "application/json",
271
- },
272
- body,
273
- });
274
- } catch (e) {
275
- lastErr = e;
276
- await sleep(500 * Math.pow(2, attempt - 1));
277
- continue;
278
- }
279
- if (res.ok) {
280
- const json = await res.json();
281
- const branchId = json.id || json.branch_id;
282
- const connectionString =
283
- json.database?.connection_string || json.connection_string || "";
284
- // A branch has its own project ref (distinct from parent). Try common
285
- // field names the Management API has used across versions.
286
- const branchProjectRef =
287
- json.project_ref ||
288
- json.ref ||
289
- json.branch_project_ref ||
290
- json.database?.project_ref ||
291
- null;
292
-
293
- // Derive REST api_url + anon key from the branch's own project.
294
- // Both lookups are best-effort — on failure we return nulls and
295
- // runner.fetchWorkItemsCount will degrade gracefully.
296
- let apiUrl = null;
297
- let anonKey = null;
298
- if (branchProjectRef) {
299
- apiUrl = `https://${branchProjectRef}.supabase.co`;
300
- try {
301
- anonKey = await fetchBranchAnonKey(branchProjectRef, token);
302
- } catch (e) {
303
- console.error(
304
- `createSupabaseTestBranch: anon key lookup failed for branch_ref=${branchProjectRef}: ${e.message}`,
305
- );
306
- }
307
- } else {
308
- console.error(
309
- `createSupabaseTestBranch: branch create response did not include a project ref — work_items assertions will be skipped. keys=${Object.keys(
310
- json,
311
- ).join(",")}`,
312
- );
313
- }
314
-
315
- return { branchId, connectionString, apiUrl, anonKey };
316
- }
317
- if (res.status === 401 || res.status === 403) {
318
- throw new Error(
319
- `Supabase branch create auth failed (${res.status}) for run=${runId}: ${await res.text()}`,
320
- );
321
- }
322
- if (res.status >= 500) {
323
- lastErr = new Error(`HTTP ${res.status}: ${await res.text()}`);
324
- await sleep(500 * Math.pow(2, attempt - 1));
325
- continue;
326
- }
327
- // 4xx non-auth — permanent
328
- throw new Error(
329
- `Supabase branch create failed (${res.status}) for run=${runId}: ${await res.text()}`,
330
- );
331
- }
332
- throw new Error(
333
- `Supabase branch create failed after 3 retries for run=${runId}: ${lastErr?.message || "unknown"}`,
334
- );
335
- }
336
-
337
- /**
338
- * Delete a Supabase test branch. Swallows 404. Logs (non-fatal) on other errors.
339
- * Always safe to call.
340
- */
341
- export async function deleteSupabaseTestBranch(branchId) {
342
- if (!branchId) return;
343
- let token;
344
- try {
345
- token = await getSupabaseMgmtToken();
346
- } catch (e) {
347
- console.error(`deleteSupabaseTestBranch: token fetch failed for branch=${branchId}: ${e.message}`);
348
- return;
349
- }
350
- const url = `${SUPABASE_MGMT_API}/v1/branches/${branchId}`;
351
- try {
352
- const res = await fetch(url, {
353
- method: "DELETE",
354
- headers: { "Authorization": `Bearer ${token}`, "Accept": "application/json" },
355
- });
356
- if (res.status === 404) return;
357
- if (!res.ok) {
358
- console.error(
359
- `deleteSupabaseTestBranch: branch=${branchId} HTTP ${res.status}: ${await res.text()}`,
360
- );
361
- }
362
- } catch (e) {
363
- console.error(`deleteSupabaseTestBranch: branch=${branchId} network error: ${e.message}`);
364
- }
365
- }
366
-
367
- // ---------- anon key + sandbox ref resolver ----------
368
-
369
- /**
370
- * Fetch the main-db anon key. Tries env var first, then clauth daemon.
371
- * Returns null on any failure — never throws.
372
- */
373
- export async function fetchSupabaseAnonKey() {
374
- if (process.env.SUPABASE_ANON_KEY) return process.env.SUPABASE_ANON_KEY;
375
- try {
376
- const res = await fetch(`${CLAUTH_URL}/get/supabase-anon`);
377
- if (!res.ok) {
378
- console.error(`fetchSupabaseAnonKey: clauth HTTP ${res.status}`);
379
- return null;
380
- }
381
- const body = await res.text();
382
- let parsed;
383
- try {
384
- parsed = JSON.parse(body);
385
- } catch {
386
- return body.trim() || null;
387
- }
388
- if (typeof parsed === "string") return parsed || null;
389
- return parsed?.value || parsed?.key || parsed?.token || null;
390
- } catch (e) {
391
- console.error(`fetchSupabaseAnonKey: ${e.message}`);
392
- return null;
393
- }
394
- }
395
-
396
- /**
397
- * Resolve the sandbox ref for a test run. Three modes:
398
- * 1. supervisor — SANDBOX_BRANCH_REF env var already set by parent
399
- * 2. main-db — default; read-only assertions against prod, no branch
400
- * 3. branch — createSupabaseTestBranch (requireBranch=true)
401
- */
402
- export async function resolveSandboxRef({ runId, requireBranch = false } = {}) {
403
- if (process.env.SANDBOX_BRANCH_REF) {
404
- const branchId = process.env.SANDBOX_BRANCH_REF;
405
- const apiUrl = process.env.SANDBOX_API_URL || null;
406
- const anonKey = process.env.SANDBOX_ANON_KEY || null;
407
- if (!apiUrl || !anonKey) {
408
- console.error(
409
- `resolveSandboxRef: supervisor mode missing ${!apiUrl ? "SANDBOX_API_URL " : ""}${!anonKey ? "SANDBOX_ANON_KEY" : ""}`.trim(),
410
- );
411
- }
412
- return { branchId, apiUrl, anonKey, mode: "supervisor" };
413
- }
414
-
415
- if (requireBranch) {
416
- const branch = await createSupabaseTestBranch(runId);
417
- return { ...branch, mode: "branch" };
418
- }
419
-
420
- const anonKey = await fetchSupabaseAnonKey();
421
- console.log(
422
- `sandbox: main-db mode — assertions read prod, no writes, no branch created (anonKey ${anonKey ? "resolved" : "missing"})`,
423
- );
424
- return { branchId: null, apiUrl: MAIN_DB_API_URL, anonKey, mode: "main-db" };
425
- }
426
-
427
- // ---------- self-test ----------
428
-
429
- if (process.argv[1] && (import.meta.url === `file://${process.argv[1]}` || import.meta.url === `file:///${process.argv[1].replace(/\\/g, "/")}`)) {
430
- const runId = generateRunId();
431
- console.log(`runId: ${runId}`);
432
- const stale = listStaleWorktrees();
433
- console.log(`stale worktrees: ${stale.length}`);
434
- process.exit(0);
435
- }
1
+ // sandbox.mjs — Tier 2 sandbox lifecycle primitives
2
+ //
3
+ // Provides isolated execution environments for rdc:* skill tests:
4
+ // 1. Git worktrees — one per skill per run, on throwaway `test/*` branches
5
+ // 2. Supabase test branches — one per run, shared across skills (budget)
6
+ //
7
+ // Consumers: scripts/self-test.mjs --tier2 (WP5, not yet written).
8
+ // This module is side-effect-free at import time. The self-test at the
9
+ // bottom exercises only pure helpers — no worktrees, no HTTP calls.
10
+ //
11
+ // See .rdc/plans/skill-self-test-tier-2.md (D1) for topology rationale.
12
+
13
+ import { execSync } from "node:child_process";
14
+ import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, appendFileSync } from "node:fs";
15
+ import { dirname, join, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { randomBytes } from "node:crypto";
18
+
19
+ const __dirname = dirname(fileURLToPath(import.meta.url));
20
+ const REPO_ROOT = resolve(__dirname, "..", "..");
21
+ const SANDBOX_ROOT = join(REPO_ROOT, ".rdc-sandbox");
22
+ const SUPABASE_PROJECT_REF = "uvojezuorjgqzmhhgluu";
23
+ const MAIN_DB_PROJECT_REF = "uvojezuorjgqzmhhgluu";
24
+ const MAIN_DB_API_URL = `https://${MAIN_DB_PROJECT_REF}.supabase.co`;
25
+ const SUPABASE_MGMT_API = "https://api.supabase.com";
26
+ const CLAUTH_URL = "http://127.0.0.1:52437";
27
+ const STALE_AGE_HOURS = 1;
28
+
29
+ // ---------- path helpers ----------
30
+
31
+ /** Forward-slash a path. Git accepts both on Windows; this keeps errors tidy. */
32
+ function fwd(p) {
33
+ return p.replace(/\\/g, "/");
34
+ }
35
+
36
+ /** Normalize a skill name for use in a git branch. Git forbids ':'. */
37
+ function normalizeSkillForBranch(skillName) {
38
+ return skillName.replace(/:/g, "-");
39
+ }
40
+
41
+ function worktreePath(runId, skillName) {
42
+ return fwd(join(SANDBOX_ROOT, runId, normalizeSkillForBranch(skillName)));
43
+ }
44
+
45
+ function branchName(runId, skillName) {
46
+ return `test/${normalizeSkillForBranch(skillName)}-${runId}`;
47
+ }
48
+
49
+ // ---------- shell ----------
50
+
51
+ function sh(cmd, opts = {}) {
52
+ try {
53
+ return execSync(cmd, {
54
+ stdio: ["ignore", "pipe", "pipe"],
55
+ encoding: "utf8",
56
+ cwd: REPO_ROOT,
57
+ ...opts,
58
+ });
59
+ } catch (e) {
60
+ const stderr = e.stderr?.toString?.() || "";
61
+ const stdout = e.stdout?.toString?.() || "";
62
+ const err = new Error(
63
+ `command failed (exit ${e.status}): ${cmd}\nstderr: ${stderr.trim()}\nstdout: ${stdout.trim()}`,
64
+ );
65
+ err.exitCode = e.status;
66
+ err.stderr = stderr;
67
+ err.stdout = stdout;
68
+ throw err;
69
+ }
70
+ }
71
+
72
+ // ---------- sandbox root ----------
73
+
74
+ /** Create (if needed) and return the sandbox root for a given project root. Idempotent. */
75
+ export function createSandboxRoot(projectRoot = REPO_ROOT) {
76
+ const sandboxRoot = join(projectRoot, ".rdc-sandbox");
77
+ if (!existsSync(sandboxRoot)) {
78
+ mkdirSync(sandboxRoot, { recursive: true });
79
+ }
80
+ return sandboxRoot;
81
+ }
82
+
83
+ /** Generate a run id: YYYY-MM-DD + 6 hex chars. */
84
+ export function generateRunId() {
85
+ const d = new Date();
86
+ const date = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
87
+ const rand = randomBytes(3).toString("hex");
88
+ return `${date}-${rand}`;
89
+ }
90
+
91
+ // ---------- git worktrees ----------
92
+
93
+ /**
94
+ * Create a new worktree on a throwaway branch inside projectRoot.
95
+ *
96
+ * projectRoot MUST be the repo that claude --print will commit to — so that
97
+ * commitsSince() and filesModifiedSince() in runner.mjs inspect the right repo.
98
+ * In practice this is the regen-root working directory (process.cwd() when
99
+ * self-test runs from regen-root).
100
+ *
101
+ * Worktrees live at <projectRoot>/.rdc-sandbox/<runId>/<skill-slug>/.
102
+ */
103
+ export function createWorktree(runId, skillName, projectRoot = REPO_ROOT) {
104
+ const sandboxRoot = createSandboxRoot(projectRoot);
105
+ const path = fwd(join(sandboxRoot, runId, normalizeSkillForBranch(skillName)));
106
+ const branch = branchName(runId, skillName);
107
+ if (existsSync(path)) {
108
+ throw new Error(
109
+ `worktree already exists for run=${runId} skill=${skillName} at ${path} — caller must decide retry policy`,
110
+ );
111
+ }
112
+ mkdirSync(dirname(path), { recursive: true });
113
+ try {
114
+ sh(`git worktree add "${path}" -b "${branch}"`, { cwd: projectRoot });
115
+ } catch (e) {
116
+ throw new Error(
117
+ `failed to create worktree for run=${runId} skill=${skillName} in ${projectRoot}: ${e.message}`,
118
+ );
119
+ }
120
+ return { path, branch, projectRoot };
121
+ }
122
+
123
+ /**
124
+ * Remove a worktree and its throwaway branch.
125
+ * projectRoot must match the one passed to createWorktree. Safe to call if already gone.
126
+ */
127
+ export function removeWorktree(runId, skillName, projectRoot = REPO_ROOT) {
128
+ const sandboxRoot = join(projectRoot, ".rdc-sandbox");
129
+ const path = fwd(join(sandboxRoot, runId, normalizeSkillForBranch(skillName)));
130
+ const branch = branchName(runId, skillName);
131
+ if (existsSync(path)) {
132
+ try {
133
+ sh(`git worktree remove "${path}" --force`, { cwd: projectRoot });
134
+ } catch {
135
+ try { sh(`git worktree prune`, { cwd: projectRoot }); } catch {}
136
+ }
137
+ }
138
+ try {
139
+ sh(`git branch -D "${branch}"`, { cwd: projectRoot });
140
+ } catch {
141
+ // branch may already be gone or never created
142
+ }
143
+ }
144
+
145
+ /** Scan .rdc-sandbox/ for worktree dirs older than STALE_AGE_HOURS. */
146
+ export function listStaleWorktrees() {
147
+ const stale = [];
148
+ if (!existsSync(SANDBOX_ROOT)) return stale;
149
+ const now = Date.now();
150
+ let runDirs;
151
+ try {
152
+ runDirs = readdirSync(SANDBOX_ROOT);
153
+ } catch {
154
+ return stale;
155
+ }
156
+ for (const runId of runDirs) {
157
+ const runPath = join(SANDBOX_ROOT, runId);
158
+ let st;
159
+ try { st = statSync(runPath); } catch { continue; }
160
+ if (!st.isDirectory()) continue;
161
+ let skills;
162
+ try { skills = readdirSync(runPath); } catch { continue; }
163
+ for (const skill of skills) {
164
+ const p = join(runPath, skill);
165
+ let sst;
166
+ try { sst = statSync(p); } catch { continue; }
167
+ if (!sst.isDirectory()) continue;
168
+ const ageHours = (now - sst.mtimeMs) / (1000 * 60 * 60);
169
+ if (ageHours >= STALE_AGE_HOURS) {
170
+ stale.push({
171
+ path: fwd(p),
172
+ branch: `test/${skill}-${runId}`,
173
+ ageHours: Math.round(ageHours * 10) / 10,
174
+ });
175
+ }
176
+ }
177
+ }
178
+ return stale;
179
+ }
180
+
181
+ /** Remove all stale worktrees. Returns count removed. Safe on-start call. */
182
+ export function cleanupStaleWorktrees() {
183
+ const stale = listStaleWorktrees();
184
+ let removed = 0;
185
+ for (const w of stale) {
186
+ try {
187
+ sh(`git worktree remove "${w.path}" --force`);
188
+ removed++;
189
+ } catch (e) {
190
+ console.error(`cleanup: failed to remove ${w.path}: ${e.message}`);
191
+ }
192
+ try { sh(`git branch -D "${w.branch}"`); } catch {}
193
+ }
194
+ try { sh(`git worktree prune`); } catch {}
195
+ return removed;
196
+ }
197
+
198
+ // ---------- Supabase test branches ----------
199
+
200
+ async function getSupabaseMgmtToken() {
201
+ const res = await fetch(`${CLAUTH_URL}/get/supabase-management`);
202
+ if (!res.ok) {
203
+ throw new Error(`clauth daemon returned ${res.status} fetching supabase-management token`);
204
+ }
205
+ const body = await res.text();
206
+ // clauth returns raw secret or JSON {value:...}; handle both
207
+ try {
208
+ const j = JSON.parse(body);
209
+ return j.value || j.secret || j.token || body.trim();
210
+ } catch {
211
+ return body.trim();
212
+ }
213
+ }
214
+
215
+ async function sleep(ms) {
216
+ return new Promise((r) => setTimeout(r, ms));
217
+ }
218
+
219
+ /**
220
+ * Fetch the anon/publishable key for a branch's own project ref.
221
+ * Uses GET /v1/projects/{ref}/api-keys?reveal=true. Returns the first key
222
+ * whose name/type indicates "anon" or "publishable". Throws on HTTP error.
223
+ */
224
+ async function fetchBranchAnonKey(projectRef, token) {
225
+ const url = `${SUPABASE_MGMT_API}/v1/projects/${projectRef}/api-keys?reveal=true`;
226
+ const res = await fetch(url, {
227
+ headers: {
228
+ Authorization: `Bearer ${token}`,
229
+ Accept: "application/json",
230
+ },
231
+ });
232
+ if (!res.ok) {
233
+ throw new Error(`HTTP ${res.status}: ${await res.text()}`);
234
+ }
235
+ const body = await res.json();
236
+ const keys = Array.isArray(body) ? body : body?.keys || [];
237
+ // Prefer anon / publishable; avoid service_role.
238
+ const pick = keys.find((k) => {
239
+ const name = (k?.name || k?.type || "").toLowerCase();
240
+ return name === "anon" || name === "publishable" || name.includes("anon") || name.includes("publishable");
241
+ });
242
+ if (!pick) {
243
+ throw new Error(
244
+ `no anon/publishable key found; got ${keys.length} keys: ${keys
245
+ .map((k) => k?.name || k?.type || "?")
246
+ .join(",")}`,
247
+ );
248
+ }
249
+ return pick.api_key || pick.key || pick.value || null;
250
+ }
251
+
252
+ /**
253
+ * Create a Supabase test branch via Management API.
254
+ * Retries 3× with exponential backoff on 5xx. Throws on auth or final failure.
255
+ */
256
+ export async function createSupabaseTestBranch(runId) {
257
+ const token = await getSupabaseMgmtToken();
258
+ const url = `${SUPABASE_MGMT_API}/v1/projects/${SUPABASE_PROJECT_REF}/branches`;
259
+ const body = JSON.stringify({ branch_name: `test-${runId}` });
260
+
261
+ let lastErr;
262
+ for (let attempt = 1; attempt <= 3; attempt++) {
263
+ let res;
264
+ try {
265
+ res = await fetch(url, {
266
+ method: "POST",
267
+ headers: {
268
+ "Authorization": `Bearer ${token}`,
269
+ "Content-Type": "application/json",
270
+ "Accept": "application/json",
271
+ },
272
+ body,
273
+ });
274
+ } catch (e) {
275
+ lastErr = e;
276
+ await sleep(500 * Math.pow(2, attempt - 1));
277
+ continue;
278
+ }
279
+ if (res.ok) {
280
+ const json = await res.json();
281
+ const branchId = json.id || json.branch_id;
282
+ const connectionString =
283
+ json.database?.connection_string || json.connection_string || "";
284
+ // A branch has its own project ref (distinct from parent). Try common
285
+ // field names the Management API has used across versions.
286
+ const branchProjectRef =
287
+ json.project_ref ||
288
+ json.ref ||
289
+ json.branch_project_ref ||
290
+ json.database?.project_ref ||
291
+ null;
292
+
293
+ // Derive REST api_url + anon key from the branch's own project.
294
+ // Both lookups are best-effort — on failure we return nulls and
295
+ // runner.fetchWorkItemsCount will degrade gracefully.
296
+ let apiUrl = null;
297
+ let anonKey = null;
298
+ if (branchProjectRef) {
299
+ apiUrl = `https://${branchProjectRef}.supabase.co`;
300
+ try {
301
+ anonKey = await fetchBranchAnonKey(branchProjectRef, token);
302
+ } catch (e) {
303
+ console.error(
304
+ `createSupabaseTestBranch: anon key lookup failed for branch_ref=${branchProjectRef}: ${e.message}`,
305
+ );
306
+ }
307
+ } else {
308
+ console.error(
309
+ `createSupabaseTestBranch: branch create response did not include a project ref — work_items assertions will be skipped. keys=${Object.keys(
310
+ json,
311
+ ).join(",")}`,
312
+ );
313
+ }
314
+
315
+ return { branchId, connectionString, apiUrl, anonKey };
316
+ }
317
+ if (res.status === 401 || res.status === 403) {
318
+ throw new Error(
319
+ `Supabase branch create auth failed (${res.status}) for run=${runId}: ${await res.text()}`,
320
+ );
321
+ }
322
+ if (res.status >= 500) {
323
+ lastErr = new Error(`HTTP ${res.status}: ${await res.text()}`);
324
+ await sleep(500 * Math.pow(2, attempt - 1));
325
+ continue;
326
+ }
327
+ // 4xx non-auth — permanent
328
+ throw new Error(
329
+ `Supabase branch create failed (${res.status}) for run=${runId}: ${await res.text()}`,
330
+ );
331
+ }
332
+ throw new Error(
333
+ `Supabase branch create failed after 3 retries for run=${runId}: ${lastErr?.message || "unknown"}`,
334
+ );
335
+ }
336
+
337
+ /**
338
+ * Delete a Supabase test branch. Swallows 404. Logs (non-fatal) on other errors.
339
+ * Always safe to call.
340
+ */
341
+ export async function deleteSupabaseTestBranch(branchId) {
342
+ if (!branchId) return;
343
+ let token;
344
+ try {
345
+ token = await getSupabaseMgmtToken();
346
+ } catch (e) {
347
+ console.error(`deleteSupabaseTestBranch: token fetch failed for branch=${branchId}: ${e.message}`);
348
+ return;
349
+ }
350
+ const url = `${SUPABASE_MGMT_API}/v1/branches/${branchId}`;
351
+ try {
352
+ const res = await fetch(url, {
353
+ method: "DELETE",
354
+ headers: { "Authorization": `Bearer ${token}`, "Accept": "application/json" },
355
+ });
356
+ if (res.status === 404) return;
357
+ if (!res.ok) {
358
+ console.error(
359
+ `deleteSupabaseTestBranch: branch=${branchId} HTTP ${res.status}: ${await res.text()}`,
360
+ );
361
+ }
362
+ } catch (e) {
363
+ console.error(`deleteSupabaseTestBranch: branch=${branchId} network error: ${e.message}`);
364
+ }
365
+ }
366
+
367
+ // ---------- anon key + sandbox ref resolver ----------
368
+
369
+ /**
370
+ * Fetch the main-db anon key. Tries env var first, then clauth daemon.
371
+ * Returns null on any failure — never throws.
372
+ */
373
+ export async function fetchSupabaseAnonKey() {
374
+ if (process.env.SUPABASE_ANON_KEY) return process.env.SUPABASE_ANON_KEY;
375
+ try {
376
+ const res = await fetch(`${CLAUTH_URL}/get/supabase-anon`);
377
+ if (!res.ok) {
378
+ console.error(`fetchSupabaseAnonKey: clauth HTTP ${res.status}`);
379
+ return null;
380
+ }
381
+ const body = await res.text();
382
+ let parsed;
383
+ try {
384
+ parsed = JSON.parse(body);
385
+ } catch {
386
+ return body.trim() || null;
387
+ }
388
+ if (typeof parsed === "string") return parsed || null;
389
+ return parsed?.value || parsed?.key || parsed?.token || null;
390
+ } catch (e) {
391
+ console.error(`fetchSupabaseAnonKey: ${e.message}`);
392
+ return null;
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Resolve the sandbox ref for a test run. Three modes:
398
+ * 1. supervisor — SANDBOX_BRANCH_REF env var already set by parent
399
+ * 2. main-db — default; read-only assertions against prod, no branch
400
+ * 3. branch — createSupabaseTestBranch (requireBranch=true)
401
+ */
402
+ export async function resolveSandboxRef({ runId, requireBranch = false } = {}) {
403
+ if (process.env.SANDBOX_BRANCH_REF) {
404
+ const branchId = process.env.SANDBOX_BRANCH_REF;
405
+ const apiUrl = process.env.SANDBOX_API_URL || null;
406
+ const anonKey = process.env.SANDBOX_ANON_KEY || null;
407
+ if (!apiUrl || !anonKey) {
408
+ console.error(
409
+ `resolveSandboxRef: supervisor mode missing ${!apiUrl ? "SANDBOX_API_URL " : ""}${!anonKey ? "SANDBOX_ANON_KEY" : ""}`.trim(),
410
+ );
411
+ }
412
+ return { branchId, apiUrl, anonKey, mode: "supervisor" };
413
+ }
414
+
415
+ if (requireBranch) {
416
+ const branch = await createSupabaseTestBranch(runId);
417
+ return { ...branch, mode: "branch" };
418
+ }
419
+
420
+ const anonKey = await fetchSupabaseAnonKey();
421
+ console.log(
422
+ `sandbox: main-db mode — assertions read prod, no writes, no branch created (anonKey ${anonKey ? "resolved" : "missing"})`,
423
+ );
424
+ return { branchId: null, apiUrl: MAIN_DB_API_URL, anonKey, mode: "main-db" };
425
+ }
426
+
427
+ // ---------- self-test ----------
428
+
429
+ if (process.argv[1] && (import.meta.url === `file://${process.argv[1]}` || import.meta.url === `file:///${process.argv[1].replace(/\\/g, "/")}`)) {
430
+ const runId = generateRunId();
431
+ console.log(`runId: ${runId}`);
432
+ const stale = listStaleWorktrees();
433
+ console.log(`stale worktrees: ${stale.length}`);
434
+ process.exit(0);
435
+ }