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

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