@stackwright-pro/raft 1.0.0-alpha.12 → 1.0.0-alpha.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,44 +1,78 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
25
3
 
26
4
  // src/index.ts
27
- var import_fs2 = require("fs");
28
- var import_path2 = require("path");
29
- var import_child_process2 = require("child_process");
5
+ var import_fs3 = require("fs");
6
+ var import_path3 = require("path");
7
+ var import_child_process3 = require("child_process");
30
8
  var import_integrity = require("@stackwright-pro/mcp/integrity");
9
+ var import_type_schemas = require("@stackwright-pro/mcp/type-schemas");
31
10
 
32
11
  // src/lib.ts
33
12
  var import_child_process = require("child_process");
34
13
  var import_fs = require("fs");
35
14
  var import_path = require("path");
36
15
  var import_os = require("os");
16
+ var CODE_PUPPY_ENV_ALLOWLIST = /* @__PURE__ */ new Set([
17
+ // Shell / execution environment
18
+ "PATH",
19
+ "HOME",
20
+ "USER",
21
+ "USERNAME",
22
+ "SHELL",
23
+ "TMPDIR",
24
+ "TMP",
25
+ "TEMP",
26
+ // Terminal
27
+ "TERM",
28
+ "COLORTERM",
29
+ "COLUMNS",
30
+ "LINES",
31
+ "NO_COLOR",
32
+ "FORCE_COLOR",
33
+ // Language / locale
34
+ "LANG",
35
+ "LC_ALL",
36
+ "LC_CTYPE",
37
+ "LC_MESSAGES",
38
+ // Network proxy — needed for outbound LLM API calls behind corporate proxies
39
+ "HTTP_PROXY",
40
+ "HTTPS_PROXY",
41
+ "NO_PROXY",
42
+ "http_proxy",
43
+ "https_proxy",
44
+ "no_proxy",
45
+ // LLM API keys — the only credentials code-puppy should have
46
+ "ANTHROPIC_API_KEY",
47
+ "ANTHROPIC_BASE_URL",
48
+ "OPENAI_API_KEY",
49
+ // Node runtime
50
+ "NODE_ENV",
51
+ // Stackwright-specific
52
+ "STACKWRIGHT_PROJECT_ROOT",
53
+ "STACKWRIGHT_SKIP_PREFLIGHT",
54
+ "STACKWRIGHT_CODE_PUPPY_PATH",
55
+ // Telemetry vars (swp-bhw1): NDJSON path is force-injected by the launcher (see index.ts),
56
+ // but listing here allows user override via shell env. DISABLED/DEBUG are opt-in toggles.
57
+ "STACKWRIGHT_TELEMETRY_NDJSON",
58
+ "STACKWRIGHT_TELEMETRY_DISABLED",
59
+ "STACKWRIGHT_TELEMETRY_DEBUG"
60
+ ]);
61
+ var CODE_PUPPY_ENV_PREFIXES = ["PYTHON", "LC_"];
62
+ var MIN_SUPPORTED_CODE_PUPPY_VERSION = "0.0.575";
37
63
  function parseArgs(argv) {
38
64
  const args = {
39
65
  projectRoot: process.cwd(),
40
66
  verbose: false,
41
- help: false
67
+ help: false,
68
+ passEnvKeys: [],
69
+ nonInteractive: false,
70
+ devOnly: false,
71
+ useCasePath: null,
72
+ skipQa: false,
73
+ qaOnly: false,
74
+ qaDevServerTimeoutMs: 6e4,
75
+ parallelPhases: false
42
76
  };
43
77
  const raw = argv.slice(2);
44
78
  for (let i = 0; i < raw.length; i++) {
@@ -54,7 +88,36 @@ function parseArgs(argv) {
54
88
  case "-h":
55
89
  args.help = true;
56
90
  break;
91
+ case "--pass-env":
92
+ args.passEnvKeys.push(raw[++i] ?? die("--pass-env requires a KEY argument"));
93
+ break;
94
+ case "--non-interactive":
95
+ args.nonInteractive = true;
96
+ break;
97
+ case "--dev-only":
98
+ args.devOnly = true;
99
+ break;
100
+ case "--use-case":
101
+ args.useCasePath = raw[++i] ?? die("--use-case requires a file path argument");
102
+ break;
103
+ case "--skip-qa":
104
+ args.skipQa = true;
105
+ break;
106
+ case "--qa-only":
107
+ args.qaOnly = true;
108
+ break;
109
+ case "--parallel-phases":
110
+ args.parallelPhases = true;
111
+ break;
57
112
  default:
113
+ if (token.startsWith("--qa-dev-server-timeout-ms=")) {
114
+ const val = parseInt(token.split("=")[1] ?? "", 10);
115
+ if (isNaN(val) || val <= 0) {
116
+ die("--qa-dev-server-timeout-ms requires a positive integer (ms)");
117
+ }
118
+ args.qaDevServerTimeoutMs = val;
119
+ break;
120
+ }
58
121
  die(`Unknown option: ${token}
59
122
  Run with --help for usage.`);
60
123
  }
@@ -69,9 +132,17 @@ function printHelp() {
69
132
  Usage: launch-raft [options]
70
133
 
71
134
  Options:
72
- --project-root <path> Project root directory (default: cwd)
73
- --verbose Enable verbose logging
74
- --help, -h Show this help
135
+ --project-root <path> Project root directory (default: cwd)
136
+ --verbose Enable verbose logging
137
+ --pass-env <KEY> Forward an additional env var to code-puppy (repeatable)
138
+ --non-interactive Skip all TUI prompts, use sane defaults for questions
139
+ --dev-only Mock auth only \u2014 roles derived from use case, no real providers
140
+ --use-case <file> Seed "what to build" from a file (plain text or markdown)
141
+ --skip-qa Skip the visual QA gate (useful for CI or fast iterations)
142
+ --qa-only Skip the otter pipeline; spawn dev server and run QA directly
143
+ --qa-dev-server-timeout-ms=<n> Dev server startup timeout in ms for QA gate (default: 60000)
144
+ --parallel-phases Enable parallel specialist invocation within dependency waves (~40% wall-time reduction). Default: off (serial).
145
+ --help, -h Show this help
75
146
 
76
147
  Prerequisites:
77
148
  pip install stackwright-puppy # provides raft-puppy + code-puppy alias
@@ -91,6 +162,29 @@ function verbose(message, isVerbose) {
91
162
  console.log(` ${message}`);
92
163
  }
93
164
  }
165
+ function buildCodePuppyEnv(extraVars = {}, passEnvKeys = []) {
166
+ const env = {};
167
+ for (const [key, value] of Object.entries(process.env)) {
168
+ if (value === void 0) continue;
169
+ const allowed = CODE_PUPPY_ENV_ALLOWLIST.has(key) || CODE_PUPPY_ENV_PREFIXES.some((prefix) => key.startsWith(prefix)) || passEnvKeys.includes(key);
170
+ if (allowed) {
171
+ env[key] = value;
172
+ }
173
+ }
174
+ for (const [key, value] of Object.entries(extraVars)) {
175
+ env[key] = value;
176
+ }
177
+ return env;
178
+ }
179
+ function buildLauncherEnvOverrides(projectRoot) {
180
+ return {
181
+ STACKWRIGHT_PROJECT_ROOT: projectRoot,
182
+ // swp-bhw1: route raft-puppy telemetry to a SEPARATE file from Pro telemetry.
183
+ // Two-file separation paves the way for the eventual message-bus architecture
184
+ // (distributed deployments, restart, replay). User can override via shell env.
185
+ STACKWRIGHT_TELEMETRY_NDJSON: (0, import_path.join)(projectRoot, ".stackwright", "raft-puppy-events.ndjson")
186
+ };
187
+ }
94
188
  var LOCK_FILE = ".stackwright/.lock";
95
189
  function acquireLock(projectRoot) {
96
190
  const lockPath = (0, import_path.join)(projectRoot, LOCK_FILE);
@@ -137,6 +231,26 @@ function releaseLock(projectRoot) {
137
231
  } catch {
138
232
  }
139
233
  }
234
+ function migrateWorkspaceDir(projectRoot) {
235
+ const oldDir = (0, import_path.join)(projectRoot, ".code-puppy");
236
+ const newDir = (0, import_path.join)(projectRoot, ".code_puppy");
237
+ const oldExists = (0, import_fs.existsSync)(oldDir);
238
+ const newExists = (0, import_fs.existsSync)(newDir);
239
+ if (!oldExists) return;
240
+ if ((0, import_fs.lstatSync)(oldDir).isSymbolicLink()) {
241
+ die(".code-puppy/ is a symlink \u2014 refusing to migrate. Check for tampering.");
242
+ }
243
+ if (newExists && (0, import_fs.lstatSync)(newDir).isSymbolicLink()) {
244
+ die(".code_puppy/ is a symlink \u2014 refusing to migrate. Check for tampering.");
245
+ }
246
+ if (!newExists) {
247
+ (0, import_fs.renameSync)(oldDir, newDir);
248
+ log("Migrated .code-puppy/ \u2192 .code_puppy/ (underscore convention)");
249
+ } else {
250
+ (0, import_fs.rmSync)(oldDir, { recursive: true });
251
+ log("Removed stale .code-puppy/ (underscore version already exists)");
252
+ }
253
+ }
140
254
  function writeInitContext(projectRoot) {
141
255
  if (!acquireLock(projectRoot)) {
142
256
  let existingPid = "unknown";
@@ -144,7 +258,8 @@ function writeInitContext(projectRoot) {
144
258
  const lockPath = (0, import_path.join)(projectRoot, LOCK_FILE);
145
259
  if ((0, import_fs.existsSync)(lockPath)) {
146
260
  const lockData = JSON.parse((0, import_fs.readFileSync)(lockPath, "utf8"));
147
- existingPid = lockData["pid"] ?? "unknown";
261
+ const rawPid = lockData["pid"];
262
+ existingPid = typeof rawPid === "string" || typeof rawPid === "number" ? rawPid : "unknown";
148
263
  }
149
264
  } catch {
150
265
  }
@@ -232,18 +347,42 @@ process.on("SIGTERM", () => {
232
347
  }
233
348
  process.exit(0);
234
349
  });
235
- function findCodePuppy() {
350
+ function getTrustedBinaryDirs() {
351
+ return [
352
+ (0, import_path.join)((0, import_os.homedir)(), ".local", "bin"),
353
+ // pip user install, uvx, pipx (Linux/macOS)
354
+ "/opt/homebrew/bin",
355
+ // brew Apple Silicon
356
+ "/usr/local/bin",
357
+ // brew Intel, pip system install
358
+ "/usr/bin"
359
+ // system package managers (apt, dnf)
360
+ ];
361
+ }
362
+ function findCodePuppy(trustedDirsOverride) {
236
363
  let candidate = null;
237
364
  const envPath = process.env["STACKWRIGHT_CODE_PUPPY_PATH"];
238
365
  if (envPath) {
239
366
  candidate = envPath;
240
367
  }
368
+ if (!candidate) {
369
+ const trustedDirs = trustedDirsOverride ?? getTrustedBinaryDirs();
370
+ outer: for (const bin of ["raft-puppy", "code-puppy"]) {
371
+ for (const dir of trustedDirs) {
372
+ const p = (0, import_path.join)(dir, bin);
373
+ if ((0, import_fs.existsSync)(p)) {
374
+ candidate = p;
375
+ break outer;
376
+ }
377
+ }
378
+ }
379
+ }
241
380
  if (!candidate) {
242
381
  for (const bin of ["raft-puppy", "code-puppy"]) {
243
- try {
244
- candidate = (0, import_child_process.execSync)(`which ${bin}`, { encoding: "utf-8" }).trim();
382
+ const whichResult = (0, import_child_process.spawnSync)("which", [bin], { encoding: "utf-8" });
383
+ if (whichResult.status === 0 && whichResult.stdout) {
384
+ candidate = whichResult.stdout.trim();
245
385
  if (candidate) break;
246
- } catch {
247
386
  }
248
387
  }
249
388
  }
@@ -267,39 +406,116 @@ function findCodePuppy() {
267
406
  if (!(0, import_fs.existsSync)(realBinary)) {
268
407
  die(`raft-puppy symlink at ${resolved} points to a missing file: ${realBinary}`);
269
408
  }
270
- const stat = (0, import_fs.lstatSync)(realBinary);
409
+ let fd;
410
+ try {
411
+ fd = (0, import_fs.openSync)(realBinary, "r");
412
+ } catch (err) {
413
+ die(
414
+ `Cannot open raft-puppy at ${realBinary} for validation: ${String(err)}. Try reinstalling stackwright-puppy or set STACKWRIGHT_CODE_PUPPY_PATH.`
415
+ );
416
+ }
417
+ const stat = (0, import_fs.fstatSync)(fd);
271
418
  if (stat.mode & 18) {
419
+ (0, import_fs.closeSync)(fd);
272
420
  die(
273
421
  `raft-puppy at ${realBinary} is group- or world-writable (mode: ${(stat.mode & 511).toString(8)}) \u2014 refusing to exec.`
274
422
  );
275
423
  }
276
424
  if (stat.mode & 3072) {
425
+ (0, import_fs.closeSync)(fd);
277
426
  die(`raft-puppy at ${realBinary} has setuid/setgid bits \u2014 refusing to exec.`);
278
427
  }
279
- return realBinary;
428
+ return { path: realBinary, fd };
429
+ }
430
+ function parseSemver(version) {
431
+ const parts = version.split("-")[0].split(".").map(Number);
432
+ return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
433
+ }
434
+ function semverGte(a, b) {
435
+ const [aMaj, aMin, aPatch] = parseSemver(a);
436
+ const [bMaj, bMin, bPatch] = parseSemver(b);
437
+ if (aMaj !== bMaj) return aMaj > bMaj;
438
+ if (aMin !== bMin) return aMin > bMin;
439
+ return aPatch >= bPatch;
440
+ }
441
+ function validateBinaryVersion(binaryPath) {
442
+ if (process.env["STACKWRIGHT_SKIP_PREFLIGHT"] === "true") {
443
+ log("Pre-flight checks skipped via STACKWRIGHT_SKIP_PREFLIGHT");
444
+ return;
445
+ }
446
+ const versionStartTime = Date.now();
447
+ const versionResult = (0, import_child_process.spawnSync)(binaryPath, ["--version"], {
448
+ encoding: "utf-8",
449
+ // 15s: uv-installed Python tools cold-start (venv activation + interpreter
450
+ // startup) can take 5-10s on first invocation; subsequent runs are ms.
451
+ timeout: 15e3,
452
+ stdio: ["ignore", "pipe", "pipe"]
453
+ });
454
+ const versionElapsed = Date.now() - versionStartTime;
455
+ if (versionResult.error !== void 0 || versionResult.status !== 0) {
456
+ const errorDetail = versionResult.error ? `${versionResult.error.code ?? "unknown"}: ${versionResult.error.message}` : `exit status ${String(versionResult.status)}`;
457
+ const stdoutSnip = (versionResult.stdout ?? "").trim() || "<empty>";
458
+ const stderrSnip = (versionResult.stderr ?? "").trim() || "<empty>";
459
+ die(
460
+ `Could not determine raft-puppy / code-puppy version.
461
+ Binary: ${binaryPath}
462
+ Failure: ${errorDetail}
463
+ Elapsed: ${String(versionElapsed)}ms (timeout: 15000ms)
464
+ Stdout: ${stdoutSnip}
465
+ Stderr: ${stderrSnip}
466
+ Required: ${MIN_SUPPORTED_CODE_PUPPY_VERSION}
467
+
468
+ Run: pip install --upgrade stackwright-puppy
469
+ Or: pip install --upgrade code-puppy
470
+
471
+ If the binary works manually but fails here, set
472
+ STACKWRIGHT_SKIP_PREFLIGHT=true to bypass this check.`
473
+ );
474
+ }
475
+ const versionStdout = versionResult.stdout.trim();
476
+ const versionStderr = versionResult.stderr.trim();
477
+ const versionOutput = versionStdout || versionStderr;
478
+ const match = /(\d+\.\d+\.\d+(?:-[^\s]+)?)/.exec(versionOutput);
479
+ if (!match || !match[1]) {
480
+ die(
481
+ `Could not parse version from raft-puppy / code-puppy output.
482
+ Binary: ${binaryPath}
483
+ Stdout: ${JSON.stringify(versionStdout) || "<empty>"}
484
+ Stderr: ${JSON.stringify(versionStderr) || "<empty>"}
485
+ Required: ${MIN_SUPPORTED_CODE_PUPPY_VERSION}
486
+
487
+ Run: pip install --upgrade stackwright-puppy
488
+ Or: pip install --upgrade code-puppy`
489
+ );
490
+ }
491
+ const installedVersion = match[1];
492
+ const isDevBuild = installedVersion === "0.0.0" || /^0\.0\.0-.+$/.test(installedVersion);
493
+ if (isDevBuild) {
494
+ console.warn(
495
+ `\u26A0\uFE0F Dev build detected (${installedVersion}) \u2014 skipping minimum version check.
496
+ Minimum required for production: ${MIN_SUPPORTED_CODE_PUPPY_VERSION}
497
+ To suppress this warning in CI: set STACKWRIGHT_SKIP_PREFLIGHT=true`
498
+ );
499
+ return;
500
+ }
501
+ if (!semverGte(installedVersion, MIN_SUPPORTED_CODE_PUPPY_VERSION)) {
502
+ die(
503
+ `raft-puppy / code-puppy ${installedVersion} is below the minimum required version.
504
+ Installed: ${installedVersion}
505
+ Minimum required: ${MIN_SUPPORTED_CODE_PUPPY_VERSION}
506
+
507
+ Run: pip install --upgrade stackwright-puppy
508
+ Or: pip install --upgrade code-puppy`
509
+ );
510
+ }
280
511
  }
281
512
  function ensureMcpConfig(projectRoot) {
282
- const xdgConfigHome = process.env["XDG_CONFIG_HOME"];
283
- const configDir = xdgConfigHome ? (0, import_path.join)(xdgConfigHome, "code_puppy") : (0, import_path.join)((0, import_os.homedir)(), ".code_puppy");
284
- const configPath = (0, import_path.join)(configDir, "mcp_servers.json");
513
+ const workspaceDir = (0, import_path.join)(projectRoot, ".code_puppy");
514
+ const configPath = (0, import_path.join)(workspaceDir, "mcp_servers.json");
285
515
  if ((0, import_fs.existsSync)(configPath) && (0, import_fs.lstatSync)(configPath).isSymbolicLink()) {
286
- die("`~/.code_puppy/mcp_servers.json` is a symlink \u2014 refusing to write. Check for tampering.");
287
- }
288
- (0, import_fs.mkdirSync)(configDir, { recursive: true });
289
- const localServerPath = (0, import_path.join)(
290
- projectRoot,
291
- "node_modules",
292
- "@stackwright-pro",
293
- "mcp",
294
- "dist",
295
- "server.js"
296
- );
297
- let raftOwnServerPath = null;
298
- try {
299
- raftOwnServerPath = require.resolve("@stackwright-pro/mcp");
300
- } catch {
516
+ die(".code_puppy/mcp_servers.json is a symlink \u2014 refusing to write. Check for tampering.");
301
517
  }
302
- const serverConfig = (0, import_fs.existsSync)(localServerPath) ? { type: "stdio", command: "node", args: [localServerPath] } : raftOwnServerPath !== null ? { type: "stdio", command: "node", args: [raftOwnServerPath] } : { type: "stdio", command: "npx", args: ["--yes", "@stackwright-pro/mcp@latest"] };
518
+ (0, import_fs.mkdirSync)(workspaceDir, { recursive: true });
303
519
  let existing = {};
304
520
  if ((0, import_fs.existsSync)(configPath)) {
305
521
  try {
@@ -308,28 +524,59 @@ function ensureMcpConfig(projectRoot) {
308
524
  } catch {
309
525
  }
310
526
  }
527
+ const shimName = (0, import_os.platform)() === "win32" ? "stackwright-pro-mcp.cmd" : "stackwright-pro-mcp";
528
+ const shimPath = (0, import_path.join)(projectRoot, "node_modules", ".bin", shimName);
529
+ if (!(0, import_fs.existsSync)(shimPath)) {
530
+ die(
531
+ `MCP server shim not found: ${shimPath}
532
+ Run \`pnpm install\` (or your package manager equivalent) before \`raft\`.`
533
+ );
534
+ }
535
+ const serverConfig = {
536
+ type: "stdio",
537
+ command: shimPath,
538
+ args: [],
539
+ enabled: true,
540
+ cwd: projectRoot
541
+ };
311
542
  const merged = {
312
543
  ...existing,
313
544
  mcp_servers: {
314
545
  ...existing.mcp_servers ?? {},
315
- "stackwright-pro": serverConfig
546
+ "stackwright-pro-mcp": serverConfig
316
547
  }
317
548
  };
318
- if (merged.mcp_servers && "stackwright" in merged.mcp_servers) {
319
- const stale = merged.mcp_servers["stackwright"];
320
- const args = stale?.["args"];
321
- const isPlaceholder = args?.includes("/path/to/dir") || stale?.["command"] === "npx" && args?.some((a) => String(a).includes("server-filesystem"));
322
- if (isPlaceholder) {
323
- delete merged.mcp_servers["stackwright"];
324
- log(
325
- "Removed stale `stackwright` placeholder from mcp_servers.json (was: @modelcontextprotocol/server-filesystem /path/to/dir \u2014 not a real server)"
326
- );
549
+ const tmpPath = `${configPath}.tmp`;
550
+ (0, import_fs.writeFileSync)(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
551
+ (0, import_fs.renameSync)(tmpPath, configPath);
552
+ log("MCP server registered \u2192 .code_puppy/mcp_servers.json");
553
+ }
554
+ function ensureWorkspaceConfig(projectRoot) {
555
+ const workspaceDir = (0, import_path.join)(projectRoot, ".code_puppy");
556
+ const configPath = (0, import_path.join)(workspaceDir, "config.json");
557
+ if ((0, import_fs.existsSync)(workspaceDir) && (0, import_fs.lstatSync)(workspaceDir).isSymbolicLink()) {
558
+ die(".code_puppy/ is a symlink \u2014 refusing to write. Check for tampering.");
559
+ }
560
+ (0, import_fs.mkdirSync)(workspaceDir, { recursive: true });
561
+ if ((0, import_fs.existsSync)(configPath) && (0, import_fs.lstatSync)(configPath).isSymbolicLink()) {
562
+ die(".code_puppy/config.json is a symlink \u2014 refusing to write. Check for tampering.");
563
+ }
564
+ let existing = {};
565
+ if ((0, import_fs.existsSync)(configPath)) {
566
+ try {
567
+ existing = JSON.parse((0, import_fs.readFileSync)(configPath, "utf-8"));
568
+ } catch {
327
569
  }
328
570
  }
571
+ const merged = {
572
+ ...existing,
573
+ $schema: "https://stackwright.dev/schemas/workspace-config/v2.json",
574
+ profile: "strict-local"
575
+ };
329
576
  const tmpPath = `${configPath}.tmp`;
330
577
  (0, import_fs.writeFileSync)(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
331
578
  (0, import_fs.renameSync)(tmpPath, configPath);
332
- log("MCP server registered \u2192 ~/.code_puppy/mcp_servers.json");
579
+ log("Workspace config written \u2192 .code_puppy/config.json (profile: strict-local)");
333
580
  }
334
581
  function printResumeStatus(projectRoot) {
335
582
  const pipelineStatePath = (0, import_path.join)(projectRoot, ".stackwright", "pipeline-state.json");
@@ -366,6 +613,17 @@ function printResumeStatus(projectRoot) {
366
613
  } catch {
367
614
  }
368
615
  }
616
+ function isPipelineResumable(projectRoot) {
617
+ const pipelineStatePath = (0, import_path.join)(projectRoot, ".stackwright", "pipeline-state.json");
618
+ try {
619
+ const raw = (0, import_fs.readFileSync)(pipelineStatePath, "utf-8");
620
+ const state = JSON.parse(raw);
621
+ const status = state["status"];
622
+ return status === "questions" || status === "execution";
623
+ } catch {
624
+ return false;
625
+ }
626
+ }
369
627
  function resolveOtterDir(projectRoot) {
370
628
  const candidates = [
371
629
  (0, import_path.join)(projectRoot, "node_modules", "@stackwright-pro", "otters", "src"),
@@ -378,25 +636,324 @@ function resolveOtterDir(projectRoot) {
378
636
  }
379
637
  return null;
380
638
  }
639
+ function syncAgents(projectRoot, isVerbose = false) {
640
+ const agentsDir = (0, import_path.join)(projectRoot, ".code_puppy", "agents");
641
+ const otterDir = resolveOtterDir(projectRoot);
642
+ if (!otterDir) {
643
+ verbose("No otters directory found \u2014 skipping agent sync", isVerbose);
644
+ return;
645
+ }
646
+ if ((0, import_fs.existsSync)(agentsDir) && (0, import_fs.lstatSync)(agentsDir).isSymbolicLink()) {
647
+ die(".code_puppy/agents is a symlink \u2014 refusing to write. Check for tampering.");
648
+ }
649
+ (0, import_fs.mkdirSync)(agentsDir, { recursive: true });
650
+ let synced = 0;
651
+ let skipped = 0;
652
+ try {
653
+ const files = (0, import_fs.readdirSync)(otterDir);
654
+ for (const file of files) {
655
+ if (!file.endsWith("-otter.json")) continue;
656
+ const src = (0, import_path.join)(otterDir, file);
657
+ const dest = (0, import_path.join)(agentsDir, file);
658
+ if ((0, import_fs.existsSync)(dest) && (0, import_fs.lstatSync)(dest).isSymbolicLink()) {
659
+ verbose(`Skipping ${file} \u2014 dest is a symlink`, isVerbose);
660
+ skipped++;
661
+ continue;
662
+ }
663
+ const tmp = `${dest}.tmp`;
664
+ const content = (0, import_fs.readFileSync)(src);
665
+ (0, import_fs.writeFileSync)(tmp, content);
666
+ (0, import_fs.renameSync)(tmp, dest);
667
+ verbose(`Synced: ${file}`, isVerbose);
668
+ synced++;
669
+ }
670
+ } catch (err) {
671
+ const msg = err instanceof Error ? err.message : String(err);
672
+ console.warn(`\u26A0\uFE0F Agent sync partial failure: ${msg}`);
673
+ return;
674
+ }
675
+ if (synced > 0) {
676
+ log(
677
+ `Agents synced \u2192 .code_puppy/agents/ (${synced} otters${skipped > 0 ? `, ${skipped} skipped` : ""})`
678
+ );
679
+ }
680
+ }
681
+ function buildSpawnConfig(platform2, executable, binaryFd) {
682
+ const PINNED_CHILD_FD = 3;
683
+ if (platform2 === "linux") {
684
+ return {
685
+ spawnTarget: `/proc/self/fd/${PINNED_CHILD_FD}`,
686
+ stdioConfig: ["inherit", "inherit", "inherit", binaryFd]
687
+ };
688
+ }
689
+ return {
690
+ spawnTarget: executable,
691
+ stdioConfig: "inherit"
692
+ };
693
+ }
694
+
695
+ // src/dev-server.ts
696
+ var import_child_process2 = require("child_process");
697
+ var import_fs2 = require("fs");
698
+ var import_path2 = require("path");
699
+ var DevServerStartupError = class extends Error {
700
+ constructor(message, logTail, elapsedMs) {
701
+ super(message);
702
+ this.logTail = logTail;
703
+ this.elapsedMs = elapsedMs;
704
+ this.name = "DevServerStartupError";
705
+ }
706
+ };
707
+ function detectPrismConfig(projectRoot, defaultPrismUrl = "http://localhost:4010") {
708
+ try {
709
+ const pkgPath = (0, import_path2.join)(projectRoot, "package.json");
710
+ const raw = (0, import_fs2.readFileSync)(pkgPath, "utf-8");
711
+ const pkg = JSON.parse(raw);
712
+ const scripts = pkg["scripts"];
713
+ const devScript = typeof scripts?.["dev"] === "string" ? scripts["dev"] : "";
714
+ const hasConcurrently = devScript.includes("concurrently");
715
+ const hasPrism = /prism/i.test(devScript);
716
+ return { hasPrism: hasConcurrently && hasPrism, prismUrl: defaultPrismUrl };
717
+ } catch {
718
+ return { hasPrism: false, prismUrl: defaultPrismUrl };
719
+ }
720
+ }
721
+ function tailLog(logPath, maxLines) {
722
+ try {
723
+ const content = (0, import_fs2.readFileSync)(logPath, "utf-8");
724
+ const lines = content.split("\n").filter((l) => l.length > 0);
725
+ return lines.slice(-maxLines);
726
+ } catch {
727
+ return [];
728
+ }
729
+ }
730
+ function sleep(ms) {
731
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
732
+ }
733
+ async function singleFetch(url, timeoutMs) {
734
+ const controller = new AbortController();
735
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
736
+ try {
737
+ const res = await globalThis.fetch(url, { signal: controller.signal });
738
+ clearTimeout(timer);
739
+ return res.status >= 200 && res.status < 300;
740
+ } catch {
741
+ clearTimeout(timer);
742
+ return false;
743
+ }
744
+ }
745
+ async function pollUntilAllReady(urls, timeoutMs, pollIntervalMs, perRequestTimeoutMs) {
746
+ const deadline = Date.now() + timeoutMs;
747
+ while (Date.now() < deadline) {
748
+ const remaining = deadline - Date.now();
749
+ const perReq = Math.min(perRequestTimeoutMs, remaining);
750
+ const results = await Promise.all(urls.map((url) => singleFetch(url, perReq)));
751
+ if (results.every(Boolean)) return true;
752
+ const sleepMs = Math.min(pollIntervalMs, deadline - Date.now());
753
+ if (sleepMs <= 0) break;
754
+ await sleep(sleepMs);
755
+ }
756
+ return false;
757
+ }
758
+ async function killChildProcess(child, pid) {
759
+ return new Promise((resolve3) => {
760
+ let settled = false;
761
+ const settle = () => {
762
+ if (!settled) {
763
+ settled = true;
764
+ clearTimeout(escalateTimer);
765
+ resolve3();
766
+ }
767
+ };
768
+ child.once("exit", settle);
769
+ const escalateTimer = setTimeout(() => {
770
+ try {
771
+ process.kill(pid, "SIGKILL");
772
+ } catch {
773
+ }
774
+ settle();
775
+ }, 5e3);
776
+ try {
777
+ process.kill(pid, "SIGTERM");
778
+ } catch {
779
+ settle();
780
+ }
781
+ });
782
+ }
783
+ async function withDevServer(projectRoot, options, body) {
784
+ const {
785
+ timeoutMs = 6e4,
786
+ baseUrl: baseUrlOpt,
787
+ prismUrl: prismUrlOpt,
788
+ detectPrism: shouldDetectPrism = true
789
+ } = options;
790
+ const baseUrl = baseUrlOpt ?? "http://localhost:3000";
791
+ let prismUrl;
792
+ if (prismUrlOpt !== void 0) {
793
+ prismUrl = prismUrlOpt;
794
+ } else if (shouldDetectPrism) {
795
+ const cfg = detectPrismConfig(projectRoot);
796
+ prismUrl = cfg.hasPrism ? cfg.prismUrl : void 0;
797
+ }
798
+ const stackwrightDir = (0, import_path2.join)(projectRoot, ".stackwright");
799
+ (0, import_fs2.mkdirSync)(stackwrightDir, { recursive: true });
800
+ const logPath = (0, import_path2.join)(stackwrightDir, "dev-server.log");
801
+ const logFd = (0, import_fs2.openSync)(logPath, "w");
802
+ const readyFilePath = (0, import_path2.join)(stackwrightDir, "dev-server-ready.json");
803
+ const startedAt = Date.now();
804
+ let child;
805
+ let pid;
806
+ let spawnErr;
807
+ try {
808
+ child = (0, import_child_process2.spawn)("pnpm", ["dev"], {
809
+ cwd: projectRoot,
810
+ detached: false,
811
+ stdio: ["ignore", logFd, logFd]
812
+ });
813
+ pid = child.pid;
814
+ child.on("error", (err) => {
815
+ spawnErr = err;
816
+ });
817
+ if (pid === void 0) {
818
+ throw new DevServerStartupError(
819
+ "pnpm dev failed to spawn (no PID)",
820
+ tailLog(logPath, 50),
821
+ Date.now() - startedAt
822
+ );
823
+ }
824
+ const urlsToProbe = [baseUrl, ...prismUrl ? [prismUrl] : []];
825
+ const ready = await pollUntilAllReady(urlsToProbe, timeoutMs, 2e3, 1e3);
826
+ if (!ready) {
827
+ const elapsedMs = Date.now() - startedAt;
828
+ const tail = tailLog(logPath, 50);
829
+ const spawnErrMsg = spawnErr ? ` Spawn error: ${spawnErr.message}.` : "";
830
+ throw new DevServerStartupError(
831
+ `Dev server did not become ready within ${timeoutMs}ms.${spawnErrMsg}`,
832
+ tail,
833
+ elapsedMs
834
+ );
835
+ }
836
+ const info = {
837
+ pid,
838
+ baseUrl,
839
+ ...prismUrl ? { prismUrl } : {},
840
+ startedAt,
841
+ logPath
842
+ };
843
+ (0, import_fs2.writeFileSync)(
844
+ readyFilePath,
845
+ JSON.stringify({ ...info, readyAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n"
846
+ );
847
+ return await body(info);
848
+ } finally {
849
+ if (child && pid !== void 0) {
850
+ await killChildProcess(child, pid);
851
+ }
852
+ try {
853
+ (0, import_fs2.unlinkSync)(readyFilePath);
854
+ } catch {
855
+ }
856
+ try {
857
+ (0, import_fs2.closeSync)(logFd);
858
+ } catch {
859
+ }
860
+ }
861
+ }
381
862
 
382
863
  // src/index.ts
383
- function main() {
864
+ var MAX_RETRIES = 3;
865
+ var BACKOFF_INITIAL_MS = 5e3;
866
+ var BACKOFF_MAX_MS = 6e4;
867
+ function backoffMs(attempt) {
868
+ return Math.min(BACKOFF_INITIAL_MS * Math.pow(2, attempt), BACKOFF_MAX_MS);
869
+ }
870
+ async function main() {
384
871
  const args = parseArgs(process.argv);
385
872
  if (args.help) {
386
873
  printHelp();
387
874
  process.exit(0);
388
875
  }
389
- const projectRoot = (0, import_path2.resolve)(args.projectRoot);
390
- if (!(0, import_fs2.existsSync)(projectRoot)) {
876
+ const projectRoot = (0, import_path3.resolve)(args.projectRoot);
877
+ if (!(0, import_fs3.existsSync)(projectRoot)) {
391
878
  die(`Project root does not exist: ${projectRoot}`);
392
879
  }
393
- if (!(0, import_fs2.existsSync)((0, import_path2.join)(projectRoot, "package.json"))) {
880
+ if (!(0, import_fs3.existsSync)((0, import_path3.join)(projectRoot, "package.json"))) {
394
881
  die("No package.json found. Run npx @stackwright-pro/launch-stackwright-pro first.");
395
882
  }
396
883
  log("Launching Pro Otter Raft...");
397
884
  writeInitContext(projectRoot);
398
885
  verbose("Init context written", args.verbose);
886
+ try {
887
+ const stackwrightDir = (0, import_path3.join)(projectRoot, ".stackwright");
888
+ (0, import_fs3.mkdirSync)(stackwrightDir, { recursive: true });
889
+ const schemaSummary = (0, import_type_schemas.buildTypeSchemaSummary)();
890
+ (0, import_fs3.writeFileSync)(
891
+ (0, import_path3.join)(stackwrightDir, "type-schemas.json"),
892
+ JSON.stringify(schemaSummary, null, 2) + "\n"
893
+ );
894
+ verbose("Type schemas sink written", args.verbose);
895
+ } catch (err) {
896
+ console.warn("\u26A0\uFE0F Could not write type-schemas.json:", String(err));
897
+ }
898
+ {
899
+ const stackwrightDir = (0, import_path3.join)(projectRoot, ".stackwright");
900
+ const initContextPath = (0, import_path3.join)(stackwrightDir, "init-context.json");
901
+ const initRaw = (0, import_fs3.readFileSync)(initContextPath, "utf-8");
902
+ const initCtx = JSON.parse(initRaw);
903
+ if (args.nonInteractive) initCtx["nonInteractive"] = true;
904
+ if (args.devOnly) initCtx["devOnly"] = true;
905
+ if (args.parallelPhases) initCtx["parallelPhases"] = true;
906
+ initCtx["skipQa"] = args.skipQa;
907
+ initCtx["qaOnly"] = args.qaOnly;
908
+ initCtx["devServer"] = {
909
+ managed: true,
910
+ baseUrl: "http://localhost:3000",
911
+ timeoutMs: args.qaDevServerTimeoutMs
912
+ };
913
+ (0, import_fs3.writeFileSync)(initContextPath, JSON.stringify(initCtx, null, 2) + "\n", "utf-8");
914
+ verbose("Raft flags written to init-context", args.verbose);
915
+ }
916
+ {
917
+ const buildContextPath = (0, import_path3.join)(projectRoot, ".stackwright", "build-context.json");
918
+ const MAX_USE_CASE_BYTES = 1 * 1024 * 1024;
919
+ const WARN_USE_CASE_BYTES = 200 * 1024;
920
+ if (args.useCasePath) {
921
+ const resolvedPath = (0, import_path3.resolve)(args.useCasePath);
922
+ if (!(0, import_fs3.existsSync)(resolvedPath)) {
923
+ die(`Use-case file not found: ${resolvedPath}`);
924
+ }
925
+ const content = (0, import_fs3.readFileSync)(resolvedPath, "utf-8");
926
+ if (content.length > MAX_USE_CASE_BYTES) {
927
+ die(
928
+ `Use-case file exceeds ${(MAX_USE_CASE_BYTES / 1024 / 1024).toFixed(0)}MB (got ${(content.length / 1024).toFixed(0)}KB). Trim the file or split into sections.`
929
+ );
930
+ }
931
+ if (content.length > WARN_USE_CASE_BYTES) {
932
+ console.warn(
933
+ `\u26A0\uFE0F Large use-case file (${(content.length / 1024).toFixed(0)}KB) \u2014 specialist otters will receive the full context via build prompts.`
934
+ );
935
+ }
936
+ const payload = {
937
+ version: "1.0",
938
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
939
+ buildContext: content
940
+ };
941
+ (0, import_fs3.writeFileSync)(buildContextPath, JSON.stringify(payload, null, 2) + "\n", "utf-8");
942
+ log(`Build context seeded from ${args.useCasePath}`);
943
+ } else if (args.nonInteractive && !(0, import_fs3.existsSync)(buildContextPath)) {
944
+ const payload = {
945
+ version: "1.0",
946
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
947
+ buildContext: "Build a sample application from the available API specs and data sources with default settings. Use all available endpoints and standard page layouts."
948
+ };
949
+ (0, import_fs3.writeFileSync)(buildContextPath, JSON.stringify(payload, null, 2) + "\n", "utf-8");
950
+ log("Build context seeded with generic defaults (--non-interactive, no --use-case)");
951
+ }
952
+ }
953
+ migrateWorkspaceDir(projectRoot);
954
+ ensureWorkspaceConfig(projectRoot);
399
955
  ensureMcpConfig(projectRoot);
956
+ syncAgents(projectRoot, args.verbose);
400
957
  const otterDir = resolveOtterDir(projectRoot);
401
958
  if (!otterDir) {
402
959
  die(
@@ -417,36 +974,107 @@ function main() {
417
974
  log(`\u2705 All ${result.verified.length} otters verified`);
418
975
  }
419
976
  printResumeStatus(projectRoot);
420
- const executable = findCodePuppy();
977
+ const { path: executable, fd: initialFd } = findCodePuppy();
421
978
  verbose(`Resolved raft-puppy / code-puppy: ${executable}`, args.verbose);
979
+ try {
980
+ (0, import_fs3.closeSync)(initialFd);
981
+ } catch {
982
+ }
983
+ validateBinaryVersion(executable);
984
+ if (args.qaOnly) {
985
+ log("--qa-only mode: skipping otter pipeline, spawning dev server for visual QA...");
986
+ await withDevServer(projectRoot, { timeoutMs: args.qaDevServerTimeoutMs }, async (info) => {
987
+ log("--qa-only: dev server ready \u2705");
988
+ log(` pid: ${info.pid}`);
989
+ log(` baseUrl: ${info.baseUrl}`);
990
+ if (info.prismUrl) log(` prismUrl: ${info.prismUrl}`);
991
+ log(` logPath: ${info.logPath}`);
992
+ log("\u23F8 QA otter invocation not yet implemented (blocked on swp-wde8 + swp-kjkg)");
993
+ });
994
+ process.exit(0);
995
+ }
422
996
  log("Spawning raft-puppy / code-puppy raft session...");
423
- const spawnArgs = ["Begin", "--interactive", "--agent", "stackwright-pro-foreman-otter"];
424
- verbose(`cmd: ${executable} ${spawnArgs.join(" ")}`, args.verbose);
425
- const child = (0, import_child_process2.spawn)(executable, spawnArgs, {
426
- stdio: "inherit",
427
- cwd: projectRoot,
428
- env: {
429
- ...process.env,
430
- STACKWRIGHT_PROJECT_ROOT: projectRoot
997
+ let retryCount = 0;
998
+ let userInterrupted = false;
999
+ function spawnSession(isResume) {
1000
+ const { path: resolvedBinary, fd: binaryFd } = findCodePuppy();
1001
+ if (process.platform !== "linux") {
1002
+ verbose(
1003
+ `macOS/other: spawning via path (residual TOCTOU \u2014 /proc unavailable). See GH#128 for threat model documentation.`,
1004
+ args.verbose
1005
+ );
431
1006
  }
432
- });
433
- const forward = (signal) => {
434
- if (child.pid) child.kill(signal);
435
- };
436
- const onSigint = () => forward("SIGINT");
437
- const onSigterm = () => forward("SIGTERM");
438
- process.on("SIGINT", onSigint);
439
- process.on("SIGTERM", onSigterm);
440
- child.on("error", (err) => die(`Failed to spawn raft-puppy / code-puppy: ${err.message}`));
441
- child.on("close", (code, signal) => {
442
- process.off("SIGINT", onSigint);
443
- process.off("SIGTERM", onSigterm);
444
- if (signal) {
445
- process.kill(process.pid, signal);
446
- } else {
447
- process.exit(code ?? 1);
1007
+ const prompt = isResume ? "Resume" : "Begin";
1008
+ const spawnArgs = [prompt, "--interactive", "--agent", "stackwright-pro-foreman-otter"];
1009
+ const { spawnTarget, stdioConfig } = buildSpawnConfig(
1010
+ process.platform,
1011
+ resolvedBinary,
1012
+ binaryFd
1013
+ );
1014
+ verbose(
1015
+ `cmd: ${spawnTarget} ${spawnArgs.join(" ")}${spawnTarget !== resolvedBinary ? ` (real: ${resolvedBinary})` : ""}${isResume ? ` [retry ${retryCount}/${MAX_RETRIES}]` : ""}`,
1016
+ args.verbose
1017
+ );
1018
+ const child = (0, import_child_process3.spawn)(spawnTarget, spawnArgs, {
1019
+ stdio: stdioConfig,
1020
+ cwd: projectRoot,
1021
+ env: buildCodePuppyEnv(buildLauncherEnvOverrides(projectRoot), args.passEnvKeys)
1022
+ });
1023
+ try {
1024
+ (0, import_fs3.closeSync)(binaryFd);
1025
+ } catch {
448
1026
  }
449
- });
1027
+ const forward = (signal) => {
1028
+ if (child.pid) child.kill(signal);
1029
+ };
1030
+ const onSigint = () => {
1031
+ userInterrupted = true;
1032
+ forward("SIGINT");
1033
+ };
1034
+ const onSigterm = () => {
1035
+ userInterrupted = true;
1036
+ forward("SIGTERM");
1037
+ };
1038
+ process.on("SIGINT", onSigint);
1039
+ process.on("SIGTERM", onSigterm);
1040
+ child.on("error", (err) => die(`Failed to spawn raft-puppy / code-puppy: ${err.message}`));
1041
+ child.on("close", (code, signal) => {
1042
+ process.off("SIGINT", onSigint);
1043
+ process.off("SIGTERM", onSigterm);
1044
+ if (signal) {
1045
+ process.kill(process.pid, signal);
1046
+ return;
1047
+ }
1048
+ if (code === 0 || userInterrupted) {
1049
+ process.exit(code ?? 0);
1050
+ return;
1051
+ }
1052
+ if (retryCount < MAX_RETRIES && isPipelineResumable(projectRoot)) {
1053
+ retryCount++;
1054
+ const delay = backoffMs(retryCount - 1);
1055
+ log(
1056
+ `\u26A0\uFE0F Raft session exited unexpectedly (code ${code ?? "?"}). Pipeline is mid-run \u2014 retrying in ${delay / 1e3}s\u2026 (attempt ${retryCount}/${MAX_RETRIES})`
1057
+ );
1058
+ setTimeout(() => spawnSession(true), delay);
1059
+ } else {
1060
+ if (retryCount >= MAX_RETRIES) {
1061
+ log(`\u274C Max retries (${MAX_RETRIES}) reached \u2014 giving up. Check logs above for errors.`);
1062
+ }
1063
+ process.exit(code ?? 1);
1064
+ }
1065
+ });
1066
+ }
1067
+ if (args.skipQa) {
1068
+ log("\u26A0\uFE0F Visual QA skipped by --skip-qa flag");
1069
+ } else {
1070
+ log(
1071
+ "\u23F8 Visual QA stub \u2014 dev server lifecycle is wired, QA otter invocation lands in swp-wde8/swp-kjkg"
1072
+ );
1073
+ }
1074
+ spawnSession(false);
450
1075
  }
451
- main();
1076
+ main().catch((err) => {
1077
+ const msg = err instanceof Error ? err.message : String(err);
1078
+ die(`Unexpected fatal error: ${msg}`);
1079
+ });
452
1080
  //# sourceMappingURL=index.js.map