@stackwright-pro/mcp 0.2.0-alpha.3 → 0.2.0-alpha.30

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/server.mjs CHANGED
@@ -3,15 +3,44 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
 
5
5
  // src/tools/data-explorer.ts
6
- import { z } from "zod";
6
+ import { z as z2 } from "zod";
7
7
  import { listEntities, generateFilter } from "@stackwright-pro/cli-data-explorer";
8
+
9
+ // src/coerce.ts
10
+ import { z } from "zod";
11
+ function jsonCoerce(schema) {
12
+ return z.preprocess((v) => {
13
+ if (typeof v === "string") {
14
+ try {
15
+ return JSON.parse(v);
16
+ } catch {
17
+ return v;
18
+ }
19
+ }
20
+ return v;
21
+ }, schema);
22
+ }
23
+ function boolCoerce(schema) {
24
+ return z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
25
+ }
26
+ function numCoerce(schema) {
27
+ return z.preprocess((v) => {
28
+ if (typeof v === "string" && v.trim() !== "") {
29
+ const n = Number(v);
30
+ if (!Number.isNaN(n)) return n;
31
+ }
32
+ return v;
33
+ }, schema);
34
+ }
35
+
36
+ // src/tools/data-explorer.ts
8
37
  function registerDataExplorerTools(server2) {
9
38
  server2.tool(
10
39
  "stackwright_pro_list_entities",
11
40
  "List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
12
41
  {
13
- specPath: z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
14
- projectRoot: z.string().optional().describe("Project root directory (auto-detected if omitted)")
42
+ specPath: z2.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
43
+ projectRoot: z2.string().optional().describe("Project root directory (auto-detected if omitted)")
15
44
  },
16
45
  async ({ specPath, projectRoot }) => {
17
46
  const result = listEntities({
@@ -59,9 +88,13 @@ function registerDataExplorerTools(server2) {
59
88
  "stackwright_pro_generate_filter",
60
89
  "Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
61
90
  {
62
- selectedEntities: z.array(z.string()).describe('Entity slugs to include (e.g., ["equipment", "supplies"])'),
63
- excludePatterns: z.array(z.string()).optional().describe('Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'),
64
- projectRoot: z.string().optional().describe("Project root directory")
91
+ selectedEntities: jsonCoerce(z2.array(z2.string())).describe(
92
+ 'Entity slugs to include (e.g., ["equipment", "supplies"])'
93
+ ),
94
+ excludePatterns: jsonCoerce(z2.array(z2.string()).optional()).describe(
95
+ 'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
96
+ ),
97
+ projectRoot: z2.string().optional().describe("Project root directory")
65
98
  },
66
99
  async ({ selectedEntities, excludePatterns, projectRoot }) => {
67
100
  const result = generateFilter({
@@ -117,7 +150,7 @@ function registerDataExplorerTools(server2) {
117
150
  }
118
151
 
119
152
  // src/tools/security.ts
120
- import { z as z2 } from "zod";
153
+ import { z as z3 } from "zod";
121
154
  import { createHash } from "crypto";
122
155
  import fs from "fs";
123
156
  import path from "path";
@@ -126,8 +159,8 @@ function registerSecurityTools(server2) {
126
159
  "stackwright_pro_validate_spec",
127
160
  "Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
128
161
  {
129
- specPath: z2.string().describe("URL or file path to the OpenAPI spec to validate"),
130
- configPath: z2.string().optional().describe("Path to stackwright.yml with prebuild.security config")
162
+ specPath: z3.string().describe("URL or file path to the OpenAPI spec to validate"),
163
+ configPath: z3.string().optional().describe("Path to stackwright.yml with prebuild.security config")
131
164
  },
132
165
  async ({ specPath, configPath }) => {
133
166
  let securityEnabled = false;
@@ -235,16 +268,15 @@ Status: Valid (${allowlist.length} specs on allowlist)`
235
268
  "stackwright_pro_add_approved_spec",
236
269
  "Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
237
270
  {
238
- name: z2.string().describe("Human-readable name for the spec"),
239
- url: z2.string().describe("URL or file path to the OpenAPI spec"),
240
- configPath: z2.string().optional().describe("Path to stackwright.yml")
271
+ name: z3.string().describe("Human-readable name for the spec"),
272
+ url: z3.string().describe("URL or file path to the OpenAPI spec"),
273
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
241
274
  },
242
275
  async ({ name, url, configPath }) => {
243
276
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
244
277
  let sha256 = "<computed-at-build>";
245
278
  try {
246
279
  if (url.startsWith("http://") || url.startsWith("https://")) {
247
- sha256 = "<computed-at-build>";
248
280
  } else if (fs.existsSync(url)) {
249
281
  const specContent = fs.readFileSync(url, "utf8");
250
282
  sha256 = createHash("sha256").update(specContent).digest("hex");
@@ -291,7 +323,7 @@ SHA-256 computed: ${sha256}`
291
323
  "stackwright_pro_list_approved_specs",
292
324
  "List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
293
325
  {
294
- configPath: z2.string().optional().describe("Path to stackwright.yml")
326
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
295
327
  },
296
328
  async ({ configPath }) => {
297
329
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
@@ -360,16 +392,18 @@ SHA-256 computed: ${sha256}`
360
392
  }
361
393
 
362
394
  // src/tools/isr.ts
363
- import { z as z3 } from "zod";
395
+ import { z as z4 } from "zod";
364
396
  function registerIsrTools(server2) {
365
397
  server2.tool(
366
398
  "stackwright_pro_configure_isr",
367
399
  "Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
368
400
  {
369
- collection: z3.string().describe('Collection name (e.g., "equipment", "supplies")'),
370
- revalidateSeconds: z3.number().optional().describe("Revalidation interval in seconds (default: 60)"),
371
- fallback: z3.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
372
- configPath: z3.string().optional().describe("Path to stackwright.yml")
401
+ collection: z4.string().describe('Collection name (e.g., "equipment", "supplies")'),
402
+ revalidateSeconds: numCoerce(z4.number().optional()).describe(
403
+ "Revalidation interval in seconds (default: 60)"
404
+ ),
405
+ fallback: z4.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
406
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
373
407
  },
374
408
  async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
375
409
  const revalidate = revalidateSeconds;
@@ -380,7 +414,7 @@ function registerIsrTools(server2) {
380
414
  isr:
381
415
  revalidate: ${revalidate}
382
416
  fallback: ${fallback}`;
383
- let description = "";
417
+ let description;
384
418
  if (revalidate < 60) {
385
419
  description = "\u26A1 Very fresh data (revalidate every " + revalidate + "s)";
386
420
  } else if (revalidate < 300) {
@@ -412,14 +446,16 @@ ${yamlSnippet}
412
446
  "stackwright_pro_configure_isr_batch",
413
447
  "Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
414
448
  {
415
- collections: z3.array(
416
- z3.object({
417
- name: z3.string().describe("Collection name"),
418
- revalidateSeconds: z3.number().optional().describe("Revalidation interval")
419
- })
449
+ collections: jsonCoerce(
450
+ z4.array(
451
+ z4.object({
452
+ name: z4.string().describe("Collection name"),
453
+ revalidateSeconds: numCoerce(z4.number().optional()).describe("Revalidation interval")
454
+ })
455
+ )
420
456
  ).describe("Array of collection configurations"),
421
- defaultFallback: z3.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
422
- configPath: z3.string().optional().describe("Path to stackwright.yml")
457
+ defaultFallback: z4.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
458
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
423
459
  },
424
460
  async ({ collections, defaultFallback = "blocking", configPath }) => {
425
461
  const lines = [`\u2699\uFE0F Batch ISR Configuration:
@@ -447,17 +483,17 @@ Fallback: ${defaultFallback}`);
447
483
  }
448
484
 
449
485
  // src/tools/dashboard.ts
450
- import { z as z4 } from "zod";
486
+ import { z as z5 } from "zod";
451
487
  import { listEntities as listEntities2 } from "@stackwright-pro/cli-data-explorer";
452
488
  function registerDashboardTools(server2) {
453
489
  server2.tool(
454
490
  "stackwright_pro_generate_dashboard",
455
491
  "Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
456
492
  {
457
- entities: z4.array(z4.string()).describe("Entity slugs to include in dashboard"),
458
- layout: z4.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
459
- pageTitle: z4.string().optional().describe("Page title"),
460
- specPath: z4.string().optional().describe("Path to OpenAPI spec for entity details")
493
+ entities: jsonCoerce(z5.array(z5.string())).describe("Entity slugs to include in dashboard"),
494
+ layout: z5.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
495
+ pageTitle: z5.string().optional().describe("Page title"),
496
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for entity details")
461
497
  },
462
498
  async ({ entities, layout = "mixed", pageTitle, specPath }) => {
463
499
  let entityDetails = [];
@@ -543,9 +579,9 @@ ${yaml}
543
579
  "stackwright_pro_generate_detail_page",
544
580
  "Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
545
581
  {
546
- entity: z4.string().describe('Entity slug (e.g., "equipment")'),
547
- slugField: z4.string().optional().describe('Field to use as URL slug (default: "id")'),
548
- specPath: z4.string().optional().describe("Path to OpenAPI spec for field details")
582
+ entity: z5.string().describe('Entity slug (e.g., "equipment")'),
583
+ slugField: z5.string().optional().describe('Field to use as URL slug (default: "id")'),
584
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for field details")
549
585
  },
550
586
  async ({ entity, slugField = "id", specPath }) => {
551
587
  let fields = [];
@@ -621,298 +657,170 @@ ${yaml}
621
657
  }
622
658
 
623
659
  // src/tools/clarification.ts
624
- import { z as z5 } from "zod";
625
- import { spawn } from "child_process";
626
- import { tmpdir } from "os";
627
- import { join } from "path";
628
- import { randomUUID } from "crypto";
629
- import { existsSync, unlinkSync } from "fs";
630
- var activeServers = /* @__PURE__ */ new Map();
631
- async function startPythonServer(sessionId) {
632
- const socketPath = join(tmpdir(), `otter-raft-${randomUUID()}.sock`);
633
- const port = 8765 + Math.floor(Math.random() * 100);
634
- return new Promise((resolve, reject) => {
635
- const pythonPath = process.platform === "win32" ? "python" : "python3";
636
- const packageRoot = findPythonPackageRoot();
637
- const proc = spawn(
638
- pythonPath,
639
- ["-m", "stackwright_pro.raft.server", "--socket", socketPath, "--port", String(port)],
640
- {
641
- stdio: ["pipe", "pipe", "pipe"],
642
- env: {
643
- ...process.env,
644
- PYTHONPATH: packageRoot
645
- }
646
- }
647
- );
648
- activeServers.set(sessionId, proc);
649
- let startupOutput = "";
650
- let started = false;
651
- proc.stdout?.on("data", (data) => {
652
- startupOutput += data.toString();
653
- if (startupOutput.includes("Server ready") || startupOutput.includes("HTTP server")) {
654
- started = true;
655
- resolve({ port, socketPath });
656
- }
657
- });
658
- proc.stderr?.on("data", (data) => {
659
- if (!startupOutput.includes("Starting")) {
660
- console.error("[Python Clarification]", data.toString().trim());
661
- }
662
- });
663
- proc.on("error", (err) => {
664
- if (!started) {
665
- activeServers.delete(sessionId);
666
- reject(new Error(`Failed to start Python server: ${err.message}`));
667
- }
668
- });
669
- proc.on("exit", (code) => {
670
- activeServers.delete(sessionId);
671
- if (existsSync(socketPath)) {
672
- try {
673
- unlinkSync(socketPath);
674
- } catch {
675
- }
676
- }
677
- });
678
- setTimeout(() => {
679
- if (!started) {
680
- proc.kill();
681
- activeServers.delete(sessionId);
682
- reject(new Error("Python server startup timeout"));
683
- }
684
- }, 1e4);
685
- });
686
- }
687
- async function stopPythonServer(sessionId) {
688
- const proc = activeServers.get(sessionId);
689
- if (proc) {
690
- proc.kill("SIGTERM");
691
- activeServers.delete(sessionId);
692
- }
693
- }
694
- async function httpRequest(host, port, path3, body) {
695
- const http = await import("http");
696
- return new Promise((resolve, reject) => {
697
- const url = new URL(path3, `http://${host}:${port}`);
698
- const reqOptions = {
699
- hostname: host,
700
- port,
701
- path: url.pathname,
702
- method: body ? "POST" : "GET",
703
- headers: {
704
- "Content-Type": "application/json"
705
- }
660
+ import { z as z6 } from "zod";
661
+ var CONTRADICTION_PATTERNS = [
662
+ {
663
+ keywords: ["minimal", "clean", "simple"],
664
+ conflicts: ["vibrant", "rich", "content-heavy", "playful"]
665
+ },
666
+ {
667
+ keywords: ["dark", "dark mode"],
668
+ conflicts: ["light mode only", "light"]
669
+ },
670
+ {
671
+ keywords: ["enterprise", "professional", "corporate"],
672
+ conflicts: ["playful", "casual", "fun"]
673
+ },
674
+ {
675
+ keywords: ["accessible", "wcag", "section 508"],
676
+ conflicts: ["compact", "dense", "small text"]
677
+ },
678
+ {
679
+ keywords: ["government", "defense", "federal"],
680
+ conflicts: ["public", "no auth", "consumer"]
681
+ }
682
+ ];
683
+ function handleClarify(input) {
684
+ const { question_type, question, choices, priority, target_field, context } = input;
685
+ const base = {
686
+ action: "ask_user",
687
+ targetField: target_field
688
+ };
689
+ if (question_type === "closed_choice" && choices && choices.length > 0) {
690
+ const header = truncateHeader(question);
691
+ base.adaptedQuestion = {
692
+ question,
693
+ header,
694
+ options: choices.map((c) => ({ label: c }))
706
695
  };
707
- const req = http.request(reqOptions, (res) => {
708
- let data = "";
709
- res.on("data", (chunk) => {
710
- data += chunk.toString();
711
- });
712
- res.on("end", () => {
713
- try {
714
- const parsed = JSON.parse(data);
715
- if (res.statusCode && res.statusCode >= 400) {
716
- reject(new Error(parsed.detail || parsed.error || `HTTP ${res.statusCode}`));
717
- } else {
718
- resolve(parsed);
719
- }
720
- } catch (e) {
721
- reject(new Error(`Failed to parse response: ${data}`));
722
- }
723
- });
724
- });
725
- req.on("error", reject);
726
- if (body) {
727
- req.write(JSON.stringify(body));
728
- }
729
- req.end();
730
- });
696
+ } else {
697
+ const contextPrefix = context ? `Context: ${context}
698
+
699
+ ` : "";
700
+ base.prompt = `${contextPrefix}${question}`;
701
+ }
702
+ if (priority === "optional") {
703
+ base.suggestedDefault = inferDefault(question_type, choices);
704
+ }
705
+ return base;
731
706
  }
732
- function findPythonPackageRoot() {
733
- const candidates = [
734
- join(__dirname, "../../python/src"),
735
- join(__dirname, "../../../python/src"),
736
- join(process.cwd(), "python/src")
737
- ];
738
- for (const candidate of candidates) {
739
- if (existsSync(candidate)) {
740
- return candidate;
707
+ function handleDetectConflict(input) {
708
+ const preferenceLower = input.stated_preference.toLowerCase();
709
+ const valuesLower = Object.values(input.selected_values).map((v) => v.toLowerCase());
710
+ for (const pattern of CONTRADICTION_PATTERNS) {
711
+ const preferenceMatch = pattern.keywords.some((kw) => preferenceLower.includes(kw));
712
+ if (!preferenceMatch) continue;
713
+ const conflictingValues = valuesLower.filter(
714
+ (val) => pattern.conflicts.some((c) => val.includes(c))
715
+ );
716
+ if (conflictingValues.length > 0) {
717
+ const matchedKeywords = pattern.keywords.filter((kw) => preferenceLower.includes(kw));
718
+ const primaryKeyword = matchedKeywords[0] ?? "preference";
719
+ return {
720
+ conflict: true,
721
+ description: `Stated preference includes "${matchedKeywords.join(", ")}" but selections contain "${conflictingValues.join(", ")}" \u2014 these are contradictory.`,
722
+ resolution_options: [
723
+ `Align selections with the "${primaryKeyword}" preference`,
724
+ `Revise stated preference to match current selections`,
725
+ "Ask user which direction they actually want"
726
+ ]
727
+ };
741
728
  }
742
729
  }
743
- return process.cwd();
730
+ return { conflict: false };
731
+ }
732
+ function truncateHeader(text) {
733
+ const MAX = 50;
734
+ if (text.length <= MAX) return text;
735
+ return text.slice(0, MAX - 1) + "\u2026";
736
+ }
737
+ function inferDefault(questionType, choices) {
738
+ if (questionType === "closed_choice" && choices && choices.length > 0) {
739
+ return choices[0] ?? "(first choice)";
740
+ }
741
+ return "(use sensible project default)";
744
742
  }
745
743
  function registerClarificationTools(server2) {
746
744
  server2.tool(
747
745
  "stackwright_pro_clarify",
748
- "Ask the user for clarification when an otter encounters ambiguity. This is for MID-EXECUTION questions, not upfront question collection. Use this when the otter needs user input to proceed. Returns the user's decision which should be used to continue execution.",
746
+ "Ask the user for clarification when a specialist otter encounters ambiguity. This is for MID-EXECUTION questions, NOT upfront question collection (use the Question Manifest Protocol for that). Returns a structured response for the foreman to present to the user via ask_user_question (closed_choice) or directly (open_text).",
749
747
  {
750
- context: z5.string().optional().describe("Context about what the otter is trying to do"),
751
- question_type: z5.enum(["closed_choice", "open_text", "conditional", "multi_step", "reconciliation"]).describe("Type of question being asked"),
752
- question: z5.string().describe("The clarification question to ask the user"),
753
- choices: z5.array(z5.string()).optional().describe("Options for closed_choice or multi_step questions"),
754
- priority: z5.enum(["blocking", "preferred", "optional"]).optional().describe("How critical is this clarification? Default: preferred"),
755
- target_field: z5.string().optional().describe("What field/config does this clarify?")
748
+ context: z6.string().optional().describe("Context about what the otter is trying to do"),
749
+ question_type: z6.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
750
+ question: z6.string().describe("The clarification question to ask the user"),
751
+ choices: jsonCoerce(z6.array(z6.string()).optional()).describe(
752
+ "Options for closed_choice questions"
753
+ ),
754
+ priority: z6.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
755
+ target_field: z6.string().optional().describe("What field/config does this clarify?")
756
756
  },
757
- async ({ context, question_type, question, choices, priority = "preferred", target_field }) => {
758
- const sessionId = `mcp_${randomUUID().slice(0, 8)}`;
759
- try {
760
- const { port } = await startPythonServer(sessionId);
761
- await httpRequest(port === 8765 ? "127.0.0.1" : "127.0.0.1", port, "/sessions", {});
762
- if (context) {
763
- await httpRequest(
764
- port === 8765 ? "127.0.0.1" : "127.0.0.1",
765
- port,
766
- `/sessions/${sessionId}/context`,
767
- { context: { purpose: context } }
768
- );
769
- }
770
- const request = {
771
- ...context !== void 0 && { context },
772
- question_type,
773
- question,
774
- ...choices !== void 0 && { choices },
775
- priority,
776
- ...target_field !== void 0 && { target_field }
777
- };
778
- const response = await httpRequest(
779
- port === 8765 ? "127.0.0.1" : "127.0.0.1",
780
- port,
781
- "/clarify",
782
- { request }
783
- );
784
- await stopPythonServer(sessionId);
785
- const decision = response.decision;
786
- const value = decision.value;
787
- const source = decision.source;
788
- const explicit = decision.explicit ? "explicitly" : "via fallback";
789
- if (response.fallback_used) {
790
- return {
791
- content: [
792
- {
793
- type: "text",
794
- text: `\u26A0\uFE0F Clarification fallback used: ${response.fallback_reason || "No user input available"}
795
-
796
- Default value used: ${JSON.stringify(value)}
797
-
798
- \u{1F4A1} Consider following up with the user later if this default isn't appropriate.`
799
- }
800
- ]
801
- };
802
- }
803
- return {
804
- content: [
805
- {
806
- type: "text",
807
- text: `\u2705 User clarified (${source}): ${JSON.stringify(value)}
808
-
809
- Use this value to continue execution.`
810
- }
811
- ]
812
- };
813
- } catch (error) {
814
- await stopPythonServer(sessionId);
815
- return {
816
- content: [
817
- {
818
- type: "text",
819
- text: `\u274C Clarification failed: ${error instanceof Error ? error.message : "Unknown error"}
820
-
821
- Cannot proceed without user input. Consider:
822
- 1. Using a reasonable default
823
- 2. Asking the user directly in your response
824
- 3. Skipping this step if optional`
825
- }
826
- ],
827
- isError: true
828
- };
829
- }
757
+ async ({ context, question_type, question, choices, priority, target_field }) => {
758
+ const result = handleClarify({
759
+ context: context ?? void 0,
760
+ question_type,
761
+ question,
762
+ choices: choices ?? void 0,
763
+ priority: priority ?? "preferred",
764
+ target_field: target_field ?? void 0
765
+ });
766
+ return {
767
+ content: [
768
+ {
769
+ type: "text",
770
+ text: `\u{1F9A6} Clarification needed${target_field ? ` for "${target_field}"` : ""}. Present the following to the user. ` + (result.adaptedQuestion ? "Pass the adaptedQuestion to ask_user_question directly." : "Ask the user the prompt below.")
771
+ },
772
+ {
773
+ type: "text",
774
+ text: JSON.stringify(result)
775
+ }
776
+ ]
777
+ };
830
778
  }
831
779
  );
832
780
  server2.tool(
833
781
  "stackwright_pro_detect_conflict",
834
- "Detect when a user's stated preference conflicts with their selected choices. Use this to identify when users might be indecisive or misunderstood a question. Returns conflict details and resolution options.",
782
+ "Detect when a user's stated preference conflicts with their selected choices. Uses keyword heuristics against known contradiction patterns (minimal vs vibrant, dark vs light, etc). Returns conflict details and resolution options.",
835
783
  {
836
- stated_preference: z5.string().describe("What the user said they wanted"),
837
- selected_values: z5.record(z5.string(), z5.string()).describe("What the user actually selected")
784
+ stated_preference: z6.string().describe("What the user said they wanted"),
785
+ selected_values: jsonCoerce(z6.record(z6.string(), z6.string())).describe(
786
+ "What the user actually selected (field \u2192 value)"
787
+ )
838
788
  },
839
789
  async ({ stated_preference, selected_values }) => {
840
- const sessionId = `mcp_${randomUUID().slice(0, 8)}`;
841
- try {
842
- const { port } = await startPythonServer(sessionId);
843
- const response = await httpRequest(
844
- port === 8765 ? "127.0.0.1" : "127.0.0.1",
845
- port,
846
- "/conflict",
847
- { stated_preference, selected_values }
848
- );
849
- await stopPythonServer(sessionId);
850
- if (response.conflict) {
851
- const data = response.data;
852
- return {
853
- content: [
854
- {
855
- type: "text",
856
- text: `\u26A0\uFE0F CONFLICT DETECTED
790
+ const result = handleDetectConflict({ stated_preference, selected_values });
791
+ if (result.conflict) {
792
+ return {
793
+ content: [
794
+ {
795
+ type: "text",
796
+ text: `\u26A0\uFE0F CONFLICT DETECTED
857
797
 
858
798
  User stated: "${stated_preference}"
859
799
  But selected: ${JSON.stringify(selected_values)}
860
800
 
861
- Conflict: ${data.description}
801
+ ${result.description}
862
802
 
863
- Resolution options: ${data.options?.join(", ") || "Ask user to clarify"}
803
+ Resolution options:
804
+ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
864
805
 
865
806
  \u{1F4A1} Consider asking the user to reconcile this conflict.`
866
- }
867
- ]
868
- };
869
- }
870
- return {
871
- content: [
807
+ },
872
808
  {
873
809
  type: "text",
874
- text: `\u2705 No conflict detected between stated preference and selections.`
810
+ text: JSON.stringify(result)
875
811
  }
876
812
  ]
877
813
  };
878
- } catch (error) {
879
- await stopPythonServer(sessionId);
880
- return {
881
- content: [
882
- {
883
- type: "text",
884
- text: `\u274C Conflict detection failed: ${error instanceof Error ? error.message : "Unknown error"}`
885
- }
886
- ],
887
- isError: true
888
- };
889
814
  }
890
- }
891
- );
892
- server2.tool(
893
- "stackwright_pro_get_defaults",
894
- "Get the current clarification defaults from config. Use this to understand what fallback values will be used if user doesn't provide input.",
895
- {
896
- config_path: z5.string().optional().describe("Path to config file. Default: .stackwright/clarification.yaml")
897
- },
898
- async ({ config_path }) => {
899
815
  return {
900
816
  content: [
901
817
  {
902
818
  type: "text",
903
- text: `\u{1F4CB} Clarification defaults
904
-
905
- Configuration is loaded from:
906
- - Environment: CLARIFICATION_* variables
907
- - Config file: ${config_path || ".stackwright/clarification.yaml"}
908
- - CLI args: --clarify-* flags
909
-
910
- Default behaviors:
911
- - allow_dont_know: true (users can skip)
912
- - default_timeout: 120 seconds
913
- - channel_priority: [tui, cli_args, config, defaults]
914
-
915
- \u{1F4A1} Set CLARIFICATION_DEFAULT_<FIELD>=value to change defaults.`
819
+ text: "\u2705 No conflict detected between stated preference and selections."
820
+ },
821
+ {
822
+ type: "text",
823
+ text: JSON.stringify(result)
916
824
  }
917
825
  ]
918
826
  };
@@ -921,31 +829,53 @@ Default behaviors:
921
829
  }
922
830
 
923
831
  // src/tools/packages.ts
924
- import { z as z6 } from "zod";
925
- import { readFileSync, writeFileSync, existsSync as existsSync2, realpathSync, lstatSync } from "fs";
832
+ import { z as z7 } from "zod";
833
+ import { readFileSync, writeFileSync, existsSync, realpathSync, lstatSync } from "fs";
926
834
  import { execSync } from "child_process";
927
835
  import path2 from "path";
836
+ var BASELINE_DEPS = {
837
+ "@stackwright-pro/mcp": "latest",
838
+ "@stackwright-pro/otters": "latest",
839
+ "@stackwright-pro/openapi": "latest",
840
+ "@stackwright-pro/auth": "latest",
841
+ "@stackwright-pro/auth-nextjs": "latest",
842
+ zod: "^3.23.0"
843
+ };
844
+ var BASELINE_DEV_DEPS = {
845
+ "@stoplight/prism-cli": "^5.14.2"
846
+ };
928
847
  function registerPackageTools(server2) {
929
848
  server2.tool(
930
849
  "stackwright_pro_setup_packages",
931
- "Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run.",
850
+ "Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run. Pass includeBaseline: true to automatically include all required @stackwright-pro/* baseline dependencies. Safe to call on existing projects \u2014 never overwrites pinned versions.",
932
851
  {
933
852
  // FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
934
- packages: z6.record(z6.string(), z6.string()).describe(
935
- 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
853
+ packages: jsonCoerce(z7.record(z7.string(), z7.string()).optional().default({})).describe(
854
+ 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
855
+ ),
856
+ devPackages: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
857
+ "devDependencies to add. Same format as packages."
858
+ ),
859
+ scripts: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
860
+ "npm scripts to add. Only adds if key does not already exist."
936
861
  ),
937
- devPackages: z6.record(z6.string(), z6.string()).optional().describe("devDependencies to add. Same format as packages."),
938
- scripts: z6.record(z6.string(), z6.string()).optional().describe("npm scripts to add. Only adds if key does not already exist."),
939
- targetDir: z6.string().optional().describe(
862
+ targetDir: z7.string().optional().describe(
940
863
  "Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
941
864
  ),
942
- runInstall: z6.boolean().optional().default(true).describe("Run pnpm install after writing package.json. Defaults to true.")
865
+ runInstall: boolCoerce(z7.boolean().optional().default(true)).describe(
866
+ "Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
867
+ ),
868
+ includeBaseline: boolCoerce(z7.boolean().optional().default(false)).describe(
869
+ "When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions. Pass boolean true/false."
870
+ )
943
871
  },
944
- async ({ packages, devPackages, scripts, targetDir, runInstall }) => {
872
+ async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
873
+ const mergedPackages = includeBaseline ? { ...BASELINE_DEPS, ...packages } : { ...packages };
874
+ const mergedDevPackages = includeBaseline ? { ...BASELINE_DEV_DEPS, ...devPackages ?? {} } : devPackages;
945
875
  const result = setupPackages({
946
- packages,
876
+ packages: mergedPackages,
947
877
  runInstall,
948
- ...devPackages !== void 0 ? { devPackages } : {},
878
+ ...mergedDevPackages !== void 0 ? { devPackages: mergedDevPackages } : {},
949
879
  ...scripts !== void 0 ? { scripts } : {},
950
880
  ...targetDir !== void 0 ? { targetDir } : {}
951
881
  });
@@ -998,7 +928,7 @@ function setupPackages(opts) {
998
928
  };
999
929
  }
1000
930
  const preResolvePackageJsonPath = path2.join(resolvedTarget, "package.json");
1001
- if (!existsSync2(preResolvePackageJsonPath)) {
931
+ if (!existsSync(preResolvePackageJsonPath)) {
1002
932
  return {
1003
933
  success: false,
1004
934
  ...emptyResult,
@@ -1094,11 +1024,11 @@ function setupPackages(opts) {
1094
1024
  }
1095
1025
  }
1096
1026
  const raw = readFileSync(realPackageJsonPath, "utf8");
1097
- const PackageJsonSchema = z6.object({
1027
+ const PackageJsonSchema = z7.object({
1098
1028
  // Zod v4: z.record(keySchema, valueSchema) — two-arg form required
1099
- dependencies: z6.record(z6.string(), z6.string()).optional(),
1100
- devDependencies: z6.record(z6.string(), z6.string()).optional(),
1101
- scripts: z6.record(z6.string(), z6.string()).optional()
1029
+ dependencies: z7.record(z7.string(), z7.string()).optional(),
1030
+ devDependencies: z7.record(z7.string(), z7.string()).optional(),
1031
+ scripts: z7.record(z7.string(), z7.string()).optional()
1102
1032
  }).passthrough();
1103
1033
  const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
1104
1034
  if (!schemaResult.success) {
@@ -1178,38 +1108,2839 @@ function setupPackages(opts) {
1178
1108
  }
1179
1109
  }
1180
1110
 
1181
- // package.json
1182
- var package_default = {
1183
- dependencies: {
1184
- "@modelcontextprotocol/sdk": "^1.10.0",
1185
- "@stackwright-pro/cli-data-explorer": "workspace:*",
1186
- zod: "^4.3.6"
1187
- },
1188
- devDependencies: {
1189
- "@types/node": "^24.1.0",
1190
- tsup: "^8.5.0",
1191
- typescript: "^5.8.3",
1192
- vitest: "^4.0.18"
1193
- },
1194
- scripts: {
1195
- build: "tsup src/server.ts --format cjs,esm --dts --clean",
1196
- dev: "tsup src/server.ts --format cjs,esm --dts --watch",
1197
- start: "node dist/server.js",
1198
- test: "vitest run",
1199
- "test:coverage": "vitest run --coverage"
1200
- },
1201
- name: "@stackwright-pro/mcp",
1202
- version: "0.2.0-alpha.3",
1203
- description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
1204
- license: "PROPRIETARY",
1205
- main: "./dist/server.js",
1206
- module: "./dist/server.mjs",
1207
- types: "./dist/server.d.ts",
1208
- exports: {
1209
- ".": {
1210
- types: "./dist/server.d.ts",
1211
- import: "./dist/server.mjs",
1212
- require: "./dist/server.js"
1111
+ // src/tools/questions.ts
1112
+ import { readFile, writeFile } from "fs/promises";
1113
+ import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync, renameSync } from "fs";
1114
+ import { join } from "path";
1115
+ import { z as z8 } from "zod";
1116
+
1117
+ // src/question-adapter.ts
1118
+ function truncate(str, maxLength) {
1119
+ if (str.length <= maxLength) return str;
1120
+ return str.substring(0, maxLength - 1) + "\u2026";
1121
+ }
1122
+ function generateHeader(id) {
1123
+ const parts = id.split("-");
1124
+ if (parts.length >= 2) {
1125
+ const prefix = parts[0].toUpperCase().substring(0, 4);
1126
+ const num = parts[1];
1127
+ return truncate(`${prefix}-${num}`, 12);
1128
+ }
1129
+ return truncate(
1130
+ id.toUpperCase().replace(/[^A-Z0-9]/g, "").substring(0, 12),
1131
+ 12
1132
+ );
1133
+ }
1134
+ function generateDefaultOptions(type) {
1135
+ switch (type) {
1136
+ case "confirm":
1137
+ return [
1138
+ { label: "Yes", description: "Enable or confirm this option" },
1139
+ { label: "No", description: "Disable or decline this option" }
1140
+ ];
1141
+ case "text":
1142
+ return [
1143
+ { label: "Specify", description: "I will provide a specific value" },
1144
+ { label: "Skip", description: "Use default or skip this question" }
1145
+ ];
1146
+ default:
1147
+ return [
1148
+ { label: "Option 1", description: "First option" },
1149
+ { label: "Option 2", description: "Second option" }
1150
+ ];
1151
+ }
1152
+ }
1153
+ function adaptQuestion(q) {
1154
+ const header = generateHeader(q.id);
1155
+ const multiSelect = q.type === "multi-select";
1156
+ let options;
1157
+ if (q.options && q.options.length >= 2) {
1158
+ options = q.options.map((opt) => ({
1159
+ label: truncate(opt.label, 50),
1160
+ description: opt.value !== opt.label ? opt.value : void 0
1161
+ }));
1162
+ } else if (q.options && q.options.length === 1) {
1163
+ options = [
1164
+ ...q.options.map((opt) => ({ label: truncate(opt.label, 50), description: opt.value })),
1165
+ { label: "Other", description: "Specify a different value" }
1166
+ ];
1167
+ } else {
1168
+ options = generateDefaultOptions(q.type);
1169
+ }
1170
+ if (options.length < 2) {
1171
+ options.push({ label: "Other", description: "Alternative option" });
1172
+ }
1173
+ options = options.slice(0, 6);
1174
+ return {
1175
+ question: q.question + (q.help ? `
1176
+
1177
+ ${q.help}` : ""),
1178
+ header,
1179
+ multi_select: multiSelect,
1180
+ options
1181
+ };
1182
+ }
1183
+ function adaptQuestions(questions, answers = {}) {
1184
+ const adapted = [];
1185
+ for (const q of questions) {
1186
+ if (q.dependsOn) {
1187
+ const dependsAnswer = answers[q.dependsOn.questionId];
1188
+ if (dependsAnswer === void 0) {
1189
+ continue;
1190
+ }
1191
+ const expectedValues = Array.isArray(q.dependsOn.value) ? q.dependsOn.value : [q.dependsOn.value];
1192
+ const answerValue = Array.isArray(dependsAnswer) ? dependsAnswer[0] : dependsAnswer;
1193
+ if (!expectedValues.includes(answerValue)) {
1194
+ continue;
1195
+ }
1196
+ }
1197
+ adapted.push(adaptQuestion(q));
1198
+ }
1199
+ return adapted;
1200
+ }
1201
+ function parseLLMQuestionsResponse(text) {
1202
+ let jsonStr = text;
1203
+ jsonStr = jsonStr.replace(/```(?:json|javascript)?\s*/gi, "");
1204
+ jsonStr = jsonStr.replace(/```\s*$/gm, "");
1205
+ const firstBrace = jsonStr.indexOf("{");
1206
+ const firstBracket = jsonStr.indexOf("[");
1207
+ let start = -1;
1208
+ if (firstBrace !== -1 && firstBracket !== -1) {
1209
+ start = Math.min(firstBrace, firstBracket);
1210
+ } else if (firstBrace !== -1) {
1211
+ start = firstBrace;
1212
+ } else if (firstBracket !== -1) {
1213
+ start = firstBracket;
1214
+ }
1215
+ if (start === -1) {
1216
+ throw new Error("No JSON found in response");
1217
+ }
1218
+ jsonStr = jsonStr.substring(start);
1219
+ const lastBrace = jsonStr.lastIndexOf("}");
1220
+ const lastBracket = jsonStr.lastIndexOf("]");
1221
+ const end = Math.max(lastBrace, lastBracket);
1222
+ if (end === -1) {
1223
+ throw new Error("Invalid JSON structure");
1224
+ }
1225
+ jsonStr = jsonStr.substring(0, end + 1);
1226
+ jsonStr = jsonStr.replace(/,(\s*[}\]])/g, "$1");
1227
+ jsonStr = jsonStr.replace(/'/g, '"');
1228
+ const parsed = JSON.parse(jsonStr);
1229
+ let questions;
1230
+ if (Array.isArray(parsed)) {
1231
+ questions = parsed;
1232
+ } else if (parsed.questions && Array.isArray(parsed.questions)) {
1233
+ questions = parsed.questions;
1234
+ } else if (parsed.data && Array.isArray(parsed.data.questions)) {
1235
+ questions = parsed.data.questions;
1236
+ } else {
1237
+ throw new Error("No questions array found in response");
1238
+ }
1239
+ function sanitize(obj) {
1240
+ const sanitized = {};
1241
+ for (const key of Object.keys(obj)) {
1242
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
1243
+ continue;
1244
+ }
1245
+ const val = obj[key];
1246
+ if (val && typeof val === "object" && !Array.isArray(val)) {
1247
+ sanitized[key] = sanitize(val);
1248
+ } else if (Array.isArray(val)) {
1249
+ sanitized[key] = val.map(
1250
+ (item) => item && typeof item === "object" && !Array.isArray(item) ? sanitize(item) : item
1251
+ );
1252
+ } else {
1253
+ sanitized[key] = val;
1254
+ }
1255
+ }
1256
+ return sanitized;
1257
+ }
1258
+ questions = questions.map((q) => {
1259
+ if (q && typeof q === "object") {
1260
+ return sanitize(q);
1261
+ }
1262
+ return q;
1263
+ });
1264
+ return questions;
1265
+ }
1266
+ function answersToManifestFormat(answers, questions) {
1267
+ const result = {};
1268
+ for (const answer of answers) {
1269
+ const headerLower = answer.question_header.toLowerCase();
1270
+ const question = questions.find((q) => {
1271
+ const qHeader = generateHeader(q.id).toLowerCase();
1272
+ return qHeader === headerLower || q.id.toLowerCase().includes(headerLower);
1273
+ });
1274
+ if (!question) {
1275
+ const matched = questions.find((q) => {
1276
+ const qHeader = generateHeader(q.id).toLowerCase();
1277
+ return qHeader.startsWith(headerLower.split("-")[0]);
1278
+ });
1279
+ if (matched) {
1280
+ result[matched.id] = answer.selected_options[0] || "";
1281
+ }
1282
+ continue;
1283
+ }
1284
+ if (question.type === "multi-select" || answer.selected_options.length > 1) {
1285
+ result[question.id] = answer.selected_options;
1286
+ } else if (question.type === "confirm") {
1287
+ result[question.id] = answer.selected_options[0] === "Yes";
1288
+ } else {
1289
+ if (answer.other_text) {
1290
+ result[question.id] = answer.other_text;
1291
+ } else if (answer.selected_options.length > 0) {
1292
+ const option = question.options?.find((o) => o.label === answer.selected_options[0]);
1293
+ result[question.id] = option?.value ?? answer.selected_options[0];
1294
+ }
1295
+ }
1296
+ }
1297
+ return result;
1298
+ }
1299
+
1300
+ // src/tools/questions.ts
1301
+ var ManifestQuestionSchema = z8.object({
1302
+ id: z8.string(),
1303
+ question: z8.string(),
1304
+ type: z8.enum(["text", "select", "multi-select", "confirm"]),
1305
+ required: z8.boolean().optional(),
1306
+ options: z8.array(
1307
+ z8.object({
1308
+ label: z8.string(),
1309
+ value: z8.string()
1310
+ })
1311
+ ).optional(),
1312
+ default: z8.union([z8.string(), z8.boolean(), z8.array(z8.string())]).optional(),
1313
+ help: z8.string().optional(),
1314
+ dependsOn: z8.object({
1315
+ questionId: z8.string(),
1316
+ value: z8.union([z8.string(), z8.array(z8.string())])
1317
+ }).optional()
1318
+ });
1319
+ function registerQuestionTools(server2) {
1320
+ server2.tool(
1321
+ "stackwright_pro_present_phase_questions",
1322
+ "Adapt manifest-format questions from a specialist otter and present them to the user via ask_user_question. Pass only the phase name \u2014 this tool reads questions from .stackwright/question-manifest.json automatically. The questions parameter is optional and only needed if the manifest has not been written yet. Use this instead of calling ask_user_question directly \u2014 it handles label truncation (50-char limit), header generation, confirm/text defaults, and correct array formatting automatically. IMPORTANT: This is the ONLY approved way to prepare questions before calling ask_user_question. Never call ask_user_question with raw manifest questions. Never retry ask_user_question validation errors by calling it directly \u2014 always re-call this tool.",
1323
+ {
1324
+ phase: z8.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1325
+ questions: jsonCoerce(z8.array(ManifestQuestionSchema).optional()).describe(
1326
+ "Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
1327
+ ),
1328
+ answers: jsonCoerce(
1329
+ z8.record(z8.string(), z8.union([z8.string(), z8.array(z8.string()), z8.boolean()])).optional()
1330
+ ).describe("Previously collected answers used to resolve dependsOn conditions")
1331
+ },
1332
+ async ({ phase, questions, answers }) => {
1333
+ let resolvedQuestions;
1334
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1335
+ if (!SAFE_PHASE.test(phase)) {
1336
+ return {
1337
+ content: [
1338
+ {
1339
+ type: "text",
1340
+ text: JSON.stringify({
1341
+ error: `Invalid phase name: "${phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
1342
+ })
1343
+ }
1344
+ ],
1345
+ isError: true
1346
+ };
1347
+ }
1348
+ if (questions && questions.length > 0) {
1349
+ resolvedQuestions = questions;
1350
+ } else {
1351
+ const phaseQuestionPath = join(process.cwd(), ".stackwright", "questions", `${phase}.json`);
1352
+ try {
1353
+ const raw = await readFile(phaseQuestionPath, "utf-8");
1354
+ const phaseData = JSON.parse(raw);
1355
+ resolvedQuestions = phaseData.questions ?? [];
1356
+ } catch {
1357
+ try {
1358
+ const manifestPath = join(process.cwd(), ".stackwright", "question-manifest.json");
1359
+ const raw = await readFile(manifestPath, "utf-8");
1360
+ const manifest = JSON.parse(raw);
1361
+ const phaseData = manifest.phases.find((p) => p.phase === phase);
1362
+ resolvedQuestions = phaseData?.questions ?? [];
1363
+ } catch (err) {
1364
+ const msg = err instanceof Error ? err.message : String(err);
1365
+ return {
1366
+ content: [
1367
+ {
1368
+ type: "text",
1369
+ text: JSON.stringify({
1370
+ error: `Could not read question manifest for phase "${phase}": ${msg}`,
1371
+ hint: "Write the manifest first, or pass questions directly to this tool."
1372
+ })
1373
+ }
1374
+ ],
1375
+ isError: true
1376
+ };
1377
+ }
1378
+ }
1379
+ }
1380
+ const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
1381
+ if (adapted.length === 0) {
1382
+ return {
1383
+ content: [
1384
+ {
1385
+ type: "text",
1386
+ text: `Phase "${phase}" has no questions to present. Do NOT call ask_user_question. Call stackwright_pro_save_phase_answers({ phase: "${phase}", rawAnswers: [] }) directly, then proceed to the execution step for this phase.`
1387
+ },
1388
+ {
1389
+ type: "text",
1390
+ // Empty array — second block always present so the foreman's two-block contract holds
1391
+ text: JSON.stringify([])
1392
+ }
1393
+ ],
1394
+ isError: false
1395
+ };
1396
+ }
1397
+ return {
1398
+ content: [
1399
+ {
1400
+ type: "text",
1401
+ text: `Adapted ${adapted.length} questions for phase "${phase}". Pass the JSON array below DIRECTLY to ask_user_question as the "questions" parameter. Do NOT JSON.stringify() it. Do NOT wrap it in an object. Pass the parsed array value as-is.`
1402
+ },
1403
+ {
1404
+ type: "text",
1405
+ text: JSON.stringify(adapted)
1406
+ }
1407
+ ],
1408
+ isError: false
1409
+ };
1410
+ }
1411
+ );
1412
+ server2.tool(
1413
+ "stackwright_pro_get_next_question",
1414
+ "Returns the next unanswered question for a phase as a plain JSON object \u2014 one question at a time. Returns { done: true } when all questions are answered or the phase has no questions. Call this in a loop: present the question in plain chat, get user reply, call record_answer, repeat.",
1415
+ { phase: z8.string().describe('Phase name e.g. "designer", "api", "auth"') },
1416
+ async ({ phase }) => {
1417
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1418
+ if (!SAFE_PHASE.test(phase)) {
1419
+ return {
1420
+ content: [
1421
+ {
1422
+ type: "text",
1423
+ text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
1424
+ }
1425
+ ],
1426
+ isError: true
1427
+ };
1428
+ }
1429
+ const cwd = process.cwd();
1430
+ const questionsPath = join(cwd, ".stackwright", "questions", `${phase}.json`);
1431
+ let questions = [];
1432
+ try {
1433
+ const raw = await readFile(questionsPath, "utf-8");
1434
+ const parsed = JSON.parse(raw);
1435
+ questions = parsed.questions ?? [];
1436
+ } catch {
1437
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1438
+ }
1439
+ if (questions.length === 0) {
1440
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1441
+ }
1442
+ const answersPath = join(cwd, ".stackwright", "answers", `${phase}.json`);
1443
+ let answeredIds = /* @__PURE__ */ new Set();
1444
+ try {
1445
+ const raw = await readFile(answersPath, "utf-8");
1446
+ const parsed = JSON.parse(raw);
1447
+ answeredIds = new Set(Object.keys(parsed.answers ?? {}));
1448
+ } catch {
1449
+ }
1450
+ const next = questions.find((q) => !answeredIds.has(q.id));
1451
+ if (!next) {
1452
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1453
+ }
1454
+ return {
1455
+ content: [
1456
+ {
1457
+ type: "text",
1458
+ text: JSON.stringify({
1459
+ done: false,
1460
+ questionId: next.id,
1461
+ question: next.question,
1462
+ type: next.type,
1463
+ options: next.options ?? null,
1464
+ help: next.help ?? null,
1465
+ index: questions.indexOf(next) + 1,
1466
+ total: questions.length
1467
+ })
1468
+ }
1469
+ ]
1470
+ };
1471
+ }
1472
+ );
1473
+ server2.tool(
1474
+ "stackwright_pro_record_answer",
1475
+ "Records a single answer to a phase question. Appends to .stackwright/answers/{phase}.json incrementally. Idempotent \u2014 calling twice for the same questionId overwrites. Call after receiving each user reply in the conversational question loop.",
1476
+ {
1477
+ phase: z8.string().describe('Phase name e.g. "designer"'),
1478
+ questionId: z8.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
1479
+ answer: z8.string().describe("The user's free-text answer")
1480
+ },
1481
+ async ({ phase, questionId, answer }) => {
1482
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1483
+ if (!SAFE_PHASE.test(phase)) {
1484
+ return {
1485
+ content: [
1486
+ { type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
1487
+ ],
1488
+ isError: true
1489
+ };
1490
+ }
1491
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(questionId)) {
1492
+ return {
1493
+ content: [
1494
+ { type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
1495
+ ],
1496
+ isError: true
1497
+ };
1498
+ }
1499
+ const safeAnswer = answer.slice(0, 2e3);
1500
+ const cwd = process.cwd();
1501
+ const answersDir = join(cwd, ".stackwright", "answers");
1502
+ const answersPath = join(answersDir, `${phase}.json`);
1503
+ if (existsSync2(answersDir) && lstatSync2(answersDir).isSymbolicLink()) {
1504
+ return {
1505
+ content: [
1506
+ {
1507
+ type: "text",
1508
+ text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
1509
+ }
1510
+ ],
1511
+ isError: true
1512
+ };
1513
+ }
1514
+ mkdirSync(answersDir, { recursive: true });
1515
+ let existing = {
1516
+ version: "1.0",
1517
+ phase,
1518
+ answers: {}
1519
+ };
1520
+ try {
1521
+ if (existsSync2(answersPath)) {
1522
+ if (lstatSync2(answersPath).isSymbolicLink()) {
1523
+ return {
1524
+ content: [
1525
+ {
1526
+ type: "text",
1527
+ text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
1528
+ }
1529
+ ],
1530
+ isError: true
1531
+ };
1532
+ }
1533
+ const raw = await readFile(answersPath, "utf-8");
1534
+ existing = JSON.parse(raw);
1535
+ }
1536
+ } catch {
1537
+ }
1538
+ existing.answers[questionId] = safeAnswer;
1539
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1540
+ const tmp = `${answersPath}.tmp`;
1541
+ await writeFile(tmp, JSON.stringify(existing, null, 2), "utf-8");
1542
+ renameSync(tmp, answersPath);
1543
+ return {
1544
+ content: [
1545
+ { type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
1546
+ ]
1547
+ };
1548
+ }
1549
+ );
1550
+ }
1551
+
1552
+ // src/tools/orchestration.ts
1553
+ import { z as z9 } from "zod";
1554
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1555
+ import { join as join2 } from "path";
1556
+ var OTTER_NAME_TO_PHASE = [
1557
+ ["designer", "designer"],
1558
+ ["theme", "theme"],
1559
+ ["api", "api"],
1560
+ ["auth", "auth"],
1561
+ ["dashboard", "dashboard"],
1562
+ ["data", "data"],
1563
+ ["page", "pages"],
1564
+ ["workflow", "workflow"]
1565
+ ];
1566
+ var PHASE_TO_OTTER = {
1567
+ designer: "stackwright-pro-designer-otter",
1568
+ theme: "stackwright-pro-theme-otter",
1569
+ api: "stackwright-pro-api-otter",
1570
+ auth: "stackwright-pro-auth-otter",
1571
+ pages: "stackwright-pro-page-otter",
1572
+ dashboard: "stackwright-pro-dashboard-otter",
1573
+ data: "stackwright-pro-data-otter",
1574
+ workflow: "stackwright-pro-workflow-otter"
1575
+ };
1576
+ function detectPhase(otterName) {
1577
+ const lower = otterName.toLowerCase();
1578
+ for (const [keyword, phase] of OTTER_NAME_TO_PHASE) {
1579
+ if (lower.includes(keyword)) return phase;
1580
+ }
1581
+ return lower.replace(/^stackwright-pro-/, "").replace(/-otter$/, "");
1582
+ }
1583
+ function handleParseOtterResponse(input) {
1584
+ const phase = detectPhase(input.otterName);
1585
+ try {
1586
+ const questions = parseLLMQuestionsResponse(input.responseText);
1587
+ return {
1588
+ result: { phase, otter: input.otterName, questions },
1589
+ isError: false
1590
+ };
1591
+ } catch (err) {
1592
+ const message = err instanceof Error ? err.message : String(err);
1593
+ return {
1594
+ result: {
1595
+ error: true,
1596
+ otterName: input.otterName,
1597
+ phase,
1598
+ questions: [],
1599
+ parseError: message
1600
+ },
1601
+ isError: true
1602
+ };
1603
+ }
1604
+ }
1605
+ function handleSaveManifest(input) {
1606
+ const cwd = input._cwd ?? process.cwd();
1607
+ const dir = join2(cwd, ".stackwright");
1608
+ const filePath = join2(dir, "question-manifest.json");
1609
+ try {
1610
+ mkdirSync2(dir, { recursive: true });
1611
+ if (existsSync3(filePath)) {
1612
+ const stat = lstatSync3(filePath);
1613
+ if (stat.isSymbolicLink()) {
1614
+ const message = `Refusing to write to symlink: ${filePath}`;
1615
+ return {
1616
+ text: JSON.stringify({ success: false, error: message }),
1617
+ isError: true
1618
+ };
1619
+ }
1620
+ }
1621
+ const manifest = {
1622
+ version: "1.0",
1623
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1624
+ phases: input.phases
1625
+ };
1626
+ writeFileSync2(filePath, JSON.stringify(manifest, null, 2) + "\n");
1627
+ return {
1628
+ text: JSON.stringify({ success: true, path: filePath, phaseCount: input.phases.length }),
1629
+ isError: false
1630
+ };
1631
+ } catch (err) {
1632
+ const message = err instanceof Error ? err.message : String(err);
1633
+ return {
1634
+ text: JSON.stringify({ success: false, error: message }),
1635
+ isError: true
1636
+ };
1637
+ }
1638
+ }
1639
+ function handleSavePhaseAnswers(input) {
1640
+ const cwd = input._cwd ?? process.cwd();
1641
+ const dir = join2(cwd, ".stackwright", "answers");
1642
+ const filePath = join2(dir, `${input.phase}.json`);
1643
+ try {
1644
+ mkdirSync2(dir, { recursive: true });
1645
+ let answers;
1646
+ if (input.questions && input.questions.length > 0) {
1647
+ answers = answersToManifestFormat(input.rawAnswers, input.questions);
1648
+ } else {
1649
+ answers = Object.fromEntries(
1650
+ input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
1651
+ );
1652
+ }
1653
+ const payload = {
1654
+ version: "1.0",
1655
+ phase: input.phase,
1656
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1657
+ answers
1658
+ };
1659
+ if (existsSync3(filePath)) {
1660
+ const stat = lstatSync3(filePath);
1661
+ if (stat.isSymbolicLink()) {
1662
+ const message = `Refusing to write to symlink: ${filePath}`;
1663
+ return {
1664
+ text: JSON.stringify({ success: false, error: message }),
1665
+ isError: true
1666
+ };
1667
+ }
1668
+ }
1669
+ writeFileSync2(filePath, JSON.stringify(payload, null, 2) + "\n");
1670
+ return {
1671
+ text: JSON.stringify({
1672
+ success: true,
1673
+ path: filePath,
1674
+ answersCount: Object.keys(answers).length
1675
+ }),
1676
+ isError: false
1677
+ };
1678
+ } catch (err) {
1679
+ const message = err instanceof Error ? err.message : String(err);
1680
+ return {
1681
+ text: JSON.stringify({ success: false, error: message }),
1682
+ isError: true
1683
+ };
1684
+ }
1685
+ }
1686
+ function handleReadPhaseAnswers(input) {
1687
+ const cwd = input._cwd ?? process.cwd();
1688
+ const filePath = join2(cwd, ".stackwright", "answers", `${input.phase}.json`);
1689
+ if (!existsSync3(filePath)) {
1690
+ return {
1691
+ text: JSON.stringify({ missing: true, phase: input.phase }),
1692
+ isError: false
1693
+ };
1694
+ }
1695
+ try {
1696
+ const raw = readFileSync2(filePath, "utf8");
1697
+ const parsed = JSON.parse(raw);
1698
+ return { text: JSON.stringify(parsed), isError: false };
1699
+ } catch (err) {
1700
+ const message = err instanceof Error ? err.message : String(err);
1701
+ return {
1702
+ text: JSON.stringify({ error: true, phase: input.phase, readError: message }),
1703
+ isError: true
1704
+ };
1705
+ }
1706
+ }
1707
+ function handleGetOtterName(input) {
1708
+ const normalised = input.phase.toLowerCase().trim();
1709
+ const otterName = PHASE_TO_OTTER[normalised];
1710
+ if (!otterName) {
1711
+ return {
1712
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${input.phase}` }),
1713
+ isError: true
1714
+ };
1715
+ }
1716
+ return {
1717
+ text: JSON.stringify({ phase: normalised, otterName }),
1718
+ isError: false
1719
+ };
1720
+ }
1721
+ function handleSaveBuildContext(input) {
1722
+ const cwd = input._cwd ?? process.cwd();
1723
+ const dir = join2(cwd, ".stackwright");
1724
+ const filePath = join2(dir, "build-context.json");
1725
+ try {
1726
+ mkdirSync2(dir, { recursive: true });
1727
+ if (existsSync3(filePath)) {
1728
+ const stat = lstatSync3(filePath);
1729
+ if (stat.isSymbolicLink()) {
1730
+ return {
1731
+ text: JSON.stringify({
1732
+ success: false,
1733
+ error: `Refusing to write to symlink: ${filePath}`
1734
+ }),
1735
+ isError: true
1736
+ };
1737
+ }
1738
+ }
1739
+ const payload = {
1740
+ version: "1.0",
1741
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1742
+ buildContext: input.buildContext
1743
+ };
1744
+ writeFileSync2(filePath, JSON.stringify(payload, null, 2) + "\n");
1745
+ return {
1746
+ text: JSON.stringify({ success: true, path: filePath }),
1747
+ isError: false
1748
+ };
1749
+ } catch (err) {
1750
+ const message = err instanceof Error ? err.message : String(err);
1751
+ return {
1752
+ text: JSON.stringify({ success: false, error: message }),
1753
+ isError: true
1754
+ };
1755
+ }
1756
+ }
1757
+ function registerOrchestrationTools(server2) {
1758
+ server2.tool(
1759
+ "stackwright_pro_save_build_context",
1760
+ `Save the user's initial build description to .stackwright/build-context.json. Call this once at startup after the user answers the opening "what are you building" question. The saved context is automatically prepended to specialist prompts by stackwright_pro_build_specialist_prompt.`,
1761
+ {
1762
+ buildContext: z9.string().describe("Free-text description of what the user wants to build")
1763
+ },
1764
+ async ({ buildContext }) => {
1765
+ const { text, isError } = handleSaveBuildContext({ buildContext });
1766
+ return {
1767
+ content: [{ type: "text", text }],
1768
+ isError
1769
+ };
1770
+ }
1771
+ );
1772
+ server2.tool(
1773
+ "stackwright_pro_parse_otter_response",
1774
+ "Parse and validate a specialist otter's QUESTION_COLLECTION_MODE JSON response. Handles JSON extraction from LLM responses (strips markdown, fixes single quotes, trailing commas). Detects the phase from the otter name. Use this immediately after invoke_agent() to get a validated manifest phase object.",
1775
+ {
1776
+ otterName: z9.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1777
+ responseText: z9.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1778
+ },
1779
+ async ({ otterName, responseText }) => {
1780
+ const { result, isError } = handleParseOtterResponse({ otterName, responseText });
1781
+ return {
1782
+ content: [{ type: "text", text: JSON.stringify(result) }],
1783
+ isError
1784
+ };
1785
+ }
1786
+ );
1787
+ server2.tool(
1788
+ "stackwright_pro_save_manifest",
1789
+ "Write the question manifest to .stackwright/question-manifest.json. Call this after collecting and parsing questions from all otters via stackwright_pro_parse_otter_response.",
1790
+ {
1791
+ phases: jsonCoerce(
1792
+ z9.array(
1793
+ z9.object({
1794
+ phase: z9.string(),
1795
+ otter: z9.string(),
1796
+ questions: z9.array(z9.any()),
1797
+ requiredPackages: z9.object({
1798
+ dependencies: z9.record(z9.string(), z9.string()).optional(),
1799
+ devPackages: z9.record(z9.string(), z9.string()).optional()
1800
+ }).optional()
1801
+ })
1802
+ )
1803
+ ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1804
+ },
1805
+ async ({ phases }) => {
1806
+ const { text, isError } = handleSaveManifest({ phases });
1807
+ return {
1808
+ content: [{ type: "text", text }],
1809
+ isError
1810
+ };
1811
+ }
1812
+ );
1813
+ server2.tool(
1814
+ "stackwright_pro_save_phase_answers",
1815
+ "Save user answers for a phase to .stackwright/answers/{phase}.json. Pass rawAnswers directly from ask_user_question and the original manifest questions for label-to-value reverse mapping.",
1816
+ {
1817
+ phase: z9.string().describe('Phase name, e.g. "designer"'),
1818
+ rawAnswers: jsonCoerce(
1819
+ z9.array(
1820
+ z9.object({
1821
+ question_header: z9.string(),
1822
+ selected_options: z9.array(z9.string()),
1823
+ other_text: z9.string().nullable().optional()
1824
+ })
1825
+ )
1826
+ ).describe(
1827
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1828
+ ),
1829
+ questions: jsonCoerce(z9.array(z9.any()).optional()).describe(
1830
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1831
+ )
1832
+ },
1833
+ async ({ phase, rawAnswers, questions }) => {
1834
+ const { text, isError } = handleSavePhaseAnswers({
1835
+ phase,
1836
+ rawAnswers,
1837
+ ...questions && questions.length > 0 ? { questions } : {}
1838
+ });
1839
+ return {
1840
+ content: [{ type: "text", text }],
1841
+ isError
1842
+ };
1843
+ }
1844
+ );
1845
+ server2.tool(
1846
+ "stackwright_pro_read_phase_answers",
1847
+ "Read saved answers for a phase from .stackwright/answers/{phase}.json. Returns { missing: true } when no answers exist yet \u2014 use this to skip phases safely in the execution loop.",
1848
+ {
1849
+ phase: z9.string().describe('Phase name, e.g. "designer"')
1850
+ },
1851
+ async ({ phase }) => {
1852
+ const { text, isError } = handleReadPhaseAnswers({ phase });
1853
+ return {
1854
+ content: [{ type: "text", text }],
1855
+ isError
1856
+ };
1857
+ }
1858
+ );
1859
+ server2.tool(
1860
+ "stackwright_pro_get_otter_name",
1861
+ "Get the agent name for a phase (e.g. 'designer' \u2192 'stackwright-pro-designer-otter'). Use this in the execution loop to invoke the correct specialist otter without hardcoding names in the prompt.",
1862
+ {
1863
+ phase: z9.string().describe('Phase name, e.g. "designer", "api", "pages"')
1864
+ },
1865
+ async ({ phase }) => {
1866
+ const { text, isError } = handleGetOtterName({ phase });
1867
+ return {
1868
+ content: [{ type: "text", text }],
1869
+ isError
1870
+ };
1871
+ }
1872
+ );
1873
+ }
1874
+
1875
+ // src/tools/pipeline.ts
1876
+ import { z as z10 } from "zod";
1877
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync4, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "fs";
1878
+ import { join as join3 } from "path";
1879
+ import { WorkflowFileSchema, authConfigSchema } from "@stackwright-pro/types";
1880
+ var PHASE_ORDER = [
1881
+ "designer",
1882
+ "theme",
1883
+ "api",
1884
+ "data",
1885
+ "workflow",
1886
+ "pages",
1887
+ "dashboard",
1888
+ "auth"
1889
+ ];
1890
+ var PHASE_DEPENDENCIES = {
1891
+ designer: [],
1892
+ theme: ["designer"],
1893
+ api: [],
1894
+ data: ["api"],
1895
+ // workflow: no hard deps — uses service: references with Prism mock fallback
1896
+ // when API artifacts aren't available; roles come from user answers
1897
+ workflow: [],
1898
+ // pages: 'api' is transitive through 'data'; auth removed — page-otter has
1899
+ // graceful fallback and reads role names from workflow artifacts instead
1900
+ pages: ["designer", "theme", "data"],
1901
+ dashboard: ["designer", "theme", "data"],
1902
+ // auth is the terminal phase — reads all available artifacts at runtime;
1903
+ // no hard upstream requirements so it always runs and never gets skipped
1904
+ auth: []
1905
+ };
1906
+ var PHASE_ARTIFACT = {
1907
+ designer: "design-language.json",
1908
+ theme: "theme-tokens.json",
1909
+ api: "api-config.json",
1910
+ auth: "auth-config.json",
1911
+ data: "data-config.json",
1912
+ pages: "pages-manifest.json",
1913
+ dashboard: "dashboard-manifest.json",
1914
+ workflow: "workflow-config.json"
1915
+ };
1916
+ var PHASE_TO_OTTER2 = {
1917
+ designer: "stackwright-pro-designer-otter",
1918
+ theme: "stackwright-pro-theme-otter",
1919
+ api: "stackwright-pro-api-otter",
1920
+ auth: "stackwright-pro-auth-otter",
1921
+ data: "stackwright-pro-data-otter",
1922
+ pages: "stackwright-pro-page-otter",
1923
+ dashboard: "stackwright-pro-dashboard-otter",
1924
+ workflow: "stackwright-pro-workflow-otter"
1925
+ };
1926
+ function isValidPhase(phase) {
1927
+ return PHASE_ORDER.includes(phase);
1928
+ }
1929
+ function defaultPhaseStatus() {
1930
+ return {
1931
+ questionsCollected: false,
1932
+ answered: false,
1933
+ executed: false,
1934
+ artifactWritten: false,
1935
+ retryCount: 0
1936
+ };
1937
+ }
1938
+ function createDefaultState() {
1939
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1940
+ const phases = {};
1941
+ for (const p of PHASE_ORDER) {
1942
+ phases[p] = defaultPhaseStatus();
1943
+ }
1944
+ return {
1945
+ version: "1.0",
1946
+ currentPhase: PHASE_ORDER[0],
1947
+ status: "setup",
1948
+ phases,
1949
+ startedAt: now,
1950
+ updatedAt: now
1951
+ };
1952
+ }
1953
+ function statePath(cwd) {
1954
+ return join3(cwd, ".stackwright", "pipeline-state.json");
1955
+ }
1956
+ function readState(cwd) {
1957
+ const p = statePath(cwd);
1958
+ if (!existsSync4(p)) return createDefaultState();
1959
+ const raw = JSON.parse(safeReadSync(p));
1960
+ if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1961
+ return createDefaultState();
1962
+ }
1963
+ return raw;
1964
+ }
1965
+ function safeWriteSync(filePath, content) {
1966
+ if (existsSync4(filePath)) {
1967
+ const stat = lstatSync4(filePath);
1968
+ if (stat.isSymbolicLink()) {
1969
+ throw new Error(`Refusing to write to symlink: ${filePath}`);
1970
+ }
1971
+ }
1972
+ writeFileSync3(filePath, content);
1973
+ }
1974
+ function safeReadSync(filePath) {
1975
+ if (existsSync4(filePath)) {
1976
+ const stat = lstatSync4(filePath);
1977
+ if (stat.isSymbolicLink()) {
1978
+ throw new Error(`Refusing to read symlink: ${filePath}`);
1979
+ }
1980
+ }
1981
+ return readFileSync3(filePath, "utf-8");
1982
+ }
1983
+ function writeState(cwd, state) {
1984
+ const dir = join3(cwd, ".stackwright");
1985
+ mkdirSync3(dir, { recursive: true });
1986
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1987
+ safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1988
+ }
1989
+ function extractJsonFromResponse(text) {
1990
+ let cleaned = text;
1991
+ cleaned = cleaned.replace(/```(?:json)?\s*/gi, "");
1992
+ cleaned = cleaned.replace(/```\s*$/gm, "");
1993
+ const firstBrace = cleaned.indexOf("{");
1994
+ if (firstBrace === -1) throw new Error("No JSON object found in response");
1995
+ cleaned = cleaned.substring(firstBrace);
1996
+ const lastBrace = cleaned.lastIndexOf("}");
1997
+ if (lastBrace === -1) throw new Error("Unclosed JSON object in response");
1998
+ cleaned = cleaned.substring(0, lastBrace + 1);
1999
+ cleaned = cleaned.replace(/,(\s*[}\]])/g, "$1");
2000
+ return JSON.parse(cleaned);
2001
+ }
2002
+ function handleGetPipelineState(_cwd) {
2003
+ const cwd = _cwd ?? process.cwd();
2004
+ try {
2005
+ const state = readState(cwd);
2006
+ return { text: JSON.stringify(state), isError: false };
2007
+ } catch (err) {
2008
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2009
+ }
2010
+ }
2011
+ function handleSetPipelineState(input) {
2012
+ const cwd = input._cwd ?? process.cwd();
2013
+ if (input.phase && !isValidPhase(input.phase)) {
2014
+ return {
2015
+ text: JSON.stringify({
2016
+ error: true,
2017
+ message: `Invalid phase: ${input.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2018
+ }),
2019
+ isError: true
2020
+ };
2021
+ }
2022
+ const VALID_FIELDS = ["questionsCollected", "answered", "executed", "artifactWritten"];
2023
+ if (input.field && !VALID_FIELDS.includes(input.field)) {
2024
+ return {
2025
+ text: JSON.stringify({
2026
+ error: true,
2027
+ message: `Invalid field: ${input.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
2028
+ }),
2029
+ isError: true
2030
+ };
2031
+ }
2032
+ try {
2033
+ const state = readState(cwd);
2034
+ if (input.status) {
2035
+ state.status = input.status;
2036
+ }
2037
+ if (input.phase) {
2038
+ const phase = input.phase;
2039
+ if (!state.phases[phase]) {
2040
+ state.phases[phase] = defaultPhaseStatus();
2041
+ }
2042
+ const phaseState = state.phases[phase];
2043
+ if (input.field && input.value !== void 0) {
2044
+ phaseState[input.field] = input.value;
2045
+ }
2046
+ if (input.incrementRetry) {
2047
+ phaseState.retryCount += 1;
2048
+ }
2049
+ state.currentPhase = phase;
2050
+ }
2051
+ writeState(cwd, state);
2052
+ return { text: JSON.stringify(state), isError: false };
2053
+ } catch (err) {
2054
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2055
+ }
2056
+ }
2057
+ function handleCheckExecutionReady(_cwd, phase) {
2058
+ const cwd = _cwd ?? process.cwd();
2059
+ if (phase) {
2060
+ if (!isValidPhase(phase)) {
2061
+ return {
2062
+ text: JSON.stringify({
2063
+ error: true,
2064
+ message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2065
+ }),
2066
+ isError: true
2067
+ };
2068
+ }
2069
+ const answerFile = join3(cwd, ".stackwright", "answers", `${phase}.json`);
2070
+ if (!existsSync4(answerFile)) {
2071
+ return {
2072
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
2073
+ isError: false
2074
+ };
2075
+ }
2076
+ try {
2077
+ const raw = safeReadSync(answerFile);
2078
+ const parsed = JSON.parse(raw);
2079
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2080
+ return {
2081
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
2082
+ isError: false
2083
+ };
2084
+ }
2085
+ return { text: JSON.stringify({ ready: true, phase }), isError: false };
2086
+ } catch {
2087
+ return {
2088
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
2089
+ isError: false
2090
+ };
2091
+ }
2092
+ }
2093
+ try {
2094
+ const answersDir = join3(cwd, ".stackwright", "answers");
2095
+ const answeredPhases = [];
2096
+ const missingPhases = [];
2097
+ for (const phase2 of PHASE_ORDER) {
2098
+ const answerFile = join3(answersDir, `${phase2}.json`);
2099
+ if (existsSync4(answerFile)) {
2100
+ try {
2101
+ const raw = safeReadSync(answerFile);
2102
+ const parsed = JSON.parse(raw);
2103
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2104
+ missingPhases.push(phase2);
2105
+ continue;
2106
+ }
2107
+ answeredPhases.push(phase2);
2108
+ } catch {
2109
+ missingPhases.push(phase2);
2110
+ }
2111
+ } else {
2112
+ missingPhases.push(phase2);
2113
+ }
2114
+ }
2115
+ return {
2116
+ text: JSON.stringify({
2117
+ ready: missingPhases.length === 0,
2118
+ answeredPhases,
2119
+ missingPhases,
2120
+ totalPhases: PHASE_ORDER.length
2121
+ }),
2122
+ isError: false
2123
+ };
2124
+ } catch (err) {
2125
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2126
+ }
2127
+ }
2128
+ function handleListArtifacts(_cwd) {
2129
+ const cwd = _cwd ?? process.cwd();
2130
+ try {
2131
+ const artifactsDir = join3(cwd, ".stackwright", "artifacts");
2132
+ const artifacts = [];
2133
+ let completedCount = 0;
2134
+ for (const phase of PHASE_ORDER) {
2135
+ const expectedFile = PHASE_ARTIFACT[phase];
2136
+ const fullPath = join3(artifactsDir, expectedFile);
2137
+ const exists = existsSync4(fullPath);
2138
+ if (exists) completedCount++;
2139
+ artifacts.push({ phase, expectedFile, exists, path: fullPath });
2140
+ }
2141
+ return {
2142
+ text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
2143
+ isError: false
2144
+ };
2145
+ } catch (err) {
2146
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2147
+ }
2148
+ }
2149
+ function handleWritePhaseQuestions(input) {
2150
+ const cwd = input._cwd ?? process.cwd();
2151
+ const { phase, responseText } = input;
2152
+ if (!isValidPhase(phase)) {
2153
+ return {
2154
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2155
+ isError: true
2156
+ };
2157
+ }
2158
+ try {
2159
+ const questions = parseLLMQuestionsResponse(responseText);
2160
+ let requiredPackages = {
2161
+ dependencies: {},
2162
+ devPackages: {}
2163
+ };
2164
+ try {
2165
+ const fullParsed = extractJsonFromResponse(responseText);
2166
+ if (fullParsed.requiredPackages && typeof fullParsed.requiredPackages === "object") {
2167
+ const rp = fullParsed.requiredPackages;
2168
+ requiredPackages = {
2169
+ dependencies: rp.dependencies ?? {},
2170
+ devPackages: rp.devPackages ?? {}
2171
+ };
2172
+ }
2173
+ } catch {
2174
+ }
2175
+ const questionsDir = join3(cwd, ".stackwright", "questions");
2176
+ mkdirSync3(questionsDir, { recursive: true });
2177
+ const filePath = join3(questionsDir, `${phase}.json`);
2178
+ const payload = {
2179
+ version: "1.0",
2180
+ phase,
2181
+ otter: PHASE_TO_OTTER2[phase],
2182
+ collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
2183
+ questions,
2184
+ requiredPackages
2185
+ };
2186
+ safeWriteSync(filePath, JSON.stringify(payload, null, 2) + "\n");
2187
+ const state = readState(cwd);
2188
+ if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2189
+ const ps = state.phases[phase];
2190
+ ps.questionsCollected = true;
2191
+ writeState(cwd, state);
2192
+ return {
2193
+ text: JSON.stringify({
2194
+ success: true,
2195
+ phase,
2196
+ questionCount: questions.length,
2197
+ requiredPackages,
2198
+ path: filePath
2199
+ }),
2200
+ isError: false
2201
+ };
2202
+ } catch (err) {
2203
+ const message = err instanceof Error ? err.message : String(err);
2204
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
2205
+ }
2206
+ }
2207
+ function handleBuildSpecialistPrompt(input) {
2208
+ const cwd = input._cwd ?? process.cwd();
2209
+ const { phase } = input;
2210
+ if (!isValidPhase(phase)) {
2211
+ return {
2212
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2213
+ isError: true
2214
+ };
2215
+ }
2216
+ try {
2217
+ const answersPath = join3(cwd, ".stackwright", "answers", `${phase}.json`);
2218
+ let answers = {};
2219
+ if (existsSync4(answersPath)) {
2220
+ answers = JSON.parse(safeReadSync(answersPath));
2221
+ }
2222
+ let buildContextText = "";
2223
+ const buildContextPath = join3(cwd, ".stackwright", "build-context.json");
2224
+ if (existsSync4(buildContextPath)) {
2225
+ try {
2226
+ const bcRaw = JSON.parse(safeReadSync(buildContextPath));
2227
+ if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
2228
+ buildContextText = bcRaw.buildContext.trim();
2229
+ }
2230
+ } catch {
2231
+ }
2232
+ }
2233
+ const deps = PHASE_DEPENDENCIES[phase];
2234
+ const artifactSections = [];
2235
+ const missingDependencies = [];
2236
+ for (const dep of deps) {
2237
+ const artifactFile = PHASE_ARTIFACT[dep];
2238
+ const artifactPath = join3(cwd, ".stackwright", "artifacts", artifactFile);
2239
+ if (existsSync4(artifactPath)) {
2240
+ const content = JSON.parse(safeReadSync(artifactPath));
2241
+ const expectedOtter = PHASE_TO_OTTER2[dep];
2242
+ const artifactOtter = content["generatedBy"];
2243
+ const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
2244
+ if (!artifactOtter) {
2245
+ missingDependencies.push(dep);
2246
+ artifactSections.push(
2247
+ `[${artifactFile}]:
2248
+ (integrity check failed: missing generatedBy field)`
2249
+ );
2250
+ } else if (normalizedOtter !== expectedOtter) {
2251
+ missingDependencies.push(dep);
2252
+ artifactSections.push(
2253
+ `[${artifactFile}]:
2254
+ (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
2255
+ );
2256
+ } else {
2257
+ artifactSections.push(`[${artifactFile}]:
2258
+ ${JSON.stringify(content, null, 2)}`);
2259
+ }
2260
+ } else {
2261
+ missingDependencies.push(dep);
2262
+ artifactSections.push(`[${artifactFile}]:
2263
+ (not yet available)`);
2264
+ }
2265
+ }
2266
+ const parts = [];
2267
+ if (buildContextText) {
2268
+ parts.push("BUILD_CONTEXT:", buildContextText, "");
2269
+ }
2270
+ parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
2271
+ if (artifactSections.length > 0) {
2272
+ parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
2273
+ }
2274
+ parts.push("", "Execute using these answers and the upstream artifacts provided.");
2275
+ const prompt = parts.join("\n");
2276
+ const dependenciesSatisfied = missingDependencies.length === 0;
2277
+ return {
2278
+ text: JSON.stringify({
2279
+ otterName: PHASE_TO_OTTER2[phase],
2280
+ phase,
2281
+ prompt,
2282
+ dependenciesSatisfied,
2283
+ missingDependencies
2284
+ }),
2285
+ isError: false
2286
+ };
2287
+ } catch (err) {
2288
+ const message = err instanceof Error ? err.message : String(err);
2289
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
2290
+ }
2291
+ }
2292
+ var OFF_SCRIPT_PATTERNS = [
2293
+ {
2294
+ pattern: /```(?:ts|tsx|js|jsx|python|bash|sh|sql|ruby|go|rust|java|csharp|c\+\+)\b/,
2295
+ label: "code fence"
2296
+ },
2297
+ { pattern: /\bimport\s+[\w{]/, label: "import statement" },
2298
+ { pattern: /\bexport\s+(?:const|function|default|class)\b/, label: "export statement" },
2299
+ { pattern: /\brequire\s*\(/, label: "require() call" },
2300
+ { pattern: /\beval\s*\(/, label: "eval() call" },
2301
+ { pattern: /^#!/m, label: "shebang" },
2302
+ { pattern: /<script[\s>]/i, label: "script tag" },
2303
+ { pattern: /\.(ts|tsx|js|jsx)\b.*\bfile\b/i, label: "code file reference" }
2304
+ ];
2305
+ var PHASE_REQUIRED_KEYS = {
2306
+ designer: ["designLanguage", "themeTokenSeeds"],
2307
+ theme: ["tokens"],
2308
+ api: ["entities"],
2309
+ auth: ["version", "generatedBy"],
2310
+ data: ["version", "generatedBy"],
2311
+ pages: ["version", "generatedBy"],
2312
+ dashboard: ["version", "generatedBy"],
2313
+ workflow: ["version", "generatedBy"]
2314
+ };
2315
+ function handleValidateArtifact(input) {
2316
+ const cwd = input._cwd ?? process.cwd();
2317
+ const { phase, responseText } = input;
2318
+ if (!isValidPhase(phase)) {
2319
+ return {
2320
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2321
+ isError: true
2322
+ };
2323
+ }
2324
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2325
+ if (pattern.test(responseText)) {
2326
+ const result = {
2327
+ valid: false,
2328
+ phase,
2329
+ violation: "off-script",
2330
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
2331
+ };
2332
+ return { text: JSON.stringify(result), isError: false };
2333
+ }
2334
+ }
2335
+ let artifact;
2336
+ try {
2337
+ artifact = extractJsonFromResponse(responseText);
2338
+ } catch {
2339
+ const result = {
2340
+ valid: false,
2341
+ phase,
2342
+ violation: "invalid-json",
2343
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2344
+ };
2345
+ return { text: JSON.stringify(result), isError: false };
2346
+ }
2347
+ if (!artifact.version || !artifact.generatedBy) {
2348
+ const result = {
2349
+ valid: false,
2350
+ phase,
2351
+ violation: "missing-fields",
2352
+ retryPrompt: 'Your JSON artifact is missing required fields. Every artifact MUST include "version" and "generatedBy" at the top level.'
2353
+ };
2354
+ return { text: JSON.stringify(result), isError: false };
2355
+ }
2356
+ const requiredKeys = PHASE_REQUIRED_KEYS[phase];
2357
+ const missingKeys = requiredKeys.filter((k) => !(k in artifact));
2358
+ if (missingKeys.length > 0) {
2359
+ const result = {
2360
+ valid: false,
2361
+ phase,
2362
+ violation: "schema-mismatch",
2363
+ retryPrompt: `Your ${phase} artifact is missing required keys: ${missingKeys.join(", ")}. Include them and try again.`
2364
+ };
2365
+ return { text: JSON.stringify(result), isError: false };
2366
+ }
2367
+ const PHASE_ZOD_VALIDATORS = {
2368
+ workflow: (artifact2) => {
2369
+ const workflowConfig = artifact2["workflowConfig"];
2370
+ if (!workflowConfig) return { success: true };
2371
+ const result = WorkflowFileSchema.safeParse(workflowConfig);
2372
+ if (!result.success) {
2373
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
2374
+ return { success: false, error: { message: issues } };
2375
+ }
2376
+ return { success: true };
2377
+ },
2378
+ auth: (artifact2) => {
2379
+ const authConfig = artifact2["authConfig"];
2380
+ if (!authConfig) return { success: true };
2381
+ const result = authConfigSchema.safeParse(authConfig);
2382
+ if (!result.success) {
2383
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
2384
+ return { success: false, error: { message: issues } };
2385
+ }
2386
+ return { success: true };
2387
+ }
2388
+ };
2389
+ const zodValidator = PHASE_ZOD_VALIDATORS[phase];
2390
+ if (zodValidator) {
2391
+ const zodResult = zodValidator(artifact);
2392
+ if (!zodResult.success) {
2393
+ const result = {
2394
+ valid: false,
2395
+ phase,
2396
+ violation: "schema-mismatch",
2397
+ retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
2398
+ };
2399
+ return { text: JSON.stringify(result), isError: false };
2400
+ }
2401
+ }
2402
+ try {
2403
+ const artifactsDir = join3(cwd, ".stackwright", "artifacts");
2404
+ mkdirSync3(artifactsDir, { recursive: true });
2405
+ const artifactFile = PHASE_ARTIFACT[phase];
2406
+ const artifactPath = join3(artifactsDir, artifactFile);
2407
+ safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
2408
+ const state = readState(cwd);
2409
+ if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2410
+ const ps = state.phases[phase];
2411
+ ps.artifactWritten = true;
2412
+ writeState(cwd, state);
2413
+ const topKeys = Object.keys(artifact).slice(0, 5).join(", ");
2414
+ const result = {
2415
+ valid: true,
2416
+ phase,
2417
+ artifactPath,
2418
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
2419
+ };
2420
+ return { text: JSON.stringify(result), isError: false };
2421
+ } catch (err) {
2422
+ const message = err instanceof Error ? err.message : String(err);
2423
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
2424
+ }
2425
+ }
2426
+ function registerPipelineTools(server2) {
2427
+ const DESC = "Writes state to .stackwright/ \u2014 the filesystem is the state machine.";
2428
+ const res = (r) => ({
2429
+ content: [{ type: "text", text: r.text }],
2430
+ isError: r.isError
2431
+ });
2432
+ server2.tool(
2433
+ "stackwright_pro_get_pipeline_state",
2434
+ `Read pipeline state from .stackwright/pipeline-state.json. ${DESC}`,
2435
+ {},
2436
+ async () => res(handleGetPipelineState())
2437
+ );
2438
+ server2.tool(
2439
+ "stackwright_pro_set_pipeline_state",
2440
+ `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2441
+ {
2442
+ phase: z10.string().optional().describe('Phase to update, e.g. "designer"'),
2443
+ field: z10.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
2444
+ value: boolCoerce(z10.boolean().optional()).describe(
2445
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
2446
+ ),
2447
+ status: z10.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
2448
+ incrementRetry: boolCoerce(z10.boolean().optional()).describe(
2449
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
2450
+ )
2451
+ },
2452
+ async (args) => res(
2453
+ handleSetPipelineState({
2454
+ ...args.phase != null ? { phase: args.phase } : {},
2455
+ ...args.field != null ? { field: args.field } : {},
2456
+ ...args.value != null ? { value: args.value } : {},
2457
+ ...args.status != null ? { status: args.status } : {},
2458
+ ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
2459
+ })
2460
+ )
2461
+ );
2462
+ server2.tool(
2463
+ "stackwright_pro_check_execution_ready",
2464
+ `Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
2465
+ {
2466
+ phase: z10.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
2467
+ },
2468
+ async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
2469
+ );
2470
+ server2.tool(
2471
+ "stackwright_pro_list_artifacts",
2472
+ `List phase artifacts in .stackwright/artifacts/ with completedCount/totalCount. ${DESC}`,
2473
+ {},
2474
+ async () => res(handleListArtifacts())
2475
+ );
2476
+ server2.tool(
2477
+ "stackwright_pro_write_phase_questions",
2478
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
2479
+ {
2480
+ phase: z10.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
2481
+ responseText: z10.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
2482
+ questions: jsonCoerce(z10.array(z10.any()).optional()).describe(
2483
+ "Questions array for direct specialist write"
2484
+ )
2485
+ },
2486
+ async ({ phase, responseText, questions }) => {
2487
+ if (phase && questions && Array.isArray(questions)) {
2488
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
2489
+ if (!SAFE_PHASE.test(phase)) {
2490
+ return {
2491
+ content: [
2492
+ { type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
2493
+ ],
2494
+ isError: true
2495
+ };
2496
+ }
2497
+ const questionsDir = join3(process.cwd(), ".stackwright", "questions");
2498
+ mkdirSync3(questionsDir, { recursive: true });
2499
+ const outPath = join3(questionsDir, `${phase}.json`);
2500
+ writeFileSync3(
2501
+ outPath,
2502
+ JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
2503
+ );
2504
+ return {
2505
+ content: [
2506
+ {
2507
+ type: "text",
2508
+ text: JSON.stringify({
2509
+ written: true,
2510
+ phase,
2511
+ count: questions.length
2512
+ })
2513
+ }
2514
+ ]
2515
+ };
2516
+ }
2517
+ return res(
2518
+ handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
2519
+ );
2520
+ }
2521
+ );
2522
+ server2.tool(
2523
+ "stackwright_pro_build_specialist_prompt",
2524
+ `Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
2525
+ { phase: z10.string().describe('Phase to build prompt for, e.g. "pages"') },
2526
+ async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2527
+ );
2528
+ server2.tool(
2529
+ "stackwright_pro_validate_artifact",
2530
+ `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2531
+ {
2532
+ phase: z10.string().describe('Phase that produced this artifact, e.g. "designer"'),
2533
+ responseText: z10.string().describe("Raw response text from the specialist otter")
2534
+ },
2535
+ async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
2536
+ );
2537
+ }
2538
+
2539
+ // src/tools/safe-write.ts
2540
+ import { z as z11 } from "zod";
2541
+ import { writeFileSync as writeFileSync4, existsSync as existsSync5, mkdirSync as mkdirSync4, lstatSync as lstatSync5 } from "fs";
2542
+ import { normalize, isAbsolute, dirname, join as join4 } from "path";
2543
+ var OTTER_WRITE_ALLOWLISTS = {
2544
+ "stackwright-pro-designer-otter": [
2545
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2546
+ ],
2547
+ "stackwright-pro-theme-otter": [
2548
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
2549
+ ],
2550
+ "stackwright-pro-auth-otter": [
2551
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
2552
+ { prefix: "config/", suffix: ".yml", description: "Auth YAML config" },
2553
+ { prefix: "config/", suffix: ".yaml", description: "Auth YAML config" },
2554
+ {
2555
+ prefix: ".env",
2556
+ suffix: "",
2557
+ description: "Dotenv files (.env, .env.local, .env.production, etc.)"
2558
+ }
2559
+ ],
2560
+ "stackwright-pro-data-otter": [
2561
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Data config artifact" },
2562
+ { prefix: "stackwright.yml", suffix: "", description: "Stackwright config" }
2563
+ ],
2564
+ "stackwright-pro-page-otter": [
2565
+ { prefix: "pages/", suffix: "/content.yml", description: "Page content YAML" },
2566
+ { prefix: "pages/", suffix: "/content.yaml", description: "Page content YAML" },
2567
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Pages manifest" }
2568
+ ],
2569
+ "stackwright-pro-dashboard-otter": [
2570
+ { prefix: "pages/", suffix: "/content.yml", description: "Dashboard content YAML" },
2571
+ { prefix: "pages/", suffix: "/content.yaml", description: "Dashboard content YAML" },
2572
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Dashboard manifest" }
2573
+ ],
2574
+ "stackwright-pro-workflow-otter": [
2575
+ { prefix: "workflows/", suffix: ".yml", description: "Workflow definition" },
2576
+ { prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
2577
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
2578
+ ],
2579
+ "stackwright-pro-api-otter": [
2580
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
2581
+ ]
2582
+ };
2583
+ var PROTECTED_PATH_PREFIXES = [
2584
+ ".stackwright/pipeline-state.json",
2585
+ ".stackwright/questions/",
2586
+ ".stackwright/answers/"
2587
+ ];
2588
+ function checkPathAllowed(callerOtter, filePath) {
2589
+ const normalized = normalize(filePath);
2590
+ if (normalized.includes("..")) {
2591
+ return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
2592
+ }
2593
+ if (isAbsolute(normalized)) {
2594
+ return {
2595
+ allowed: false,
2596
+ error: "Absolute paths are not allowed \u2014 use paths relative to project root"
2597
+ };
2598
+ }
2599
+ if (callerOtter === "stackwright-pro-foreman-otter") {
2600
+ return {
2601
+ allowed: false,
2602
+ error: "The foreman otter coordinates \u2014 it does not write files directly"
2603
+ };
2604
+ }
2605
+ const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter];
2606
+ if (!allowlist) {
2607
+ return {
2608
+ allowed: false,
2609
+ error: `Unknown otter: "${callerOtter}" is not in the write allowlist`
2610
+ };
2611
+ }
2612
+ for (const protectedPrefix of PROTECTED_PATH_PREFIXES) {
2613
+ if (normalized === protectedPrefix || normalized.startsWith(protectedPrefix)) {
2614
+ return {
2615
+ allowed: false,
2616
+ error: `Path "${normalized}" is managed by dedicated sink tools, not safe_write`
2617
+ };
2618
+ }
2619
+ }
2620
+ for (const rule of allowlist) {
2621
+ const prefixMatch = normalized.startsWith(rule.prefix);
2622
+ const suffixMatch = rule.suffix === "" || normalized.endsWith(rule.suffix);
2623
+ if (prefixMatch && suffixMatch) {
2624
+ if (rule.prefix === ".env" && rule.suffix === "") {
2625
+ if (!/^\.env(\.[a-zA-Z0-9]{3,})*$/.test(normalized)) {
2626
+ continue;
2627
+ }
2628
+ }
2629
+ return { allowed: true, rule: rule.description };
2630
+ }
2631
+ }
2632
+ return {
2633
+ allowed: false,
2634
+ error: `Path "${normalized}" does not match any allowed write pattern for ${callerOtter}`
2635
+ };
2636
+ }
2637
+ function validateJsonContent(content) {
2638
+ try {
2639
+ JSON.parse(content);
2640
+ return null;
2641
+ } catch (err) {
2642
+ return `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`;
2643
+ }
2644
+ }
2645
+ function validateYamlContent(content) {
2646
+ const trimmed = content.trimStart();
2647
+ const anchorRefPattern = /\[(\*[\w]+)\]/g;
2648
+ const matches = [...content.matchAll(anchorRefPattern)];
2649
+ if (matches.length >= 20) {
2650
+ return "YAML entity expansion pattern detected \u2014 too many anchor references";
2651
+ }
2652
+ const anchorDefPattern = /&([\w]+)/g;
2653
+ const defs = [...content.matchAll(anchorDefPattern)];
2654
+ if (defs.length >= 10) {
2655
+ const anchorNameCounts = /* @__PURE__ */ new Map();
2656
+ for (const [, name] of defs) {
2657
+ const count = (anchorNameCounts.get(name) ?? 0) + 1;
2658
+ anchorNameCounts.set(name, count);
2659
+ if (count >= 10) {
2660
+ return "YAML entity expansion: repeated anchor definitions detected";
2661
+ }
2662
+ }
2663
+ }
2664
+ if (trimmed.startsWith("import ") || trimmed.startsWith("import{")) {
2665
+ return 'Content starts with "import" \u2014 this looks like code, not YAML';
2666
+ }
2667
+ if (trimmed.startsWith("export ") || trimmed.startsWith("export{")) {
2668
+ return 'Content starts with "export" \u2014 this looks like code, not YAML';
2669
+ }
2670
+ if (trimmed.startsWith("#!"))
2671
+ return "Content starts with shebang \u2014 this looks like a script, not YAML";
2672
+ if (/!!(?:python|ruby|perl|js|java)/i.test(content))
2673
+ return "YAML deserialization attack tags detected";
2674
+ if (trimmed.startsWith("<") && !trimmed.startsWith("<<"))
2675
+ return "Content looks like markup, not YAML";
2676
+ return null;
2677
+ }
2678
+ function validateEnvContent(content) {
2679
+ const lines = content.split("\n");
2680
+ for (let i = 0; i < lines.length; i++) {
2681
+ const raw = lines[i];
2682
+ if (raw === void 0) continue;
2683
+ const line = raw.trim();
2684
+ if (line === "" || line.startsWith("#")) continue;
2685
+ if (!/^[A-Za-z_][A-Za-z0-9_]*=/.test(line)) {
2686
+ return `Line ${i + 1} is not a valid env entry (expected KEY=value): "${line}"`;
2687
+ }
2688
+ }
2689
+ return null;
2690
+ }
2691
+ function validateContent(filePath, content) {
2692
+ if (filePath.endsWith(".json")) return validateJsonContent(content);
2693
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml")) return validateYamlContent(content);
2694
+ if (filePath === ".env" || filePath.startsWith(".env")) return validateEnvContent(content);
2695
+ return null;
2696
+ }
2697
+ function handleSafeWrite(input) {
2698
+ const cwd = input._cwd ?? process.cwd();
2699
+ const { callerOtter, filePath, content, createDirectories = true } = input;
2700
+ const check = checkPathAllowed(callerOtter, filePath);
2701
+ if (!check.allowed) {
2702
+ const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter] ?? [];
2703
+ const allowedPaths = allowlist.map((r) => `${r.prefix}*${r.suffix} (${r.description})`);
2704
+ const result = {
2705
+ success: false,
2706
+ error: check.error ?? "Path not allowed",
2707
+ callerOtter,
2708
+ attemptedPath: filePath,
2709
+ allowedPaths
2710
+ };
2711
+ return { text: JSON.stringify(result), isError: true };
2712
+ }
2713
+ const normalized = normalize(filePath);
2714
+ const fullPath = join4(cwd, normalized);
2715
+ if (existsSync5(fullPath)) {
2716
+ try {
2717
+ const stat = lstatSync5(fullPath);
2718
+ if (stat.isSymbolicLink()) {
2719
+ const result = {
2720
+ success: false,
2721
+ error: "Target path is a symlink \u2014 refusing to write through symlinks for security",
2722
+ callerOtter,
2723
+ attemptedPath: filePath,
2724
+ allowedPaths: []
2725
+ };
2726
+ return { text: JSON.stringify(result), isError: true };
2727
+ }
2728
+ } catch {
2729
+ }
2730
+ }
2731
+ const contentError = validateContent(normalized, content);
2732
+ if (contentError) {
2733
+ const result = {
2734
+ success: false,
2735
+ error: `Content validation failed: ${contentError}`,
2736
+ callerOtter,
2737
+ attemptedPath: filePath,
2738
+ allowedPaths: []
2739
+ };
2740
+ return { text: JSON.stringify(result), isError: true };
2741
+ }
2742
+ try {
2743
+ if (createDirectories) {
2744
+ mkdirSync4(dirname(fullPath), { recursive: true });
2745
+ }
2746
+ writeFileSync4(fullPath, content, { encoding: "utf-8" });
2747
+ const result = {
2748
+ success: true,
2749
+ path: normalized,
2750
+ bytesWritten: Buffer.byteLength(content, "utf-8"),
2751
+ allowRule: check.rule ?? "unknown"
2752
+ };
2753
+ return { text: JSON.stringify(result), isError: false };
2754
+ } catch (err) {
2755
+ const message = err instanceof Error ? err.message : String(err);
2756
+ const result = {
2757
+ success: false,
2758
+ error: `Write failed: ${message}`,
2759
+ callerOtter,
2760
+ attemptedPath: filePath,
2761
+ allowedPaths: []
2762
+ };
2763
+ return { text: JSON.stringify(result), isError: true };
2764
+ }
2765
+ }
2766
+ function registerSafeWriteTools(server2) {
2767
+ const DESC = "Controlled file-write chokepoint. Every write from specialist otters goes through this tool with per-otter path allowlists. The LLM cannot write to arbitrary filesystem paths.";
2768
+ server2.tool(
2769
+ "stackwright_pro_safe_write",
2770
+ DESC,
2771
+ {
2772
+ callerOtter: z11.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
2773
+ filePath: z11.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
2774
+ content: z11.string().describe("File content to write"),
2775
+ createDirectories: boolCoerce(z11.boolean().optional().default(true)).describe(
2776
+ "Create parent directories if they don't exist. Default: true"
2777
+ )
2778
+ },
2779
+ async ({ callerOtter, filePath, content, createDirectories }) => {
2780
+ const result = handleSafeWrite({
2781
+ callerOtter,
2782
+ filePath,
2783
+ content,
2784
+ ...createDirectories != null ? { createDirectories } : {}
2785
+ });
2786
+ return { content: [{ type: "text", text: result.text }], isError: result.isError };
2787
+ }
2788
+ );
2789
+ }
2790
+
2791
+ // src/tools/auth.ts
2792
+ import { z as z12 } from "zod";
2793
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync6 } from "fs";
2794
+ import { join as join5 } from "path";
2795
+ function buildHierarchy(roles) {
2796
+ const h = {};
2797
+ for (let i = 0; i < roles.length - 1; i++) {
2798
+ h[roles[i]] = roles.slice(i + 1);
2799
+ }
2800
+ return h;
2801
+ }
2802
+ function hierarchyToYaml(hierarchy, indent) {
2803
+ const entries = Object.entries(hierarchy);
2804
+ if (entries.length === 0) return `${indent}{}`;
2805
+ return entries.map(([role, subs]) => `${indent}${role}: [${subs.join(", ")}]`).join("\n");
2806
+ }
2807
+ function rolesToYaml(roles, indent) {
2808
+ return roles.map((r) => `${indent}- ${r}`).join("\n");
2809
+ }
2810
+ function routesToYaml(routes, defaultRole, indent) {
2811
+ return routes.map((r) => `${indent}- pattern: ${r}
2812
+ ${indent} requiredRole: ${defaultRole}`).join("\n");
2813
+ }
2814
+ function upsertAuthBlock(existing, authYaml) {
2815
+ const lines = existing.split("\n");
2816
+ let authStart = -1;
2817
+ let authEnd = lines.length;
2818
+ for (let i = 0; i < lines.length; i++) {
2819
+ if (/^auth:/.test(lines[i])) {
2820
+ authStart = i;
2821
+ } else if (authStart >= 0 && i > authStart && /^\S/.test(lines[i]) && lines[i].trim() !== "") {
2822
+ authEnd = i;
2823
+ break;
2824
+ }
2825
+ }
2826
+ if (authStart < 0) {
2827
+ return existing.trimEnd() + "\n" + authYaml + "\n";
2828
+ }
2829
+ const before = lines.slice(0, authStart);
2830
+ const after = lines.slice(authEnd);
2831
+ return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
2832
+ }
2833
+ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2834
+ const rbacBlock = ` rbac: {
2835
+ roles: ${JSON.stringify(roles)},
2836
+ defaultRole: '${defaultRole}',
2837
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
2838
+ },`;
2839
+ const auditBlock = ` audit: {
2840
+ enabled: ${auditEnabled},
2841
+ retentionDays: ${auditRetentionDays},
2842
+ },`;
2843
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
2844
+ const configBlock = `export const config = {
2845
+ matcher: ${JSON.stringify(protectedRoutes)},
2846
+ };`;
2847
+ if (method === "cac") {
2848
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
2849
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2850
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2851
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2852
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth
2853
+ // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
2854
+ // DoD security officer review required before production deployment.
2855
+ // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
2856
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2857
+
2858
+ export const middleware = createProMiddleware({
2859
+ method: 'cac',
2860
+ cac: {
2861
+ caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
2862
+ edipiLookup: '${edipiLookup}',
2863
+ ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
2864
+ certHeader: '${certHeader}',
2865
+ },
2866
+ ${rbacBlock}
2867
+ ${auditBlock}
2868
+ ${routesBlock}
2869
+ });
2870
+
2871
+ ${configBlock}
2872
+ `;
2873
+ }
2874
+ if (method === "oidc") {
2875
+ const scopes2 = params.oidcScopes ?? "openid profile email";
2876
+ const roleClaim = params.oidcRoleClaim ?? "roles";
2877
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2878
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2879
+
2880
+ export const middleware = createProMiddleware({
2881
+ method: 'oidc',
2882
+ oidc: {
2883
+ discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
2884
+ clientId: process.env.OIDC_CLIENT_ID!,
2885
+ clientSecret: process.env.OIDC_CLIENT_SECRET!,
2886
+ scopes: '${scopes2}',
2887
+ roleClaim: '${roleClaim}',
2888
+ },
2889
+ ${rbacBlock}
2890
+ ${auditBlock}
2891
+ ${routesBlock}
2892
+ });
2893
+
2894
+ ${configBlock}
2895
+ `;
2896
+ }
2897
+ const scopes = params.oauth2Scopes ?? "read write";
2898
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2899
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2900
+
2901
+ export const middleware = createProMiddleware({
2902
+ method: 'oauth2',
2903
+ oauth2: {
2904
+ authorizationUrl: process.env.OAUTH2_AUTH_URL!,
2905
+ tokenUrl: process.env.OAUTH2_TOKEN_URL!,
2906
+ clientId: process.env.OAUTH2_CLIENT_ID!,
2907
+ clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
2908
+ scopes: '${scopes}',
2909
+ },
2910
+ ${rbacBlock}
2911
+ ${auditBlock}
2912
+ ${routesBlock}
2913
+ });
2914
+
2915
+ ${configBlock}
2916
+ `;
2917
+ }
2918
+ function generateEnvBlock(method, params) {
2919
+ if (method === "cac") {
2920
+ return `# Authentication (CAC/PKI \u2014 DoD)
2921
+ # \u26A0\uFE0F SECURITY REVIEW REQUIRED before production deployment
2922
+ CAC_CA_BUNDLE=./certs/dod-ca-bundle.pem
2923
+ CAC_OCSP_ENDPOINT=https://ocsp.disa.mil
2924
+ `;
2925
+ }
2926
+ if (method === "oidc") {
2927
+ const label = params.provider ?? "OIDC";
2928
+ const discoveryUrl = params.oidcDiscoveryUrl ?? "https://your-provider/.well-known/openid-configuration";
2929
+ return `# Authentication (OIDC \u2014 ${label})
2930
+ OIDC_DISCOVERY_URL=${discoveryUrl}
2931
+ OIDC_CLIENT_ID=your-client-id
2932
+ OIDC_CLIENT_SECRET=your-client-secret
2933
+ `;
2934
+ }
2935
+ const authUrl = params.oauth2AuthUrl ?? "https://your-auth-server/authorize";
2936
+ const tokenUrl = params.oauth2TokenUrl ?? "https://your-auth-server/token";
2937
+ return `# Authentication (OAuth2)
2938
+ OAUTH2_AUTH_URL=${authUrl}
2939
+ OAUTH2_TOKEN_URL=${tokenUrl}
2940
+ OAUTH2_CLIENT_ID=your-client-id
2941
+ OAUTH2_CLIENT_SECRET=your-client-secret
2942
+ `;
2943
+ }
2944
+ function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2945
+ const rbacSection = ` rbac:
2946
+ roles:
2947
+ ${rolesToYaml(roles, " ")}
2948
+ defaultRole: ${defaultRole}
2949
+ hierarchy:
2950
+ ${hierarchyToYaml(hierarchy, " ")}`;
2951
+ const auditSection = ` audit:
2952
+ enabled: ${auditEnabled}
2953
+ retentionDays: ${auditRetentionDays}`;
2954
+ const routesSection = ` protectedRoutes:
2955
+ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
2956
+ const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
2957
+ requiredRole: ${defaultRole}`).join("\n");
2958
+ const providerLine = params.provider ? ` provider: ${params.provider}
2959
+ ` : "";
2960
+ if (method === "cac") {
2961
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
2962
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2963
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2964
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2965
+ return `auth:
2966
+ method: cac
2967
+ ${providerLine} middleware: ./middleware.ts
2968
+ cac:
2969
+ caBundle: \${CAC_CA_BUNDLE}
2970
+ edipiLookup: ${edipiLookup}
2971
+ ocspEndpoint: \${CAC_OCSP_ENDPOINT}
2972
+ certHeader: ${certHeader}
2973
+ ${rbacSection}
2974
+ protectedRoutes:
2975
+ ${routeLines}
2976
+ ${auditSection}
2977
+ `;
2978
+ }
2979
+ if (method === "oidc") {
2980
+ const scopes2 = params.oidcScopes ?? "openid profile email";
2981
+ const roleClaim = params.oidcRoleClaim ?? "roles";
2982
+ return `auth:
2983
+ method: oidc
2984
+ ${providerLine} middleware: ./middleware.ts
2985
+ oidc:
2986
+ discoveryUrl: \${OIDC_DISCOVERY_URL}
2987
+ clientId: \${OIDC_CLIENT_ID}
2988
+ clientSecret: \${OIDC_CLIENT_SECRET}
2989
+ scopes: ${scopes2}
2990
+ roleClaim: ${roleClaim}
2991
+ ${rbacSection}
2992
+ protectedRoutes:
2993
+ ${routeLines}
2994
+ ${auditSection}
2995
+ `;
2996
+ }
2997
+ const scopes = params.oauth2Scopes ?? "read write";
2998
+ return `auth:
2999
+ method: oauth2
3000
+ ${providerLine} middleware: ./middleware.ts
3001
+ oauth2:
3002
+ authorizationUrl: \${OAUTH2_AUTH_URL}
3003
+ tokenUrl: \${OAUTH2_TOKEN_URL}
3004
+ clientId: \${OAUTH2_CLIENT_ID}
3005
+ clientSecret: \${OAUTH2_CLIENT_SECRET}
3006
+ scopes: ${scopes}
3007
+ ${rbacSection}
3008
+ protectedRoutes:
3009
+ ${routeLines}
3010
+ ${auditSection}
3011
+ `;
3012
+ }
3013
+ async function configureAuthHandler(params, cwd) {
3014
+ const {
3015
+ method,
3016
+ provider,
3017
+ rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
3018
+ auditEnabled = true,
3019
+ auditRetentionDays = 90,
3020
+ protectedRoutes = ["/dashboard/:path*"]
3021
+ } = params;
3022
+ const roles = rbacRoles;
3023
+ const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
3024
+ const hierarchy = buildHierarchy(roles);
3025
+ if (method === "none") {
3026
+ return {
3027
+ content: [
3028
+ {
3029
+ type: "text",
3030
+ text: JSON.stringify({
3031
+ success: true,
3032
+ method: "none",
3033
+ provider: null,
3034
+ rbacRoles: roles,
3035
+ rbacDefaultRole: defaultRole,
3036
+ protectedRoutesCount: protectedRoutes.length,
3037
+ filesWritten: [],
3038
+ securityWarning: null
3039
+ })
3040
+ }
3041
+ ]
3042
+ };
3043
+ }
3044
+ const filesWritten = [];
3045
+ try {
3046
+ const middlewareContent = generateMiddlewareContent(
3047
+ method,
3048
+ params,
3049
+ roles,
3050
+ defaultRole,
3051
+ hierarchy,
3052
+ auditEnabled,
3053
+ auditRetentionDays,
3054
+ protectedRoutes
3055
+ );
3056
+ writeFileSync5(join5(cwd, "middleware.ts"), middlewareContent, "utf8");
3057
+ filesWritten.push("middleware.ts");
3058
+ } catch (err) {
3059
+ const msg = err instanceof Error ? err.message : String(err);
3060
+ return {
3061
+ content: [
3062
+ {
3063
+ type: "text",
3064
+ text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
3065
+ }
3066
+ ],
3067
+ isError: true
3068
+ };
3069
+ }
3070
+ try {
3071
+ const envBlock = generateEnvBlock(method, params);
3072
+ const envPath = join5(cwd, ".env.example");
3073
+ if (existsSync6(envPath)) {
3074
+ const existing = readFileSync4(envPath, "utf8");
3075
+ writeFileSync5(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
3076
+ } else {
3077
+ writeFileSync5(envPath, envBlock, "utf8");
3078
+ }
3079
+ filesWritten.push(".env.example");
3080
+ } catch (err) {
3081
+ const msg = err instanceof Error ? err.message : String(err);
3082
+ return {
3083
+ content: [
3084
+ {
3085
+ type: "text",
3086
+ text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
3087
+ }
3088
+ ],
3089
+ isError: true
3090
+ };
3091
+ }
3092
+ try {
3093
+ const authYaml = generateYamlBlock(
3094
+ method,
3095
+ params,
3096
+ roles,
3097
+ defaultRole,
3098
+ hierarchy,
3099
+ auditEnabled,
3100
+ auditRetentionDays,
3101
+ protectedRoutes
3102
+ );
3103
+ const ymlPath = join5(cwd, "stackwright.yml");
3104
+ if (!existsSync6(ymlPath)) {
3105
+ writeFileSync5(ymlPath, authYaml, "utf8");
3106
+ } else {
3107
+ const existing = readFileSync4(ymlPath, "utf8");
3108
+ writeFileSync5(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
3109
+ }
3110
+ filesWritten.push("stackwright.yml");
3111
+ } catch (err) {
3112
+ const msg = err instanceof Error ? err.message : String(err);
3113
+ return {
3114
+ content: [
3115
+ {
3116
+ type: "text",
3117
+ text: JSON.stringify({ success: false, error: `Failed writing stackwright.yml: ${msg}` })
3118
+ }
3119
+ ],
3120
+ isError: true
3121
+ };
3122
+ }
3123
+ const securityWarning = method === "cac" ? "SECURITY REVIEW REQUIRED \u2014 CAC certificate chain must be verified before production deployment" : null;
3124
+ return {
3125
+ content: [
3126
+ {
3127
+ type: "text",
3128
+ text: JSON.stringify({
3129
+ success: true,
3130
+ method,
3131
+ provider: provider ?? null,
3132
+ rbacRoles: roles,
3133
+ rbacDefaultRole: defaultRole,
3134
+ protectedRoutesCount: protectedRoutes.length,
3135
+ filesWritten,
3136
+ securityWarning
3137
+ })
3138
+ }
3139
+ ]
3140
+ };
3141
+ }
3142
+ function registerAuthTools(server2) {
3143
+ server2.tool(
3144
+ "stackwright_pro_configure_auth",
3145
+ "Generate authentication middleware and configuration for a Next.js Stackwright application. Writes `middleware.ts` from a secure template, appends/updates the `auth:` section in `stackwright.yml`, and generates `.env.example` with required environment variables. \u26A0\uFE0F For CAC/PKI: generated `middleware.ts` carries a SECURITY REVIEW REQUIRED comment \u2014 certificate chain validation must be verified by a DoD security officer before production deployment. This is the ONLY approved path to generating `middleware.ts`. Never write TypeScript auth files directly.",
3146
+ {
3147
+ method: z12.enum(["cac", "oidc", "oauth2", "none"]),
3148
+ provider: z12.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
3149
+ // CAC
3150
+ cacCaBundle: z12.string().optional(),
3151
+ cacEdipiLookup: z12.string().optional(),
3152
+ cacOcspEndpoint: z12.string().optional(),
3153
+ cacCertHeader: z12.string().optional(),
3154
+ // OIDC
3155
+ oidcDiscoveryUrl: z12.string().optional(),
3156
+ oidcClientId: z12.string().optional(),
3157
+ oidcClientSecret: z12.string().optional(),
3158
+ oidcScopes: z12.string().optional(),
3159
+ oidcRoleClaim: z12.string().optional(),
3160
+ // OAuth2
3161
+ oauth2AuthUrl: z12.string().optional(),
3162
+ oauth2TokenUrl: z12.string().optional(),
3163
+ oauth2ClientId: z12.string().optional(),
3164
+ oauth2ClientSecret: z12.string().optional(),
3165
+ oauth2Scopes: z12.string().optional(),
3166
+ // RBAC
3167
+ rbacRoles: jsonCoerce(z12.array(z12.string()).optional()),
3168
+ rbacDefaultRole: z12.string().optional(),
3169
+ // Audit
3170
+ auditEnabled: boolCoerce(z12.boolean().optional()),
3171
+ auditRetentionDays: numCoerce(z12.number().int().positive().optional()),
3172
+ // Routes
3173
+ protectedRoutes: jsonCoerce(z12.array(z12.string()).optional()),
3174
+ // Injection for tests
3175
+ _cwd: z12.string().optional()
3176
+ },
3177
+ async (params) => {
3178
+ const cwd = params._cwd ?? process.cwd();
3179
+ return configureAuthHandler(params, cwd);
3180
+ }
3181
+ );
3182
+ }
3183
+
3184
+ // src/integrity.ts
3185
+ import { createHash as createHash2, timingSafeEqual } from "crypto";
3186
+ import { readFileSync as readFileSync5, readdirSync, lstatSync as lstatSync6 } from "fs";
3187
+ import { join as join6, basename } from "path";
3188
+ var _checksums = /* @__PURE__ */ new Map([
3189
+ [
3190
+ "stackwright-pro-api-otter.json",
3191
+ "0ac26d85a5ad35b072a58965e1d5e090dd5c5f16dc14e68c452c3e99fcbb5510"
3192
+ ],
3193
+ [
3194
+ "stackwright-pro-auth-otter.json",
3195
+ "e4314897e7dead94cbd07cf58cd9df1a2614a207c85bdddf9259121945903721"
3196
+ ],
3197
+ [
3198
+ "stackwright-pro-dashboard-otter.json",
3199
+ "600e8597429c353e5b886f316731be84a86cd8b93617bf046e3cbf390b31a431"
3200
+ ],
3201
+ [
3202
+ "stackwright-pro-data-otter.json",
3203
+ "08352843c3dbfd1e20171493fb95ae7c73fde9dca0e2d6eecb5dc2d7d7b3cda7"
3204
+ ],
3205
+ [
3206
+ "stackwright-pro-designer-otter.json",
3207
+ "f4dbff5149051c77be1645de5ee12c0bd7d590c687a0b2d86737b915a5a6d5f0"
3208
+ ],
3209
+ [
3210
+ "stackwright-pro-foreman-otter.json",
3211
+ "e361cc30f013e1e423ebb4f59c54fd1452d049fabcc0539ce56b4a49cb5ec3ea"
3212
+ ],
3213
+ [
3214
+ "stackwright-pro-page-otter.json",
3215
+ "0323d9c9f4b4008b516d7615f24c0ebab9470bdf9cd37e1d48cfc06ccf6fccee"
3216
+ ],
3217
+ [
3218
+ "stackwright-pro-theme-otter.json",
3219
+ "a303ec6c045420f2c916583e3f6efcda469e9610fedfc84a508ed8a8a75866bc"
3220
+ ],
3221
+ [
3222
+ "stackwright-pro-workflow-otter.json",
3223
+ "ec203f222b2771f2bc3b29f340d881480c6a23188667e533476f4245e78453ef"
3224
+ ]
3225
+ ]);
3226
+ Object.freeze(_checksums);
3227
+ var CANONICAL_CHECKSUMS = _checksums;
3228
+ var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
3229
+ for (const [name, digest] of CANONICAL_CHECKSUMS) {
3230
+ if (!SHA256_HEX_RE.test(digest)) {
3231
+ throw new Error(
3232
+ `Malformed SHA-256 in CANONICAL_CHECKSUMS for "${name}": expected 64 hex chars, got ${digest.length}: "${digest}"`
3233
+ );
3234
+ }
3235
+ }
3236
+ var MAX_OTTER_BYTES = 1 * 1024 * 1024;
3237
+ function computeSha256(data) {
3238
+ return createHash2("sha256").update(data).digest("hex");
3239
+ }
3240
+ function safeEqual(a, b) {
3241
+ if (a.length !== b.length) return false;
3242
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
3243
+ }
3244
+ function verifyOtterFile(filePath) {
3245
+ const filename = basename(filePath);
3246
+ const expected = CANONICAL_CHECKSUMS.get(filename);
3247
+ if (expected === void 0) {
3248
+ return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
3249
+ }
3250
+ let stat;
3251
+ try {
3252
+ stat = lstatSync6(filePath);
3253
+ } catch (err) {
3254
+ const msg = err instanceof Error ? err.message : String(err);
3255
+ return { verified: false, filename, error: `Cannot stat file: ${msg}` };
3256
+ }
3257
+ if (stat.isSymbolicLink()) {
3258
+ return { verified: false, filename, error: "Refusing to verify symlink" };
3259
+ }
3260
+ const size = stat.size;
3261
+ if (size > MAX_OTTER_BYTES) {
3262
+ return {
3263
+ verified: false,
3264
+ filename,
3265
+ error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`
3266
+ };
3267
+ }
3268
+ let raw;
3269
+ try {
3270
+ raw = readFileSync5(filePath);
3271
+ } catch (err) {
3272
+ const msg = err instanceof Error ? err.message : String(err);
3273
+ return { verified: false, filename, error: `Cannot read file: ${msg}` };
3274
+ }
3275
+ if (raw.length > MAX_OTTER_BYTES) {
3276
+ return {
3277
+ verified: false,
3278
+ filename,
3279
+ error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`
3280
+ };
3281
+ }
3282
+ const actual = computeSha256(raw);
3283
+ if (!safeEqual(actual, expected)) {
3284
+ return {
3285
+ verified: false,
3286
+ filename,
3287
+ error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}\u2026, got ${actual.substring(0, 8)}\u2026`
3288
+ };
3289
+ }
3290
+ try {
3291
+ const decoder = new TextDecoder("utf-8", { fatal: true });
3292
+ decoder.decode(raw);
3293
+ } catch {
3294
+ return {
3295
+ verified: false,
3296
+ filename,
3297
+ error: "File is not valid UTF-8 \u2014 may be corrupted or contain binary injection"
3298
+ };
3299
+ }
3300
+ return { verified: true, filename };
3301
+ }
3302
+ function verifyAllOtters(otterDir) {
3303
+ const verified = [];
3304
+ const failed = [];
3305
+ const unknown = [];
3306
+ let entries;
3307
+ try {
3308
+ entries = readdirSync(otterDir);
3309
+ } catch (err) {
3310
+ const msg = err instanceof Error ? err.message : String(err);
3311
+ return {
3312
+ verified: [],
3313
+ failed: [{ filename: "<directory>", error: `Cannot read directory: ${msg}` }],
3314
+ unknown: []
3315
+ };
3316
+ }
3317
+ const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
3318
+ for (const filename of otterFiles) {
3319
+ const filePath = join6(otterDir, filename);
3320
+ try {
3321
+ if (lstatSync6(filePath).isSymbolicLink()) {
3322
+ failed.push({ filename, error: "Skipped: symlink" });
3323
+ continue;
3324
+ }
3325
+ } catch {
3326
+ }
3327
+ const result = verifyOtterFile(filePath);
3328
+ if (result.verified) {
3329
+ verified.push(result.filename);
3330
+ } else if (result.error?.startsWith("Unknown otter file")) {
3331
+ unknown.push(result.filename);
3332
+ } else {
3333
+ failed.push({ filename: result.filename, error: result.error ?? "Unknown error" });
3334
+ }
3335
+ }
3336
+ for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {
3337
+ if (!otterFiles.includes(canonicalName)) {
3338
+ failed.push({ filename: canonicalName, error: "Missing from directory" });
3339
+ }
3340
+ }
3341
+ return { verified, failed, unknown };
3342
+ }
3343
+ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packages/otters/src/"];
3344
+ function resolveOtterDir() {
3345
+ const cwd = process.cwd();
3346
+ for (const relative of DEFAULT_SEARCH_PATHS) {
3347
+ const candidate = join6(cwd, relative);
3348
+ try {
3349
+ lstatSync6(candidate);
3350
+ return candidate;
3351
+ } catch {
3352
+ }
3353
+ }
3354
+ return null;
3355
+ }
3356
+ function registerIntegrityTools(server2) {
3357
+ server2.tool(
3358
+ "stackwright_pro_verify_otter_integrity",
3359
+ "Verify SHA-256 integrity of all Pro otter agent definitions. Call this at startup before discovering otters. Auto-discovers the otter directory from known paths. Returns verified/failed/unknown lists.",
3360
+ {},
3361
+ async () => {
3362
+ const resolved = resolveOtterDir();
3363
+ if (!resolved) {
3364
+ return {
3365
+ content: [
3366
+ {
3367
+ type: "text",
3368
+ text: JSON.stringify({
3369
+ error: true,
3370
+ message: "Could not locate otter directory. Searched: " + DEFAULT_SEARCH_PATHS.join(", ")
3371
+ })
3372
+ }
3373
+ ],
3374
+ isError: true
3375
+ };
3376
+ }
3377
+ const result = verifyAllOtters(resolved);
3378
+ const allGood = result.failed.length === 0 && result.unknown.length === 0;
3379
+ return {
3380
+ content: [
3381
+ {
3382
+ type: "text",
3383
+ text: JSON.stringify({
3384
+ otterDir: resolved,
3385
+ totalCanonical: CANONICAL_CHECKSUMS.size,
3386
+ verifiedCount: result.verified.length,
3387
+ failedCount: result.failed.length,
3388
+ unknownCount: result.unknown.length,
3389
+ verified: result.verified,
3390
+ failed: result.failed,
3391
+ unknown: result.unknown,
3392
+ warning: result.failed.length > 0 ? "SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon." : void 0
3393
+ })
3394
+ }
3395
+ ],
3396
+ isError: false
3397
+ };
3398
+ }
3399
+ );
3400
+ }
3401
+
3402
+ // src/tools/domain.ts
3403
+ import { z as z13 } from "zod";
3404
+ import { readFileSync as readFileSync6, existsSync as existsSync7 } from "fs";
3405
+ import { join as join7 } from "path";
3406
+ function handleListCollections(input) {
3407
+ const cwd = input._cwd ?? process.cwd();
3408
+ const sources = [
3409
+ {
3410
+ path: join7(cwd, ".stackwright", "artifacts", "data-config.json"),
3411
+ source: "data-config.json",
3412
+ parse: (raw) => {
3413
+ const parsed = JSON.parse(raw);
3414
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
3415
+ return [];
3416
+ }
3417
+ return extractCollectionsFromArtifact(parsed);
3418
+ }
3419
+ },
3420
+ {
3421
+ path: join7(cwd, "stackwright.yml"),
3422
+ source: "stackwright.yml",
3423
+ parse: extractCollectionsFromYaml
3424
+ }
3425
+ ];
3426
+ for (const { path: path3, source, parse } of sources) {
3427
+ if (!existsSync7(path3)) continue;
3428
+ try {
3429
+ const collections = parse(readFileSync6(path3, "utf8"));
3430
+ return {
3431
+ text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3432
+ isError: false
3433
+ };
3434
+ } catch {
3435
+ }
3436
+ }
3437
+ return {
3438
+ text: JSON.stringify({
3439
+ collections: [],
3440
+ source: "none",
3441
+ collectionCount: 0,
3442
+ hint: "Run API Otter and Data Otter first"
3443
+ }),
3444
+ isError: false
3445
+ };
3446
+ }
3447
+ function extractCollectionsFromArtifact(raw) {
3448
+ const collections = [];
3449
+ const integrations = raw.integrations ?? raw.collections ?? [];
3450
+ if (!Array.isArray(integrations)) return collections;
3451
+ for (const item of integrations) {
3452
+ if (!item || typeof item !== "object") continue;
3453
+ const obj = item;
3454
+ if (typeof obj.name === "string" && typeof obj.endpoint === "string") {
3455
+ collections.push(makeCollectionInfo(obj.name, obj.endpoint, obj.type));
3456
+ continue;
3457
+ }
3458
+ if (!Array.isArray(obj.collections)) continue;
3459
+ for (const col of obj.collections) {
3460
+ if (!col || typeof col !== "object") continue;
3461
+ const c = col;
3462
+ if (typeof c.name === "string" && typeof c.endpoint === "string") {
3463
+ collections.push(makeCollectionInfo(c.name, c.endpoint, c.type ?? obj.type));
3464
+ }
3465
+ }
3466
+ }
3467
+ return collections;
3468
+ }
3469
+ function makeCollectionInfo(name, endpoint, type) {
3470
+ return { name, endpoint, ...typeof type === "string" ? { type } : {} };
3471
+ }
3472
+ function extractCollectionsFromYaml(yamlText) {
3473
+ const collections = [];
3474
+ const lines = yamlText.split("\n");
3475
+ let inIntegrations = false;
3476
+ let currentName = null;
3477
+ let currentEndpoint = null;
3478
+ let currentType = null;
3479
+ for (const line of lines) {
3480
+ if (line.length > 1e3) continue;
3481
+ if (/^integrations:\s*$/.test(line)) {
3482
+ inIntegrations = true;
3483
+ continue;
3484
+ }
3485
+ if (inIntegrations && /^[a-z]/.test(line) && !line.startsWith(" ")) {
3486
+ inIntegrations = false;
3487
+ }
3488
+ if (!inIntegrations) continue;
3489
+ const stripQuotes = (s) => s.trim().replace(/^['"]|['"]$/g, "");
3490
+ const typeMatch = line.match(/^\s+type:\s*(.+)$/);
3491
+ if (typeMatch?.[1]) currentType = stripQuotes(typeMatch[1]);
3492
+ const nameMatch = line.match(/^[\s-]+name:\s*(.+)$/);
3493
+ if (nameMatch?.[1]) {
3494
+ if (currentName && currentEndpoint) {
3495
+ collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
3496
+ }
3497
+ currentName = stripQuotes(nameMatch[1]);
3498
+ currentEndpoint = null;
3499
+ }
3500
+ const endpointMatch = line.match(/^\s+endpoint:\s*(.+)$/);
3501
+ if (endpointMatch?.[1]) currentEndpoint = stripQuotes(endpointMatch[1]);
3502
+ }
3503
+ if (currentName && currentEndpoint) {
3504
+ collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
3505
+ }
3506
+ return collections;
3507
+ }
3508
+ var DATA_STRATEGIES = {
3509
+ "pulse-fast": {
3510
+ strategy: "pulse-fast",
3511
+ mechanism: "Client-side polling via @stackwright-pro/pulse",
3512
+ mechanismPackage: "@stackwright-pro/pulse",
3513
+ pulse: true,
3514
+ requiredPackages: { "@stackwright-pro/pulse": "latest", "@tanstack/react-query": "^5.0.0" },
3515
+ handoffFlags: ["PULSE_MODE=true"],
3516
+ description: "Real-time updates every few seconds. Uses client-side polling. Dashboard Otter should use *_pulse component variants."
3517
+ },
3518
+ "isr-fast": {
3519
+ strategy: "isr-fast",
3520
+ mechanism: "Next.js ISR",
3521
+ revalidateSeconds: 60,
3522
+ pulse: false,
3523
+ requiredPackages: {},
3524
+ handoffFlags: [],
3525
+ description: "Near real-time with 60-second ISR revalidation. Good for dashboards that need minute-level freshness."
3526
+ },
3527
+ "isr-standard": {
3528
+ strategy: "isr-standard",
3529
+ mechanism: "Next.js ISR",
3530
+ revalidateSeconds: 3600,
3531
+ pulse: false,
3532
+ requiredPackages: {},
3533
+ handoffFlags: [],
3534
+ description: "Standard hourly revalidation. Good for most API-backed pages."
3535
+ },
3536
+ "isr-slow": {
3537
+ strategy: "isr-slow",
3538
+ mechanism: "Next.js ISR",
3539
+ revalidateSeconds: 86400,
3540
+ pulse: false,
3541
+ requiredPackages: {},
3542
+ handoffFlags: [],
3543
+ description: "Daily revalidation. Good for infrequently changing data."
3544
+ }
3545
+ };
3546
+ function handleResolveDataStrategy(input) {
3547
+ const key = input.strategy.trim().toLowerCase();
3548
+ const match = DATA_STRATEGIES[key];
3549
+ if (!match) {
3550
+ const validKeys = Object.keys(DATA_STRATEGIES).join(", ");
3551
+ return {
3552
+ text: JSON.stringify({
3553
+ error: true,
3554
+ message: `Unknown strategy: "${input.strategy}". Valid strategies: ${validKeys}`,
3555
+ validStrategies: Object.keys(DATA_STRATEGIES)
3556
+ }),
3557
+ isError: true
3558
+ };
3559
+ }
3560
+ const configureIsrCall = match.pulse ? null : {
3561
+ tool: "stackwright_pro_configure_isr_batch",
3562
+ args: {
3563
+ collections: [{ name: "$COLLECTION", revalidateSeconds: match.revalidateSeconds }]
3564
+ }
3565
+ };
3566
+ return {
3567
+ text: JSON.stringify({ ...match, configureIsrCall }),
3568
+ isError: false
3569
+ };
3570
+ }
3571
+ function fail(errors) {
3572
+ return { text: JSON.stringify({ valid: false, errors, warnings: [] }), isError: true };
3573
+ }
3574
+ function handleValidateWorkflow(input) {
3575
+ const cwd = input._cwd ?? process.cwd();
3576
+ let raw;
3577
+ if (input.workflow && Object.keys(input.workflow).length > 0) {
3578
+ raw = input.workflow;
3579
+ } else {
3580
+ const artifactPath = join7(cwd, ".stackwright", "artifacts", "workflow-config.json");
3581
+ if (!existsSync7(artifactPath)) {
3582
+ return fail([
3583
+ {
3584
+ code: "NO_WORKFLOW",
3585
+ message: "No workflow provided and .stackwright/artifacts/workflow-config.json not found. Pass a workflow object or run the workflow otter first."
3586
+ }
3587
+ ]);
3588
+ }
3589
+ try {
3590
+ raw = JSON.parse(readFileSync6(artifactPath, "utf8"));
3591
+ } catch (err) {
3592
+ return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3593
+ }
3594
+ }
3595
+ const workflow = raw.workflow && typeof raw.workflow === "object" ? raw.workflow : raw;
3596
+ const errors = [];
3597
+ const warnings = [];
3598
+ if (typeof workflow.id !== "string" || !workflow.id) {
3599
+ errors.push({ code: "MISSING_ID", message: "workflow.id is required", path: "workflow.id" });
3600
+ } else if (!/^[a-z0-9-]+$/.test(workflow.id)) {
3601
+ errors.push({
3602
+ code: "INVALID_ID",
3603
+ message: `workflow.id "${workflow.id}" must match ^[a-z0-9-]+$`,
3604
+ path: "workflow.id"
3605
+ });
3606
+ }
3607
+ if (typeof workflow.label !== "string" || !workflow.label) {
3608
+ errors.push({
3609
+ code: "MISSING_LABEL",
3610
+ message: "workflow.label is required",
3611
+ path: "workflow.label"
3612
+ });
3613
+ }
3614
+ const steps = workflow.steps;
3615
+ if (!Array.isArray(steps)) {
3616
+ errors.push({
3617
+ code: "MISSING_STEPS",
3618
+ message: "workflow.steps must be an array",
3619
+ path: "workflow.steps"
3620
+ });
3621
+ return { text: JSON.stringify({ valid: false, errors, warnings }), isError: false };
3622
+ }
3623
+ if (steps.length < 2) {
3624
+ errors.push({
3625
+ code: "TOO_FEW_STEPS",
3626
+ message: "A workflow must have at least 2 steps",
3627
+ path: "workflow.steps"
3628
+ });
3629
+ }
3630
+ const stepIds = /* @__PURE__ */ new Set();
3631
+ const duplicateIds = [];
3632
+ for (const step of steps) {
3633
+ if (!step || typeof step !== "object") continue;
3634
+ const id = step.id;
3635
+ if (typeof id !== "string" || !id) {
3636
+ errors.push({
3637
+ code: "MISSING_STEP_ID",
3638
+ message: "Every step must have an id",
3639
+ path: "workflow.steps"
3640
+ });
3641
+ continue;
3642
+ }
3643
+ if (!/^[a-z0-9_]+$/.test(id)) {
3644
+ errors.push({
3645
+ code: "INVALID_STEP_ID",
3646
+ message: `Step ID "${id}" must match ^[a-z0-9_]+$`,
3647
+ path: `workflow.steps[${id}].id`
3648
+ });
3649
+ }
3650
+ if (stepIds.has(id)) duplicateIds.push(id);
3651
+ stepIds.add(id);
3652
+ }
3653
+ if (duplicateIds.length > 0) {
3654
+ errors.push({
3655
+ code: "DUPLICATE_STEP_IDS",
3656
+ message: `Duplicate step IDs: ${duplicateIds.join(", ")}`,
3657
+ path: "workflow.steps"
3658
+ });
3659
+ }
3660
+ const initialStep = workflow.initial_step;
3661
+ if (typeof initialStep !== "string" || !initialStep) {
3662
+ errors.push({
3663
+ code: "MISSING_INITIAL_STEP",
3664
+ message: "workflow.initial_step is required",
3665
+ path: "workflow.initial_step"
3666
+ });
3667
+ } else if (!stepIds.has(initialStep)) {
3668
+ errors.push({
3669
+ code: "INVALID_INITIAL_STEP",
3670
+ message: `initial_step "${initialStep}" does not reference an existing step. Valid: ${[...stepIds].join(", ")}`,
3671
+ path: "workflow.initial_step"
3672
+ });
3673
+ }
3674
+ for (const step of steps) {
3675
+ if (!step || typeof step !== "object") continue;
3676
+ const s = step;
3677
+ const stepId = String(s.id ?? "??");
3678
+ validateTransitionTargets(s, stepId, stepIds, errors);
3679
+ collectServiceWarnings(s, stepId, warnings);
3680
+ }
3681
+ if (typeof workflow.persistence === "string" && workflow.persistence.startsWith("service:")) {
3682
+ warnings.push({
3683
+ code: "WARN_SERVICE_REFERENCE",
3684
+ message: 'service: reference at "workflow.persistence" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.',
3685
+ path: "workflow.persistence"
3686
+ });
3687
+ }
3688
+ const hasTerminal = steps.some((step) => {
3689
+ if (!step || typeof step !== "object") return false;
3690
+ return step.type === "terminal";
3691
+ });
3692
+ if (!hasTerminal) {
3693
+ errors.push({
3694
+ code: "NO_TERMINAL_STATE",
3695
+ message: "Workflow must have at least one step with type: terminal",
3696
+ path: "workflow.steps"
3697
+ });
3698
+ }
3699
+ return { text: JSON.stringify({ valid: errors.length === 0, errors, warnings }), isError: false };
3700
+ }
3701
+ function validateTransitionTargets(step, stepId, stepIds, errors) {
3702
+ const check = (target, path3) => {
3703
+ if (typeof target === "string" && !stepIds.has(target)) {
3704
+ errors.push({
3705
+ code: "ORPHANED_TRANSITION",
3706
+ message: `Step "${stepId}" transitions to "${target}" which does not exist`,
3707
+ path: path3
3708
+ });
3709
+ }
3710
+ };
3711
+ const onSubmit = step.on_submit;
3712
+ if (onSubmit && typeof onSubmit === "object") {
3713
+ check(onSubmit.transition, `workflow.steps[${stepId}].on_submit.transition`);
3714
+ }
3715
+ if (Array.isArray(step.actions)) {
3716
+ for (const action of step.actions) {
3717
+ if (!action || typeof action !== "object") continue;
3718
+ const a = action;
3719
+ check(a.transition, `workflow.steps[${stepId}].actions[${a.id ?? "??"}].transition`);
3720
+ }
3721
+ }
3722
+ if (Array.isArray(step.conditions)) {
3723
+ for (const cond of step.conditions) {
3724
+ if (!cond || typeof cond !== "object") continue;
3725
+ const then = cond.then;
3726
+ if (then && typeof then === "object") {
3727
+ check(then.transition, `workflow.steps[${stepId}].conditions`);
3728
+ }
3729
+ }
3730
+ }
3731
+ if (Array.isArray(step.show_fields_from)) {
3732
+ for (const ref of step.show_fields_from)
3733
+ check(ref, `workflow.steps[${stepId}].show_fields_from`);
3734
+ }
3735
+ const display = step.display;
3736
+ if (display && typeof display === "object") {
3737
+ check(display.source_step, `workflow.steps[${stepId}].display.source_step`);
3738
+ if (Array.isArray(display.source_steps)) {
3739
+ for (const ref of display.source_steps)
3740
+ check(ref, `workflow.steps[${stepId}].display.source_steps`);
3741
+ }
3742
+ }
3743
+ }
3744
+ function collectServiceWarnings(step, stepId, warnings) {
3745
+ const isService = (val) => typeof val === "string" && val.startsWith("service:");
3746
+ const warn = (path3) => {
3747
+ warnings.push({
3748
+ code: "WARN_SERVICE_REFERENCE",
3749
+ message: `service: reference at "${path3}" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.`,
3750
+ path: path3
3751
+ });
3752
+ };
3753
+ const onSubmit = step.on_submit;
3754
+ if (onSubmit && typeof onSubmit === "object" && isService(onSubmit.action))
3755
+ warn(`${stepId}.on_submit.action`);
3756
+ const onEnter = step.on_enter;
3757
+ if (onEnter && typeof onEnter === "object" && isService(onEnter.action))
3758
+ warn(`${stepId}.on_enter.action`);
3759
+ if (Array.isArray(step.actions)) {
3760
+ for (const action of step.actions) {
3761
+ if (!action || typeof action !== "object") continue;
3762
+ const a = action;
3763
+ if (isService(a.action)) warn(`${stepId}.actions.${a.id ?? "??"}.action`);
3764
+ }
3765
+ }
3766
+ if (Array.isArray(step.fields)) {
3767
+ for (const field of step.fields) {
3768
+ if (!field || typeof field !== "object") continue;
3769
+ const f = field;
3770
+ if (isService(f.data_source)) warn(`${stepId}.fields.${f.name ?? "??"}.data_source`);
3771
+ }
3772
+ }
3773
+ }
3774
+ function registerDomainTools(server2) {
3775
+ const res = (r) => ({
3776
+ content: [{ type: "text", text: r.text }],
3777
+ isError: r.isError
3778
+ });
3779
+ server2.tool(
3780
+ "stackwright_pro_list_collections",
3781
+ "List API-backed collections available for page generation. Reads from Data Otter artifact (.stackwright/artifacts/data-config.json) or stackwright.yml. Call this before generating pages that bind to data.",
3782
+ {},
3783
+ async () => res(handleListCollections({}))
3784
+ );
3785
+ server2.tool(
3786
+ "stackwright_pro_resolve_data_strategy",
3787
+ "Look up the data freshness strategy configuration from the user's answer. Returns mechanism, revalidation seconds, required packages, and the exact MCP tool call to make. Replaces the strategy table in the data-otter prompt.",
3788
+ {
3789
+ strategy: z13.string().describe(
3790
+ 'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3791
+ )
3792
+ },
3793
+ async ({ strategy }) => res(handleResolveDataStrategy({ strategy }))
3794
+ );
3795
+ server2.tool(
3796
+ "stackwright_pro_validate_workflow",
3797
+ "Validate a workflow definition against the Stackwright workflow schema. Checks step ID uniqueness, transition targets, terminal state existence, and service references. Call this after the workflow otter produces output.",
3798
+ {
3799
+ workflow: jsonCoerce(z13.record(z13.string(), z13.unknown()).optional()).describe(
3800
+ "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3801
+ )
3802
+ },
3803
+ async ({ workflow }) => res(handleValidateWorkflow(workflow ? { workflow } : {}))
3804
+ );
3805
+ }
3806
+
3807
+ // src/tools/type-schemas.ts
3808
+ import { z as z14 } from "zod";
3809
+ function buildTypeSchemaSummary() {
3810
+ return {
3811
+ version: "1.0",
3812
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3813
+ domains: {
3814
+ workflow: {
3815
+ description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
3816
+ schemas: [
3817
+ "WorkflowFileSchema",
3818
+ "WorkflowDefinitionSchema",
3819
+ "WorkflowStepSchema",
3820
+ "WorkflowStepTypeSchema",
3821
+ "WorkflowFieldSchema",
3822
+ "WorkflowActionSchema",
3823
+ "WorkflowAuthSchema",
3824
+ "WorkflowThemeSchema",
3825
+ "TransitionConditionSchema",
3826
+ "PersistenceSchema"
3827
+ ],
3828
+ otter: "stackwright-pro-workflow-otter",
3829
+ artifactKey: "workflowConfig"
3830
+ },
3831
+ auth: {
3832
+ description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
3833
+ schemas: [
3834
+ "authConfigSchema",
3835
+ "pkiConfigSchema",
3836
+ "oidcConfigSchema",
3837
+ "rbacConfigSchema",
3838
+ "componentAuthSchema",
3839
+ "authUserSchema",
3840
+ "authSessionSchema"
3841
+ ],
3842
+ otter: "stackwright-pro-auth-otter",
3843
+ artifactKey: "authConfig"
3844
+ },
3845
+ openapi: {
3846
+ description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
3847
+ interfaces: [
3848
+ "OpenAPIConfig",
3849
+ "ActionConfig",
3850
+ "EndpointFilter",
3851
+ "ApprovedSpec",
3852
+ "PrebuildSecurityConfig",
3853
+ "SiteConfig",
3854
+ "ValidationResult"
3855
+ ],
3856
+ otter: "stackwright-pro-api-otter",
3857
+ artifactKey: "apiConfig"
3858
+ },
3859
+ pulse: {
3860
+ description: "Real-time data polling \u2014 source-agnostic polling options and states",
3861
+ interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
3862
+ note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
3863
+ },
3864
+ enterprise: {
3865
+ description: "Enterprise collection access \u2014 multi-tenant provider extension",
3866
+ interfaces: [
3867
+ "EnterpriseCollectionProvider",
3868
+ "CollectionProvider",
3869
+ "CollectionEntry",
3870
+ "CollectionListOptions",
3871
+ "CollectionListResult",
3872
+ "TenantFilter",
3873
+ "Collection"
3874
+ ],
3875
+ note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
3876
+ }
3877
+ }
3878
+ };
3879
+ }
3880
+ function registerTypeSchemasTool(server2) {
3881
+ server2.tool(
3882
+ "stackwright_pro_get_type_schemas",
3883
+ "Returns a structured summary of all canonical @stackwright-pro/types schemas, organized by domain. Use this to determine which otter owns a given schema and what artifact key to expect.",
3884
+ {
3885
+ format: z14.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
3886
+ },
3887
+ async ({ format }) => {
3888
+ const summary = buildTypeSchemaSummary();
3889
+ const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
3890
+ return {
3891
+ content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
3892
+ };
3893
+ }
3894
+ );
3895
+ }
3896
+
3897
+ // package.json
3898
+ var package_default = {
3899
+ dependencies: {
3900
+ "@stackwright-pro/types": "workspace:*",
3901
+ "@modelcontextprotocol/sdk": "^1.10.0",
3902
+ "@stackwright-pro/cli-data-explorer": "workspace:*",
3903
+ zod: "^4.3.6"
3904
+ },
3905
+ devDependencies: {
3906
+ "@types/node": "^24.1.0",
3907
+ tsup: "^8.5.0",
3908
+ typescript: "^5.8.3",
3909
+ vitest: "^4.0.18"
3910
+ },
3911
+ scripts: {
3912
+ prepublishOnly: "node scripts/verify-integrity-sync.js",
3913
+ build: "tsup",
3914
+ dev: "tsup --watch",
3915
+ start: "node dist/server.js",
3916
+ test: "vitest run",
3917
+ "test:coverage": "vitest run --coverage"
3918
+ },
3919
+ name: "@stackwright-pro/mcp",
3920
+ version: "0.2.0-alpha.30",
3921
+ description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3922
+ license: "PROPRIETARY",
3923
+ main: "./dist/server.js",
3924
+ bin: {
3925
+ "stackwright-pro-mcp": "./dist/server.js"
3926
+ },
3927
+ module: "./dist/server.mjs",
3928
+ types: "./dist/server.d.ts",
3929
+ exports: {
3930
+ ".": {
3931
+ types: "./dist/server.d.ts",
3932
+ import: "./dist/server.mjs",
3933
+ require: "./dist/server.js"
3934
+ },
3935
+ "./integrity": {
3936
+ types: "./dist/integrity.d.ts",
3937
+ import: "./dist/integrity.mjs",
3938
+ require: "./dist/integrity.js"
3939
+ },
3940
+ "./type-schemas": {
3941
+ types: "./dist/tools/type-schemas.d.ts",
3942
+ import: "./dist/tools/type-schemas.mjs",
3943
+ require: "./dist/tools/type-schemas.js"
1213
3944
  }
1214
3945
  },
1215
3946
  files: [
@@ -1231,6 +3962,14 @@ registerIsrTools(server);
1231
3962
  registerDashboardTools(server);
1232
3963
  registerClarificationTools(server);
1233
3964
  registerPackageTools(server);
3965
+ registerQuestionTools(server);
3966
+ registerOrchestrationTools(server);
3967
+ registerPipelineTools(server);
3968
+ registerSafeWriteTools(server);
3969
+ registerAuthTools(server);
3970
+ registerIntegrityTools(server);
3971
+ registerDomainTools(server);
3972
+ registerTypeSchemasTool(server);
1234
3973
  async function main() {
1235
3974
  const transport = new StdioServerTransport();
1236
3975
  await server.connect(transport);